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