-
Notifications
You must be signed in to change notification settings - Fork 22
/
main.tsx
336 lines (293 loc) · 9.44 KB
/
main.tsx
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
'use client'
import {
YSweetProvider,
YSweetProviderParams,
createYjsProvider,
debuggerUrl,
} from '@y-sweet/client'
import { ClientToken } from '@y-sweet/sdk'
import type { ReactNode } from 'react'
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'
import type { Awareness } from 'y-protocols/awareness'
import * as Y from 'yjs'
export { createYjsProvider, YSweetProvider, debuggerUrl, type YSweetProviderParams }
type YjsContextType = {
doc: Y.Doc
provider: YSweetProvider
clientToken: ClientToken
}
const YjsContext = createContext<YjsContextType | null>(null)
type YDocOptions = {
hideDebuggerLink?: boolean
}
/**
* React hook to get the Y.Doc instance from the current context.
*
* @returns The Y.Doc instance.
*/
export function useYDoc(options?: YDocOptions): Y.Doc {
const yjsCtx = useContext(YjsContext)
useEffect(() => {
if (!options?.hideDebuggerLink && yjsCtx) {
const url = debuggerUrl(yjsCtx.clientToken)
console.log(
`%cOpen this in Y-Sweet Debugger ⮕ ${url}`,
'font-size: 1.5em; display: block; padding: 10px;',
)
console.log(
'%cTo hide the debugger link, pass { hideDebuggerLink: true } to useYDoc',
'font-style: italic;',
)
}
}, [options?.hideDebuggerLink, yjsCtx])
if (!yjsCtx) {
throw new Error('Yjs hooks must be used within a YDocProvider')
}
return yjsCtx.doc
}
/**
* React hook to get the Y.Doc instance from the current context.
*
* @returns A debugger URL as a string.
*/
export function useYSweetDebugUrl(): string {
const yjsCtx = useContext(YjsContext)
if (!yjsCtx) {
throw new Error('Yjs hooks must be used within a YDocProvider')
}
return debuggerUrl(yjsCtx.clientToken)
}
/**
* React hook for obtaining the YSweetProvider instance from the current context.
*
* This is useful for integrating components that expect a direct reference
* to the provider.
*
* @returns The YSweetProvider instance.
*/
export function useYjsProvider(): YSweetProvider {
const yjsCtx = useContext(YjsContext)
if (!yjsCtx) {
throw new Error('Yjs hooks must be used within a YDocProvider')
}
return yjsCtx.provider
}
/**
* React hook for obtaining the Yjs Awareness instance from the current context.
*
* @returns The Yjs Awareness instance for the current document.
*/
export function useAwareness(): Awareness {
const yjsCtx = useContext(YjsContext)
if (!yjsCtx) {
throw new Error('Yjs hooks must be used within a YDocProvider')
}
return yjsCtx.provider.awareness
}
/**
* Options for the {@link usePresence} hook.
*/
type UsePresenceOptions = {
/** Whether the presence object should include the local client.
* Defaults to `false`.
*/
includeSelf?: boolean
}
/**
* React hook that returs a setter function for the local presence object.
*
* @returns A setter function for the local presence object.
*/
export function usePresenceSetter<T extends Record<string, any>>(): (presence: T) => void {
const awareness = useAwareness()
const setLocalPresence = useCallback(
(localState: any) => {
if (awareness) {
awareness.setLocalState(localState)
}
},
[awareness],
)
return setLocalPresence
}
/** React hook that returns other users’ presence values as a `Map<number, any>`. */
export function usePresence<T extends Record<string, any>>(
options?: UsePresenceOptions,
): Map<number, T> {
const awareness = useAwareness()
const [presence, setPresence] = useState<Map<number, T>>(new Map())
const includeSelf = options?.includeSelf || false
useEffect(() => {
if (awareness) {
const callback = () => {
const map = new Map()
awareness.getStates().forEach((state, clientID) => {
if (!includeSelf && clientID === awareness.clientID) return
if (Object.keys(state).length > 0) {
map.set(clientID, state)
}
})
setPresence(map)
}
awareness.on('change', callback)
return () => {
awareness.off('change', callback)
}
}
}, [awareness])
return presence
}
/**
* Props to the {@link YDocProvider} component.
*/
export type YDocProviderProps = {
/** The children to render. */
children: ReactNode
/** Response of a `getConnectionKey` call, passed from server to client. */
clientToken: ClientToken
/** If set to a string, the URL query parameter with this name
* will be set to the doc id from connectionKey. */
setQueryParam?: string
}
/**
* A React component that provides a Y.Doc instance to its children.
*/
export function YDocProvider(props: YDocProviderProps) {
const { children, clientToken } = props
const [ctx, setCtx] = useState<YjsContextType | null>(null)
useEffect(() => {
const doc = new Y.Doc()
const provider = createYjsProvider(doc, clientToken, {
// TODO: this disables local cross-tab communication, which makes
// debugging easier, but should be re-enabled eventually
disableBc: true,
})
setCtx({ doc, provider, clientToken })
return () => {
provider.destroy()
doc.destroy()
}
}, [clientToken.token, clientToken.url, clientToken.docId])
useEffect(() => {
if (props.setQueryParam) {
const url = new URL(window.location.href)
url.searchParams.set(props.setQueryParam, clientToken.docId)
window.history.replaceState({}, '', url.toString())
}
}, [props.setQueryParam, clientToken.docId])
if (ctx === null) return null
return <YjsContext.Provider value={ctx}>{children}</YjsContext.Provider>
}
function useRedraw() {
const [_, setRedraw] = useState(0)
return useCallback(() => setRedraw((x) => x + 1), [setRedraw])
}
/** Represents possible values to pass to hooks that return Yjs objects,
* which determines whether or not they trigger a re-render when the
* Yjs object changes.
*
* - `'deep'` will re-render when any nested property changes.
* - `'shallow'` will re-render when the object itself changes.
* - `'none'` will never re-render.
*/
export type ObserverKind = 'deep' | 'shallow' | 'none'
/**
* Options for hooks that return Yjs objects, like {@link useMap}.
*
* @see {@link ObserverKind}
*/
export type ObjectOptions = {
observe?: ObserverKind
}
/**
* Returns a `Y.Map<T>` object from the `Y.Doc` in the current context.
*
* The string `name` is the name of the top-level Yjs object to return.
* Two clients that call `useMap(...)` with the same `name` will get
* the same object.
*
* By default, this will subscribe the calling component to updates on
* the object and its children. See {@link ObjectOptions} and
* {@link ObserverKind} for finer control of observer behavior.
*
* @typeParam T The type of the values in the map. Keys are always strings.
* @param name The name of the top-level Yjs object to return.
* @param objectOptions
* @returns
*/
export function useMap<T>(name: string, objectOptions?: ObjectOptions): Y.Map<T> {
const doc = useYDoc({ hideDebuggerLink: true })
const map = useMemo(() => doc.getMap<T>(name), [doc, name])
useObserve(map, objectOptions?.observe || 'deep')
return map
}
/**
* Returns a `Y.Array<T>` object from the `Y.Doc` in the current context.
*
* The string `name` is the name of the top-level Yjs object to return.
* Two clients that call `useArray(...)` with the same `name` will get
* the same object.
*
* By default, this will subscribe the calling component to updates on
* the object and its children. See {@link ObjectOptions} and
* {@link ObserverKind} for finer control of observer behavior.
*
* @typeParam T The type of the values in the array.
* @param name The name of the top-level Yjs object to return.
* @param objectOptions
* @returns
*/
export function useArray<T>(name: string, objectOptions?: ObjectOptions): Y.Array<T> {
const doc = useYDoc({ hideDebuggerLink: true })
const array = useMemo(() => doc.getArray<T>(name), [doc, name])
useObserve(array, objectOptions?.observe || 'deep')
return array
}
/**
* Returns a `Y.Text` object from the `Y.Doc` in the current context.
*
* The string `name` is the name of the top-level Yjs object to return.
* Two clients that call `useText(...)` with the same `name` will get
* the same object.
*
* By default, this will subscribe the calling component to updates on
* the object and its children. See {@link ObjectOptions} and
* {@link ObserverKind} for finer control of observer behavior.
*
* @param name The name of the top-level Yjs object to return.
* @param objectOptions
* @returns
*/
export function useText(name: string, observerKind?: ObjectOptions): Y.Text {
const doc = useYDoc({ hideDebuggerLink: true })
const text = useMemo(() => doc.getText(name), [doc, name])
useObserve(text, observerKind?.observe || 'deep')
return text
}
/**
* A hook that causes its calling component to re-render when the given
* Yjs object changes.
*
* The `kind` parameter determines the level of change that will trigger
* a re-render. See {@link ObserverKind} for more information.
*
* @param object The Yjs object to observe.
* @param kind The kind of observation to perform.
*/
export function useObserve(object: Y.AbstractType<any>, kind: ObserverKind) {
const redraw = useRedraw()
useEffect(() => {
if (kind === 'deep') {
object.observeDeep(redraw)
} else if (kind === 'shallow') {
object.observe(redraw)
}
return () => {
if (kind === 'deep') {
object.unobserveDeep(redraw)
} else if (kind === 'shallow') {
object.unobserve(redraw)
}
}
})
}