@tangle-network/ui 11.10.0 → 11.11.1

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.
Files changed (132) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +4 -1
  3. package/dist/active-sessions-store-Gt1R0rFG.js +262 -0
  4. package/dist/{active-sessions-store-CeOmXgv5.d.ts → active-sessions-store-nl70ZnMC.d.ts} +40 -41
  5. package/dist/artifact-pane-BL_DFWNl.d.ts +32 -0
  6. package/dist/artifact-pane-DMXT9a8U.js +70 -0
  7. package/dist/auth-DOETfnd9.js +154 -0
  8. package/dist/auth.d.ts +2 -74
  9. package/dist/auth.js +2 -16
  10. package/dist/branding-26d5ARIr.d.ts +14 -0
  11. package/dist/button-C87nEe2R.js +78 -0
  12. package/dist/button-yoIv77e2.d.ts +16 -0
  13. package/dist/chat-D4jAfEmj.js +667 -0
  14. package/dist/chat.d.ts +2 -201
  15. package/dist/chat.js +2 -31
  16. package/dist/code-block-B36KVUSN.js +165 -0
  17. package/dist/code-block-B9miUPht.d.ts +23 -0
  18. package/dist/diff-preview-BcK3nRXb.js +533 -0
  19. package/dist/document-editor-pane-BcoABlhn.d.ts +131 -0
  20. package/dist/document-editor-pane-BxlPjaTP.js +1287 -0
  21. package/dist/dropdown-menu-BpcLa5vF.js +101 -0
  22. package/dist/editor.d.ts +76 -78
  23. package/dist/editor.js +2 -34
  24. package/dist/file-format-BgXbr-Ib.js +160 -0
  25. package/dist/files-Bug33qCl.js +743 -0
  26. package/dist/files.d.ts +2 -243
  27. package/dist/files.js +3 -41
  28. package/dist/focus-BcE_SHqz.js +57 -0
  29. package/dist/format-DfcLWqMa.js +54 -0
  30. package/dist/hooks.d.ts +30 -37
  31. package/dist/hooks.js +111 -46
  32. package/dist/index-2UntyjBb.d.ts +52 -0
  33. package/dist/index-BgUHilZm.d.ts +108 -0
  34. package/dist/index-COgqsFAQ.d.ts +42 -0
  35. package/dist/index-CPDET_s1.d.ts +549 -0
  36. package/dist/index-CUhfHT_V.d.ts +204 -0
  37. package/dist/index-Cg6gYAqh.d.ts +73 -0
  38. package/dist/index-Cq-EJzqW.d.ts +16 -0
  39. package/dist/index-DhYmSaLF.d.ts +245 -0
  40. package/dist/index-DjKxO357.d.ts +128 -0
  41. package/dist/index.d.ts +26 -43
  42. package/dist/index.js +35 -472
  43. package/dist/markdown-BGqicV82.js +45 -0
  44. package/dist/markdown.d.ts +3 -18
  45. package/dist/markdown.js +3 -15
  46. package/dist/message-vhUI0c5G.d.ts +16 -0
  47. package/dist/nav.d.ts +6 -8
  48. package/dist/nav.js +29 -11
  49. package/dist/openui-artifact-renderer-D3E5bIAI.d.ts +114 -0
  50. package/dist/openui-artifact-renderer-DrU1AdVk.js +266 -0
  51. package/dist/openui.d.ts +2 -115
  52. package/dist/openui.js +2 -13
  53. package/dist/parts-5mhy9yJ3.d.ts +37 -0
  54. package/dist/primitives-Cb8GGVKr.js +1239 -0
  55. package/dist/primitives.d.ts +5 -525
  56. package/dist/primitives.js +9 -212
  57. package/dist/redaction-CGGB2ENG.js +74 -0
  58. package/dist/redaction.d.ts +2 -42
  59. package/dist/redaction.js +2 -7
  60. package/dist/run-OyWmIDqu.d.ts +41 -0
  61. package/dist/run-ZsIKPA6J.js +17 -0
  62. package/dist/run-group-BACLbCFl.js +410 -0
  63. package/dist/run.d.ts +3 -126
  64. package/dist/run.js +5 -40
  65. package/dist/sdk-hooks.d.ts +2 -285
  66. package/dist/sdk-hooks.js +3 -36
  67. package/dist/stores.d.ts +13 -14
  68. package/dist/stores.js +34 -76
  69. package/dist/table-Bss73DhB.js +146 -0
  70. package/dist/tabs-BVHR6NkO.js +40 -0
  71. package/dist/text-shimmer-BUUo6I-g.js +64 -0
  72. package/dist/tool-call-feed-BeB1_4pX.d.ts +47 -0
  73. package/dist/tool-call-feed-Djt2q11V.js +109 -0
  74. package/dist/tool-call-step-DNebqhmX.js +434 -0
  75. package/dist/tool-display-BAuAVa43.js +158 -0
  76. package/dist/{tool-display-z4JcDmMQ.d.ts → tool-display-DgmL5rIU.d.ts} +16 -16
  77. package/dist/tool-previews.d.ts +2 -48
  78. package/dist/tool-previews.js +2 -23
  79. package/dist/types.d.ts +6 -19
  80. package/dist/types.js +0 -1
  81. package/dist/use-auto-scroll-C5Pjeqon.js +153 -0
  82. package/dist/use-sse-stream-BVgO1QBN.js +884 -0
  83. package/dist/use-sse-stream-Dm6R5YWz.d.ts +282 -0
  84. package/dist/utils-Bl_CZ0Qp.js +37 -0
  85. package/dist/{chunk-RQHJBTEU.js → utils-C_uf36nf.js} +4 -6
  86. package/dist/utils.d.ts +2 -104
  87. package/dist/utils.js +6 -44
  88. package/package.json +39 -41
  89. package/src/lib/focus.ts +2 -1
  90. package/dist/artifact-pane-DpuWcAiF.d.ts +0 -33
  91. package/dist/button-CMQuQEW_.d.ts +0 -17
  92. package/dist/chunk-34A66VBG.js +0 -214
  93. package/dist/chunk-3OI2QKFD.js +0 -0
  94. package/dist/chunk-3XXBZL53.js +0 -174
  95. package/dist/chunk-42PAH5D2.js +0 -112
  96. package/dist/chunk-4CLN43XT.js +0 -45
  97. package/dist/chunk-55WHV7SS.js +0 -1604
  98. package/dist/chunk-565EATZZ.js +0 -156
  99. package/dist/chunk-5Z5ZYMOJ.js +0 -0
  100. package/dist/chunk-6BGQA4BQ.js +0 -0
  101. package/dist/chunk-BEBXZPHW.js +0 -299
  102. package/dist/chunk-C5WF4WMV.js +0 -734
  103. package/dist/chunk-HFL6R6IF.js +0 -37
  104. package/dist/chunk-HGML45QH.js +0 -104
  105. package/dist/chunk-HMAPIH7L.js +0 -595
  106. package/dist/chunk-K5XFRUS4.js +0 -1401
  107. package/dist/chunk-KFQGHD73.js +0 -198
  108. package/dist/chunk-L57WRIND.js +0 -59
  109. package/dist/chunk-LTEKI7YJ.js +0 -59
  110. package/dist/chunk-M3QZK62R.js +0 -233
  111. package/dist/chunk-ND3ZFXQK.js +0 -179
  112. package/dist/chunk-OEX7NZE3.js +0 -321
  113. package/dist/chunk-OL5GYLHV.js +0 -60
  114. package/dist/chunk-QGFYBNSO.js +0 -133
  115. package/dist/chunk-R7B3UWPF.js +0 -550
  116. package/dist/chunk-R7SUY4E3.js +0 -65
  117. package/dist/chunk-REJESC5U.js +0 -117
  118. package/dist/chunk-RQGKSCEZ.js +0 -0
  119. package/dist/chunk-SNLR2AEA.js +0 -40
  120. package/dist/chunk-WKWBTL2V.js +0 -15
  121. package/dist/chunk-X7CU776B.js +0 -1048
  122. package/dist/chunk-XU3HB5QL.js +0 -127
  123. package/dist/chunk-YTO5V6QS.js +0 -19
  124. package/dist/chunk-YU4E5J2N.js +0 -437
  125. package/dist/chunk-YZ6AK25N.js +0 -886
  126. package/dist/code-block-0kSpWMnf.d.ts +0 -25
  127. package/dist/document-editor-pane-IAEQn_Dl.d.ts +0 -128
  128. package/dist/document-editor-pane-QHDOBA43.js +0 -13
  129. package/dist/message-BHWbxBtT.d.ts +0 -15
  130. package/dist/parts-dj7AcUg0.d.ts +0 -36
  131. package/dist/run-PfLmDAox.d.ts +0 -41
  132. package/dist/tool-call-feed-D9iofJgW.d.ts +0 -46
@@ -0,0 +1,1287 @@
1
+ import { i as focusRing } from "./focus-BcE_SHqz.js";
2
+ import { t as cn } from "./utils-C_uf36nf.js";
3
+ import { i as TabsTrigger, n as TabsContent, r as TabsList, t as Tabs } from "./tabs-BVHR6NkO.js";
4
+ import { t as ArtifactPane } from "./artifact-pane-DMXT9a8U.js";
5
+ import { t as Markdown } from "./markdown-BGqicV82.js";
6
+ import { Suspense, createContext, lazy, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
7
+ import { jsx, jsxs } from "react/jsx-runtime";
8
+ import { PencilLine, Save, Users, Wifi, WifiOff } from "lucide-react";
9
+ import { marked } from "marked";
10
+ import TurndownService from "turndown";
11
+ //#region \0rolldown/runtime.js
12
+ var __defProp = Object.defineProperty;
13
+ var __exportAll = (all, no_symbols) => {
14
+ let target = {};
15
+ for (var name in all) __defProp(target, name, {
16
+ get: all[name],
17
+ enumerable: true
18
+ });
19
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
20
+ return target;
21
+ };
22
+ //#endregion
23
+ //#region src/editor/editor-peers.ts
24
+ const DOCUMENT_PEERS_MISSING = "@tangle-network/ui/editor needs its optional editor peers. Install @tiptap/react and @tiptap/starter-kit.";
25
+ const PROVIDER_PEERS_MISSING = "@tangle-network/ui/editor needs its optional collaboration transport peers. Install @hocuspocus/provider and yjs.";
26
+ const COLLABORATION_PEERS_MISSING = "@tangle-network/ui/editor needs its optional collaboration peers. Install @tiptap/react, @tiptap/starter-kit, @tiptap/extension-collaboration, @tiptap/extension-collaboration-caret, @hocuspocus/provider and yjs.";
27
+ /**
28
+ * A peer the editor needs is absent, or resolved to a stub that carries none
29
+ * of the members the editor calls. The condition holds for the rest of the
30
+ * session, because a package does not install itself mid-run.
31
+ */
32
+ var MissingEditorPeersError = class extends Error {
33
+ constructor(message, options) {
34
+ super(message, options);
35
+ this.name = "MissingEditorPeersError";
36
+ }
37
+ };
38
+ /**
39
+ * True for the error above. The name carries the answer, so a duplicated copy
40
+ * of this module in a consumer's bundle still reports its own error correctly.
41
+ */
42
+ function isMissingEditorPeersError(error) {
43
+ return error instanceof Error && error.name === "MissingEditorPeersError";
44
+ }
45
+ /** The messages a bundler or a runtime gives for a module it cannot resolve. */
46
+ const RESOLUTION_FAILURE = /could not resolve|cannot find (?:module|package)|can't resolve|failed to resolve|module not found/i;
47
+ /**
48
+ * True when the rejection says the package is not installed. Only such an
49
+ * error gets the install list: a transient chunk-fetch failure that reads as
50
+ * "install the peers" sends the reader to the wrong fix. An error this
51
+ * predicate does not match keeps its own message, so it can only
52
+ * under-report.
53
+ */
54
+ function isMissingPeerError(error) {
55
+ return error instanceof Error && RESOLUTION_FAILURE.test(error.message);
56
+ }
57
+ /**
58
+ * Hands an `import()` rejection on unchanged. esbuild reports an unresolvable
59
+ * literal `import()` as a build error and defers it to run time only when the
60
+ * call carries a `.catch()`, so every peer import attaches this handler. It
61
+ * changes nothing at run time.
62
+ */
63
+ function rethrow(error) {
64
+ throw error;
65
+ }
66
+ /**
67
+ * Every optional peer the `./editor` entry needs at run time. The loaders
68
+ * import all but `@tiptap/core`, which the tiptap packages need in turn: a
69
+ * consumer that resolves it to nothing breaks the same way, so a failure that
70
+ * names it is a missing peer too. `scripts/validate-dist.mjs` holds the same
71
+ * list and rejects a build where the two disagree.
72
+ */
73
+ const DEFERRED_PEERS = [
74
+ "@tiptap/core",
75
+ "@tiptap/react",
76
+ "@tiptap/starter-kit",
77
+ "@tiptap/extension-collaboration",
78
+ "@tiptap/extension-collaboration-caret",
79
+ "@hocuspocus/provider",
80
+ "yjs"
81
+ ];
82
+ /** Every deferred peer a resolution failure names. */
83
+ function unresolvedPeersFrom(error) {
84
+ if (!(error instanceof Error)) return [];
85
+ const named = DEFERRED_PEERS.filter((name) => error.message.includes(name));
86
+ return named.filter((name) => !named.some((other) => other !== name && other.includes(name)));
87
+ }
88
+ /**
89
+ * Turns a rejection that names an unresolved peer into the install-list error,
90
+ * and keeps the original as its cause. Any other rejection passes through, so
91
+ * a transient chunk fetch keeps its own message and stays retryable.
92
+ */
93
+ function asMissingEditorPeersError(error, missingMessage) {
94
+ if (!isMissingPeerError(error)) return error;
95
+ const unresolved = unresolvedPeersFrom(error);
96
+ if (unresolved.length === 0) return error;
97
+ return new MissingEditorPeersError(missingMessage + (unresolved.length === 1 ? ` ${unresolved[0]} did not resolve.` : ""), { cause: error });
98
+ }
99
+ async function loadPeers(load, missingMessage) {
100
+ try {
101
+ return await load();
102
+ } catch (error) {
103
+ throw asMissingEditorPeersError(error, missingMessage);
104
+ }
105
+ }
106
+ /**
107
+ * True for a tiptap extension the editor can configure. A bundler can stub a
108
+ * missing optional peer as a silent namespace whose default export is an empty
109
+ * object, which is defined but carries no `configure`. Reading the member the
110
+ * factories call separates that shape from a real extension.
111
+ */
112
+ function isConfigurableExtension(value) {
113
+ return typeof value?.configure === "function";
114
+ }
115
+ /**
116
+ * Reads the members the editor calls, so a stub namespace fails with the
117
+ * install list, and not as an undefined-property crash in the middle of a
118
+ * render.
119
+ */
120
+ function assertDocumentEditorPeers(peers, missingMessage) {
121
+ if (typeof peers.react.useEditor !== "function" || peers.react.EditorContent === void 0 || !isConfigurableExtension(peers.starterKit.default)) throw new MissingEditorPeersError(missingMessage);
122
+ }
123
+ function assertEditorProviderPeers(peers, missingMessage) {
124
+ if (typeof peers.hocuspocus.HocuspocusProvider !== "function" || typeof peers.yjs.Doc !== "function") throw new MissingEditorPeersError(missingMessage);
125
+ }
126
+ function assertCollaborationPeers(peers) {
127
+ assertDocumentEditorPeers(peers, COLLABORATION_PEERS_MISSING);
128
+ assertEditorProviderPeers(peers, COLLABORATION_PEERS_MISSING);
129
+ if (!isConfigurableExtension(peers.collaboration.default) || !isConfigurableExtension(peers.collaborationCaret.default)) throw new MissingEditorPeersError(COLLABORATION_PEERS_MISSING);
130
+ }
131
+ async function importDocumentEditorPeers() {
132
+ const [react, starterKit] = await Promise.all([import("@tiptap/react").catch(rethrow), import("@tiptap/starter-kit").catch(rethrow)]);
133
+ return {
134
+ react,
135
+ starterKit
136
+ };
137
+ }
138
+ async function importEditorProviderPeers() {
139
+ const [hocuspocus, yjs] = await Promise.all([import("@hocuspocus/provider").catch(rethrow), import("yjs").catch(rethrow)]);
140
+ return {
141
+ hocuspocus,
142
+ yjs
143
+ };
144
+ }
145
+ /** Resolve the collaboration transport's peers, or throw and name them. */
146
+ async function loadEditorProviderPeers() {
147
+ const peers = await loadPeers(importEditorProviderPeers, PROVIDER_PEERS_MISSING);
148
+ assertEditorProviderPeers(peers, PROVIDER_PEERS_MISSING);
149
+ return peers;
150
+ }
151
+ /** Resolve the local markdown editor's peers, or throw and name them. */
152
+ async function loadDocumentEditorPeers() {
153
+ const peers = await loadPeers(importDocumentEditorPeers, DOCUMENT_PEERS_MISSING);
154
+ assertDocumentEditorPeers(peers, DOCUMENT_PEERS_MISSING);
155
+ return peers;
156
+ }
157
+ /** Resolve the collaborative editor's peers, or throw and name them. */
158
+ async function loadCollaborationPeers() {
159
+ const peers = await loadPeers(async () => {
160
+ const [documentPeers, providerPeers, collaboration, collaborationCaret] = await Promise.all([
161
+ importDocumentEditorPeers(),
162
+ importEditorProviderPeers(),
163
+ import("@tiptap/extension-collaboration").catch(rethrow),
164
+ import("@tiptap/extension-collaboration-caret").catch(rethrow)
165
+ ]);
166
+ return {
167
+ ...documentPeers,
168
+ ...providerPeers,
169
+ collaboration,
170
+ collaborationCaret
171
+ };
172
+ }, COLLABORATION_PEERS_MISSING);
173
+ assertCollaborationPeers(peers);
174
+ return peers;
175
+ }
176
+ //#endregion
177
+ //#region src/editor/editor-lazy.ts
178
+ /**
179
+ * Builds a `lazy` editor component that a remount can re-attempt.
180
+ *
181
+ * `lazy` caches its first rejection for the life of the component. That is
182
+ * right for a missing peer, which stays missing for the session, and wrong for
183
+ * a transient chunk fetch: one failed network request would otherwise hold the
184
+ * editor broken until a full page reload.
185
+ *
186
+ * The returned function gives the component to render, and a caller must call
187
+ * it on every render: a transient failure replaces the component, and a caller
188
+ * that holds the one it got earlier keeps replaying the cached rejection.
189
+ *
190
+ * A `MissingEditorPeersError` keeps the cached rejection, so the install list
191
+ * reaches the consumer's error boundary once and the loader does not run
192
+ * again. Any other rejection replaces the component, so the next mount — an
193
+ * error boundary that resets, or a remount by the parent — starts a fresh
194
+ * attempt.
195
+ */
196
+ function retryableLazyEditor(loadComponent) {
197
+ function build() {
198
+ return lazy(async () => {
199
+ try {
200
+ return { default: await loadComponent() };
201
+ } catch (error) {
202
+ if (!isMissingEditorPeersError(error)) current = build();
203
+ throw error;
204
+ }
205
+ });
206
+ }
207
+ let current = build();
208
+ return () => current;
209
+ }
210
+ //#endregion
211
+ //#region src/editor/editor-provider.tsx
212
+ const EditorContext = createContext(null);
213
+ /**
214
+ * Generate a random color for user presence.
215
+ */
216
+ function generateUserColor() {
217
+ const colors = [
218
+ "#FF6B6B",
219
+ "#4ECDC4",
220
+ "#45B7D1",
221
+ "#96CEB4",
222
+ "#FFEAA7",
223
+ "#DDA0DD",
224
+ "#98D8C8",
225
+ "#F7DC6F",
226
+ "#BB8FCE",
227
+ "#85C1E9"
228
+ ];
229
+ return colors[Math.floor(Math.random() * colors.length)];
230
+ }
231
+ /**
232
+ * Builds the collaboration provider against loaded yjs and Hocuspocus
233
+ * namespaces. The peers arrive as an argument so that this module reaches
234
+ * them through type-only imports, which a bundler erases.
235
+ */
236
+ function createEditorProvider(peers) {
237
+ const { Doc } = peers.yjs;
238
+ const { HocuspocusProvider } = peers.hocuspocus;
239
+ return function EditorProvider({ websocketUrl, documentName, token, tokenExpiresAt, user, autoConnect = true, autoReconnect = true, maxReconnectAttempts = 5, onConnectionChange, onSync, onAuthError, onRefreshToken, children }) {
240
+ const [connectionState, setConnectionState] = useState("disconnected");
241
+ const [collaborators, setCollaborators] = useState([]);
242
+ const [isSynced, setIsSynced] = useState(false);
243
+ const docRef = useRef(null);
244
+ const providerRef = useRef(null);
245
+ const reconnectAttemptsRef = useRef(0);
246
+ const tokenRef = useRef(token);
247
+ const tokenExpiryRef = useRef(tokenExpiresAt);
248
+ const refreshPromiseRef = useRef(null);
249
+ const refreshTimerRef = useRef(null);
250
+ tokenRef.current = token;
251
+ tokenExpiryRef.current = tokenExpiresAt;
252
+ if (!docRef.current) docRef.current = new Doc();
253
+ const doc = docRef.current;
254
+ const userColor = useMemo(() => user.color ?? generateUserColor(), [user.color]);
255
+ const updateConnectionState = useCallback((state) => {
256
+ setConnectionState(state);
257
+ onConnectionChange?.(state);
258
+ }, [onConnectionChange]);
259
+ const updateCollaborators = useCallback((awareness) => {
260
+ if (!awareness) return;
261
+ const states = awareness.getStates();
262
+ const collabs = [];
263
+ states.forEach((state, clientId) => {
264
+ if (clientId === awareness.clientID) return;
265
+ if (state.user) collabs.push({
266
+ clientId,
267
+ user: state.user
268
+ });
269
+ });
270
+ setCollaborators(collabs);
271
+ }, []);
272
+ const clearRefreshTimer = useCallback(() => {
273
+ if (refreshTimerRef.current != null) {
274
+ window.clearTimeout(refreshTimerRef.current);
275
+ refreshTimerRef.current = null;
276
+ }
277
+ }, []);
278
+ const refreshToken = useCallback(async () => {
279
+ if (!onRefreshToken) return null;
280
+ if (refreshPromiseRef.current) return refreshPromiseRef.current;
281
+ const refreshPromise = (async () => {
282
+ const next = await onRefreshToken();
283
+ const resolvedToken = typeof next === "string" ? next : next.token;
284
+ const resolvedExpiry = typeof next === "string" ? void 0 : next.expiresAt;
285
+ tokenRef.current = resolvedToken;
286
+ tokenExpiryRef.current = resolvedExpiry;
287
+ return resolvedToken;
288
+ })().catch((error) => {
289
+ onAuthError?.(error instanceof Error ? error : new Error(String(error)));
290
+ return null;
291
+ }).finally(() => {
292
+ refreshPromiseRef.current = null;
293
+ });
294
+ refreshPromiseRef.current = refreshPromise;
295
+ return refreshPromise;
296
+ }, [onAuthError, onRefreshToken]);
297
+ const scheduleTokenRefresh = useCallback(() => {
298
+ clearRefreshTimer();
299
+ if (!tokenExpiryRef.current || !onRefreshToken || typeof window === "undefined") return;
300
+ const delay = tokenExpiryRef.current * 1e3 - 6e4 - Date.now();
301
+ if (delay <= 0) {
302
+ refreshToken();
303
+ return;
304
+ }
305
+ refreshTimerRef.current = window.setTimeout(() => {
306
+ refreshToken();
307
+ }, delay);
308
+ }, [
309
+ clearRefreshTimer,
310
+ onRefreshToken,
311
+ refreshToken
312
+ ]);
313
+ const connect = useCallback(() => {
314
+ if (providerRef.current) {
315
+ providerRef.current.connect();
316
+ return;
317
+ }
318
+ updateConnectionState("connecting");
319
+ const provider = new HocuspocusProvider({
320
+ url: websocketUrl,
321
+ name: documentName,
322
+ document: doc,
323
+ token: async () => tokenRef.current,
324
+ onConnect: () => {
325
+ reconnectAttemptsRef.current = 0;
326
+ updateConnectionState("connected");
327
+ scheduleTokenRefresh();
328
+ },
329
+ onSynced: () => {
330
+ setIsSynced(true);
331
+ updateConnectionState("synced");
332
+ onSync?.();
333
+ },
334
+ onDisconnect: () => {
335
+ updateConnectionState("disconnected");
336
+ setIsSynced(false);
337
+ clearRefreshTimer();
338
+ if (autoReconnect && reconnectAttemptsRef.current < maxReconnectAttempts) {
339
+ reconnectAttemptsRef.current += 1;
340
+ const delay = Math.min(1e3 * 2 ** reconnectAttemptsRef.current, 3e4);
341
+ setTimeout(() => {
342
+ if (providerRef.current && !providerRef.current.isConnected) providerRef.current.connect();
343
+ }, delay);
344
+ }
345
+ },
346
+ onAuthenticationFailed: ({ reason }) => {
347
+ const error = new Error(reason ?? "Authentication failed");
348
+ updateConnectionState("disconnected");
349
+ clearRefreshTimer();
350
+ if (onRefreshToken) {
351
+ refreshToken().then((nextToken) => {
352
+ if (nextToken && providerRef.current) {
353
+ providerRef.current.connect();
354
+ return;
355
+ }
356
+ onAuthError?.(error);
357
+ });
358
+ return;
359
+ }
360
+ onAuthError?.(error);
361
+ },
362
+ onAwarenessUpdate: () => {
363
+ updateCollaborators(provider.awareness);
364
+ }
365
+ });
366
+ provider.awareness?.setLocalStateField("user", {
367
+ name: user.name,
368
+ color: userColor,
369
+ userId: user.userId
370
+ });
371
+ providerRef.current = provider;
372
+ }, [
373
+ websocketUrl,
374
+ documentName,
375
+ doc,
376
+ user.name,
377
+ user.userId,
378
+ userColor,
379
+ autoReconnect,
380
+ maxReconnectAttempts,
381
+ clearRefreshTimer,
382
+ updateConnectionState,
383
+ updateCollaborators,
384
+ onSync,
385
+ onAuthError,
386
+ onRefreshToken,
387
+ refreshToken,
388
+ scheduleTokenRefresh
389
+ ]);
390
+ const disconnect = useCallback(() => {
391
+ if (providerRef.current) {
392
+ providerRef.current.disconnect();
393
+ updateConnectionState("disconnected");
394
+ }
395
+ }, [updateConnectionState]);
396
+ useEffect(() => {
397
+ if (autoConnect) connect();
398
+ return () => {
399
+ clearRefreshTimer();
400
+ if (providerRef.current) {
401
+ providerRef.current.destroy();
402
+ providerRef.current = null;
403
+ }
404
+ };
405
+ }, [
406
+ autoConnect,
407
+ clearRefreshTimer,
408
+ connect
409
+ ]);
410
+ const contextValue = useMemo(() => ({
411
+ doc,
412
+ provider: providerRef.current,
413
+ connectionState,
414
+ collaborators,
415
+ isSynced,
416
+ connect,
417
+ disconnect
418
+ }), [
419
+ doc,
420
+ connectionState,
421
+ collaborators,
422
+ isSynced,
423
+ connect,
424
+ disconnect
425
+ ]);
426
+ return /* @__PURE__ */ jsx(EditorContext.Provider, {
427
+ value: contextValue,
428
+ children
429
+ });
430
+ };
431
+ }
432
+ const lazyEditorProvider = retryableLazyEditor(async () => createEditorProvider(await loadEditorProviderPeers()));
433
+ /**
434
+ * EditorProvider wraps children with Hocuspocus collaboration context.
435
+ * Manages WebSocket connection, Y.Doc, and awareness state. Loads `yjs` and
436
+ * `@hocuspocus/provider` — and no tiptap package — before it renders children,
437
+ * because every child hook reads a context that only the loaded provider can
438
+ * supply. A consumer that drives its own editor from that context therefore
439
+ * needs those two peers alone.
440
+ */
441
+ function EditorProvider(props) {
442
+ const LazyEditorProvider = lazyEditorProvider();
443
+ return /* @__PURE__ */ jsx(Suspense, {
444
+ fallback: null,
445
+ children: /* @__PURE__ */ jsx(LazyEditorProvider, { ...props })
446
+ });
447
+ }
448
+ /**
449
+ * Hook to access the editor context.
450
+ * Must be used within an EditorProvider.
451
+ */
452
+ function useEditorContext() {
453
+ const context = useContext(EditorContext);
454
+ if (!context) throw new Error("useEditorContext must be used within an EditorProvider");
455
+ return context;
456
+ }
457
+ //#endregion
458
+ //#region src/editor/editor-loading.tsx
459
+ /**
460
+ * Stands in for an editor while its optional peers load. The editors reach
461
+ * tiptap through a dynamic import, so an editor's first frame waits for that
462
+ * chunk. The live region announces the wait, which a screen reader has no
463
+ * other way to notice. Callers put their own minimum height first, so a
464
+ * caller-supplied className still wins.
465
+ */
466
+ function EditorLoadingPlaceholder({ className }) {
467
+ return /* @__PURE__ */ jsx("div", {
468
+ role: "status",
469
+ "aria-live": "polite",
470
+ className: cn("flex w-full items-center justify-center rounded-lg border border-border border-dashed bg-muted text-muted-foreground text-sm", className),
471
+ children: "Loading editor…"
472
+ });
473
+ }
474
+ //#endregion
475
+ //#region src/editor/editor-toolbar.tsx
476
+ /**
477
+ * Editor toolbar component.
478
+ * Provides basic formatting controls.
479
+ */
480
+ function EditorToolbar({ editor, className }) {
481
+ if (!editor) return null;
482
+ const buttons = [
483
+ {
484
+ id: "bold",
485
+ label: "Bold",
486
+ action: () => editor.chain().focus().toggleBold().run(),
487
+ isActive: editor.isActive("bold"),
488
+ shortcut: "Ctrl+B"
489
+ },
490
+ {
491
+ id: "italic",
492
+ label: "Italic",
493
+ action: () => editor.chain().focus().toggleItalic().run(),
494
+ isActive: editor.isActive("italic"),
495
+ shortcut: "Ctrl+I"
496
+ },
497
+ {
498
+ id: "strike",
499
+ label: "Strike",
500
+ action: () => editor.chain().focus().toggleStrike().run(),
501
+ isActive: editor.isActive("strike"),
502
+ shortcut: "Ctrl+Shift+X"
503
+ },
504
+ {
505
+ id: "code",
506
+ label: "Code",
507
+ action: () => editor.chain().focus().toggleCode().run(),
508
+ isActive: editor.isActive("code"),
509
+ shortcut: "Ctrl+E"
510
+ },
511
+ {
512
+ id: "sep-1",
513
+ type: "separator"
514
+ },
515
+ {
516
+ id: "h1",
517
+ label: "H1",
518
+ action: () => editor.chain().focus().toggleHeading({ level: 1 }).run(),
519
+ isActive: editor.isActive("heading", { level: 1 })
520
+ },
521
+ {
522
+ id: "h2",
523
+ label: "H2",
524
+ action: () => editor.chain().focus().toggleHeading({ level: 2 }).run(),
525
+ isActive: editor.isActive("heading", { level: 2 })
526
+ },
527
+ {
528
+ id: "h3",
529
+ label: "H3",
530
+ action: () => editor.chain().focus().toggleHeading({ level: 3 }).run(),
531
+ isActive: editor.isActive("heading", { level: 3 })
532
+ },
533
+ {
534
+ id: "sep-2",
535
+ type: "separator"
536
+ },
537
+ {
538
+ id: "bullet-list",
539
+ label: "Bullet List",
540
+ action: () => editor.chain().focus().toggleBulletList().run(),
541
+ isActive: editor.isActive("bulletList")
542
+ },
543
+ {
544
+ id: "ordered-list",
545
+ label: "Ordered List",
546
+ action: () => editor.chain().focus().toggleOrderedList().run(),
547
+ isActive: editor.isActive("orderedList")
548
+ },
549
+ {
550
+ id: "code-block",
551
+ label: "Code Block",
552
+ action: () => editor.chain().focus().toggleCodeBlock().run(),
553
+ isActive: editor.isActive("codeBlock")
554
+ },
555
+ {
556
+ id: "blockquote",
557
+ label: "Blockquote",
558
+ action: () => editor.chain().focus().toggleBlockquote().run(),
559
+ isActive: editor.isActive("blockquote")
560
+ }
561
+ ];
562
+ return /* @__PURE__ */ jsx("div", {
563
+ className: cn("flex items-center gap-1 border-border border-b bg-card p-2", className),
564
+ children: buttons.map((button) => {
565
+ if ("type" in button && button.type === "separator") return /* @__PURE__ */ jsx("div", { className: "mx-1 h-6 w-px bg-border" }, button.id);
566
+ return /* @__PURE__ */ jsx("button", {
567
+ onClick: button.action,
568
+ type: "button",
569
+ title: "shortcut" in button ? `${button.label} (${button.shortcut})` : button.label,
570
+ className: cn("rounded px-2 py-1 font-medium text-xs transition-colors", "hover:bg-accent hover:text-accent-foreground", button.isActive && "bg-accent text-accent-foreground"),
571
+ children: button.label
572
+ }, button.id);
573
+ })
574
+ });
575
+ }
576
+ //#endregion
577
+ //#region src/editor/tiptap-editor.tsx
578
+ /**
579
+ * Cursor colors with contrasting text.
580
+ */
581
+ const cursorColors = {
582
+ "#FF6B6B": {
583
+ background: "#FF6B6B",
584
+ text: "#FFFFFF"
585
+ },
586
+ "#4ECDC4": {
587
+ background: "#4ECDC4",
588
+ text: "#000000"
589
+ },
590
+ "#45B7D1": {
591
+ background: "#45B7D1",
592
+ text: "#000000"
593
+ },
594
+ "#96CEB4": {
595
+ background: "#96CEB4",
596
+ text: "#000000"
597
+ },
598
+ "#FFEAA7": {
599
+ background: "#FFEAA7",
600
+ text: "#000000"
601
+ },
602
+ "#DDA0DD": {
603
+ background: "#DDA0DD",
604
+ text: "#000000"
605
+ },
606
+ "#98D8C8": {
607
+ background: "#98D8C8",
608
+ text: "#000000"
609
+ },
610
+ "#F7DC6F": {
611
+ background: "#F7DC6F",
612
+ text: "#000000"
613
+ },
614
+ "#BB8FCE": {
615
+ background: "#BB8FCE",
616
+ text: "#000000"
617
+ },
618
+ "#85C1E9": {
619
+ background: "#85C1E9",
620
+ text: "#000000"
621
+ }
622
+ };
623
+ /**
624
+ * Get cursor label colors based on user color.
625
+ */
626
+ function getCursorColors(color) {
627
+ return cursorColors[color] ?? {
628
+ background: color,
629
+ text: "#FFFFFF"
630
+ };
631
+ }
632
+ /**
633
+ * Builds the collaborative editor against loaded tiptap namespaces. The peers
634
+ * arrive as an argument so that this module reaches them through type-only
635
+ * imports, which a bundler erases.
636
+ */
637
+ function createTiptapEditor(peers) {
638
+ const { EditorContent, useEditor } = peers.react;
639
+ const StarterKit = peers.starterKit.default;
640
+ const Collaboration = peers.collaboration.default;
641
+ const CollaborationCaret = peers.collaborationCaret.default;
642
+ return function TiptapEditor({ initialContent, placeholder = "Start writing...", readOnly = false, autoFocus = false, className, contentClassName, onUpdate, onSelectionUpdate, onReady }) {
643
+ const { doc, provider, connectionState } = useEditorContext();
644
+ const fragment = useMemo(() => doc.getXmlFragment("prosemirror"), [doc]);
645
+ const extensions = useMemo(() => {
646
+ const baseExtensions = [StarterKit.configure({
647
+ history: false,
648
+ codeBlock: { HTMLAttributes: { class: "hljs" } }
649
+ }), Collaboration.configure({ fragment })];
650
+ if (provider?.awareness) baseExtensions.push(CollaborationCaret.configure({
651
+ provider,
652
+ user: provider.awareness.getLocalState()?.user ?? {
653
+ name: "Anonymous",
654
+ color: "#808080"
655
+ },
656
+ render: (user) => {
657
+ const { background, text } = getCursorColors(user.color);
658
+ const cursor = document.createElement("span");
659
+ cursor.className = "collaboration-cursor";
660
+ cursor.style.borderColor = background;
661
+ const label = document.createElement("span");
662
+ label.className = "collaboration-cursor-label";
663
+ label.style.backgroundColor = background;
664
+ label.style.color = text;
665
+ label.textContent = user.name;
666
+ cursor.appendChild(label);
667
+ return cursor;
668
+ }
669
+ }));
670
+ return baseExtensions;
671
+ }, [fragment, provider]);
672
+ const editor = useEditor({
673
+ extensions,
674
+ editable: !readOnly,
675
+ autofocus: autoFocus,
676
+ editorProps: { attributes: {
677
+ class: cn("prose prose-sm sm:prose-base dark:prose-invert max-w-none", "focus:outline-none", contentClassName),
678
+ "data-placeholder": placeholder
679
+ } },
680
+ onUpdate: ({ editor: ed }) => {
681
+ onUpdate?.(ed);
682
+ },
683
+ onSelectionUpdate: ({ editor: ed }) => {
684
+ onSelectionUpdate?.(ed);
685
+ },
686
+ onCreate: ({ editor: ed }) => {
687
+ onReady?.(ed);
688
+ }
689
+ });
690
+ useEffect(() => {
691
+ if (editor) editor.setEditable(!readOnly);
692
+ }, [editor, readOnly]);
693
+ useEffect(() => {
694
+ if (editor && initialContent && connectionState === "synced" && editor.isEmpty) editor.commands.setContent(initialContent);
695
+ }, [
696
+ editor,
697
+ initialContent,
698
+ connectionState
699
+ ]);
700
+ return /* @__PURE__ */ jsxs("div", {
701
+ className: cn("relative min-h-[200px] w-full rounded-lg border border-border", "bg-background", className),
702
+ children: [
703
+ /* @__PURE__ */ jsx("div", {
704
+ className: "absolute top-2 right-2 z-10",
705
+ children: /* @__PURE__ */ jsx(ConnectionIndicator, { state: connectionState })
706
+ }),
707
+ /* @__PURE__ */ jsx("div", {
708
+ className: "p-4 pt-10",
709
+ children: /* @__PURE__ */ jsx(EditorContent, { editor })
710
+ }),
711
+ /* @__PURE__ */ jsx("style", { children: `
712
+ .ProseMirror p.is-editor-empty:first-child::before {
713
+ content: attr(data-placeholder);
714
+ float: left;
715
+ color: var(--muted-foreground, #999);
716
+ pointer-events: none;
717
+ height: 0;
718
+ }
719
+
720
+ .collaboration-cursor {
721
+ position: relative;
722
+ border-left: 2px solid;
723
+ margin-left: -1px;
724
+ margin-right: -1px;
725
+ pointer-events: none;
726
+ word-break: normal;
727
+ }
728
+
729
+ .collaboration-cursor-label {
730
+ position: absolute;
731
+ top: -1.4em;
732
+ left: -1px;
733
+ font-size: 12px;
734
+ font-style: normal;
735
+ font-weight: 600;
736
+ line-height: normal;
737
+ padding: 2px 6px;
738
+ border-radius: 4px 4px 4px 0;
739
+ white-space: nowrap;
740
+ user-select: none;
741
+ }
742
+
743
+ .ProseMirror pre {
744
+ background: var(--muted, #f4f4f5);
745
+ border-radius: 0.375rem;
746
+ padding: 0.75rem 1rem;
747
+ font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
748
+ font-size: 0.875rem;
749
+ overflow-x: auto;
750
+ }
751
+
752
+ .dark .ProseMirror pre {
753
+ background: var(--muted, #27272a);
754
+ }
755
+
756
+ .ProseMirror code {
757
+ background: var(--muted, #f4f4f5);
758
+ border-radius: 0.25rem;
759
+ padding: 0.125rem 0.25rem;
760
+ font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
761
+ font-size: 0.875em;
762
+ }
763
+
764
+ .dark .ProseMirror code {
765
+ background: var(--muted, #27272a);
766
+ }
767
+
768
+ .ProseMirror pre code {
769
+ background: transparent;
770
+ padding: 0;
771
+ font-size: inherit;
772
+ }
773
+ ` })
774
+ ]
775
+ });
776
+ };
777
+ }
778
+ const lazyTiptapEditor = retryableLazyEditor(async () => createTiptapEditor(await loadCollaborationPeers()));
779
+ /**
780
+ * TiptapEditor - Collaborative markdown editor with Y.js sync.
781
+ * Must be used within an EditorProvider. Loads its tiptap, Hocuspocus and
782
+ * yjs peers on first render.
783
+ */
784
+ function TiptapEditor(props) {
785
+ const LazyTiptapEditor = lazyTiptapEditor();
786
+ return /* @__PURE__ */ jsx(Suspense, {
787
+ fallback: /* @__PURE__ */ jsx(EditorLoadingPlaceholder, { className: cn("min-h-[200px]", props.className) }),
788
+ children: /* @__PURE__ */ jsx(LazyTiptapEditor, { ...props })
789
+ });
790
+ }
791
+ /**
792
+ * Connection status indicator component.
793
+ */
794
+ function ConnectionIndicator({ state }) {
795
+ const config = {
796
+ disconnected: {
797
+ color: "bg-red-500",
798
+ label: "Disconnected"
799
+ },
800
+ connecting: {
801
+ color: "bg-yellow-500 animate-pulse",
802
+ label: "Connecting..."
803
+ },
804
+ connected: {
805
+ color: "bg-blue-500",
806
+ label: "Connected"
807
+ },
808
+ synced: {
809
+ color: "bg-green-500",
810
+ label: "Synced"
811
+ }
812
+ }[state];
813
+ return /* @__PURE__ */ jsxs("div", {
814
+ className: "flex items-center gap-1.5 text-muted-foreground text-xs",
815
+ children: [/* @__PURE__ */ jsx("span", { className: cn("h-2 w-2 rounded-full", config.color) }), /* @__PURE__ */ jsx("span", { children: config.label })]
816
+ });
817
+ }
818
+ /**
819
+ * Collaborators list component.
820
+ * Shows active users in the document.
821
+ */
822
+ function CollaboratorsList({ collaborators, className }) {
823
+ if (collaborators.length === 0) return null;
824
+ return /* @__PURE__ */ jsxs("div", {
825
+ className: cn("flex items-center gap-1", className),
826
+ children: [collaborators.slice(0, 5).map((collab) => /* @__PURE__ */ jsx("div", {
827
+ className: "flex h-6 w-6 items-center justify-center rounded-full font-medium text-xs",
828
+ style: { backgroundColor: collab.user.color },
829
+ title: collab.user.name,
830
+ children: collab.user.name.charAt(0).toUpperCase()
831
+ }, collab.clientId)), collaborators.length > 5 && /* @__PURE__ */ jsxs("div", {
832
+ className: "flex h-6 w-6 items-center justify-center rounded-full bg-muted font-medium text-xs",
833
+ children: ["+", collaborators.length - 5]
834
+ })]
835
+ });
836
+ }
837
+ //#endregion
838
+ //#region src/editor/markdown-conversion.ts
839
+ const turndown = new TurndownService({
840
+ bulletListMarker: "-",
841
+ codeBlockStyle: "fenced",
842
+ emDelimiter: "*",
843
+ headingStyle: "atx"
844
+ });
845
+ function markdownToHtml(markdown) {
846
+ return String(marked.parse(markdown, {
847
+ async: false,
848
+ gfm: true
849
+ }));
850
+ }
851
+ function htmlToMarkdown(html) {
852
+ return turndown.turndown(html);
853
+ }
854
+ function normalizeMarkdown(markdown) {
855
+ return markdown.replace(/\r\n/g, "\n").trimEnd();
856
+ }
857
+ //#endregion
858
+ //#region src/editor/markdown-document-editor.tsx
859
+ /**
860
+ * Builds the local markdown editor against loaded tiptap namespaces. The
861
+ * peers arrive as an argument so that this module reaches them through
862
+ * type-only imports, which a bundler erases.
863
+ */
864
+ function createMarkdownDocumentEditor(peers) {
865
+ const { EditorContent, useEditor } = peers.react;
866
+ const StarterKit = peers.starterKit.default;
867
+ return function MarkdownDocumentEditor({ value = "", placeholder = "Start writing...", readOnly = false, autoFocus = false, className, contentClassName, onChange, onReady }) {
868
+ const initialHtml = useMemo(() => markdownToHtml(value), []);
869
+ const lastAppliedMarkdownRef = useRef(normalizeMarkdown(value));
870
+ const editor = useEditor({
871
+ extensions: [StarterKit.configure({ codeBlock: { HTMLAttributes: { class: "hljs" } } })],
872
+ content: initialHtml,
873
+ editable: !readOnly,
874
+ autofocus: autoFocus,
875
+ editorProps: { attributes: {
876
+ class: cn("prose prose-sm sm:prose-base max-w-none focus:outline-none", "prose-headings:text-foreground prose-p:text-foreground prose-li:text-foreground", "prose-strong:text-foreground prose-code:text-foreground prose-pre:text-foreground", contentClassName),
877
+ "data-placeholder": placeholder
878
+ } },
879
+ onUpdate: ({ editor: currentEditor }) => {
880
+ const nextMarkdown = normalizeMarkdown(htmlToMarkdown(currentEditor.getHTML()));
881
+ lastAppliedMarkdownRef.current = nextMarkdown;
882
+ onChange?.(nextMarkdown, currentEditor);
883
+ },
884
+ onCreate: ({ editor: currentEditor }) => {
885
+ onReady?.(currentEditor);
886
+ }
887
+ });
888
+ useEffect(() => {
889
+ if (editor) editor.setEditable(!readOnly);
890
+ }, [editor, readOnly]);
891
+ useEffect(() => {
892
+ if (!editor) return;
893
+ const normalizedValue = normalizeMarkdown(value);
894
+ if (normalizedValue === lastAppliedMarkdownRef.current) return;
895
+ editor.commands.setContent(markdownToHtml(value), { emitUpdate: false });
896
+ lastAppliedMarkdownRef.current = normalizedValue;
897
+ }, [editor, value]);
898
+ return /* @__PURE__ */ jsxs("div", {
899
+ className: cn("flex min-h-[14rem] w-full flex-col overflow-hidden rounded-lg border border-border bg-background", className),
900
+ children: [
901
+ /* @__PURE__ */ jsx(EditorToolbar, {
902
+ editor,
903
+ className: "border-border bg-card px-2 py-2"
904
+ }),
905
+ /* @__PURE__ */ jsx("div", {
906
+ className: "min-h-0 flex-1 overflow-auto px-5 py-4",
907
+ children: /* @__PURE__ */ jsx(EditorContent, { editor })
908
+ }),
909
+ /* @__PURE__ */ jsx("style", { children: `
910
+ .ProseMirror p.is-editor-empty:first-child::before {
911
+ content: attr(data-placeholder);
912
+ float: left;
913
+ color: hsl(var(--muted-foreground));
914
+ pointer-events: none;
915
+ height: 0;
916
+ }
917
+
918
+ .ProseMirror pre {
919
+ background: hsl(var(--muted));
920
+ border: 1px solid hsl(var(--border));
921
+ border-radius: 0.75rem;
922
+ padding: 0.875rem 1rem;
923
+ overflow-x: auto;
924
+ }
925
+
926
+ .ProseMirror code {
927
+ background: hsl(var(--muted));
928
+ border-radius: 0.35rem;
929
+ padding: 0.12rem 0.3rem;
930
+ }
931
+
932
+ .ProseMirror pre code {
933
+ background: transparent;
934
+ padding: 0;
935
+ }
936
+ ` })
937
+ ]
938
+ });
939
+ };
940
+ }
941
+ const lazyMarkdownDocumentEditor = retryableLazyEditor(async () => createMarkdownDocumentEditor(await loadDocumentEditorPeers()));
942
+ /** Local markdown editor. Loads its tiptap peers on first render. */
943
+ function MarkdownDocumentEditor(props) {
944
+ const LazyMarkdownDocumentEditor = lazyMarkdownDocumentEditor();
945
+ return /* @__PURE__ */ jsx(Suspense, {
946
+ fallback: /* @__PURE__ */ jsx(EditorLoadingPlaceholder, { className: cn("min-h-[14rem]", props.className) }),
947
+ children: /* @__PURE__ */ jsx(LazyMarkdownDocumentEditor, { ...props })
948
+ });
949
+ }
950
+ //#endregion
951
+ //#region src/editor/use-editor.ts
952
+ /**
953
+ * Hook to get the current connection state and helpers.
954
+ */
955
+ function useEditorConnection() {
956
+ const { connectionState, isSynced, connect, disconnect } = useEditorContext();
957
+ return {
958
+ /** Current connection state string */
959
+ state: connectionState,
960
+ /** Whether connected to the server (connected or synced) */
961
+ isConnected: connectionState === "connected" || connectionState === "synced",
962
+ /** Whether currently attempting to connect */
963
+ isConnecting: connectionState === "connecting",
964
+ /** Whether disconnected from the server */
965
+ isDisconnected: connectionState === "disconnected",
966
+ /** Whether the document is synced with the server */
967
+ isSynced,
968
+ /** Connect to the collaboration server */
969
+ connect,
970
+ /** Disconnect from the collaboration server */
971
+ disconnect
972
+ };
973
+ }
974
+ /**
975
+ * Hook to get the list of active collaborators.
976
+ */
977
+ function useCollaborators() {
978
+ const { collaborators } = useEditorContext();
979
+ const count = collaborators.length;
980
+ return {
981
+ /** List of active collaborators (excluding self) */
982
+ collaborators,
983
+ /** Number of other collaborators */
984
+ count,
985
+ /** Whether there are other collaborators present */
986
+ hasOthers: count > 0
987
+ };
988
+ }
989
+ /**
990
+ * Hook to track a specific collaborator's presence.
991
+ */
992
+ function useCollaboratorPresence(userId) {
993
+ const { collaborators } = useEditorContext();
994
+ return collaborators.find((c) => c.user.userId === userId) ?? null;
995
+ }
996
+ /**
997
+ * Hook to sync local state with the Y.Doc.
998
+ * Useful for persisting editor metadata.
999
+ */
1000
+ function useYjsState(key, initialValue) {
1001
+ const { doc } = useEditorContext();
1002
+ const [value, setLocalValue] = useState(initialValue);
1003
+ const metaMap = doc.getMap("metadata");
1004
+ useEffect(() => {
1005
+ const updateValue = () => {
1006
+ const stored = metaMap.get(key);
1007
+ if (stored !== void 0) setLocalValue(stored);
1008
+ };
1009
+ updateValue();
1010
+ metaMap.observe(updateValue);
1011
+ return () => {
1012
+ metaMap.unobserve(updateValue);
1013
+ };
1014
+ }, [metaMap, key]);
1015
+ return [value, useCallback((newValue) => {
1016
+ doc.transact(() => {
1017
+ metaMap.set(key, newValue);
1018
+ });
1019
+ }, [
1020
+ doc,
1021
+ metaMap,
1022
+ key
1023
+ ])];
1024
+ }
1025
+ /**
1026
+ * Hook to track document changes.
1027
+ * Returns true if there are unsaved changes since the last save.
1028
+ */
1029
+ function useDocumentChanges(onSave) {
1030
+ const { doc } = useEditorContext();
1031
+ const [isDirty, setIsDirty] = useState(false);
1032
+ const [isSaving, setIsSaving] = useState(false);
1033
+ const [lastSaved, setLastSaved] = useState(null);
1034
+ useEffect(() => {
1035
+ const handleUpdate = () => {
1036
+ setIsDirty(true);
1037
+ };
1038
+ doc.on("update", handleUpdate);
1039
+ return () => {
1040
+ doc.off("update", handleUpdate);
1041
+ };
1042
+ }, [doc]);
1043
+ return {
1044
+ /** Whether there are unsaved changes */
1045
+ isDirty,
1046
+ /** Whether save is in progress */
1047
+ isSaving,
1048
+ /** When the document was last saved */
1049
+ lastSaved,
1050
+ /** Save the document */
1051
+ save: useCallback(async () => {
1052
+ if (!onSave || isSaving) return;
1053
+ setIsSaving(true);
1054
+ try {
1055
+ await onSave();
1056
+ setIsDirty(false);
1057
+ setLastSaved(/* @__PURE__ */ new Date());
1058
+ } finally {
1059
+ setIsSaving(false);
1060
+ }
1061
+ }, [onSave, isSaving])
1062
+ };
1063
+ }
1064
+ /**
1065
+ * Hook to get awareness state for presence features.
1066
+ * Provides lower-level access to the Hocuspocus awareness.
1067
+ */
1068
+ function useAwareness() {
1069
+ const { provider } = useEditorContext();
1070
+ const [localState, setLocalStateValue] = useState({});
1071
+ const awareness = provider?.awareness;
1072
+ useEffect(() => {
1073
+ if (!awareness) return;
1074
+ const updateState = () => {
1075
+ setLocalStateValue(awareness.getLocalState() ?? {});
1076
+ };
1077
+ updateState();
1078
+ awareness.on("change", updateState);
1079
+ return () => {
1080
+ awareness.off("change", updateState);
1081
+ };
1082
+ }, [awareness]);
1083
+ return {
1084
+ /** Current local awareness state */
1085
+ localState,
1086
+ /** Set the entire local state (merges with existing) */
1087
+ setLocalState: useCallback((state) => {
1088
+ if (!awareness) return;
1089
+ const current = awareness.getLocalState() ?? {};
1090
+ awareness.setLocalState({
1091
+ ...current,
1092
+ ...state
1093
+ });
1094
+ }, [awareness]),
1095
+ /** Set a single field in the local state */
1096
+ setLocalStateField: useCallback((field, value) => {
1097
+ if (!awareness) return;
1098
+ awareness.setLocalStateField(field, value);
1099
+ }, [awareness]),
1100
+ /** The raw awareness instance */
1101
+ awareness
1102
+ };
1103
+ }
1104
+ //#endregion
1105
+ //#region src/editor/document-editor-pane.tsx
1106
+ var document_editor_pane_exports = /* @__PURE__ */ __exportAll({ DocumentEditorPane: () => DocumentEditorPane });
1107
+ function connectionTone(state) {
1108
+ switch (state) {
1109
+ case "synced": return "text-[var(--surface-success-text)] border-[var(--surface-success-border)] bg-[var(--surface-success-bg)]";
1110
+ case "connected":
1111
+ case "connecting": return "text-[var(--surface-info-text)] border-[var(--surface-info-border)] bg-[var(--surface-info-bg)]";
1112
+ default: return "text-[var(--surface-warning-text)] border-[var(--surface-warning-border)] bg-[var(--surface-warning-bg)]";
1113
+ }
1114
+ }
1115
+ function connectionLabel(state) {
1116
+ switch (state) {
1117
+ case "synced": return "Live synced";
1118
+ case "connected": return "Connected";
1119
+ case "connecting": return "Connecting";
1120
+ default: return "Offline";
1121
+ }
1122
+ }
1123
+ function connectionDescription(state, collaborators, readOnly) {
1124
+ if (readOnly) return state === "disconnected" ? "Live access is paused. You can keep reading while the editor reconnects." : "You are viewing the live document in read-only mode.";
1125
+ switch (state) {
1126
+ case "synced": return collaborators > 0 ? `You and ${collaborators} collaborator${collaborators === 1 ? "" : "s"} are editing the same document.` : "You are editing the live document. Changes sync automatically.";
1127
+ case "connected":
1128
+ case "connecting": return "Connecting the live document. Local edits stay in place while sync catches up.";
1129
+ default: return "Live updates are paused. You can keep editing and reconnect when the transport is healthy again.";
1130
+ }
1131
+ }
1132
+ function CollaborativeDocumentSurface({ markdown, placeholder, autoFocus, readOnly, className, onChange }) {
1133
+ const { state } = useEditorConnection();
1134
+ const { collaborators } = useCollaborators();
1135
+ const initialContent = useMemo(() => markdownToHtml(markdown), [markdown]);
1136
+ const collaboratorCount = collaborators.length + 1;
1137
+ return /* @__PURE__ */ jsxs("div", {
1138
+ className: cn("flex h-full min-h-0 flex-col gap-3", className),
1139
+ children: [/* @__PURE__ */ jsxs("div", {
1140
+ className: "flex flex-wrap items-center justify-between gap-3 rounded-[var(--radius-lg)] border border-border bg-card px-3 py-2",
1141
+ children: [/* @__PURE__ */ jsxs("div", {
1142
+ className: "min-w-0 space-y-2",
1143
+ children: [/* @__PURE__ */ jsxs("div", {
1144
+ className: "flex flex-wrap items-center gap-2 text-xs text-muted-foreground",
1145
+ children: [/* @__PURE__ */ jsxs("span", {
1146
+ className: cn("inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 font-medium", connectionTone(state)),
1147
+ children: [state === "disconnected" ? /* @__PURE__ */ jsx(WifiOff, { className: "h-3.5 w-3.5" }) : /* @__PURE__ */ jsx(Wifi, { className: "h-3.5 w-3.5" }), connectionLabel(state)]
1148
+ }), /* @__PURE__ */ jsxs("span", {
1149
+ className: "inline-flex items-center gap-1.5 rounded-full border border-border bg-background px-2.5 py-1",
1150
+ children: [/* @__PURE__ */ jsx(Users, { className: "h-3.5 w-3.5" }), collaborators.length === 0 ? "Solo editing" : `${collaboratorCount} active`]
1151
+ })]
1152
+ }), /* @__PURE__ */ jsx("p", {
1153
+ className: "text-xs text-muted-foreground",
1154
+ children: connectionDescription(state, collaborators.length, readOnly)
1155
+ })]
1156
+ }), /* @__PURE__ */ jsx(CollaboratorsList, { collaborators })]
1157
+ }), /* @__PURE__ */ jsx(TiptapEditor, {
1158
+ initialContent,
1159
+ placeholder,
1160
+ autoFocus,
1161
+ readOnly,
1162
+ className: cn("h-full min-h-[16rem]", className),
1163
+ onUpdate: (editor) => {
1164
+ onChange?.(normalizeMarkdown(htmlToMarkdown(editor.getHTML())));
1165
+ }
1166
+ })]
1167
+ });
1168
+ }
1169
+ /**
1170
+ * DocumentEditorPane — reusable markdown document surface with preview/edit
1171
+ * modes and optional collaborative editing backed by Yjs/Hocuspocus.
1172
+ */
1173
+ function DocumentEditorPane({ eyebrow, title, subtitle, meta, headerActions, footer, className, contentClassName, headerClassName, hideTitleBlock, tabs, toolbar, markdown = "", mode, defaultMode = "preview", onModeChange, backend = "local", placeholder = "Start writing...", autoFocus = false, readOnly = false, onChange, onSave, saving = false, saveLabel = "Save changes", previewClassName, editorClassName, collaboration }) {
1174
+ const [draft, setDraft] = useState(markdown);
1175
+ const [uncontrolledMode, setUncontrolledMode] = useState(defaultMode);
1176
+ const activeMode = mode ?? uncontrolledMode;
1177
+ const isCollaborative = backend === "collaborative" && Boolean(collaboration);
1178
+ const isDirty = normalizeMarkdown(draft) !== normalizeMarkdown(markdown);
1179
+ const saveStateLabel = readOnly ? "Read only" : isCollaborative ? isDirty ? "Snapshot pending" : "Live document current" : isDirty ? "Unsaved changes" : "Saved";
1180
+ useEffect(() => {
1181
+ setDraft(markdown);
1182
+ }, [markdown]);
1183
+ useEffect(() => {
1184
+ if (mode === void 0) setUncontrolledMode(defaultMode);
1185
+ }, [defaultMode, mode]);
1186
+ const setMode = (nextMode) => {
1187
+ if (mode === void 0) setUncontrolledMode(nextMode);
1188
+ onModeChange?.(nextMode);
1189
+ };
1190
+ const handleChange = (nextMarkdown) => {
1191
+ setDraft(nextMarkdown);
1192
+ onChange?.(nextMarkdown);
1193
+ };
1194
+ const editorToolbar = /* @__PURE__ */ jsxs("div", {
1195
+ className: "flex flex-wrap items-center justify-between gap-3",
1196
+ children: [/* @__PURE__ */ jsxs(TabsList, {
1197
+ variant: "underline",
1198
+ className: "h-auto gap-4 border-0 bg-transparent p-0 text-muted-foreground",
1199
+ children: [/* @__PURE__ */ jsx(TabsTrigger, {
1200
+ value: "preview",
1201
+ variant: "underline",
1202
+ className: "pb-2 data-[state=active]:border-primary data-[state=active]:text-foreground",
1203
+ children: "Preview"
1204
+ }), /* @__PURE__ */ jsxs(TabsTrigger, {
1205
+ value: "edit",
1206
+ variant: "underline",
1207
+ className: "flex items-center gap-2 pb-2 data-[state=active]:border-primary data-[state=active]:text-foreground",
1208
+ children: [/* @__PURE__ */ jsx(PencilLine, { className: "h-3.5 w-3.5" }), isCollaborative ? "Live edit" : "Edit"]
1209
+ })]
1210
+ }), /* @__PURE__ */ jsxs("div", {
1211
+ className: "flex flex-wrap items-center gap-2 text-xs text-muted-foreground",
1212
+ children: [
1213
+ toolbar,
1214
+ /* @__PURE__ */ jsx("span", {
1215
+ className: "rounded-full border border-border bg-card px-2.5 py-1 font-medium",
1216
+ children: isCollaborative ? "Live document" : "Local draft"
1217
+ }),
1218
+ /* @__PURE__ */ jsx("span", {
1219
+ className: "rounded-full border border-border bg-background px-2.5 py-1",
1220
+ children: saveStateLabel
1221
+ }),
1222
+ onSave && !readOnly && /* @__PURE__ */ jsxs("button", {
1223
+ type: "button",
1224
+ onClick: () => void onSave(draft),
1225
+ disabled: saving || !isDirty,
1226
+ className: cn("inline-flex items-center gap-2 rounded-[var(--radius-full)] border border-border bg-card px-3 py-1.5 text-xs font-semibold text-foreground transition-colors hover:border-[var(--border-strong)] hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50", focusRing),
1227
+ children: [/* @__PURE__ */ jsx(Save, { className: "h-3.5 w-3.5" }), saving ? "Saving..." : saveLabel]
1228
+ })
1229
+ ]
1230
+ })]
1231
+ });
1232
+ const preview = /* @__PURE__ */ jsx("div", {
1233
+ className: cn("m-4 rounded-[var(--radius-lg)] border border-border bg-card p-5", previewClassName),
1234
+ children: /* @__PURE__ */ jsx(Markdown, { children: draft })
1235
+ });
1236
+ const localEditor = /* @__PURE__ */ jsx(MarkdownDocumentEditor, {
1237
+ value: draft,
1238
+ placeholder,
1239
+ autoFocus,
1240
+ readOnly,
1241
+ onChange: (nextMarkdown) => {
1242
+ handleChange(nextMarkdown);
1243
+ },
1244
+ className: editorClassName
1245
+ });
1246
+ const collaborativeEditor = collaboration ? /* @__PURE__ */ jsx(EditorProvider, {
1247
+ ...collaboration,
1248
+ children: /* @__PURE__ */ jsx(CollaborativeDocumentSurface, {
1249
+ markdown: draft,
1250
+ placeholder,
1251
+ autoFocus,
1252
+ readOnly,
1253
+ className: editorClassName,
1254
+ onChange: handleChange
1255
+ })
1256
+ }, collaboration.documentName) : localEditor;
1257
+ return /* @__PURE__ */ jsx(Tabs, {
1258
+ value: activeMode,
1259
+ onValueChange: (nextValue) => setMode(nextValue),
1260
+ className: "h-full",
1261
+ children: /* @__PURE__ */ jsxs(ArtifactPane, {
1262
+ eyebrow,
1263
+ title,
1264
+ subtitle,
1265
+ meta,
1266
+ headerActions,
1267
+ footer,
1268
+ tabs,
1269
+ className,
1270
+ contentClassName,
1271
+ headerClassName,
1272
+ toolbar: editorToolbar,
1273
+ hideTitleBlock,
1274
+ children: [/* @__PURE__ */ jsx(TabsContent, {
1275
+ value: "preview",
1276
+ className: "mt-0 h-full",
1277
+ children: preview
1278
+ }), /* @__PURE__ */ jsx(TabsContent, {
1279
+ value: "edit",
1280
+ className: "mt-0 h-full px-4 py-4",
1281
+ children: isCollaborative ? collaborativeEditor : localEditor
1282
+ })]
1283
+ })
1284
+ });
1285
+ }
1286
+ //#endregion
1287
+ export { useCollaborators as a, useYjsState as c, EditorToolbar as d, EditorProvider as f, useCollaboratorPresence as i, CollaboratorsList as l, document_editor_pane_exports as n, useDocumentChanges as o, useEditorContext as p, useAwareness as r, useEditorConnection as s, DocumentEditorPane as t, TiptapEditor as u };