File size: 1,248 Bytes
6a839c1
423b87b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d2cb9e
423b87b
 
 
3d2cb9e
 
 
423b87b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// @ts-nocheck
import type { Presence } from "@liveblocks/client";
import { onDestroy } from "svelte";
import { writable } from "svelte/store";
import { useRoom } from "./useRoom";

/**
 * Works similarly to `liveblocks-react` useMyPresence
 * https://liveblocks.io/docs/api-reference/liveblocks-react#useMyPresence
 *
 * The main difference is that it returns a custom Svelte store:
 * const presence = useMyPresence()
 * presence.update({ name: 'Chris })
 * console.log($presence.name)
 * <div>{$presence.count}</div>
 *
 * USAGE NOTE:
 * This is a custom Svelte store, `set` does nothing, only `update`.
 * `update` does NOT take a function like regular Svelte stores,
 * it takes an object and works like `useUpdateMyPresence` in Liveblocks
 */

export function useMyPresence(_options: { addToHistory: boolean } = {}) {
  const room = useRoom();
  const { subscribe, set } = writable<Presence>();

  function update(newPresence, options?: { addToHistory: boolean }
  ) {
    room.updatePresence(newPresence, { ..._options, ...options });
  }

  const unsubscribePresence = room.subscribe("my-presence", (presence) => {
    set(presence);
  });

  onDestroy(() => {
    unsubscribePresence();
  });

  return {
    subscribe,
    update,
  };
}