@hocuspocus/provider-react 4.0.0-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,647 @@
1
+ "use client";
2
+
3
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4
+ //#region \0rolldown/runtime.js
5
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
6
+
7
+ //#endregion
8
+ let react = require("react");
9
+ let _hocuspocus_provider = require("@hocuspocus/provider");
10
+
11
+ //#region packages/provider-react/src/context.ts
12
+ /**
13
+ * Context for the WebSocket connection shared across rooms
14
+ */
15
+ const HocuspocusContext = (0, react.createContext)(null);
16
+ /**
17
+ * Context for the room/document provider
18
+ */
19
+ const HocuspocusRoomContext = (0, react.createContext)(null);
20
+
21
+ //#endregion
22
+ //#region node_modules/.pnpm/react@19.2.4/node_modules/react/cjs/react-jsx-runtime.production.js
23
+ /**
24
+ * @license React
25
+ * react-jsx-runtime.production.js
26
+ *
27
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
28
+ *
29
+ * This source code is licensed under the MIT license found in the
30
+ * LICENSE file in the root directory of this source tree.
31
+ */
32
+ var require_react_jsx_runtime_production = /* @__PURE__ */ __commonJSMin(((exports) => {
33
+ var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
34
+ function jsxProd(type, config, maybeKey) {
35
+ var key = null;
36
+ void 0 !== maybeKey && (key = "" + maybeKey);
37
+ void 0 !== config.key && (key = "" + config.key);
38
+ if ("key" in config) {
39
+ maybeKey = {};
40
+ for (var propName in config) "key" !== propName && (maybeKey[propName] = config[propName]);
41
+ } else maybeKey = config;
42
+ config = maybeKey.ref;
43
+ return {
44
+ $$typeof: REACT_ELEMENT_TYPE,
45
+ type,
46
+ key,
47
+ ref: void 0 !== config ? config : null,
48
+ props: maybeKey
49
+ };
50
+ }
51
+ exports.Fragment = REACT_FRAGMENT_TYPE;
52
+ exports.jsx = jsxProd;
53
+ exports.jsxs = jsxProd;
54
+ }));
55
+
56
+ //#endregion
57
+ //#region node_modules/.pnpm/react@19.2.4/node_modules/react/cjs/react-jsx-runtime.development.js
58
+ /**
59
+ * @license React
60
+ * react-jsx-runtime.development.js
61
+ *
62
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
63
+ *
64
+ * This source code is licensed under the MIT license found in the
65
+ * LICENSE file in the root directory of this source tree.
66
+ */
67
+ var require_react_jsx_runtime_development = /* @__PURE__ */ __commonJSMin(((exports) => {
68
+ "production" !== process.env.NODE_ENV && (function() {
69
+ function getComponentNameFromType(type) {
70
+ if (null == type) return null;
71
+ if ("function" === typeof type) return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
72
+ if ("string" === typeof type) return type;
73
+ switch (type) {
74
+ case REACT_FRAGMENT_TYPE: return "Fragment";
75
+ case REACT_PROFILER_TYPE: return "Profiler";
76
+ case REACT_STRICT_MODE_TYPE: return "StrictMode";
77
+ case REACT_SUSPENSE_TYPE: return "Suspense";
78
+ case REACT_SUSPENSE_LIST_TYPE: return "SuspenseList";
79
+ case REACT_ACTIVITY_TYPE: return "Activity";
80
+ }
81
+ if ("object" === typeof type) switch ("number" === typeof type.tag && console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."), type.$$typeof) {
82
+ case REACT_PORTAL_TYPE: return "Portal";
83
+ case REACT_CONTEXT_TYPE: return type.displayName || "Context";
84
+ case REACT_CONSUMER_TYPE: return (type._context.displayName || "Context") + ".Consumer";
85
+ case REACT_FORWARD_REF_TYPE:
86
+ var innerType = type.render;
87
+ type = type.displayName;
88
+ type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
89
+ return type;
90
+ case REACT_MEMO_TYPE: return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
91
+ case REACT_LAZY_TYPE:
92
+ innerType = type._payload;
93
+ type = type._init;
94
+ try {
95
+ return getComponentNameFromType(type(innerType));
96
+ } catch (x) {}
97
+ }
98
+ return null;
99
+ }
100
+ function testStringCoercion(value) {
101
+ return "" + value;
102
+ }
103
+ function checkKeyStringCoercion(value) {
104
+ try {
105
+ testStringCoercion(value);
106
+ var JSCompiler_inline_result = !1;
107
+ } catch (e) {
108
+ JSCompiler_inline_result = !0;
109
+ }
110
+ if (JSCompiler_inline_result) {
111
+ JSCompiler_inline_result = console;
112
+ var JSCompiler_temp_const = JSCompiler_inline_result.error;
113
+ var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
114
+ JSCompiler_temp_const.call(JSCompiler_inline_result, "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", JSCompiler_inline_result$jscomp$0);
115
+ return testStringCoercion(value);
116
+ }
117
+ }
118
+ function getTaskName(type) {
119
+ if (type === REACT_FRAGMENT_TYPE) return "<>";
120
+ if ("object" === typeof type && null !== type && type.$$typeof === REACT_LAZY_TYPE) return "<...>";
121
+ try {
122
+ var name = getComponentNameFromType(type);
123
+ return name ? "<" + name + ">" : "<...>";
124
+ } catch (x) {
125
+ return "<...>";
126
+ }
127
+ }
128
+ function getOwner() {
129
+ var dispatcher = ReactSharedInternals.A;
130
+ return null === dispatcher ? null : dispatcher.getOwner();
131
+ }
132
+ function UnknownOwner() {
133
+ return Error("react-stack-top-frame");
134
+ }
135
+ function hasValidKey(config) {
136
+ if (hasOwnProperty.call(config, "key")) {
137
+ var getter = Object.getOwnPropertyDescriptor(config, "key").get;
138
+ if (getter && getter.isReactWarning) return !1;
139
+ }
140
+ return void 0 !== config.key;
141
+ }
142
+ function defineKeyPropWarningGetter(props, displayName) {
143
+ function warnAboutAccessingKey() {
144
+ specialPropKeyWarningShown || (specialPropKeyWarningShown = !0, console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", displayName));
145
+ }
146
+ warnAboutAccessingKey.isReactWarning = !0;
147
+ Object.defineProperty(props, "key", {
148
+ get: warnAboutAccessingKey,
149
+ configurable: !0
150
+ });
151
+ }
152
+ function elementRefGetterWithDeprecationWarning() {
153
+ var componentName = getComponentNameFromType(this.type);
154
+ didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = !0, console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."));
155
+ componentName = this.props.ref;
156
+ return void 0 !== componentName ? componentName : null;
157
+ }
158
+ function ReactElement(type, key, props, owner, debugStack, debugTask) {
159
+ var refProp = props.ref;
160
+ type = {
161
+ $$typeof: REACT_ELEMENT_TYPE,
162
+ type,
163
+ key,
164
+ props,
165
+ _owner: owner
166
+ };
167
+ null !== (void 0 !== refProp ? refProp : null) ? Object.defineProperty(type, "ref", {
168
+ enumerable: !1,
169
+ get: elementRefGetterWithDeprecationWarning
170
+ }) : Object.defineProperty(type, "ref", {
171
+ enumerable: !1,
172
+ value: null
173
+ });
174
+ type._store = {};
175
+ Object.defineProperty(type._store, "validated", {
176
+ configurable: !1,
177
+ enumerable: !1,
178
+ writable: !0,
179
+ value: 0
180
+ });
181
+ Object.defineProperty(type, "_debugInfo", {
182
+ configurable: !1,
183
+ enumerable: !1,
184
+ writable: !0,
185
+ value: null
186
+ });
187
+ Object.defineProperty(type, "_debugStack", {
188
+ configurable: !1,
189
+ enumerable: !1,
190
+ writable: !0,
191
+ value: debugStack
192
+ });
193
+ Object.defineProperty(type, "_debugTask", {
194
+ configurable: !1,
195
+ enumerable: !1,
196
+ writable: !0,
197
+ value: debugTask
198
+ });
199
+ Object.freeze && (Object.freeze(type.props), Object.freeze(type));
200
+ return type;
201
+ }
202
+ function jsxDEVImpl(type, config, maybeKey, isStaticChildren, debugStack, debugTask) {
203
+ var children = config.children;
204
+ if (void 0 !== children) if (isStaticChildren) if (isArrayImpl(children)) {
205
+ for (isStaticChildren = 0; isStaticChildren < children.length; isStaticChildren++) validateChildKeys(children[isStaticChildren]);
206
+ Object.freeze && Object.freeze(children);
207
+ } else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");
208
+ else validateChildKeys(children);
209
+ if (hasOwnProperty.call(config, "key")) {
210
+ children = getComponentNameFromType(type);
211
+ var keys = Object.keys(config).filter(function(k) {
212
+ return "key" !== k;
213
+ });
214
+ isStaticChildren = 0 < keys.length ? "{key: someKey, " + keys.join(": ..., ") + ": ...}" : "{key: someKey}";
215
+ didWarnAboutKeySpread[children + isStaticChildren] || (keys = 0 < keys.length ? "{" + keys.join(": ..., ") + ": ...}" : "{}", console.error("A props object containing a \"key\" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />", isStaticChildren, children, keys, children), didWarnAboutKeySpread[children + isStaticChildren] = !0);
216
+ }
217
+ children = null;
218
+ void 0 !== maybeKey && (checkKeyStringCoercion(maybeKey), children = "" + maybeKey);
219
+ hasValidKey(config) && (checkKeyStringCoercion(config.key), children = "" + config.key);
220
+ if ("key" in config) {
221
+ maybeKey = {};
222
+ for (var propName in config) "key" !== propName && (maybeKey[propName] = config[propName]);
223
+ } else maybeKey = config;
224
+ children && defineKeyPropWarningGetter(maybeKey, "function" === typeof type ? type.displayName || type.name || "Unknown" : type);
225
+ return ReactElement(type, children, maybeKey, getOwner(), debugStack, debugTask);
226
+ }
227
+ function validateChildKeys(node) {
228
+ isValidElement(node) ? node._store && (node._store.validated = 1) : "object" === typeof node && null !== node && node.$$typeof === REACT_LAZY_TYPE && ("fulfilled" === node._payload.status ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1));
229
+ }
230
+ function isValidElement(object) {
231
+ return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
232
+ }
233
+ var React = require("react"), REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), ReactSharedInternals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, hasOwnProperty = Object.prototype.hasOwnProperty, isArrayImpl = Array.isArray, createTask = console.createTask ? console.createTask : function() {
234
+ return null;
235
+ };
236
+ React = { react_stack_bottom_frame: function(callStackForError) {
237
+ return callStackForError();
238
+ } };
239
+ var specialPropKeyWarningShown;
240
+ var didWarnAboutElementRef = {};
241
+ var unknownOwnerDebugStack = React.react_stack_bottom_frame.bind(React, UnknownOwner)();
242
+ var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
243
+ var didWarnAboutKeySpread = {};
244
+ exports.Fragment = REACT_FRAGMENT_TYPE;
245
+ exports.jsx = function(type, config, maybeKey) {
246
+ var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
247
+ return jsxDEVImpl(type, config, maybeKey, !1, trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack, trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask);
248
+ };
249
+ exports.jsxs = function(type, config, maybeKey) {
250
+ var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
251
+ return jsxDEVImpl(type, config, maybeKey, !0, trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack, trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask);
252
+ };
253
+ })();
254
+ }));
255
+
256
+ //#endregion
257
+ //#region node_modules/.pnpm/react@19.2.4/node_modules/react/jsx-runtime.js
258
+ var require_jsx_runtime = /* @__PURE__ */ __commonJSMin(((exports, module) => {
259
+ if (process.env.NODE_ENV === "production") module.exports = require_react_jsx_runtime_production();
260
+ else module.exports = require_react_jsx_runtime_development();
261
+ }));
262
+
263
+ //#endregion
264
+ //#region packages/provider-react/src/HocuspocusProviderWebsocketComponent.tsx
265
+ var import_jsx_runtime = require_jsx_runtime();
266
+ /**
267
+ * HocuspocusProviderWebsocketComponent manages the WebSocket connection that is shared across all rooms.
268
+ *
269
+ * This component creates a single WebSocket connection that can be used by multiple
270
+ * HocuspocusRoom components, preventing connection overhead when switching between documents.
271
+ *
272
+ * @example
273
+ * ```tsx
274
+ * <HocuspocusProviderWebsocketComponent url="ws://localhost:1234">
275
+ * <HocuspocusRoom name="document-1">
276
+ * <Editor />
277
+ * </HocuspocusRoom>
278
+ * </HocuspocusProviderWebsocketComponent>
279
+ * ```
280
+ */
281
+ function HocuspocusProviderWebsocketComponent({ children, url, websocketProvider: externalWebsocketProvider }) {
282
+ const websocketRef = (0, react.useRef)(null);
283
+ const destroyTimeoutRef = (0, react.useRef)(null);
284
+ if (!websocketRef.current && !externalWebsocketProvider) websocketRef.current = new _hocuspocus_provider.HocuspocusProviderWebsocket({ url });
285
+ const websocketProvider = externalWebsocketProvider ?? websocketRef.current;
286
+ (0, react.useEffect)(() => {
287
+ if (destroyTimeoutRef.current) {
288
+ clearTimeout(destroyTimeoutRef.current);
289
+ destroyTimeoutRef.current = null;
290
+ }
291
+ return () => {
292
+ if (!externalWebsocketProvider) destroyTimeoutRef.current = setTimeout(() => {
293
+ if (websocketRef.current) {
294
+ websocketRef.current.destroy();
295
+ websocketRef.current = null;
296
+ }
297
+ }, 0);
298
+ };
299
+ }, [externalWebsocketProvider]);
300
+ const contextValue = (0, react.useMemo)(() => ({ websocketProvider }), [websocketProvider]);
301
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HocuspocusContext.Provider, {
302
+ value: contextValue,
303
+ children
304
+ });
305
+ }
306
+
307
+ //#endregion
308
+ //#region packages/provider-react/src/HocuspocusRoom.tsx
309
+ /**
310
+ * Mapping from HocuspocusRoom `on*` prop names to provider event names.
311
+ */
312
+ const EVENT_PROP_MAP = {
313
+ onOpen: "open",
314
+ onConnect: "connect",
315
+ onClose: "close",
316
+ onDisconnect: "disconnect",
317
+ onStatus: "status",
318
+ onSynced: "synced",
319
+ onUnsyncedChanges: "unsyncedChanges",
320
+ onMessage: "message",
321
+ onOutgoingMessage: "outgoingMessage",
322
+ onStateless: "stateless",
323
+ onAuthenticated: "authenticated",
324
+ onAuthenticationFailed: "authenticationFailed",
325
+ onAwarenessUpdate: "awarenessUpdate",
326
+ onAwarenessChange: "awarenessChange",
327
+ onDestroy: "destroy"
328
+ };
329
+ /**
330
+ * HocuspocusRoom manages the connection to a specific document.
331
+ *
332
+ * It uses the shared WebSocket from HocuspocusProviderWebsocketComponent and creates a document-specific
333
+ * provider that connects on mount and disconnects on unmount.
334
+ *
335
+ * This component handles React's StrictMode gracefully by using deferred destruction,
336
+ * preventing unnecessary reconnections during development double-mounts.
337
+ *
338
+ * @example
339
+ * ```tsx
340
+ * <HocuspocusProviderWebsocketComponent url="ws://localhost:1234">
341
+ * <HocuspocusRoom
342
+ * name="document-1"
343
+ * onAuthenticationFailed={(data) => console.error(data.reason)}
344
+ * >
345
+ * <Editor />
346
+ * </HocuspocusRoom>
347
+ * </HocuspocusProviderWebsocketComponent>
348
+ * ```
349
+ */
350
+ function HocuspocusRoom({ children, name, document, token, ...eventHandlers }) {
351
+ const hocuspocusContext = (0, react.useContext)(HocuspocusContext);
352
+ if (!hocuspocusContext) throw new Error("HocuspocusRoom must be used within a HocuspocusProviderWebsocketComponent");
353
+ const { websocketProvider } = hocuspocusContext;
354
+ const [provider, setProvider] = (0, react.useState)(() => new _hocuspocus_provider.HocuspocusProvider({
355
+ name,
356
+ websocketProvider,
357
+ document,
358
+ token
359
+ }));
360
+ const destroyTimeoutRef = (0, react.useRef)(null);
361
+ (0, react.useEffect)(() => {
362
+ if (provider.configuration.name !== name || provider.configuration.document !== document || provider.configuration.token !== (token ?? null) || provider.configuration.websocketProvider !== websocketProvider) {
363
+ provider.destroy();
364
+ setProvider(new _hocuspocus_provider.HocuspocusProvider({
365
+ name,
366
+ websocketProvider,
367
+ document,
368
+ token
369
+ }));
370
+ }
371
+ }, [
372
+ name,
373
+ document,
374
+ token,
375
+ websocketProvider
376
+ ]);
377
+ (0, react.useEffect)(() => {
378
+ if (destroyTimeoutRef.current) {
379
+ clearTimeout(destroyTimeoutRef.current);
380
+ destroyTimeoutRef.current = null;
381
+ }
382
+ provider.attach();
383
+ return () => {
384
+ destroyTimeoutRef.current = setTimeout(() => {
385
+ provider.destroy();
386
+ }, 0);
387
+ };
388
+ }, [provider]);
389
+ const handlersRef = (0, react.useRef)(eventHandlers);
390
+ handlersRef.current = eventHandlers;
391
+ (0, react.useEffect)(() => {
392
+ const cleanups = [];
393
+ for (const [propName, eventName] of Object.entries(EVENT_PROP_MAP)) {
394
+ const listener = (...args) => {
395
+ const handler = handlersRef.current[propName];
396
+ handler?.(...args);
397
+ };
398
+ provider.on(eventName, listener);
399
+ cleanups.push(() => provider.off(eventName, listener));
400
+ }
401
+ return () => {
402
+ for (const cleanup of cleanups) cleanup();
403
+ };
404
+ }, [provider]);
405
+ const contextValue = (0, react.useMemo)(() => ({ provider }), [provider]);
406
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HocuspocusRoomContext.Provider, {
407
+ value: contextValue,
408
+ children
409
+ });
410
+ }
411
+
412
+ //#endregion
413
+ //#region packages/provider-react/src/hooks/useHocuspocusProvider.ts
414
+ /**
415
+ * Access the HocuspocusProvider instance for the current room.
416
+ *
417
+ * Must be used within a HocuspocusRoom component.
418
+ *
419
+ * @returns The HocuspocusProvider instance
420
+ * @throws Error if used outside of HocuspocusRoom
421
+ *
422
+ * @example
423
+ * ```tsx
424
+ * function Editor() {
425
+ * const provider = useHocuspocusProvider()
426
+ *
427
+ * const editor = useEditor({
428
+ * extensions: [
429
+ * Collaboration.configure({ document: provider.document }),
430
+ * CollaborationCursor.configure({ provider }),
431
+ * ],
432
+ * })
433
+ *
434
+ * return <EditorContent editor={editor} />
435
+ * }
436
+ * ```
437
+ */
438
+ function useHocuspocusProvider() {
439
+ const context = (0, react.useContext)(HocuspocusRoomContext);
440
+ if (!context) throw new Error("useHocuspocusProvider must be used within a HocuspocusRoom");
441
+ return context.provider;
442
+ }
443
+
444
+ //#endregion
445
+ //#region packages/provider-react/src/hooks/useHocuspocusAwareness.ts
446
+ /**
447
+ * Subscribe to the list of connected users in the document.
448
+ *
449
+ * This hook uses the Yjs awareness protocol to track users currently
450
+ * connected to the document.
451
+ *
452
+ * @returns Array of user objects with their awareness state
453
+ *
454
+ * @example
455
+ * ```tsx
456
+ * function UserList() {
457
+ * const users = useHocuspocusAwareness()
458
+ *
459
+ * return (
460
+ * <div className="avatars">
461
+ * {users.map(user => (
462
+ * <div
463
+ * key={user.clientId}
464
+ * style={{ backgroundColor: user.color }}
465
+ * title={user.name}
466
+ * >
467
+ * {user.name?.[0]}
468
+ * </div>
469
+ * ))}
470
+ * </div>
471
+ * )
472
+ * }
473
+ * ```
474
+ */
475
+ function useHocuspocusAwareness() {
476
+ const provider = useHocuspocusProvider();
477
+ const versionRef = (0, react.useRef)(0);
478
+ const cacheRef = (0, react.useRef)({
479
+ users: [],
480
+ version: -1
481
+ });
482
+ (0, react.useEffect)(() => {
483
+ versionRef.current++;
484
+ cacheRef.current = {
485
+ users: [],
486
+ version: -1
487
+ };
488
+ }, [provider]);
489
+ const subscribe = (0, react.useCallback)((onStoreChange) => {
490
+ const onChange = () => {
491
+ versionRef.current++;
492
+ onStoreChange();
493
+ };
494
+ provider.awareness?.on("change", onChange);
495
+ return () => {
496
+ provider.awareness?.off("change", onChange);
497
+ };
498
+ }, [provider]);
499
+ const getSnapshot = (0, react.useCallback)(() => {
500
+ const awareness = provider.awareness;
501
+ if (!awareness) return [];
502
+ if (cacheRef.current.version === versionRef.current) return cacheRef.current.users;
503
+ const users = [];
504
+ awareness.getStates().forEach((state, clientId) => {
505
+ users.push({
506
+ clientId,
507
+ ...state
508
+ });
509
+ });
510
+ cacheRef.current = {
511
+ users,
512
+ version: versionRef.current
513
+ };
514
+ return users;
515
+ }, [provider]);
516
+ return (0, react.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
517
+ }
518
+
519
+ //#endregion
520
+ //#region packages/provider-react/src/hooks/useHocuspocusConnectionStatus.ts
521
+ /**
522
+ * Subscribe to the connection status of the collaboration provider.
523
+ *
524
+ * This hook uses React's useSyncExternalStore for optimal integration with
525
+ * concurrent rendering features.
526
+ *
527
+ * @returns The current connection status: 'connecting', 'connected', or 'disconnected'
528
+ *
529
+ * @example
530
+ * ```tsx
531
+ * function ConnectionIndicator() {
532
+ * const status = useHocuspocusConnectionStatus()
533
+ *
534
+ * return (
535
+ * <div className={`status-${status}`}>
536
+ * {status === 'connected' ? 'Online' : status === 'connecting' ? 'Connecting...' : 'Offline'}
537
+ * </div>
538
+ * )
539
+ * }
540
+ * ```
541
+ */
542
+ function useHocuspocusConnectionStatus() {
543
+ const provider = useHocuspocusProvider();
544
+ const subscribe = (0, react.useCallback)((onStoreChange) => {
545
+ provider.on("status", onStoreChange);
546
+ return () => {
547
+ provider.off("status", onStoreChange);
548
+ };
549
+ }, [provider]);
550
+ const getSnapshot = (0, react.useCallback)(() => provider.configuration.websocketProvider.status, [provider]);
551
+ return (0, react.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
552
+ }
553
+
554
+ //#endregion
555
+ //#region packages/provider-react/src/hooks/useHocuspocusEvent.ts
556
+ /**
557
+ * Subscribe to events from the HocuspocusProvider for the current room.
558
+ *
559
+ * The handler is stored in a ref so the subscription stays stable even if
560
+ * the handler identity changes between renders.
561
+ *
562
+ * Must be used within a HocuspocusRoom component.
563
+ *
564
+ * @param event - The event name to subscribe to
565
+ * @param handler - Callback invoked when the event fires
566
+ *
567
+ * @example
568
+ * ```tsx
569
+ * function AuthGuard() {
570
+ * useHocuspocusEvent('authenticationFailed', (data) => {
571
+ * console.error('Auth failed:', data.reason)
572
+ * redirectToLogin()
573
+ * })
574
+ *
575
+ * useHocuspocusEvent('close', (data) => {
576
+ * console.log('Connection closed', data.event)
577
+ * })
578
+ *
579
+ * return null
580
+ * }
581
+ * ```
582
+ */
583
+ function useHocuspocusEvent(event, handler) {
584
+ const provider = useHocuspocusProvider();
585
+ const handlerRef = (0, react.useRef)(handler);
586
+ handlerRef.current = handler;
587
+ (0, react.useEffect)(() => {
588
+ const listener = (...args) => {
589
+ handlerRef.current(...args);
590
+ };
591
+ provider.on(event, listener);
592
+ return () => {
593
+ provider.off(event, listener);
594
+ };
595
+ }, [provider, event]);
596
+ }
597
+
598
+ //#endregion
599
+ //#region packages/provider-react/src/hooks/useHocuspocusSyncStatus.ts
600
+ /**
601
+ * Subscribe to the sync status of local changes.
602
+ *
603
+ * This hook indicates whether local changes have been synced with the server.
604
+ *
605
+ * @returns The current sync status: 'synced' or 'syncing'
606
+ *
607
+ * @example
608
+ * ```tsx
609
+ * function SaveIndicator() {
610
+ * const syncStatus = useHocuspocusSyncStatus()
611
+ *
612
+ * return (
613
+ * <div>
614
+ * {syncStatus === 'syncing' ? 'Saving...' : 'All changes saved'}
615
+ * </div>
616
+ * )
617
+ * }
618
+ * ```
619
+ */
620
+ function useHocuspocusSyncStatus() {
621
+ const provider = useHocuspocusProvider();
622
+ const subscribe = (0, react.useCallback)((onStoreChange) => {
623
+ provider.on("synced", onStoreChange);
624
+ provider.on("unsyncedChanges", onStoreChange);
625
+ return () => {
626
+ provider.off("synced", onStoreChange);
627
+ provider.off("unsyncedChanges", onStoreChange);
628
+ };
629
+ }, [provider]);
630
+ const getSnapshot = (0, react.useCallback)(() => {
631
+ if (provider.unsyncedChanges > 0) return "syncing";
632
+ return "synced";
633
+ }, [provider]);
634
+ return (0, react.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
635
+ }
636
+
637
+ //#endregion
638
+ exports.HocuspocusContext = HocuspocusContext;
639
+ exports.HocuspocusProviderWebsocketComponent = HocuspocusProviderWebsocketComponent;
640
+ exports.HocuspocusRoom = HocuspocusRoom;
641
+ exports.HocuspocusRoomContext = HocuspocusRoomContext;
642
+ exports.useHocuspocusAwareness = useHocuspocusAwareness;
643
+ exports.useHocuspocusConnectionStatus = useHocuspocusConnectionStatus;
644
+ exports.useHocuspocusEvent = useHocuspocusEvent;
645
+ exports.useHocuspocusProvider = useHocuspocusProvider;
646
+ exports.useHocuspocusSyncStatus = useHocuspocusSyncStatus;
647
+ //# sourceMappingURL=hocuspocus-provider-react.cjs.map