-
-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathuseRemoteCursorStateStore.ts
More file actions
89 lines (74 loc) · 2.59 KB
/
useRemoteCursorStateStore.ts
File metadata and controls
89 lines (74 loc) · 2.59 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import {
CursorEditor,
CursorState,
RemoteCursorChangeEventListener,
} from '@slate-yjs/core';
import { BaseEditor } from 'slate';
import { Store } from '../types';
import { useRemoteCursorEditor } from './useRemoteCursorEditor';
export type CursorStore<
TCursorData extends Record<string, unknown> = Record<string, unknown>
> = Store<Record<string, CursorState<TCursorData>>>;
const EDITOR_TO_CURSOR_STORE: WeakMap<BaseEditor, CursorStore> = new WeakMap();
function createRemoteCursorStateStore<
TCursorData extends Record<string, unknown>
>(editor: CursorEditor<TCursorData>): CursorStore<TCursorData> {
let cursors: Record<string, CursorState<TCursorData>> = {};
const changed = new Set<number>();
const addChanged = changed.add.bind(changed);
const onStoreChangeListeners: Set<() => void> = new Set();
let changeHandler: RemoteCursorChangeEventListener | null = null;
const subscribe = (onStoreChange: () => void) => {
onStoreChangeListeners.add(onStoreChange);
if (!changeHandler) {
changeHandler = (event) => {
event.added.forEach(addChanged);
event.removed.forEach(addChanged);
event.updated.forEach(addChanged);
onStoreChangeListeners.forEach((listener) => listener());
};
CursorEditor.on(editor, 'change', changeHandler);
}
return () => {
onStoreChangeListeners.delete(onStoreChange);
if (changeHandler && onStoreChangeListeners.size === 0) {
CursorEditor.off(editor, 'change', changeHandler);
changeHandler = null;
}
};
};
const getSnapshot = () => {
if (changed.size === 0) {
return cursors;
}
changed.forEach((clientId) => {
const state = CursorEditor.cursorState(editor, clientId);
if (state === null || state.relativeSelection === null) {
delete cursors[clientId.toString()];
return;
}
cursors[clientId] = state;
});
changed.clear();
cursors = { ...cursors };
return cursors;
};
return [subscribe, getSnapshot];
}
function getCursorStateStore<TCursorData extends Record<string, unknown>>(
editor: CursorEditor<TCursorData>
): CursorStore<TCursorData> {
const existing = EDITOR_TO_CURSOR_STORE.get(editor);
if (existing) {
return existing as CursorStore<TCursorData>;
}
const store = createRemoteCursorStateStore(editor);
EDITOR_TO_CURSOR_STORE.set(editor, store);
return store;
}
export function useRemoteCursorStateStore<
TCursorData extends Record<string, unknown> = Record<string, unknown>
>() {
const editor = useRemoteCursorEditor<TCursorData>();
return getCursorStateStore(editor);
}