@gantfdt/semiword 0.0.0-stage → 1.0.0

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 (97) hide show
  1. package/LICENSE +6 -0
  2. package/README.md +258 -2
  3. package/dist-lib/FlowchartEditor-EFUVACVN.mjs +442 -0
  4. package/dist-lib/FlowchartEditor-EFUVACVN.mjs.map +1 -0
  5. package/dist-lib/MindmapEditor-CCJRPI4I.mjs +141 -0
  6. package/dist-lib/MindmapEditor-CCJRPI4I.mjs.map +1 -0
  7. package/dist-lib/WhiteboardEditor-STZ7W7XX.mjs +120 -0
  8. package/dist-lib/WhiteboardEditor-STZ7W7XX.mjs.map +1 -0
  9. package/dist-lib/ai.d.mts +33 -0
  10. package/dist-lib/ai.mjs +14 -0
  11. package/dist-lib/ai.mjs.map +1 -0
  12. package/dist-lib/chunk-347SCO7S.mjs +3 -0
  13. package/dist-lib/chunk-347SCO7S.mjs.map +1 -0
  14. package/dist-lib/chunk-4F4NEVHE.mjs +100 -0
  15. package/dist-lib/chunk-4F4NEVHE.mjs.map +1 -0
  16. package/dist-lib/chunk-4W6PPBHQ.mjs +474 -0
  17. package/dist-lib/chunk-4W6PPBHQ.mjs.map +1 -0
  18. package/dist-lib/chunk-7AAZUM6M.mjs +45 -0
  19. package/dist-lib/chunk-7AAZUM6M.mjs.map +1 -0
  20. package/dist-lib/chunk-BBZ5ZBEK.mjs +1510 -0
  21. package/dist-lib/chunk-BBZ5ZBEK.mjs.map +1 -0
  22. package/dist-lib/chunk-CREU4TZJ.mjs +24 -0
  23. package/dist-lib/chunk-CREU4TZJ.mjs.map +1 -0
  24. package/dist-lib/chunk-EEUFVA37.mjs +4024 -0
  25. package/dist-lib/chunk-EEUFVA37.mjs.map +1 -0
  26. package/dist-lib/chunk-EOIJPQZI.mjs +370 -0
  27. package/dist-lib/chunk-EOIJPQZI.mjs.map +1 -0
  28. package/dist-lib/chunk-EOUNN3NA.mjs +1517 -0
  29. package/dist-lib/chunk-EOUNN3NA.mjs.map +1 -0
  30. package/dist-lib/chunk-FOIP7DEC.mjs +12 -0
  31. package/dist-lib/chunk-FOIP7DEC.mjs.map +1 -0
  32. package/dist-lib/chunk-GGIOCI2I.mjs +2442 -0
  33. package/dist-lib/chunk-GGIOCI2I.mjs.map +1 -0
  34. package/dist-lib/chunk-IICCIMZU.mjs +5272 -0
  35. package/dist-lib/chunk-IICCIMZU.mjs.map +1 -0
  36. package/dist-lib/chunk-JC5ZZPSL.mjs +600 -0
  37. package/dist-lib/chunk-JC5ZZPSL.mjs.map +1 -0
  38. package/dist-lib/chunk-K7Z56Q4M.mjs +6327 -0
  39. package/dist-lib/chunk-K7Z56Q4M.mjs.map +1 -0
  40. package/dist-lib/chunk-NPPS63UI.mjs +285 -0
  41. package/dist-lib/chunk-NPPS63UI.mjs.map +1 -0
  42. package/dist-lib/chunk-PFA3XERW.mjs +19 -0
  43. package/dist-lib/chunk-PFA3XERW.mjs.map +1 -0
  44. package/dist-lib/chunk-QWDJU3H7.mjs +18 -0
  45. package/dist-lib/chunk-QWDJU3H7.mjs.map +1 -0
  46. package/dist-lib/chunk-TOA6CRSJ.mjs +3917 -0
  47. package/dist-lib/chunk-TOA6CRSJ.mjs.map +1 -0
  48. package/dist-lib/chunk-W627LLF4.mjs +16 -0
  49. package/dist-lib/chunk-W627LLF4.mjs.map +1 -0
  50. package/dist-lib/chunk-XAEALEVP.mjs +547 -0
  51. package/dist-lib/chunk-XAEALEVP.mjs.map +1 -0
  52. package/dist-lib/chunk-ZM3WULHX.mjs +910 -0
  53. package/dist-lib/chunk-ZM3WULHX.mjs.map +1 -0
  54. package/dist-lib/context-DKwyjx1q.d.mts +37 -0
  55. package/dist-lib/designer.d.mts +215 -0
  56. package/dist-lib/designer.mjs +15 -0
  57. package/dist-lib/designer.mjs.map +1 -0
  58. package/dist-lib/document.d.mts +12 -0
  59. package/dist-lib/document.mjs +4 -0
  60. package/dist-lib/document.mjs.map +1 -0
  61. package/dist-lib/editor.d.mts +408 -0
  62. package/dist-lib/editor.mjs +19 -0
  63. package/dist-lib/editor.mjs.map +1 -0
  64. package/dist-lib/gant-ai.d.mts +40 -0
  65. package/dist-lib/gant-ai.mjs +217 -0
  66. package/dist-lib/gant-ai.mjs.map +1 -0
  67. package/dist-lib/index.d.mts +22 -0
  68. package/dist-lib/index.mjs +19 -0
  69. package/dist-lib/index.mjs.map +1 -0
  70. package/dist-lib/interface-RYndHNLS.d.mts +91 -0
  71. package/dist-lib/io.d.mts +75 -0
  72. package/dist-lib/io.mjs +9 -0
  73. package/dist-lib/io.mjs.map +1 -0
  74. package/dist-lib/memoryHistoryStore-DY47xjO_.d.mts +280 -0
  75. package/dist-lib/mindmapConstants-X75XUXV3.mjs +4 -0
  76. package/dist-lib/mindmapConstants-X75XUXV3.mjs.map +1 -0
  77. package/dist-lib/resolve-BMcwblyP.d.mts +114 -0
  78. package/dist-lib/sdk.d.mts +60 -0
  79. package/dist-lib/sdk.mjs +137 -0
  80. package/dist-lib/sdk.mjs.map +1 -0
  81. package/dist-lib/shapes-5SMSF6ML.mjs +4 -0
  82. package/dist-lib/shapes-5SMSF6ML.mjs.map +1 -0
  83. package/dist-lib/storage.d.mts +91 -0
  84. package/dist-lib/storage.mjs +5 -0
  85. package/dist-lib/storage.mjs.map +1 -0
  86. package/dist-lib/template.d.mts +155 -0
  87. package/dist-lib/template.mjs +6 -0
  88. package/dist-lib/template.mjs.map +1 -0
  89. package/dist-lib/types-CO6ppyIY.d.mts +18 -0
  90. package/dist-lib/types-CUsV1hUm.d.mts +49 -0
  91. package/dist-lib/types-ClQ38-C_.d.mts +256 -0
  92. package/dist-lib/types-D1D2miCr.d.mts +117 -0
  93. package/dist-lib/types-DiyyKlc1.d.mts +355 -0
  94. package/dist-lib/types-s1JYaGtG.d.mts +56 -0
  95. package/dist-lib/types-vl8k8NDK.d.mts +562 -0
  96. package/dist-lib/useDocumentPersistence-DOpnQsZQ.d.mts +228 -0
  97. package/package.json +282 -4
@@ -0,0 +1,2442 @@
1
+ import { useEditorRefApi, isTemplateTableEl, useTableActions, useTableRowColActions } from './chunk-BBZ5ZBEK.mjs';
2
+ import { glassSurfaceCss, createCssScope, templateCss, typographyCss, codeBlockCss, tableCss, fixedTableCss, getDefaultPlaceholder, PluginRegistry, BUILTIN_PLUGINS, MINIMAL_PLUGINS, isSafeCssColor, sanitizeJsonContent, findAncestor } from './chunk-K7Z56Q4M.mjs';
3
+ import { createStyles, Button, Tooltip, Tag, Dropdown, Divider } from './chunk-ZM3WULHX.mjs';
4
+ import { sanitizeHtml } from './chunk-4W6PPBHQ.mjs';
5
+ import { tr } from './chunk-W627LLF4.mjs';
6
+ import { createContext, forwardRef, memo, useMemo, useRef, useEffect, useState, useCallback, useImperativeHandle, useContext, Fragment, createElement, useReducer } from 'react';
7
+ import { jsxs, jsx, Fragment as Fragment$1 } from 'react/jsx-runtime';
8
+ import { Collaboration } from '@tiptap/extension-collaboration';
9
+ import { CollaborationCursor } from '@tiptap/extension-collaboration-cursor';
10
+ import * as Y from 'yjs';
11
+ import { HocuspocusProvider } from '@hocuspocus/provider';
12
+ import { IndexeddbPersistence } from 'y-indexeddb';
13
+ import { EditorContent, useEditor } from '@tiptap/react';
14
+ import { getSchema } from '@tiptap/core';
15
+ import { DownOutlined, InsertRowAboveOutlined, InsertRowBelowOutlined, DeleteRowOutlined, InsertRowLeftOutlined, InsertRowRightOutlined, DeleteColumnOutlined, MergeCellsOutlined, SplitCellsOutlined, BorderOutlined, DeleteOutlined } from '@ant-design/icons';
16
+
17
+ var registrationIdentities = /* @__PURE__ */ new WeakMap();
18
+ var registrationIdentitySeq = 0;
19
+ function getRegistrationIdentity(value) {
20
+ let identity = registrationIdentities.get(value);
21
+ if (identity === void 0) {
22
+ identity = ++registrationIdentitySeq;
23
+ registrationIdentities.set(value, identity);
24
+ }
25
+ return identity;
26
+ }
27
+ function createComponentPlugin({
28
+ name,
29
+ component,
30
+ group = "insert",
31
+ order = 999
32
+ }) {
33
+ return {
34
+ name,
35
+ category: "interaction",
36
+ tiptapExtensions: () => [],
37
+ toolbarItems: () => [
38
+ {
39
+ id: name,
40
+ type: "custom",
41
+ group,
42
+ order,
43
+ render: (editor) => createElement(component, { editor })
44
+ }
45
+ ]
46
+ };
47
+ }
48
+ function isEditorPlugin(input) {
49
+ return "tiptapExtensions" in input;
50
+ }
51
+ function isComponentConfig(input) {
52
+ return "component" in input;
53
+ }
54
+ function normalizeEditorPluginOptions(options) {
55
+ if (!options || !Array.isArray(options)) {
56
+ return {
57
+ configs: options ?? {},
58
+ registrations: [],
59
+ registrationSignature: ""
60
+ };
61
+ }
62
+ const configs = {};
63
+ const registrations = [];
64
+ const registrationSignatures = [];
65
+ const selection = [];
66
+ for (const input of options) {
67
+ if (typeof input === "string") {
68
+ configs[input] = { enabled: true };
69
+ selection.push(input);
70
+ continue;
71
+ }
72
+ selection.push(input.name);
73
+ if (isEditorPlugin(input)) {
74
+ registrations.push(input);
75
+ registrationSignatures.push(["plugin", input.name, getRegistrationIdentity(input)]);
76
+ configs[input.name] = { enabled: true };
77
+ } else if (isComponentConfig(input)) {
78
+ registrations.push(createComponentPlugin(input));
79
+ registrationSignatures.push([
80
+ "component",
81
+ input.name,
82
+ input.group ?? "insert",
83
+ input.order ?? 999,
84
+ getRegistrationIdentity(input.component)
85
+ ]);
86
+ configs[input.name] = { enabled: input.enabled ?? true };
87
+ } else {
88
+ configs[input.name] = { enabled: input.enabled ?? true, config: input.config };
89
+ }
90
+ }
91
+ return { configs, registrations, registrationSignature: JSON.stringify(registrationSignatures), selection };
92
+ }
93
+
94
+ // src/editor/plugins/usePluginRegistry.ts
95
+ function configureRegisteredPlugins(registry) {
96
+ for (const plugin of registry.getAllPlugins()) {
97
+ plugin.configureRegistry?.(registry);
98
+ }
99
+ }
100
+ function serializePluginConfig(plugins) {
101
+ if (!plugins) return "";
102
+ try {
103
+ return JSON.stringify(plugins, (_key, value) => typeof value === "function" ? "__fn__" : value);
104
+ } catch {
105
+ if (process.env.NODE_ENV !== "production") {
106
+ console.warn(
107
+ "[usePluginRegistry] plugins \u914D\u7F6E\u542B\u65E0\u6CD5\u5E8F\u5217\u5316\u7684\u503C\uFF08\u5982\u5FAA\u73AF\u5F15\u7528\uFF09\uFF0C\u5DF2\u9000\u56DE\u6309 key \u6BD4\u8F83\u3002\u8BF7\u786E\u4FDD plugins \u5F15\u7528\u7A33\u5B9A\uFF0C\u907F\u514D\u5185\u8054\u5B57\u9762\u91CF\u3002"
108
+ );
109
+ }
110
+ return `__unserializable__:${Object.keys(plugins).sort().join("|")}`;
111
+ }
112
+ }
113
+ function usePluginRegistry(options) {
114
+ const { plugins, customPlugins, selection, registrationSignature, minimal, collaboration } = options;
115
+ const normalizedPlugins = normalizeEditorPluginOptions(plugins);
116
+ const resolvedConfigs = plugins === void 0 ? void 0 : normalizedPlugins.configs;
117
+ const resolvedSelection = selection ?? normalizedPlugins.selection;
118
+ const resolvedRegistrationSignature = registrationSignature ?? normalizedPlugins.registrationSignature;
119
+ const registeredPlugins = normalizedPlugins.registrations.length > 0 ? [...customPlugins ?? [], ...normalizedPlugins.registrations] : customPlugins;
120
+ const pluginsSignature = serializePluginConfig(resolvedConfigs);
121
+ const customPluginsSignature = registeredPlugins ? registeredPlugins.map((p) => p.name).join("|") : "";
122
+ const selectionSignature = resolvedSelection === void 0 ? "" : JSON.stringify(resolvedSelection);
123
+ const latestRef = useRef({ plugins: resolvedConfigs, customPlugins: registeredPlugins, selection: resolvedSelection });
124
+ latestRef.current = { plugins: resolvedConfigs, customPlugins: registeredPlugins, selection: resolvedSelection };
125
+ const registry = useMemo(() => {
126
+ const { plugins: plugins2, customPlugins: customPlugins2, selection: selection2 } = latestRef.current;
127
+ const reg = new PluginRegistry();
128
+ reg.registerAll(BUILTIN_PLUGINS);
129
+ if (customPlugins2 && customPlugins2.length > 0) {
130
+ reg.registerAll(customPlugins2);
131
+ }
132
+ if (selection2 !== void 0) {
133
+ reg.configureSelection(selection2);
134
+ } else if (minimal) {
135
+ reg.configureSelection(MINIMAL_PLUGINS);
136
+ }
137
+ if (collaboration) {
138
+ reg.configure({ starter: { config: { collaboration: true } } });
139
+ }
140
+ configureRegisteredPlugins(reg);
141
+ if (plugins2) {
142
+ reg.configure(plugins2);
143
+ }
144
+ return reg;
145
+ }, [
146
+ pluginsSignature,
147
+ customPluginsSignature,
148
+ selectionSignature,
149
+ resolvedRegistrationSignature,
150
+ minimal,
151
+ collaboration
152
+ ]);
153
+ return registry;
154
+ }
155
+ var CollaborationContext = createContext({
156
+ ready: true,
157
+ resourcesKey: "local",
158
+ ydoc: null,
159
+ provider: null,
160
+ connectionStatus: "disconnected",
161
+ onlineUsers: [],
162
+ error: null,
163
+ reconnect: () => {
164
+ }
165
+ });
166
+ function CollaborationProvider({ resources, children }) {
167
+ return /* @__PURE__ */ jsx(CollaborationContext.Provider, { value: resources, children });
168
+ }
169
+ function useCollaboration() {
170
+ return useContext(CollaborationContext);
171
+ }
172
+
173
+ // src/editor/features/collaboration/utils/constants.ts
174
+ var ROOM_PREFIX = "doc-v1-";
175
+ var ANONYMOUS_COLOR = "#0d99ff";
176
+ function getAnonymousUser() {
177
+ return {
178
+ name: tr("\u533F\u540D\u7528\u6237"),
179
+ color: ANONYMOUS_COLOR
180
+ };
181
+ }
182
+ var CONNECTION_STATUS_LABEL = {
183
+ connecting: "\u8FDE\u63A5\u4E2D",
184
+ connected: "\u5DF2\u8FDE\u63A5",
185
+ disconnected: "\u672A\u8FDE\u63A5",
186
+ error: "\u8FDE\u63A5\u9519\u8BEF"
187
+ };
188
+
189
+ // src/editor/features/collaboration/utils/awareness.ts
190
+ var MAX_AWARENESS_NAME_LENGTH = 40;
191
+ function sanitizeAwarenessName(name) {
192
+ if (typeof name !== "string" || !name) return getAnonymousUser().name;
193
+ const cleaned = name.replace(/[\x00-\x1F\x7F]/g, "").trim();
194
+ if (!cleaned) return getAnonymousUser().name;
195
+ return cleaned.length > MAX_AWARENESS_NAME_LENGTH ? cleaned.slice(0, MAX_AWARENESS_NAME_LENGTH) : cleaned;
196
+ }
197
+ function sanitizeAwarenessColor(color) {
198
+ if (typeof color !== "string") return getAnonymousUser().color;
199
+ if (isSafeCssColor(color)) return color.trim();
200
+ return getAnonymousUser().color;
201
+ }
202
+ function getSafeAvatarUrl(url) {
203
+ if (!url || typeof window === "undefined") return null;
204
+ try {
205
+ const parsed = new URL(url, window.location.href);
206
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
207
+ return null;
208
+ }
209
+ if (parsed.origin !== window.location.origin) {
210
+ return null;
211
+ }
212
+ return parsed.href;
213
+ } catch {
214
+ }
215
+ return null;
216
+ }
217
+ function areUsersEqual(prev, next) {
218
+ return prev.id === next.id && prev.name === next.name && prev.color === next.color && prev.avatar === next.avatar;
219
+ }
220
+ function areUserListsEqual(prev, next) {
221
+ return prev.length === next.length && prev.every((user, index) => areUsersEqual(user, next[index]));
222
+ }
223
+ function collectOnlineUsers(provider) {
224
+ const seen = /* @__PURE__ */ new Set();
225
+ const users = [];
226
+ provider.awareness?.getStates().forEach((state, clientId) => {
227
+ if (!state.user) return;
228
+ const userId = typeof state.user.id === "string" && state.user.id ? state.user.id : void 0;
229
+ const key = userId ? `user:${userId}` : `client:${clientId}`;
230
+ if (seen.has(key)) return;
231
+ seen.add(key);
232
+ const safeAvatar = typeof state.user.avatar === "string" ? getSafeAvatarUrl(state.user.avatar) : null;
233
+ users.push({
234
+ ...userId ? { id: userId } : {},
235
+ name: sanitizeAwarenessName(state.user.name),
236
+ color: sanitizeAwarenessColor(state.user.color),
237
+ avatar: safeAvatar ?? void 0
238
+ });
239
+ });
240
+ return users;
241
+ }
242
+ function toAwarenessUser(user) {
243
+ return {
244
+ name: user.name,
245
+ color: user.color,
246
+ ...user.id ? { id: user.id } : {},
247
+ ...user.avatar ? { avatar: user.avatar } : {}
248
+ };
249
+ }
250
+
251
+ // src/editor/features/collaboration/utils/collaborationExtension.ts
252
+ function renderCollaborationCursor(user) {
253
+ const safeColor = typeof user.color === "string" && isSafeCssColor(user.color) ? user.color.trim() : getAnonymousUser().color;
254
+ const cursor = document.createElement("span");
255
+ cursor.classList.add("collaboration-cursor__caret");
256
+ cursor.setAttribute("style", `border-color: ${safeColor}`);
257
+ const label = document.createElement("div");
258
+ label.classList.add("collaboration-cursor__label");
259
+ label.setAttribute("style", `background-color: ${safeColor}`);
260
+ label.insertBefore(document.createTextNode(user.name ?? ""), null);
261
+ cursor.insertBefore(label, null);
262
+ return cursor;
263
+ }
264
+ function createCollaborationExtensions(options) {
265
+ return [
266
+ Collaboration.configure({
267
+ document: options.ydoc
268
+ }),
269
+ CollaborationCursor.configure({
270
+ provider: options.provider,
271
+ // 此处 user 为本地当前用户(可信来源),avatar 直接透传。
272
+ // 注意:远端用户的 avatar 来自 awareness 自报数据(不可信),在 OnlineUsersBadge
273
+ // 渲染前经 getSafeAvatarUrl 做同源校验,二者威胁模型不同,不要混用。
274
+ user: toAwarenessUser(options.user),
275
+ // 渲染的是远端用户(不可信),render 内对 color 做 isSafeCssColor 净化。
276
+ render: renderCollaborationCursor
277
+ })
278
+ ];
279
+ }
280
+ var PERSISTENCE_SYNC_TIMEOUT = 3e3;
281
+ var RECONNECT_BASE_DELAY = 1e3;
282
+ var RECONNECT_MAX_DELAY = 3e4;
283
+ var EMPTY_HOLDER = {
284
+ key: "",
285
+ ydoc: null,
286
+ provider: null,
287
+ persistence: null,
288
+ createError: null
289
+ };
290
+ function getReconnectDelay(attempt) {
291
+ if (attempt <= 0) return 0;
292
+ return Math.min(RECONNECT_MAX_DELAY, RECONNECT_BASE_DELAY * 2 ** (attempt - 1));
293
+ }
294
+ function clearReconnectTimer(timerRef) {
295
+ if (!timerRef.current) return;
296
+ clearTimeout(timerRef.current);
297
+ timerRef.current = null;
298
+ }
299
+ function resetReconnectBackoff(timerRef, attemptRef) {
300
+ clearReconnectTimer(timerRef);
301
+ attemptRef.current = 0;
302
+ }
303
+ function normalizeProviderStatus(status) {
304
+ if (status === "connected") return "connected";
305
+ if (status === "connecting") return "connecting";
306
+ return "disconnected";
307
+ }
308
+ function attachProviderListeners(provider, callbacks) {
309
+ provider.on("connect", callbacks.onConnect);
310
+ provider.on("disconnect", callbacks.onDisconnect);
311
+ provider.on("authenticationFailed", callbacks.onAuthFailed);
312
+ provider.on("status", callbacks.onStatus);
313
+ provider.awareness?.on("change", callbacks.onAwarenessChange);
314
+ return () => {
315
+ try {
316
+ provider.awareness?.off("change", callbacks.onAwarenessChange);
317
+ provider.off("connect", callbacks.onConnect);
318
+ provider.off("disconnect", callbacks.onDisconnect);
319
+ provider.off("authenticationFailed", callbacks.onAuthFailed);
320
+ provider.off("status", callbacks.onStatus);
321
+ } catch {
322
+ }
323
+ };
324
+ }
325
+ function connectAfterPersistenceSync(persistence, connect) {
326
+ if (!persistence) {
327
+ connect();
328
+ return () => {
329
+ };
330
+ }
331
+ let fallbackTimer = null;
332
+ let fired = false;
333
+ const clearFallback = () => {
334
+ if (fallbackTimer) {
335
+ clearTimeout(fallbackTimer);
336
+ fallbackTimer = null;
337
+ }
338
+ };
339
+ const onSynced = () => {
340
+ if (fired) return;
341
+ fired = true;
342
+ clearFallback();
343
+ try {
344
+ persistence.off("synced", onSynced);
345
+ } catch {
346
+ }
347
+ connect();
348
+ };
349
+ persistence.on("synced", onSynced);
350
+ fallbackTimer = setTimeout(() => {
351
+ if (fired) return;
352
+ fired = true;
353
+ fallbackTimer = null;
354
+ try {
355
+ persistence.off("synced", onSynced);
356
+ } catch {
357
+ }
358
+ console.warn("[collaboration] persistence synced \u8D85\u65F6\uFF0C\u515C\u5E95\u8FDE\u63A5");
359
+ connect();
360
+ }, PERSISTENCE_SYNC_TIMEOUT);
361
+ return () => {
362
+ fired = true;
363
+ clearFallback();
364
+ try {
365
+ persistence.off("synced", onSynced);
366
+ } catch {
367
+ }
368
+ };
369
+ }
370
+ function destroyResources(holder) {
371
+ const parts = [
372
+ { label: "provider", resource: holder.provider },
373
+ { label: "persistence", resource: holder.persistence },
374
+ { label: "ydoc", resource: holder.ydoc }
375
+ ];
376
+ for (const { label, resource } of parts) {
377
+ try {
378
+ resource?.destroy();
379
+ } catch (e) {
380
+ console.warn(`[collaboration] destroy ${label} failed:`, e);
381
+ }
382
+ }
383
+ }
384
+ function bindCollaborationResource(holder, callbacks) {
385
+ const { provider, persistence } = holder;
386
+ if (holder.createError || !provider) return () => {
387
+ };
388
+ const detachListeners = attachProviderListeners(provider, callbacks);
389
+ callbacks.onAwarenessChange();
390
+ let didStartConnect = false;
391
+ const cancelPendingConnect = connectAfterPersistenceSync(persistence, () => {
392
+ if (didStartConnect) return;
393
+ didStartConnect = true;
394
+ callbacks.onReadyToConnect();
395
+ try {
396
+ provider.connect();
397
+ } catch (e) {
398
+ callbacks.onConnectError(e);
399
+ }
400
+ });
401
+ return () => {
402
+ cancelPendingConnect();
403
+ detachListeners();
404
+ destroyResources(holder);
405
+ };
406
+ }
407
+ function createResourcesForKey(key, config, currentUser, getToken) {
408
+ if (!config) {
409
+ return { ...EMPTY_HOLDER, key };
410
+ }
411
+ const user = currentUser ?? config.user ?? getAnonymousUser();
412
+ const ydoc = new Y.Doc();
413
+ const roomName = ROOM_PREFIX + config.documentId;
414
+ let persistence = null;
415
+ if (config.enableOffline !== false) {
416
+ try {
417
+ persistence = new IndexeddbPersistence(roomName, ydoc);
418
+ } catch (e) {
419
+ console.warn("[collaboration] IndexedDB persistence failed:", e);
420
+ }
421
+ }
422
+ try {
423
+ const provider = new HocuspocusProvider({
424
+ url: config.endpoint,
425
+ name: roomName,
426
+ document: ydoc,
427
+ // 延迟连接:等本地离线数据 apply 到 ydoc 后再连服务端
428
+ connect: false,
429
+ // token 用函数形式惰性读取最新值(HocuspocusProvider 支持 string | fn | Promise)。
430
+ // token 轮换(JWT 刷新)时只更新 ref,不重建 ydoc/provider,避免撤销栈清空、
431
+ // 未 flush 更新丢失、编辑器重挂载。故 token 不再进入 resourcesKey。
432
+ token: () => getToken() ?? ""
433
+ });
434
+ provider.setAwarenessField("user", toAwarenessUser(user));
435
+ return { key, ydoc, provider, persistence, createError: null };
436
+ } catch (e) {
437
+ try {
438
+ persistence?.destroy();
439
+ } catch {
440
+ }
441
+ try {
442
+ ydoc.destroy();
443
+ } catch {
444
+ }
445
+ return {
446
+ key,
447
+ ydoc: null,
448
+ provider: null,
449
+ persistence: null,
450
+ createError: tr("\u534F\u540C\u8FDE\u63A5\u521D\u59CB\u5316\u5931\u8D25: ${0}", [e instanceof Error ? e.message : String(e)])
451
+ };
452
+ }
453
+ }
454
+
455
+ // src/editor/features/collaboration/hooks/useCollaborationResources.ts
456
+ function useCollaborationResources(config, currentUser) {
457
+ const [ready, setReady] = useState(false);
458
+ const [connectionStatus, setConnectionStatus] = useState("disconnected");
459
+ const [onlineUsers, setOnlineUsers] = useState([]);
460
+ const [error, setError] = useState(null);
461
+ const [resourceState, setResourceState] = useState({
462
+ key: "local",
463
+ ydoc: null,
464
+ provider: null
465
+ });
466
+ const resourcesKey = config ? `${config.endpoint}::${config.documentId}::${config.enableOffline ?? ""}` : "local";
467
+ const resourcesRef = useRef(EMPTY_HOLDER);
468
+ const latestTokenRef = useRef(config?.token);
469
+ latestTokenRef.current = config?.token;
470
+ const reconnectAttemptRef = useRef(0);
471
+ const reconnectTimerRef = useRef(null);
472
+ const authFailedRef = useRef(false);
473
+ const lastAwarenessUserRef = useRef(null);
474
+ useEffect(() => {
475
+ resetReconnectBackoff(reconnectTimerRef, reconnectAttemptRef);
476
+ authFailedRef.current = false;
477
+ if (resourcesKey === "local") {
478
+ resourcesRef.current = { ...EMPTY_HOLDER, key: "local" };
479
+ lastAwarenessUserRef.current = null;
480
+ setResourceState({ key: "local", ydoc: null, provider: null });
481
+ setReady(true);
482
+ setConnectionStatus("disconnected");
483
+ setOnlineUsers([]);
484
+ setError(null);
485
+ return;
486
+ }
487
+ setReady(false);
488
+ const holder = createResourcesForKey(resourcesKey, config, currentUser, () => latestTokenRef.current);
489
+ resourcesRef.current = holder;
490
+ lastAwarenessUserRef.current = currentUser ?? config?.user ?? getAnonymousUser();
491
+ setResourceState({
492
+ key: holder.key,
493
+ ydoc: holder.ydoc,
494
+ provider: holder.provider
495
+ });
496
+ if (holder.createError || !holder.provider) {
497
+ setConnectionStatus("error");
498
+ setError(holder.createError);
499
+ setReady(true);
500
+ return;
501
+ }
502
+ setConnectionStatus("disconnected");
503
+ setError(null);
504
+ const provider = holder.provider;
505
+ const updateUsers = () => {
506
+ try {
507
+ if (!provider.awareness) return;
508
+ const users = collectOnlineUsers(provider);
509
+ setOnlineUsers((prev) => areUserListsEqual(prev, users) ? prev : users);
510
+ } catch (e) {
511
+ console.warn("[collaboration] update awareness users failed:", e);
512
+ }
513
+ };
514
+ const cancelBinding = bindCollaborationResource(holder, {
515
+ onConnect: () => {
516
+ authFailedRef.current = false;
517
+ resetReconnectBackoff(reconnectTimerRef, reconnectAttemptRef);
518
+ setConnectionStatus("connected");
519
+ setError(null);
520
+ },
521
+ onDisconnect: () => {
522
+ if (authFailedRef.current) return;
523
+ setConnectionStatus("disconnected");
524
+ },
525
+ onAuthFailed: () => {
526
+ authFailedRef.current = true;
527
+ setConnectionStatus("error");
528
+ setError(tr("\u534F\u540C\u9274\u6743\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 token"));
529
+ },
530
+ onStatus: ({ status }) => {
531
+ if (authFailedRef.current) return;
532
+ setConnectionStatus(normalizeProviderStatus(status));
533
+ },
534
+ onAwarenessChange: updateUsers,
535
+ onReadyToConnect: () => {
536
+ setReady(true);
537
+ setConnectionStatus("connecting");
538
+ },
539
+ onConnectError: (e) => {
540
+ console.warn("[collaboration] provider.connect failed:", e);
541
+ setConnectionStatus("error");
542
+ setError(tr("\u534F\u540C\u8FDE\u63A5\u5931\u8D25: ${0}", [e instanceof Error ? e.message : String(e)]));
543
+ }
544
+ });
545
+ return () => {
546
+ resetReconnectBackoff(reconnectTimerRef, reconnectAttemptRef);
547
+ cancelBinding();
548
+ resourcesRef.current = EMPTY_HOLDER;
549
+ lastAwarenessUserRef.current = null;
550
+ };
551
+ }, [resourcesKey]);
552
+ useEffect(() => {
553
+ const provider = resourcesRef.current.provider;
554
+ const user = currentUser ?? config?.user;
555
+ if (!provider || !user) return;
556
+ const prev = lastAwarenessUserRef.current;
557
+ if (prev && areUsersEqual(prev, user)) return;
558
+ lastAwarenessUserRef.current = user;
559
+ provider.setAwarenessField("user", toAwarenessUser(user));
560
+ }, [currentUser, config?.user, resourcesKey]);
561
+ const reconnect = useCallback(() => {
562
+ const provider = resourcesRef.current.provider;
563
+ if (!provider) {
564
+ setError(tr("\u534F\u540C provider \u4E0D\u5B58\u5728\uFF0C\u65E0\u6CD5\u91CD\u8FDE"));
565
+ setConnectionStatus("error");
566
+ return;
567
+ }
568
+ clearReconnectTimer(reconnectTimerRef);
569
+ const delay = getReconnectDelay(reconnectAttemptRef.current);
570
+ reconnectAttemptRef.current += 1;
571
+ authFailedRef.current = false;
572
+ setConnectionStatus("connecting");
573
+ setError(null);
574
+ const connect = () => {
575
+ reconnectTimerRef.current = null;
576
+ const latestProvider = resourcesRef.current.provider;
577
+ if (!latestProvider || latestProvider !== provider) return;
578
+ try {
579
+ latestProvider.connect();
580
+ } catch (e) {
581
+ setConnectionStatus("error");
582
+ setError(tr("\u91CD\u8FDE\u5931\u8D25: ${0}", [e instanceof Error ? e.message : String(e)]));
583
+ }
584
+ };
585
+ if (delay === 0) {
586
+ connect();
587
+ return;
588
+ }
589
+ reconnectTimerRef.current = setTimeout(() => {
590
+ connect();
591
+ }, delay);
592
+ }, []);
593
+ const isCurrentResource = resourceState.key === resourcesKey;
594
+ const isReady = resourcesKey === "local" || ready && isCurrentResource;
595
+ return {
596
+ ready: isReady,
597
+ resourcesKey,
598
+ ydoc: isCurrentResource ? resourceState.ydoc : null,
599
+ provider: isCurrentResource ? resourceState.provider : null,
600
+ connectionStatus,
601
+ onlineUsers,
602
+ error,
603
+ reconnect
604
+ };
605
+ }
606
+
607
+ // src/editor/utils/normalizeInitialContent.ts
608
+ var EMPTY_DOCUMENT_HTML = "<p></p>";
609
+ function normalizeInitialContent(content, schema) {
610
+ if (!content) return EMPTY_DOCUMENT_HTML;
611
+ if (typeof content !== "string") return sanitizeJsonContent(content, schema);
612
+ return sanitizeHtml(content);
613
+ }
614
+
615
+ // src/editor/features/collaboration/utils/seeding.ts
616
+ var COLLABORATION_FRAGMENT_FIELD = "default";
617
+ var COLLABORATION_META_MAP = "idocs:meta";
618
+ var INITIAL_CONTENT_META_KEY = "initialContentApplied";
619
+ function hasInitialContent(content) {
620
+ if (typeof content === "string") return content.trim().length > 0;
621
+ return !!content?.content?.length;
622
+ }
623
+ function isInitialContentApplied(ydoc) {
624
+ return ydoc.getMap(COLLABORATION_META_MAP).get(INITIAL_CONTENT_META_KEY) === true;
625
+ }
626
+ function isCollaborationFragmentEmpty(ydoc) {
627
+ return ydoc.getXmlFragment(COLLABORATION_FRAGMENT_FIELD).length === 0;
628
+ }
629
+ function isSmallestAwarenessClient(ydoc, provider) {
630
+ const awarenessClientIds = Array.from(provider.awareness?.getStates().keys() ?? []);
631
+ const localClientId = ydoc.clientID;
632
+ if (!awarenessClientIds.includes(localClientId)) {
633
+ awarenessClientIds.push(localClientId);
634
+ }
635
+ return localClientId === Math.min(...awarenessClientIds);
636
+ }
637
+ function initializeEmptyCollaborationDocument(options) {
638
+ const { editor, ydoc, provider, content } = options;
639
+ const metadata = ydoc.getMap(COLLABORATION_META_MAP);
640
+ if (isInitialContentApplied(ydoc)) return;
641
+ if (!isCollaborationFragmentEmpty(ydoc)) {
642
+ metadata.set(INITIAL_CONTENT_META_KEY, true);
643
+ return;
644
+ }
645
+ if (!hasInitialContent(content)) return;
646
+ if (!isSmallestAwarenessClient(ydoc, provider)) return;
647
+ let didSetContent = false;
648
+ ydoc.transact(() => {
649
+ if (!isCollaborationFragmentEmpty(ydoc)) return;
650
+ didSetContent = editor.commands.setContent(normalizeInitialContent(content, editor.schema), false);
651
+ if (didSetContent) {
652
+ metadata.set(INITIAL_CONTENT_META_KEY, true);
653
+ }
654
+ });
655
+ }
656
+ var CURSOR_CSS = `
657
+ .collaboration-cursor__caret {
658
+ border-left: 1px solid currentColor;
659
+ border-right: 1px solid currentColor;
660
+ margin-left: -1px;
661
+ margin-right: -1px;
662
+ pointer-events: none;
663
+ position: relative;
664
+ word-break: normal;
665
+ }
666
+ .collaboration-cursor__label {
667
+ border-radius: var(--borderRadiusXS, 3px) var(--borderRadiusXS, 3px) var(--borderRadiusXS, 3px) 0;
668
+ color: var(--colorWhite, #fff);
669
+ font-size: 12px;
670
+ font-weight: 600;
671
+ left: -1px;
672
+ opacity: 1;
673
+ padding: 0.1rem 0.3rem;
674
+ position: absolute;
675
+ top: -1.4em;
676
+ user-select: none;
677
+ white-space: nowrap;
678
+ z-index: 10;
679
+ }
680
+ `;
681
+ var STYLE_ID = "idocs-collaboration-cursor-styles";
682
+ var cursorStyleRefCount = 0;
683
+ function UserCursorStyles() {
684
+ useEffect(() => {
685
+ cursorStyleRefCount += 1;
686
+ if (!document.getElementById(STYLE_ID)) {
687
+ const style = document.createElement("style");
688
+ style.id = STYLE_ID;
689
+ style.textContent = CURSOR_CSS;
690
+ document.head.appendChild(style);
691
+ }
692
+ return () => {
693
+ cursorStyleRefCount = Math.max(0, cursorStyleRefCount - 1);
694
+ if (cursorStyleRefCount === 0) {
695
+ document.getElementById(STYLE_ID)?.remove();
696
+ }
697
+ };
698
+ }, []);
699
+ return null;
700
+ }
701
+
702
+ // src/editor/features/collaboration/styles.ts
703
+ var useOnlineUsersStyles = createStyles(({ css, token }) => ({
704
+ avatar: css`
705
+ color: ${token.colorWhite};
706
+ border: 2px solid ${token.colorBgContainer};
707
+ box-shadow: 0 0 0 1px ${token.colorBorderSecondary};
708
+ `,
709
+ overflowAvatar: css`
710
+ background: ${token.colorFillSecondary};
711
+ color: ${token.colorTextSecondary};
712
+ border: 2px solid ${token.colorBgContainer};
713
+ `
714
+ }));
715
+ var MAX_VISIBLE = 5;
716
+ function AvatarCircle({
717
+ title,
718
+ className,
719
+ backgroundColor,
720
+ fontSize = 12,
721
+ marginLeft = 0,
722
+ zIndex = 0,
723
+ children
724
+ }) {
725
+ return /* @__PURE__ */ jsx(
726
+ "div",
727
+ {
728
+ title,
729
+ className,
730
+ style: {
731
+ width: 24,
732
+ height: 24,
733
+ borderRadius: "50%",
734
+ backgroundColor,
735
+ fontSize,
736
+ fontWeight: 600,
737
+ display: "flex",
738
+ alignItems: "center",
739
+ justifyContent: "center",
740
+ marginLeft,
741
+ zIndex,
742
+ overflow: "hidden",
743
+ flexShrink: 0
744
+ },
745
+ children
746
+ }
747
+ );
748
+ }
749
+ function avatarKeyOf(user, usedBases, index) {
750
+ const base = user.id ?? user.name ?? "";
751
+ if (!usedBases.has(base)) {
752
+ usedBases.add(base);
753
+ return base;
754
+ }
755
+ return `${base}-${index}`;
756
+ }
757
+ function OnlineUsersBadge() {
758
+ const { onlineUsers } = useCollaboration();
759
+ const { styles } = useOnlineUsersStyles();
760
+ if (!onlineUsers || onlineUsers.length === 0) {
761
+ return null;
762
+ }
763
+ const visible = onlineUsers.slice(0, MAX_VISIBLE);
764
+ const overflow = onlineUsers.length - visible.length;
765
+ const usedBases = /* @__PURE__ */ new Set();
766
+ return /* @__PURE__ */ jsxs(
767
+ "div",
768
+ {
769
+ style: {
770
+ display: "inline-flex",
771
+ alignItems: "center"
772
+ },
773
+ children: [
774
+ visible.map((user, index) => {
775
+ const avatarUrl = getSafeAvatarUrl(user.avatar);
776
+ return /* @__PURE__ */ jsx(
777
+ AvatarCircle,
778
+ {
779
+ title: user.name,
780
+ className: styles.avatar,
781
+ backgroundColor: user.color,
782
+ marginLeft: index === 0 ? 0 : -8,
783
+ zIndex: onlineUsers.length - index,
784
+ children: avatarUrl ? /* @__PURE__ */ jsx("img", { src: avatarUrl, alt: user.name, style: { width: "100%", height: "100%", objectFit: "cover" } }) : /* @__PURE__ */ jsx("span", { children: user.name?.charAt(0)?.toUpperCase() ?? "?" })
785
+ },
786
+ avatarKeyOf(user, usedBases, index)
787
+ );
788
+ }),
789
+ overflow > 0 && /* @__PURE__ */ jsxs(
790
+ AvatarCircle,
791
+ {
792
+ title: tr("\u8FD8\u6709 ${0} \u4F4D\u534F\u4F5C\u8005", [overflow]),
793
+ className: styles.overflowAvatar,
794
+ fontSize: 11,
795
+ marginLeft: -8,
796
+ children: [
797
+ "+",
798
+ overflow
799
+ ]
800
+ }
801
+ )
802
+ ]
803
+ }
804
+ );
805
+ }
806
+ var EditorContext = createContext(null);
807
+ function useEditorContext() {
808
+ const ctx = useContext(EditorContext);
809
+ if (!ctx) {
810
+ throw new Error("useEditorContext must be used within EditorContext.Provider");
811
+ }
812
+ return ctx;
813
+ }
814
+
815
+ // src/editor/core/styles.ts
816
+ var useStyles = createStyles(({ css, token }) => ({
817
+ statusBar: css`
818
+ display: flex;
819
+ align-items: center;
820
+ justify-content: space-between;
821
+ padding: ${token.paddingXXS}px ${token.paddingSM}px;
822
+ border-top: 1px solid ${token.colorBorderSecondary};
823
+ font-size: ${token.fontSizeSM}px;
824
+ color: ${token.colorTextTertiary};
825
+ /* 背景透明,透出 editorWrapper 的表面(毛玻璃态呈现玻璃质感,传统态为容器底色) */
826
+ background: transparent;
827
+ min-height: ${token.controlHeightSM}px;
828
+ flex-shrink: 0;
829
+ user-select: none;
830
+ `,
831
+ leftSection: css`
832
+ display: flex;
833
+ align-items: center;
834
+ gap: 12px;
835
+ `,
836
+ rightSection: css`
837
+ display: flex;
838
+ align-items: center;
839
+ gap: 8px;
840
+ `,
841
+ statusIndicator: css`
842
+ display: inline-flex;
843
+ align-items: center;
844
+ gap: 4px;
845
+ `,
846
+ statusDot: css`
847
+ display: inline-block;
848
+ width: 8px;
849
+ height: 8px;
850
+ border-radius: 50%;
851
+ flex-shrink: 0;
852
+ `,
853
+ statusDotConnecting: css`
854
+ background: ${token.colorWarning};
855
+ `,
856
+ statusDotConnected: css`
857
+ background: ${token.colorSuccess};
858
+ `,
859
+ statusDotDisconnected: css`
860
+ background: ${token.colorTextDisabled};
861
+ `,
862
+ statusDotError: css`
863
+ background: ${token.colorError};
864
+ `,
865
+ charCount: css`
866
+ display: flex;
867
+ align-items: center;
868
+ gap: 12px;
869
+
870
+ span {
871
+ white-space: nowrap;
872
+ }
873
+ `,
874
+ reconnectButton: css`
875
+ border: none;
876
+ padding: 0;
877
+ background: transparent;
878
+ color: ${token.colorLink};
879
+ cursor: pointer;
880
+ font-size: ${token.fontSizeSM}px;
881
+
882
+ &:hover {
883
+ color: ${token.colorPrimaryHover};
884
+ }
885
+ `
886
+ }));
887
+ function useEditorRerenderOn(editor, events) {
888
+ const [version, forceUpdate] = useState(0);
889
+ useEffect(() => {
890
+ if (!editor) return;
891
+ let rafId = null;
892
+ const handleUpdate = () => {
893
+ if (rafId !== null) return;
894
+ rafId = requestAnimationFrame(() => {
895
+ rafId = null;
896
+ forceUpdate((n) => n + 1);
897
+ });
898
+ };
899
+ events.forEach((event) => {
900
+ editor.on(event, handleUpdate);
901
+ });
902
+ return () => {
903
+ events.forEach((event) => {
904
+ editor.off(event, handleUpdate);
905
+ });
906
+ if (rafId !== null) cancelAnimationFrame(rafId);
907
+ };
908
+ }, [editor, events.join(",")]);
909
+ return version;
910
+ }
911
+ var STATUS_BAR_RERENDER_EVENTS = ["update"];
912
+ function EditorStatusBar({ editor, collaborationEnabled }) {
913
+ const { styles } = useStyles();
914
+ const { reconnect, connectionStatus: collabStatus, onlineUsers, error: collabError } = useCollaboration();
915
+ const onlineCount = onlineUsers.length;
916
+ useEditorRerenderOn(editor, STATUS_BAR_RERENDER_EVENTS);
917
+ const characterCount = editor?.storage?.characterCount;
918
+ const characters = characterCount?.characters?.() ?? 0;
919
+ const words = characterCount?.words?.() ?? 0;
920
+ const status = collabStatus ?? "disconnected";
921
+ const STATUS_META = {
922
+ connecting: { label: tr(CONNECTION_STATUS_LABEL.connecting), dotClass: styles.statusDotConnecting },
923
+ connected: { label: tr(CONNECTION_STATUS_LABEL.connected), dotClass: styles.statusDotConnected },
924
+ disconnected: { label: tr(CONNECTION_STATUS_LABEL.disconnected), dotClass: styles.statusDotDisconnected },
925
+ error: { label: tr(CONNECTION_STATUS_LABEL.error), dotClass: styles.statusDotError }
926
+ };
927
+ const statusMeta = STATUS_META[status] ?? STATUS_META.disconnected;
928
+ return /* @__PURE__ */ jsxs("div", { className: styles.statusBar, children: [
929
+ /* @__PURE__ */ jsx("div", { className: styles.leftSection, children: /* @__PURE__ */ jsxs("div", { className: styles.charCount, children: [
930
+ /* @__PURE__ */ jsxs("span", { children: [
931
+ tr("\u5B57\u6570"),
932
+ ": ",
933
+ characters
934
+ ] }),
935
+ /* @__PURE__ */ jsxs("span", { children: [
936
+ tr("\u8BCD\u6570"),
937
+ ": ",
938
+ words
939
+ ] })
940
+ ] }) }),
941
+ collaborationEnabled && /* @__PURE__ */ jsxs("div", { className: styles.rightSection, children: [
942
+ /* @__PURE__ */ jsx(Tooltip, { title: collabError ?? "", children: /* @__PURE__ */ jsxs("span", { className: styles.statusIndicator, children: [
943
+ /* @__PURE__ */ jsx("span", { className: `${styles.statusDot} ${statusMeta.dotClass}` }),
944
+ statusMeta.label
945
+ ] }) }),
946
+ onlineCount > 0 && /* @__PURE__ */ jsxs(Tag, { color: "blue", children: [
947
+ tr("\u5728\u7EBF"),
948
+ ": ",
949
+ onlineCount
950
+ ] }),
951
+ (status === "disconnected" || status === "error") && /* @__PURE__ */ jsx("button", { type: "button", className: styles.reconnectButton, onClick: reconnect, children: tr("\u91CD\u8FDE") })
952
+ ] })
953
+ ] });
954
+ }
955
+ var Y_SYNC_META_KEYS = ["y-sync", "y-sync$"];
956
+ function isLocalTransaction(transaction, hasCollab) {
957
+ if (!hasCollab || !transaction) return true;
958
+ const syncMeta = Y_SYNC_META_KEYS.map(
959
+ (key) => transaction.getMeta(key)
960
+ ).find(Boolean);
961
+ return !syncMeta?.isChangeOrigin;
962
+ }
963
+ function useEditorInstance(options) {
964
+ const { registry, content, editable = true, collabExtensions = null, onUpdate, onEditorReady } = options;
965
+ const isReadyRef = useRef(false);
966
+ const onUpdateRef = useRef(onUpdate);
967
+ onUpdateRef.current = onUpdate;
968
+ const onEditorReadyRef = useRef(onEditorReady);
969
+ onEditorReadyRef.current = onEditorReady;
970
+ const hasCollab = !!collabExtensions && collabExtensions.length > 0;
971
+ const lastEmittedHtmlRef = useRef(null);
972
+ const editorRef = useRef(null);
973
+ const extensions = useMemo(() => {
974
+ const base = registry.buildExtensions();
975
+ if (collabExtensions && collabExtensions.length > 0) {
976
+ return [...base, ...collabExtensions];
977
+ }
978
+ return base;
979
+ }, [registry, collabExtensions]);
980
+ const enabledPlugins = useMemo(() => registry.resolveEnabled(), [registry]);
981
+ const schema = useMemo(() => getSchema(extensions), [extensions]);
982
+ const initialContent = useMemo(() => normalizeInitialContent(content, schema), []);
983
+ const contentRef = useRef(content);
984
+ const editor = useEditor({
985
+ extensions,
986
+ editable,
987
+ content: hasCollab ? void 0 : initialContent,
988
+ onCreate: ({ editor: ed }) => {
989
+ for (const plugin of enabledPlugins) {
990
+ try {
991
+ plugin.onEditorCreate?.(ed, registry.getResolvedConfig(plugin));
992
+ } catch (e) {
993
+ console.error(`[idocs-editor] plugin "${plugin.name}" onEditorCreate failed:`, e);
994
+ }
995
+ }
996
+ isReadyRef.current = true;
997
+ },
998
+ onUpdate: ({ editor: ed, transaction }) => {
999
+ if (!isReadyRef.current) return;
1000
+ const isLocal = isLocalTransaction(transaction, hasCollab);
1001
+ const isUserEdit = isLocal && transaction?.getMeta("addToHistory") !== false;
1002
+ let htmlCache = null;
1003
+ onUpdateRef.current?.({
1004
+ isUserEdit,
1005
+ get html() {
1006
+ if (htmlCache === null) {
1007
+ htmlCache = ed.getHTML();
1008
+ lastEmittedHtmlRef.current = htmlCache;
1009
+ }
1010
+ return htmlCache;
1011
+ },
1012
+ isLocal
1013
+ });
1014
+ }
1015
+ });
1016
+ useEffect(() => {
1017
+ if (editor) {
1018
+ editor.setEditable(editable);
1019
+ }
1020
+ }, [editor, editable]);
1021
+ useEffect(() => {
1022
+ if (!editor || hasCollab) return;
1023
+ if (contentRef.current === content) return;
1024
+ contentRef.current = content;
1025
+ if (typeof content === "string" && content === lastEmittedHtmlRef.current) return;
1026
+ editor.commands.setContent(normalizeInitialContent(content, editor.schema), false);
1027
+ }, [editor, content, hasCollab]);
1028
+ useEffect(() => {
1029
+ onEditorReadyRef.current?.(editor || null);
1030
+ return () => {
1031
+ onEditorReadyRef.current?.(null);
1032
+ };
1033
+ }, [editor]);
1034
+ const destroyDepsRef = useRef({ enabledPlugins, registry });
1035
+ destroyDepsRef.current = { enabledPlugins, registry };
1036
+ useEffect(() => {
1037
+ if (!editor) return;
1038
+ return () => {
1039
+ const { enabledPlugins: plugins, registry: reg } = destroyDepsRef.current;
1040
+ for (const plugin of plugins) {
1041
+ try {
1042
+ plugin.onEditorDestroy?.(editor, reg.getResolvedConfig(plugin));
1043
+ } catch (e) {
1044
+ console.error(`[idocs-editor] plugin "${plugin.name}" onEditorDestroy failed:`, e);
1045
+ }
1046
+ }
1047
+ };
1048
+ }, [editor]);
1049
+ return {
1050
+ editor,
1051
+ editorRef
1052
+ };
1053
+ }
1054
+
1055
+ // src/editor/toolbar/styles.ts
1056
+ var useToolbarStyles = createStyles(({ css, token, sizeToken, glassEffect, getAlphaColor }) => {
1057
+ const { controlHeight, paddingContentHorizontal, borderRadius } = sizeToken;
1058
+ return {
1059
+ toolbar: css`
1060
+ display: flex;
1061
+ align-items: center;
1062
+ padding: 4px ${paddingContentHorizontal}px;
1063
+ /* 毛玻璃表面走共享工厂的 strip 变体(贴顶条带:底边框 + container 背景 + -sm 模糊) */
1064
+ ${glassSurfaceCss({ token, glassEffect, getAlphaColor, borderRadius }, { variant: "strip" })}
1065
+ overflow-x: auto;
1066
+ flex-shrink: 0;
1067
+
1068
+ /* 隐藏横向滚动条(WebKit + Firefox/Chrome 121+) */
1069
+ &::-webkit-scrollbar {
1070
+ height: 0;
1071
+ }
1072
+ scrollbar-width: none;
1073
+ `,
1074
+ toolbarGroup: css`
1075
+ display: flex;
1076
+ align-items: center;
1077
+ gap: 2px;
1078
+ flex-wrap: nowrap;
1079
+
1080
+ .ant-divider-vertical {
1081
+ margin: 0 4px;
1082
+ height: ${controlHeight - 8}px;
1083
+ }
1084
+ `,
1085
+ activeBtn: css`
1086
+ background: ${getAlphaColor(token.colorPrimary, 0.1)} !important;
1087
+ color: ${token.colorPrimary} !important;
1088
+ border-radius: ${borderRadius}px;
1089
+ `,
1090
+ /* ---- 颜色选择器 ---- */
1091
+ colorPaletteWrapper: css`
1092
+ padding: 8px;
1093
+ /* 宽度由色板行内容撑开,不写死,避免与 COLOR_GRID_COLS(每行格子数)耦合 */
1094
+ width: fit-content;
1095
+ `,
1096
+ colorPalette: css`
1097
+ display: flex;
1098
+ flex-direction: column;
1099
+ gap: 4px;
1100
+ `,
1101
+ colorRow: css`
1102
+ display: flex;
1103
+ gap: 4px;
1104
+ `,
1105
+ colorCell: css`
1106
+ width: 20px;
1107
+ height: 20px;
1108
+ border-radius: ${borderRadius}px;
1109
+ cursor: pointer;
1110
+ border: 1px solid ${token.colorBorderSecondary};
1111
+ transition: transform 0.15s ease;
1112
+
1113
+ &:hover {
1114
+ transform: scale(1.15);
1115
+ border-color: ${token.colorPrimary};
1116
+ }
1117
+ `,
1118
+ clearColorBtn: css`
1119
+ margin-top: 4px;
1120
+ text-align: center;
1121
+ `,
1122
+ /* ---- 表格插入网格 ---- */
1123
+ tableGrid: css`
1124
+ padding: 8px;
1125
+ `,
1126
+ tableGridTable: css`
1127
+ border-collapse: collapse;
1128
+
1129
+ td {
1130
+ width: 18px;
1131
+ height: 18px;
1132
+ border: 1px solid ${token.colorBorderSecondary};
1133
+ cursor: pointer;
1134
+ }
1135
+ `,
1136
+ tableGridCellActive: css`
1137
+ background: ${getAlphaColor(token.colorPrimary, 0.15)} !important;
1138
+ `,
1139
+ tableGridLabel: css`
1140
+ text-align: center;
1141
+ padding: 4px 0 0;
1142
+ color: ${token.colorTextSecondary};
1143
+ font-size: 12px;
1144
+ `,
1145
+ /* ---- tooltip 内容(操作名 + 快捷键) ---- */
1146
+ tooltipContent: css`
1147
+ text-align: center;
1148
+ line-height: 1.6;
1149
+ `,
1150
+ tooltipLabel: css`
1151
+ font-size: 13px;
1152
+ font-weight: 500;
1153
+ `,
1154
+ tooltipShortcut: css`
1155
+ font-size: 12px;
1156
+ opacity: 0.75;
1157
+ `,
1158
+ /* ---- 通用下拉触发器 ---- */
1159
+ dropdownTrigger: css`
1160
+ display: inline-flex;
1161
+ align-items: center;
1162
+ gap: 2px;
1163
+ `,
1164
+ /* 触发器右侧下拉箭头(10px 小号图标) */
1165
+ dropdownTriggerIcon: css`
1166
+ font-size: 10px;
1167
+ `
1168
+ };
1169
+ });
1170
+ var ToolbarDropdownTrigger = forwardRef(
1171
+ ({ children, className, ...rest }, ref) => {
1172
+ const { styles, cx } = useToolbarStyles();
1173
+ return /* @__PURE__ */ jsxs(
1174
+ Button,
1175
+ {
1176
+ ref,
1177
+ type: "text",
1178
+ size: "small",
1179
+ ...rest,
1180
+ className: cx(styles.dropdownTrigger, className),
1181
+ children: [
1182
+ children,
1183
+ /* @__PURE__ */ jsx(DownOutlined, { className: styles.dropdownTriggerIcon })
1184
+ ]
1185
+ }
1186
+ );
1187
+ }
1188
+ );
1189
+ ToolbarDropdownTrigger.displayName = "ToolbarDropdownTrigger";
1190
+ function useRovingFocus({
1191
+ containerRef,
1192
+ count,
1193
+ cols,
1194
+ navigation,
1195
+ cellSelector,
1196
+ onSelect,
1197
+ onNavigate
1198
+ }) {
1199
+ const focusCell = useCallback(
1200
+ (index) => {
1201
+ containerRef.current?.querySelector(cellSelector(index))?.focus();
1202
+ },
1203
+ [containerRef, cellSelector]
1204
+ );
1205
+ const handleKeyDown = useCallback(
1206
+ (event, index) => {
1207
+ let nextIndex = index;
1208
+ const row = Math.floor(index / cols);
1209
+ const col = index % cols;
1210
+ const rows = Math.ceil(count / cols);
1211
+ switch (event.key) {
1212
+ case "Enter":
1213
+ case " ":
1214
+ event.preventDefault();
1215
+ onSelect(index);
1216
+ return;
1217
+ case "ArrowLeft":
1218
+ nextIndex = navigation === "linear" ? Math.max(0, index - 1) : col > 0 ? index - 1 : index;
1219
+ break;
1220
+ case "ArrowRight":
1221
+ nextIndex = navigation === "linear" ? Math.min(count - 1, index + 1) : col < cols - 1 ? index + 1 : index;
1222
+ break;
1223
+ case "ArrowUp":
1224
+ nextIndex = navigation === "linear" ? Math.max(0, index - cols) : row > 0 ? index - cols : index;
1225
+ break;
1226
+ case "ArrowDown":
1227
+ nextIndex = navigation === "linear" ? Math.min(count - 1, index + cols) : row < rows - 1 ? index + cols : index;
1228
+ break;
1229
+ case "Home":
1230
+ nextIndex = navigation === "linear" ? 0 : row * cols;
1231
+ break;
1232
+ case "End":
1233
+ nextIndex = navigation === "linear" ? count - 1 : Math.min(count - 1, row * cols + cols - 1);
1234
+ break;
1235
+ default:
1236
+ return;
1237
+ }
1238
+ event.preventDefault();
1239
+ onNavigate?.(nextIndex);
1240
+ focusCell(nextIndex);
1241
+ },
1242
+ [count, cols, navigation, onSelect, onNavigate, focusCell]
1243
+ );
1244
+ return { handleKeyDown, focusCell };
1245
+ }
1246
+ var PRESET_COLORS = [
1247
+ "#000000",
1248
+ "#434343",
1249
+ "#666666",
1250
+ "#999999",
1251
+ "#E74C3C",
1252
+ "#E67E22",
1253
+ "#F1C40F",
1254
+ "#27AE60",
1255
+ "#1ABC9C",
1256
+ "#3498DB",
1257
+ "#9B59B6",
1258
+ "#95A5A6",
1259
+ "#FF6B6B",
1260
+ "#FFA500",
1261
+ "#00BFFF",
1262
+ "#9C27B0"
1263
+ ];
1264
+ var COLOR_GRID_COLS = 8;
1265
+ function ColorPickerButton({ item, editor }) {
1266
+ const { styles } = useToolbarStyles();
1267
+ const [open, setOpen] = useState(false);
1268
+ const paletteRef = useRef(null);
1269
+ const handleColorSelect = (color) => {
1270
+ item.onColorSelect?.(editor, color);
1271
+ setOpen(false);
1272
+ };
1273
+ const { handleKeyDown } = useRovingFocus({
1274
+ containerRef: paletteRef,
1275
+ count: PRESET_COLORS.length,
1276
+ cols: COLOR_GRID_COLS,
1277
+ navigation: "linear",
1278
+ cellSelector: (index) => `[data-idocs-color-index="${index}"]`,
1279
+ onSelect: (index) => handleColorSelect(PRESET_COLORS[index])
1280
+ });
1281
+ const handleClear = () => {
1282
+ if (item.onClear) {
1283
+ item.onClear(editor);
1284
+ } else if (item.onColorSelect) {
1285
+ item.onColorSelect(editor, "");
1286
+ }
1287
+ setOpen(false);
1288
+ };
1289
+ const colorRows = [];
1290
+ for (let i = 0; i < PRESET_COLORS.length; i += COLOR_GRID_COLS) {
1291
+ colorRows.push(PRESET_COLORS.slice(i, i + COLOR_GRID_COLS));
1292
+ }
1293
+ const palette = /* @__PURE__ */ jsxs("div", { ref: paletteRef, className: styles.colorPaletteWrapper, children: [
1294
+ /* @__PURE__ */ jsx("div", { className: styles.colorPalette, role: "grid", "aria-label": item.label ?? tr("\u989C\u8272"), children: colorRows.map((row, rowIndex) => /* @__PURE__ */ jsx("div", { role: "row", className: styles.colorRow, children: row.map((color, colIndex) => {
1295
+ const index = rowIndex * COLOR_GRID_COLS + colIndex;
1296
+ return /* @__PURE__ */ jsx(
1297
+ "div",
1298
+ {
1299
+ role: "gridcell",
1300
+ "aria-label": tr("\u9009\u62E9\u989C\u8272 ${0}", [color]),
1301
+ tabIndex: index === 0 ? 0 : -1,
1302
+ "data-idocs-color-index": index,
1303
+ className: styles.colorCell,
1304
+ style: { backgroundColor: color },
1305
+ onClick: () => handleColorSelect(color),
1306
+ onKeyDown: (event) => handleKeyDown(event, index)
1307
+ },
1308
+ color
1309
+ );
1310
+ }) }, rowIndex)) }),
1311
+ /* @__PURE__ */ jsx("div", { className: styles.clearColorBtn, children: /* @__PURE__ */ jsx(Button, { type: "text", size: "small", block: true, onClick: handleClear, children: tr("\u6E05\u9664\u989C\u8272") }) })
1312
+ ] });
1313
+ const triggerBtn = /* @__PURE__ */ jsx(ToolbarDropdownTrigger, { children: item.icon });
1314
+ return /* @__PURE__ */ jsx(Dropdown, { trigger: ["click"], open, onOpenChange: setOpen, popupRender: () => palette, children: item.label ? /* @__PURE__ */ jsx(Tooltip, { title: item.label, children: triggerBtn }) : triggerBtn });
1315
+ }
1316
+ var MAX_ROWS = 5;
1317
+ var MAX_COLS = 5;
1318
+ function TableInsertMenu({ item, editor }) {
1319
+ const { styles } = useToolbarStyles();
1320
+ const [open, setOpen] = useState(false);
1321
+ const [hover, setHover] = useState({ row: 0, col: 0 });
1322
+ const gridRef = useRef(null);
1323
+ const handleCellClick = (rows, cols) => {
1324
+ item.onClick?.(editor, rows, cols);
1325
+ setOpen(false);
1326
+ setHover({ row: 0, col: 0 });
1327
+ };
1328
+ const { handleKeyDown } = useRovingFocus({
1329
+ containerRef: gridRef,
1330
+ count: MAX_ROWS * MAX_COLS,
1331
+ cols: MAX_COLS,
1332
+ navigation: "grid",
1333
+ cellSelector: (index) => `[data-idocs-table-cell="${Math.floor(index / MAX_COLS) + 1}-${index % MAX_COLS + 1}"]`,
1334
+ onSelect: (index) => handleCellClick(Math.floor(index / MAX_COLS) + 1, index % MAX_COLS + 1),
1335
+ onNavigate: (index) => setHover({ row: Math.floor(index / MAX_COLS) + 1, col: index % MAX_COLS + 1 })
1336
+ });
1337
+ const handleCellKeyDown = (event, row, col) => handleKeyDown(event, (row - 1) * MAX_COLS + (col - 1));
1338
+ const grid = /* @__PURE__ */ jsxs("div", { ref: gridRef, className: styles.tableGrid, children: [
1339
+ /* @__PURE__ */ jsx("table", { className: styles.tableGridTable, role: "grid", "aria-label": item.label ?? tr("\u63D2\u5165\u8868\u683C"), children: /* @__PURE__ */ jsx("tbody", { children: Array.from({ length: MAX_ROWS }, (_, i) => /* @__PURE__ */ jsx("tr", { role: "row", children: Array.from({ length: MAX_COLS }, (_2, j) => {
1340
+ const row = i + 1;
1341
+ const col = j + 1;
1342
+ const isActive = i < hover.row && j < hover.col;
1343
+ return /* @__PURE__ */ jsx(
1344
+ "td",
1345
+ {
1346
+ role: "gridcell",
1347
+ tabIndex: i === 0 && j === 0 ? 0 : -1,
1348
+ "aria-label": tr("\u63D2\u5165 ${0}\xD7${1} \u8868\u683C", [row, col]),
1349
+ "data-idocs-table-cell": `${row}-${col}`,
1350
+ className: isActive ? styles.tableGridCellActive : void 0,
1351
+ onFocus: () => setHover({ row, col }),
1352
+ onMouseEnter: () => setHover({ row, col }),
1353
+ onClick: () => handleCellClick(row, col),
1354
+ onKeyDown: (event) => handleCellKeyDown(event, row, col)
1355
+ },
1356
+ j
1357
+ );
1358
+ }) }, i)) }) }),
1359
+ /* @__PURE__ */ jsx("div", { className: styles.tableGridLabel, children: hover.row > 0 && hover.col > 0 ? `${hover.row}\xD7${hover.col}` : item.label ?? "" })
1360
+ ] });
1361
+ return /* @__PURE__ */ jsx(
1362
+ Dropdown,
1363
+ {
1364
+ trigger: ["click"],
1365
+ open,
1366
+ onOpenChange: (visible) => {
1367
+ setOpen(visible);
1368
+ if (!visible) setHover({ row: 0, col: 0 });
1369
+ },
1370
+ popupRender: () => grid,
1371
+ children: /* @__PURE__ */ jsx(ToolbarDropdownTrigger, { children: item.icon })
1372
+ }
1373
+ );
1374
+ }
1375
+ function ToolbarButton({ item, editor }) {
1376
+ const { styles } = useToolbarStyles();
1377
+ const active = item.isActive?.(editor) ?? false;
1378
+ const disabled = item.disabled?.(editor) ?? false;
1379
+ const btn = /* @__PURE__ */ jsx(
1380
+ Button,
1381
+ {
1382
+ type: "text",
1383
+ size: "small",
1384
+ icon: item.icon,
1385
+ disabled,
1386
+ className: active ? styles.activeBtn : void 0,
1387
+ onClick: () => item.onClick?.(editor)
1388
+ }
1389
+ );
1390
+ if (!item.label) return btn;
1391
+ const tooltipTitle = item.shortcut ? /* @__PURE__ */ jsxs("div", { className: styles.tooltipContent, children: [
1392
+ /* @__PURE__ */ jsx("div", { className: styles.tooltipLabel, children: item.label }),
1393
+ /* @__PURE__ */ jsx("div", { className: styles.tooltipShortcut, children: item.shortcut })
1394
+ ] }) : item.label;
1395
+ return /* @__PURE__ */ jsx(Tooltip, { title: tooltipTitle, children: btn });
1396
+ }
1397
+ function ToolbarDivider() {
1398
+ return /* @__PURE__ */ jsx(Divider, { type: "vertical" });
1399
+ }
1400
+ function ToolbarDropdown({ item, editor }) {
1401
+ const options = item.options ?? [];
1402
+ if (options.length === 0) return null;
1403
+ const activeIndex = options.findIndex((opt) => opt.isActive?.(editor) ?? false);
1404
+ const activeOption = activeIndex >= 0 ? options[activeIndex] : null;
1405
+ const triggerLabel = activeOption?.label ?? item.label ?? "";
1406
+ const menuItems = options.map((opt, index) => ({
1407
+ key: String(index),
1408
+ label: opt.label,
1409
+ icon: opt.icon
1410
+ }));
1411
+ return /* @__PURE__ */ jsx(
1412
+ Dropdown,
1413
+ {
1414
+ trigger: ["click"],
1415
+ menu: {
1416
+ items: menuItems,
1417
+ // 高亮当前激活的选项
1418
+ selectedKeys: activeIndex >= 0 ? [String(activeIndex)] : [],
1419
+ onClick: ({ key }) => {
1420
+ const idx = Number(key);
1421
+ const opt = options[idx];
1422
+ opt?.onClick(editor);
1423
+ }
1424
+ },
1425
+ children: /* @__PURE__ */ jsx(ToolbarDropdownTrigger, { children: triggerLabel })
1426
+ }
1427
+ );
1428
+ }
1429
+
1430
+ // src/editor/toolbar/filterToolbarItems.ts
1431
+ function filterToolbarItems(items, toolbar) {
1432
+ let result = items;
1433
+ const include = toolbar?.groups;
1434
+ const exclude = toolbar?.excludeGroups;
1435
+ if (include && include.length > 0) {
1436
+ const includeSet = new Set(include);
1437
+ result = result.filter((item) => includeSet.has(item.group));
1438
+ }
1439
+ if (exclude && exclude.length > 0) {
1440
+ const excludeSet = new Set(exclude);
1441
+ result = result.filter((item) => !excludeSet.has(item.group));
1442
+ }
1443
+ return result;
1444
+ }
1445
+ var TOOLBAR_RERENDER_EVENTS = ["transaction", "selectionUpdate", "focus", "blur"];
1446
+ function renderToolbarItem(item, editor) {
1447
+ switch (item.type) {
1448
+ case "button":
1449
+ return /* @__PURE__ */ jsx(ToolbarButton, { item, editor });
1450
+ case "dropdown":
1451
+ return /* @__PURE__ */ jsx(ToolbarDropdown, { item, editor });
1452
+ case "divider":
1453
+ return /* @__PURE__ */ jsx(ToolbarDivider, {});
1454
+ case "color-picker":
1455
+ return /* @__PURE__ */ jsx(ColorPickerButton, { item, editor });
1456
+ case "table-grid":
1457
+ return /* @__PURE__ */ jsx(TableInsertMenu, { item, editor });
1458
+ case "custom":
1459
+ return /* @__PURE__ */ jsx(Fragment, { children: item.render?.(editor) });
1460
+ default:
1461
+ return null;
1462
+ }
1463
+ }
1464
+ function renderToolbarItems(items, editor) {
1465
+ const nodes = [];
1466
+ let currentGroup = null;
1467
+ items.forEach((item) => {
1468
+ if (currentGroup !== null && item.group !== currentGroup) {
1469
+ nodes.push(/* @__PURE__ */ jsx(ToolbarDivider, {}, `divider-before-${item.group}`));
1470
+ }
1471
+ currentGroup = item.group;
1472
+ nodes.push(/* @__PURE__ */ jsx(Fragment, { children: renderToolbarItem(item, editor) }, item.id));
1473
+ });
1474
+ return nodes;
1475
+ }
1476
+ function ToolbarBase({ toolbar }) {
1477
+ const { editor, registry } = useEditorContext();
1478
+ const { styles } = useToolbarStyles();
1479
+ const toolbarVersion = useEditorRerenderOn(editor, TOOLBAR_RERENDER_EVENTS);
1480
+ const items = useMemo(
1481
+ () => filterToolbarItems(registry?.buildToolbarItems() ?? [], toolbar),
1482
+ [registry, toolbar, toolbarVersion]
1483
+ );
1484
+ if (!editor) {
1485
+ return /* @__PURE__ */ jsx("div", { className: styles.toolbar });
1486
+ }
1487
+ return /* @__PURE__ */ jsx("div", { className: styles.toolbar, children: /* @__PURE__ */ jsx("div", { className: styles.toolbarGroup, children: renderToolbarItems(items, editor) }) });
1488
+ }
1489
+ var Toolbar = memo(ToolbarBase);
1490
+
1491
+ // src/editor/plugins/builtin/table/tableControlStyle.ts
1492
+ var useTableControlStyles = createStyles(({ css, token, sizeToken, glassEffect, getAlphaColor }) => {
1493
+ const { borderRadius } = sizeToken;
1494
+ return {
1495
+ /** hover 浮层根容器,绝对定位到编辑器滚动容器内 */
1496
+ overlay: css`
1497
+ position: absolute;
1498
+ top: 0;
1499
+ left: 0;
1500
+ width: 0;
1501
+ height: 0;
1502
+ pointer-events: none;
1503
+ z-index: 50;
1504
+ `,
1505
+ /** 菜单容器:一排按钮的浮动条(毛玻璃表面见 glassSurfaceCss,圆角 +2) */
1506
+ menu: css`
1507
+ display: flex;
1508
+ align-items: center;
1509
+ gap: 2px;
1510
+ padding: 4px;
1511
+ ${glassSurfaceCss({ token, glassEffect, getAlphaColor, borderRadius: borderRadius + 2 })}
1512
+ `,
1513
+ /** hover 工具栏在 menu 基础上的定位增量(覆盖 overlay 的 pointer-events:none) */
1514
+ hoverToolbar: css`
1515
+ position: absolute;
1516
+ pointer-events: auto;
1517
+ z-index: 52;
1518
+ `,
1519
+ /** 图标按钮(28px,选区浮动菜单尺寸) */
1520
+ button: css`
1521
+ display: inline-flex;
1522
+ align-items: center;
1523
+ justify-content: center;
1524
+ width: 28px;
1525
+ height: 28px;
1526
+ padding: 0;
1527
+ border: none;
1528
+ border-radius: ${borderRadius}px;
1529
+ background: transparent;
1530
+ color: ${token.colorText};
1531
+ cursor: pointer;
1532
+ font-size: 15px;
1533
+ transition: background 0.15s;
1534
+
1535
+ &:hover:not(:disabled) {
1536
+ background: ${token.colorFillSecondary};
1537
+ }
1538
+
1539
+ &:disabled {
1540
+ color: ${token.colorTextDisabled};
1541
+ cursor: not-allowed;
1542
+ }
1543
+ `,
1544
+ /** 图标按钮尺寸增量(26px,hover 工具栏尺寸),与 button 组合使用 */
1545
+ buttonSm: css`
1546
+ width: 26px;
1547
+ height: 26px;
1548
+ font-size: 14px;
1549
+ `,
1550
+ danger: css`
1551
+ &:hover:not(:disabled) {
1552
+ color: ${token.colorError};
1553
+ background: ${token.colorErrorBg};
1554
+ }
1555
+ `,
1556
+ /** 工具栏分割线 */
1557
+ divider: css`
1558
+ width: 1px;
1559
+ height: 18px;
1560
+ background: ${token.colorBorderSecondary};
1561
+ margin: 0 2px;
1562
+ flex-shrink: 0;
1563
+ `,
1564
+ /** 工具栏文字按钮(列等宽/自适应等) */
1565
+ textButton: css`
1566
+ display: inline-flex;
1567
+ align-items: center;
1568
+ justify-content: center;
1569
+ height: 26px;
1570
+ padding: 0 8px;
1571
+ border: none;
1572
+ border-radius: ${borderRadius}px;
1573
+ background: transparent;
1574
+ color: ${token.colorTextSecondary};
1575
+ cursor: pointer;
1576
+ font-size: 12px;
1577
+ white-space: nowrap;
1578
+ transition:
1579
+ background 0.15s,
1580
+ color 0.15s;
1581
+
1582
+ &:hover:not(:disabled) {
1583
+ background: ${token.colorFillSecondary};
1584
+ color: ${token.colorText};
1585
+ }
1586
+ `
1587
+ };
1588
+ });
1589
+ var ROW_RESIZE_BAR = 6;
1590
+ var MIN_ROW_HEIGHT = 24;
1591
+ function RowResizeHandles({
1592
+ editor,
1593
+ rows,
1594
+ onResized
1595
+ }) {
1596
+ const detachDragListenersRef = useRef(null);
1597
+ useEffect(
1598
+ () => () => {
1599
+ const session = detachDragListenersRef.current;
1600
+ detachDragListenersRef.current = null;
1601
+ session?.detach();
1602
+ session?.restorePreview();
1603
+ },
1604
+ []
1605
+ );
1606
+ const handleRowResizeStart = useCallback(
1607
+ (e, handle) => {
1608
+ e.preventDefault();
1609
+ e.stopPropagation();
1610
+ const startY = e.clientY;
1611
+ const startHeight = handle.height;
1612
+ const rowDom = editor.view.nodeDOM(handle.rowPos);
1613
+ const compute = (clientY) => Math.max(MIN_ROW_HEIGHT, Math.round(startHeight + (clientY - startY)));
1614
+ const onMove = (ev) => {
1615
+ if (rowDom) rowDom.style.height = `${compute(ev.clientY)}px`;
1616
+ };
1617
+ const onUp = (ev) => {
1618
+ detachDragListenersRef.current?.detach();
1619
+ detachDragListenersRef.current = null;
1620
+ const next = compute(ev.clientY);
1621
+ if (editor.isDestroyed) return;
1622
+ editor.chain().command(({ tr: tr2 }) => {
1623
+ tr2.setNodeAttribute(handle.rowPos, "rowHeight", next);
1624
+ return true;
1625
+ }).run();
1626
+ onResized();
1627
+ };
1628
+ window.addEventListener("mousemove", onMove);
1629
+ window.addEventListener("mouseup", onUp);
1630
+ detachDragListenersRef.current = {
1631
+ detach: () => {
1632
+ window.removeEventListener("mousemove", onMove);
1633
+ window.removeEventListener("mouseup", onUp);
1634
+ },
1635
+ // 预览高度还原为拖前值(仅卸载清理路径调用;正常 mouseup 经事务写入新 rowHeight)。
1636
+ restorePreview: () => {
1637
+ if (rowDom) rowDom.style.height = `${startHeight}px`;
1638
+ }
1639
+ };
1640
+ },
1641
+ [editor, onResized]
1642
+ );
1643
+ return /* @__PURE__ */ jsx(Fragment$1, { children: rows.map((handle) => /* @__PURE__ */ jsx(
1644
+ "div",
1645
+ {
1646
+ role: "separator",
1647
+ "aria-label": tr("\u62D6\u52A8\u8C03\u6574\u884C\u9AD8"),
1648
+ title: tr("\u62D6\u52A8\u8C03\u6574\u884C\u9AD8"),
1649
+ onMouseDown: (e) => handleRowResizeStart(e, handle),
1650
+ style: {
1651
+ position: "absolute",
1652
+ left: handle.left,
1653
+ top: handle.top - ROW_RESIZE_BAR / 2,
1654
+ width: handle.width,
1655
+ height: ROW_RESIZE_BAR,
1656
+ cursor: "row-resize",
1657
+ zIndex: 5
1658
+ }
1659
+ },
1660
+ handle.rowPos
1661
+ )) });
1662
+ }
1663
+ var TOOLBAR_HEIGHT = 32;
1664
+ var TOOLBAR_GAP = 2;
1665
+ var TOOLBAR_ALIGN_MARGIN = 24;
1666
+ var TOOLBAR_ZONE_PAD = 4;
1667
+ var ZONE_PAD_LEFT = 22;
1668
+ var ZONE_PAD_RIGHT = 28;
1669
+ var ZONE_PAD_BOTTOM = 28;
1670
+ var ZONE_PAD_TOP = TOOLBAR_HEIGHT + TOOLBAR_GAP + 4;
1671
+ function isInTableExtendedZone(rect, x, y) {
1672
+ return x >= rect.left - ZONE_PAD_LEFT && x <= rect.right + ZONE_PAD_RIGHT && y >= rect.top - ZONE_PAD_TOP && y <= rect.bottom + ZONE_PAD_BOTTOM;
1673
+ }
1674
+ function isOverlayEqual(a, b) {
1675
+ if (a.toolbar?.x !== b.toolbar?.x || a.toolbar?.y !== b.toolbar?.y) return false;
1676
+ if (a.toolbar?.align !== b.toolbar?.align) return false;
1677
+ if (a.rows.length !== b.rows.length) return false;
1678
+ for (let i = 0; i < a.rows.length; i += 1) {
1679
+ const ra = a.rows[i];
1680
+ const rb = b.rows[i];
1681
+ if (ra.top !== rb.top || ra.left !== rb.left || ra.width !== rb.width || ra.rowPos !== rb.rowPos || ra.height !== rb.height) {
1682
+ return false;
1683
+ }
1684
+ }
1685
+ return true;
1686
+ }
1687
+ function useTableHoverGeometry(editor, toolbarRef) {
1688
+ const scrollContainerRef = useRef(null);
1689
+ const computeTableRect = useCallback((table) => {
1690
+ const container = scrollContainerRef.current;
1691
+ if (!container) return null;
1692
+ const tableRect = table.getBoundingClientRect();
1693
+ const containerRect = container.getBoundingClientRect();
1694
+ return {
1695
+ left: tableRect.left - containerRect.left + container.scrollLeft,
1696
+ top: tableRect.top - containerRect.top + container.scrollTop,
1697
+ width: tableRect.width,
1698
+ height: tableRect.height
1699
+ };
1700
+ }, []);
1701
+ const getRowPos = useCallback(
1702
+ (rowEl) => {
1703
+ try {
1704
+ return findAncestor(editor.view.state.doc, editor.view.posAtDOM(rowEl, 0), ["tableRow"])?.pos ?? null;
1705
+ } catch {
1706
+ return null;
1707
+ }
1708
+ },
1709
+ [editor]
1710
+ );
1711
+ const computeRowHandles = useCallback(
1712
+ (table) => {
1713
+ const container = scrollContainerRef.current;
1714
+ if (!container) return [];
1715
+ const containerRect = container.getBoundingClientRect();
1716
+ const handles = [];
1717
+ for (let i = 0; i < table.rows.length; i += 1) {
1718
+ const rowEl = table.rows[i];
1719
+ const rowPos = getRowPos(rowEl);
1720
+ if (rowPos == null) continue;
1721
+ const r = rowEl.getBoundingClientRect();
1722
+ handles.push({
1723
+ top: r.bottom - containerRect.top + container.scrollTop,
1724
+ left: r.left - containerRect.left + container.scrollLeft,
1725
+ width: r.width,
1726
+ rowPos,
1727
+ height: Math.round(r.height)
1728
+ });
1729
+ }
1730
+ return handles;
1731
+ },
1732
+ [getRowPos]
1733
+ );
1734
+ const isInToolbarZone = useCallback(
1735
+ (x, y) => {
1736
+ const toolbarEl = toolbarRef.current;
1737
+ if (!toolbarEl) return false;
1738
+ const rect = toolbarEl.getBoundingClientRect();
1739
+ return x >= rect.left - TOOLBAR_ZONE_PAD && x <= rect.right + TOOLBAR_ZONE_PAD && y >= rect.top - TOOLBAR_ZONE_PAD && y <= rect.bottom + TOOLBAR_ZONE_PAD;
1740
+ },
1741
+ [toolbarRef]
1742
+ );
1743
+ return { scrollContainerRef, computeTableRect, computeRowHandles, isInToolbarZone };
1744
+ }
1745
+ var DATA_TABLE_KEEP_IDS = /* @__PURE__ */ new Set(["add-row-below", "delete-row", "equal-width", "auto-fit", "delete-table"]);
1746
+ var LOCKED_TEMPLATE_DROP_IDS = /* @__PURE__ */ new Set([
1747
+ "add-row-above",
1748
+ "add-row-below",
1749
+ "delete-row",
1750
+ "add-column-before",
1751
+ "add-column-after",
1752
+ "delete-column",
1753
+ "merge-cells",
1754
+ "split-cells",
1755
+ "toggle-header"
1756
+ ]);
1757
+ function filterToolbarItemsFor(items, dataMode, structureLocked) {
1758
+ let kept = items;
1759
+ if (dataMode) {
1760
+ kept = items.filter((item) => item.kind === "divider" || DATA_TABLE_KEEP_IDS.has(item.id));
1761
+ } else if (structureLocked) {
1762
+ kept = items.filter((item) => !LOCKED_TEMPLATE_DROP_IDS.has(item.id));
1763
+ }
1764
+ return kept.filter((item, i) => {
1765
+ if (item.kind !== "divider") return true;
1766
+ const prev = kept[i - 1];
1767
+ const next = kept[i + 1];
1768
+ return !!prev && prev.kind !== "divider" && !!next && next.kind !== "divider";
1769
+ });
1770
+ }
1771
+ function buildToolbarItems(handlers, can) {
1772
+ return [
1773
+ {
1774
+ id: "add-row-above",
1775
+ kind: "icon",
1776
+ icon: /* @__PURE__ */ jsx(InsertRowAboveOutlined, {}),
1777
+ label: tr("\u4E0A\u65B9\u63D2\u5165\u884C"),
1778
+ disabled: !can.addRowAbove,
1779
+ onClick: handlers.addRowBefore
1780
+ },
1781
+ {
1782
+ id: "add-row-below",
1783
+ kind: "icon",
1784
+ icon: /* @__PURE__ */ jsx(InsertRowBelowOutlined, {}),
1785
+ label: tr("\u4E0B\u65B9\u63D2\u5165\u884C"),
1786
+ disabled: !can.addRowBelow,
1787
+ onClick: handlers.addRowAfter
1788
+ },
1789
+ {
1790
+ id: "delete-row",
1791
+ kind: "icon",
1792
+ icon: /* @__PURE__ */ jsx(DeleteRowOutlined, {}),
1793
+ label: tr("\u5220\u9664\u884C"),
1794
+ danger: true,
1795
+ disabled: !can.deleteRow,
1796
+ onClick: handlers.deleteRow
1797
+ },
1798
+ { id: "divider-rows", kind: "divider" },
1799
+ {
1800
+ id: "add-column-before",
1801
+ kind: "icon",
1802
+ icon: /* @__PURE__ */ jsx(InsertRowLeftOutlined, {}),
1803
+ label: tr("\u5DE6\u4FA7\u63D2\u5165\u5217"),
1804
+ disabled: !can.addColLeft,
1805
+ onClick: handlers.addColumnBefore
1806
+ },
1807
+ {
1808
+ id: "add-column-after",
1809
+ kind: "icon",
1810
+ icon: /* @__PURE__ */ jsx(InsertRowRightOutlined, {}),
1811
+ label: tr("\u53F3\u4FA7\u63D2\u5165\u5217"),
1812
+ disabled: !can.addColRight,
1813
+ onClick: handlers.addColumnAfter
1814
+ },
1815
+ {
1816
+ id: "delete-column",
1817
+ kind: "icon",
1818
+ icon: /* @__PURE__ */ jsx(DeleteColumnOutlined, {}),
1819
+ label: tr("\u5220\u9664\u5217"),
1820
+ danger: true,
1821
+ disabled: !can.deleteColumn,
1822
+ onClick: handlers.deleteColumn
1823
+ },
1824
+ { id: "divider-cols", kind: "divider" },
1825
+ {
1826
+ id: "merge-cells",
1827
+ kind: "icon",
1828
+ icon: /* @__PURE__ */ jsx(MergeCellsOutlined, {}),
1829
+ label: tr("\u5408\u5E76\u5355\u5143\u683C"),
1830
+ disabled: !can.merge,
1831
+ onClick: handlers.mergeCells
1832
+ },
1833
+ {
1834
+ id: "split-cells",
1835
+ kind: "icon",
1836
+ icon: /* @__PURE__ */ jsx(SplitCellsOutlined, {}),
1837
+ label: tr("\u62C6\u5206\u5355\u5143\u683C"),
1838
+ disabled: !can.split,
1839
+ onClick: handlers.splitCells
1840
+ },
1841
+ { id: "divider-merge", kind: "divider" },
1842
+ {
1843
+ id: "toggle-header",
1844
+ kind: "icon",
1845
+ icon: /* @__PURE__ */ jsx(BorderOutlined, {}),
1846
+ label: tr("\u5207\u6362\u8868\u5934\u884C"),
1847
+ templateDisabledLabel: tr("\u6A21\u677F\u8868\u683C\u4E0D\u53EF\u5207\u6362\u8868\u5934"),
1848
+ disabledForTemplate: true,
1849
+ onClick: handlers.toggleHeaderRow
1850
+ },
1851
+ {
1852
+ id: "equal-width",
1853
+ kind: "text",
1854
+ text: tr("\u5217\u7B49\u5BBD"),
1855
+ label: tr("\u5217\u7B49\u5BBD"),
1856
+ onClick: handlers.equalColumnWidth
1857
+ },
1858
+ {
1859
+ id: "auto-fit",
1860
+ kind: "text",
1861
+ text: tr("\u81EA\u9002\u5E94"),
1862
+ label: tr("\u81EA\u9002\u5E94\u5BBD\u5EA6"),
1863
+ onClick: handlers.autoFitWidth
1864
+ },
1865
+ { id: "divider-table", kind: "divider" },
1866
+ {
1867
+ id: "delete-table",
1868
+ kind: "icon",
1869
+ icon: /* @__PURE__ */ jsx(DeleteOutlined, {}),
1870
+ label: tr("\u5220\u9664\u8868\u683C"),
1871
+ templateDisabledLabel: tr("\u6A21\u677F\u8868\u683C\u4E0D\u53EF\u5220\u9664"),
1872
+ disabledForTemplate: true,
1873
+ danger: true,
1874
+ onClick: handlers.deleteTable
1875
+ }
1876
+ ];
1877
+ }
1878
+ function HoverToolbarButton({
1879
+ item,
1880
+ templateDisabled
1881
+ }) {
1882
+ const { styles, cx } = useTableControlStyles();
1883
+ const disabled = !!item.disabledForTemplate && templateDisabled || item.disabled === true;
1884
+ const tip = disabled && item.templateDisabledLabel ? item.templateDisabledLabel : item.label;
1885
+ return /* @__PURE__ */ jsx(Tooltip, { title: tip, children: /* @__PURE__ */ jsx(
1886
+ "button",
1887
+ {
1888
+ type: "button",
1889
+ "aria-label": item.label,
1890
+ className: item.kind === "icon" ? cx(styles.button, styles.buttonSm, item.danger && styles.danger) : styles.textButton,
1891
+ disabled,
1892
+ onMouseDown: (e) => e.preventDefault(),
1893
+ onClick: item.onClick,
1894
+ children: item.kind === "icon" ? item.icon : item.text
1895
+ }
1896
+ ) });
1897
+ }
1898
+ function TableHoverControls({ editor }) {
1899
+ const { styles, cx } = useTableControlStyles();
1900
+ const overlayRef = useRef(null);
1901
+ const toolbarRef = useRef(null);
1902
+ const { scrollContainerRef, computeTableRect, computeRowHandles, isInToolbarZone } = useTableHoverGeometry(
1903
+ editor,
1904
+ toolbarRef
1905
+ );
1906
+ const [overlay, setOverlay] = useState({ toolbar: null, rows: [] });
1907
+ const [isTemplateTable, setIsTemplateTable] = useState(false);
1908
+ const hoveredTableRef = useRef(null);
1909
+ const hoveredCellRef = useRef(null);
1910
+ const [, forceUpdate] = useReducer((x) => x + 1, 0);
1911
+ const rafIdRef = useRef(0);
1912
+ const refreshTimerRef = useRef(null);
1913
+ const updateOverlay = useCallback(() => {
1914
+ cancelAnimationFrame(rafIdRef.current);
1915
+ rafIdRef.current = requestAnimationFrame(() => {
1916
+ const table = hoveredTableRef.current;
1917
+ if (!table) {
1918
+ setOverlay((prev) => prev.toolbar === null && prev.rows.length === 0 ? prev : { toolbar: null, rows: [] });
1919
+ return;
1920
+ }
1921
+ const rect = computeTableRect(table);
1922
+ if (!rect) return;
1923
+ const templateTable = isTemplateTableEl(table);
1924
+ setIsTemplateTable(templateTable);
1925
+ let align = "right";
1926
+ const toolbarEl = toolbarRef.current;
1927
+ if (toolbarEl) {
1928
+ const toolbarWidth = toolbarEl.getBoundingClientRect().width;
1929
+ if (rect.width < toolbarWidth + TOOLBAR_ALIGN_MARGIN) align = "left";
1930
+ }
1931
+ const next = {
1932
+ toolbar: {
1933
+ x: align === "left" ? rect.left : rect.left + rect.width,
1934
+ // 上移到表格上边缘之外:配合渲染层 translateY(-100%)(按自身高度整体上移),
1935
+ // 使工具栏底边贴在表格顶边上方 TOOLBAR_GAP 处,不再压住表头行
1936
+ y: rect.top - TOOLBAR_GAP,
1937
+ align
1938
+ },
1939
+ // 仅锁定模板表格显示行高拖拽条(普通表格不介入行高控制)。
1940
+ rows: templateTable ? computeRowHandles(table) : []
1941
+ };
1942
+ setOverlay((prev) => isOverlayEqual(prev, next) ? prev : next);
1943
+ });
1944
+ }, [computeTableRect, computeRowHandles]);
1945
+ const scheduleOverlayRefresh = useCallback(() => {
1946
+ if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current);
1947
+ refreshTimerRef.current = setTimeout(() => {
1948
+ refreshTimerRef.current = null;
1949
+ updateOverlay();
1950
+ }, 0);
1951
+ }, [updateOverlay]);
1952
+ const hideOverlay = useCallback(() => {
1953
+ hoveredTableRef.current = null;
1954
+ hoveredCellRef.current = null;
1955
+ setOverlay((prev) => prev.toolbar === null && prev.rows.length === 0 ? prev : { toolbar: null, rows: [] });
1956
+ }, []);
1957
+ const getHoverCellPos = useCallback(() => {
1958
+ const cellEl = hoveredCellRef.current;
1959
+ const tableEl = hoveredTableRef.current;
1960
+ if (!cellEl || !tableEl?.contains(cellEl)) return null;
1961
+ try {
1962
+ return editor.view.posAtDOM(cellEl, 0);
1963
+ } catch {
1964
+ return null;
1965
+ }
1966
+ }, [editor]);
1967
+ const { handleToggleHeaderRow, handleDeleteTable, handleEqualColumnWidth, handleAutoFitWidth } = useTableActions({
1968
+ editor,
1969
+ hoveredTableRef,
1970
+ scheduleOverlayRefresh,
1971
+ onTableDeleted: hideOverlay
1972
+ });
1973
+ const {
1974
+ context: rowColContext,
1975
+ can: rowColCan,
1976
+ handleAddRowBefore,
1977
+ handleAddRowAfter,
1978
+ handleDeleteRow,
1979
+ handleAddColumnBefore,
1980
+ handleAddColumnAfter,
1981
+ handleDeleteColumn,
1982
+ handleMergeCells,
1983
+ handleSplitCells
1984
+ } = useTableRowColActions({ editor, hoveredTableRef, hoverCellPos: getHoverCellPos(), scheduleOverlayRefresh });
1985
+ const findClosestTable = useCallback(
1986
+ (el) => {
1987
+ if (!el) return null;
1988
+ const editorDom = editor.view.dom;
1989
+ if (!editorDom.contains(el)) return null;
1990
+ let current = el;
1991
+ while (current && current !== editorDom) {
1992
+ if (current.tagName === "TABLE") return current;
1993
+ if (current.classList?.contains("tableWrapper")) {
1994
+ return current.querySelector("table");
1995
+ }
1996
+ current = current.parentElement;
1997
+ }
1998
+ return null;
1999
+ },
2000
+ [editor]
2001
+ );
2002
+ const handleMouseMove = useCallback(
2003
+ (e) => {
2004
+ if (!editor.isEditable) return;
2005
+ const target = e.target;
2006
+ if (!target) return;
2007
+ if (overlayRef.current?.contains(target)) return;
2008
+ const table = findClosestTable(target);
2009
+ if (!table) {
2010
+ const hoveredTable = hoveredTableRef.current;
2011
+ if (hoveredTable) {
2012
+ const rect = hoveredTable.getBoundingClientRect();
2013
+ if (!isInTableExtendedZone(rect, e.clientX, e.clientY) && !isInToolbarZone(e.clientX, e.clientY)) {
2014
+ hideOverlay();
2015
+ }
2016
+ }
2017
+ return;
2018
+ }
2019
+ if (table !== hoveredTableRef.current) {
2020
+ hoveredTableRef.current = table;
2021
+ hoveredCellRef.current = null;
2022
+ }
2023
+ const cellEl = target.closest("td,th");
2024
+ if (cellEl && table.contains(cellEl) && cellEl !== hoveredCellRef.current) {
2025
+ hoveredCellRef.current = cellEl;
2026
+ forceUpdate();
2027
+ }
2028
+ updateOverlay();
2029
+ },
2030
+ [editor, findClosestTable, updateOverlay, isInToolbarZone, hideOverlay]
2031
+ );
2032
+ const handleMouseLeave = useCallback(
2033
+ (e) => {
2034
+ const related = e.relatedTarget;
2035
+ if (related && overlayRef.current?.contains(related)) return;
2036
+ hideOverlay();
2037
+ },
2038
+ [hideOverlay]
2039
+ );
2040
+ const handleMouseOut = useCallback(
2041
+ (e) => {
2042
+ const related = e.relatedTarget;
2043
+ const table = hoveredTableRef.current;
2044
+ if (!table) return;
2045
+ if (related && overlayRef.current?.contains(related)) return;
2046
+ const stillInTable = table.contains(related || e.target);
2047
+ const inZone = isInTableExtendedZone(table.getBoundingClientRect(), e.clientX, e.clientY);
2048
+ if (!stillInTable && !inZone && !isInToolbarZone(e.clientX, e.clientY)) {
2049
+ hideOverlay();
2050
+ }
2051
+ },
2052
+ [isInToolbarZone, hideOverlay]
2053
+ );
2054
+ useEffect(() => {
2055
+ const editorDom = editor.view.dom;
2056
+ const container = editorDom.closest("[data-idocs-scroll-container]");
2057
+ scrollContainerRef.current = container;
2058
+ const eventDom = container ?? editorDom;
2059
+ eventDom.addEventListener("mousemove", handleMouseMove);
2060
+ eventDom.addEventListener("mouseout", handleMouseOut);
2061
+ eventDom.addEventListener("mouseleave", handleMouseLeave);
2062
+ container?.addEventListener("scroll", updateOverlay, { passive: true });
2063
+ const onTransaction = ({ transaction: tr2 }) => {
2064
+ scheduleOverlayRefresh();
2065
+ if (tr2.selectionSet || tr2.docChanged) forceUpdate();
2066
+ };
2067
+ editor.on("transaction", onTransaction);
2068
+ return () => {
2069
+ eventDom.removeEventListener("mousemove", handleMouseMove);
2070
+ eventDom.removeEventListener("mouseout", handleMouseOut);
2071
+ eventDom.removeEventListener("mouseleave", handleMouseLeave);
2072
+ container?.removeEventListener("scroll", updateOverlay);
2073
+ editor.off("transaction", onTransaction);
2074
+ cancelAnimationFrame(rafIdRef.current);
2075
+ if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current);
2076
+ };
2077
+ }, [editor, handleMouseMove, handleMouseOut, handleMouseLeave, updateOverlay, scheduleOverlayRefresh, forceUpdate]);
2078
+ const toolbarItems = buildToolbarItems(
2079
+ {
2080
+ addRowBefore: handleAddRowBefore,
2081
+ addRowAfter: handleAddRowAfter,
2082
+ deleteRow: handleDeleteRow,
2083
+ addColumnBefore: handleAddColumnBefore,
2084
+ addColumnAfter: handleAddColumnAfter,
2085
+ deleteColumn: handleDeleteColumn,
2086
+ mergeCells: handleMergeCells,
2087
+ splitCells: handleSplitCells,
2088
+ toggleHeaderRow: handleToggleHeaderRow,
2089
+ deleteTable: handleDeleteTable,
2090
+ equalColumnWidth: handleEqualColumnWidth,
2091
+ autoFitWidth: handleAutoFitWidth
2092
+ },
2093
+ rowColCan
2094
+ );
2095
+ const visibleItems = filterToolbarItemsFor(
2096
+ toolbarItems,
2097
+ rowColContext.mode === "data",
2098
+ rowColContext.inProtected && rowColContext.mode !== "data"
2099
+ );
2100
+ return /* @__PURE__ */ jsxs("div", { ref: overlayRef, className: styles.overlay, children: [
2101
+ overlay.toolbar && /* @__PURE__ */ jsx(
2102
+ "div",
2103
+ {
2104
+ ref: toolbarRef,
2105
+ className: cx(styles.menu, styles.hoverToolbar),
2106
+ style: {
2107
+ left: overlay.toolbar.x,
2108
+ top: overlay.toolbar.y,
2109
+ transform: overlay.toolbar.align === "left" ? "translate(0, -100%)" : "translate(-100%, -100%)"
2110
+ },
2111
+ children: visibleItems.map(
2112
+ (item) => item.kind === "divider" ? /* @__PURE__ */ jsx("div", { className: styles.divider }, item.id) : /* @__PURE__ */ jsx(HoverToolbarButton, { item, templateDisabled: isTemplateTable }, item.id)
2113
+ )
2114
+ }
2115
+ ),
2116
+ /* @__PURE__ */ jsx(RowResizeHandles, { editor, rows: overlay.rows, onResized: scheduleOverlayRefresh })
2117
+ ] });
2118
+ }
2119
+
2120
+ // src/editor/styles/editorStyles.ts
2121
+ var useEditorStyles = createStyles(({ css, token, sizeToken, getAlphaColor }) => {
2122
+ const { paddingContentHorizontal, paddingContentVertical, fontSize, borderRadius } = sizeToken;
2123
+ const pa = (alpha) => getAlphaColor(token.colorPrimary, alpha);
2124
+ const ctx = {
2125
+ token,
2126
+ getAlphaColor,
2127
+ pa,
2128
+ borderRadius,
2129
+ paddingContentHorizontal,
2130
+ paddingContentVertical,
2131
+ fontSize,
2132
+ mode: "editor",
2133
+ sel: createCssScope(".tiptap", ".tiptap")
2134
+ };
2135
+ return {
2136
+ editorWrapper: css`
2137
+ position: relative;
2138
+ display: flex;
2139
+ flex-direction: column;
2140
+ height: 100%;
2141
+ overflow: hidden;
2142
+ /* 框架 CSS 变量自切换:毛玻璃态为 40% 透明容器色,传统态为不透明 colorBgContainer */
2143
+ background: var(--colorBgAlphaColorContainer, ${token.colorBgContainer});
2144
+ /* 毛玻璃态模糊背景(传统态 --glass-blur 为 blur(0px),无视觉差异) */
2145
+ backdrop-filter: var(--glass-blur, none);
2146
+ `,
2147
+ /** 在线协作者头像徽标锚点:定位在编辑器右上角。 */
2148
+ onlineBadgeAnchor: css`
2149
+ position: absolute;
2150
+ top: ${paddingContentVertical / 2}px;
2151
+ right: ${paddingContentHorizontal / 2}px;
2152
+ z-index: 10;
2153
+ `,
2154
+ editorContent: css`
2155
+ position: relative;
2156
+ flex: 1;
2157
+ overflow-y: auto;
2158
+ padding: ${paddingContentVertical}px ${paddingContentHorizontal}px;
2159
+ /* 背景由 editorWrapper 提供(毛玻璃态透出玻璃质感),此处透明避免遮盖 */
2160
+ background: transparent;
2161
+
2162
+ .tiptap {
2163
+ outline: none;
2164
+ min-height: 100%;
2165
+ font-size: ${fontSize + 2}px;
2166
+ line-height: 1.75;
2167
+ color: ${token.colorText};
2168
+ /* 为块左侧拖拽手柄预留装订线(drag-handle 插件手柄定位在块左缘 -25px 槽位,
2169
+ 即这段 26px padding 内),避免手柄压住正文 */
2170
+ padding-left: 26px;
2171
+ }
2172
+
2173
+ ${templateCss(ctx)}
2174
+ ${typographyCss(ctx)}
2175
+ ${codeBlockCss(ctx)}
2176
+ ${tableCss(ctx)}
2177
+ ${fixedTableCss(ctx)}
2178
+ `
2179
+ };
2180
+ });
2181
+ function EditorBody(props) {
2182
+ const {
2183
+ registry,
2184
+ content,
2185
+ editable,
2186
+ mode,
2187
+ collabExtensions,
2188
+ onUpdate,
2189
+ onEditorReady,
2190
+ showToolbar,
2191
+ toolbar,
2192
+ collaboration,
2193
+ className,
2194
+ style
2195
+ } = props;
2196
+ const { ydoc, provider } = useCollaboration();
2197
+ const { editor, editorRef } = useEditorInstance({
2198
+ registry,
2199
+ content: collaboration ? void 0 : content,
2200
+ editable,
2201
+ collabExtensions,
2202
+ onUpdate,
2203
+ onEditorReady
2204
+ });
2205
+ const contentRef = useRef(content);
2206
+ contentRef.current = content;
2207
+ const hasContent = !!content;
2208
+ useEffect(() => {
2209
+ if (!collaboration || !editor || !ydoc || !provider) return;
2210
+ let disposed = false;
2211
+ let initTimer = null;
2212
+ const maybeInitialize = () => {
2213
+ if (disposed) return;
2214
+ initializeEmptyCollaborationDocument({
2215
+ editor,
2216
+ ydoc,
2217
+ provider,
2218
+ content: contentRef.current
2219
+ });
2220
+ };
2221
+ const scheduleInitialize = () => {
2222
+ if (initTimer) {
2223
+ clearTimeout(initTimer);
2224
+ }
2225
+ initTimer = setTimeout(maybeInitialize, 0);
2226
+ };
2227
+ const handleSynced = ({ state = true } = {}) => {
2228
+ if (state) {
2229
+ scheduleInitialize();
2230
+ }
2231
+ };
2232
+ provider.on("synced", handleSynced);
2233
+ if (provider.synced) {
2234
+ scheduleInitialize();
2235
+ }
2236
+ return () => {
2237
+ disposed = true;
2238
+ if (initTimer) {
2239
+ clearTimeout(initTimer);
2240
+ }
2241
+ provider.off("synced", handleSynced);
2242
+ };
2243
+ }, [collaboration, editor, ydoc, provider, hasContent]);
2244
+ const { styles, cx } = useEditorStyles();
2245
+ const hasTableExtension = editor?.extensionManager.extensions.some((ext) => ext.name === "table");
2246
+ const contextValue = useMemo(
2247
+ () => ({
2248
+ editor,
2249
+ registry
2250
+ }),
2251
+ [editor, registry]
2252
+ );
2253
+ return /* @__PURE__ */ jsx(EditorContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxs(
2254
+ "div",
2255
+ {
2256
+ className: cx(styles.editorWrapper, className),
2257
+ style,
2258
+ "data-idocs-editor-mode": mode,
2259
+ children: [
2260
+ collaboration && /* @__PURE__ */ jsx(UserCursorStyles, {}),
2261
+ showToolbar && /* @__PURE__ */ jsx(Toolbar, { toolbar }),
2262
+ /* @__PURE__ */ jsxs("div", { className: styles.editorContent, "data-idocs-scroll-container": true, ref: editorRef, children: [
2263
+ /* @__PURE__ */ jsx(EditorContent, { editor }),
2264
+ editor && hasTableExtension && mode !== "readonly" && /* @__PURE__ */ jsx(TableHoverControls, { editor })
2265
+ ] }),
2266
+ /* @__PURE__ */ jsx(EditorStatusBar, { editor, collaborationEnabled: collaboration }),
2267
+ collaboration && /* @__PURE__ */ jsx("div", { className: styles.onlineBadgeAnchor, children: /* @__PURE__ */ jsx(OnlineUsersBadge, {}) })
2268
+ ]
2269
+ }
2270
+ ) });
2271
+ }
2272
+ function useCollaborationExtensions(options) {
2273
+ const { collabConfig, collabResources, currentUser } = options;
2274
+ const collabUser = collabConfig ? currentUser ?? collabConfig.user ?? getAnonymousUser() : null;
2275
+ const collabUserSignature = collabUser ? JSON.stringify([collabUser.id ?? null, collabUser.name, collabUser.color, collabUser.avatar ?? null]) : "";
2276
+ return useMemo(() => {
2277
+ if (!collabConfig || !collabResources.ydoc || !collabResources.provider || !collabUser) {
2278
+ return null;
2279
+ }
2280
+ return createCollaborationExtensions({
2281
+ ydoc: collabResources.ydoc,
2282
+ provider: collabResources.provider,
2283
+ user: collabUser
2284
+ });
2285
+ }, [collabResources.ydoc, collabResources.provider, collabUserSignature]);
2286
+ }
2287
+
2288
+ // src/editor/core/utils/pluginConfig.ts
2289
+ function mergePluginConfigEntry(prev, patch) {
2290
+ const merged = {
2291
+ ...prev ?? {},
2292
+ ...patch,
2293
+ enabled: patch.enabled ?? prev?.enabled,
2294
+ config: {
2295
+ ...prev?.config ?? {},
2296
+ ...patch.config
2297
+ }
2298
+ };
2299
+ if (merged.enabled === void 0) delete merged.enabled;
2300
+ return merged;
2301
+ }
2302
+ function resolveEditorPluginConfigs({
2303
+ plugins,
2304
+ placeholder,
2305
+ template,
2306
+ outline,
2307
+ fillMode
2308
+ }) {
2309
+ let resolved = plugins ?? {};
2310
+ if (placeholder) {
2311
+ resolved = {
2312
+ ...resolved,
2313
+ placeholder: mergePluginConfigEntry(resolved.placeholder, { config: { placeholder } })
2314
+ };
2315
+ }
2316
+ if (template) {
2317
+ const { enabled: templateEnabled, ...templateConfig } = template;
2318
+ resolved = {
2319
+ ...resolved,
2320
+ template: mergePluginConfigEntry(resolved.template, {
2321
+ enabled: templateEnabled ?? true,
2322
+ config: { ...templateConfig, fillMode: fillMode === true }
2323
+ })
2324
+ };
2325
+ }
2326
+ if (outline) {
2327
+ const { enabled: outlineEnabled, ...outlineConfig } = outline;
2328
+ resolved = {
2329
+ ...resolved,
2330
+ outline: mergePluginConfigEntry(resolved.outline, {
2331
+ enabled: outlineEnabled !== false,
2332
+ config: outlineConfig
2333
+ })
2334
+ };
2335
+ }
2336
+ return resolved;
2337
+ }
2338
+ function getTemplateRevision(template) {
2339
+ return JSON.stringify({
2340
+ enabled: template?.enabled ?? null,
2341
+ initialTemplateId: template?.initialTemplateId ?? null,
2342
+ definitions: template?.definitions?.map(({ id, version }) => ({ id, version })) ?? []
2343
+ });
2344
+ }
2345
+ var RichEditor = forwardRef(function RichEditor2(props, ref) {
2346
+ const {
2347
+ content,
2348
+ editable = true,
2349
+ mode,
2350
+ onUpdate,
2351
+ onEditorReady,
2352
+ onCollaborationStatusChange,
2353
+ collaboration = false,
2354
+ collaborationConfig,
2355
+ currentUser,
2356
+ plugins,
2357
+ customPlugins,
2358
+ minimal,
2359
+ toolbar,
2360
+ className,
2361
+ style,
2362
+ placeholder = getDefaultPlaceholder(),
2363
+ template,
2364
+ outline,
2365
+ documentId
2366
+ } = props;
2367
+ const resolvedDocumentId = documentId ?? collaborationConfig?.documentId ?? "local";
2368
+ const resolvedMode = mode ?? (editable ? "edit" : "readonly");
2369
+ const effectiveEditable = resolvedMode !== "readonly";
2370
+ const collabConfig = collaboration && collaborationConfig ? collaborationConfig : null;
2371
+ const collabResources = useCollaborationResources(collabConfig, currentUser);
2372
+ const collabExtensions = useCollaborationExtensions({ collabConfig, collabResources, currentUser });
2373
+ const effectiveCollaboration = !!collabConfig && !!collabExtensions;
2374
+ const normalizedPlugins = useMemo(() => normalizeEditorPluginOptions(plugins), [plugins]);
2375
+ const resolvedPlugins = useMemo(
2376
+ () => resolveEditorPluginConfigs({
2377
+ plugins: normalizedPlugins.configs,
2378
+ placeholder,
2379
+ template,
2380
+ outline,
2381
+ fillMode: resolvedMode === "fill"
2382
+ }),
2383
+ [normalizedPlugins.configs, placeholder, template, outline, resolvedMode]
2384
+ );
2385
+ const registeredPlugins = useMemo(
2386
+ () => [...customPlugins ?? [], ...normalizedPlugins.registrations],
2387
+ [customPlugins, normalizedPlugins.registrations]
2388
+ );
2389
+ const registry = usePluginRegistry({
2390
+ plugins: resolvedPlugins,
2391
+ customPlugins: registeredPlugins,
2392
+ selection: normalizedPlugins.selection,
2393
+ registrationSignature: normalizedPlugins.registrationSignature,
2394
+ minimal,
2395
+ collaboration: effectiveCollaboration
2396
+ });
2397
+ const templateRevision = getTemplateRevision(template);
2398
+ const editorReady = !collabConfig || collabResources.ready;
2399
+ const onCollaborationStatusChangeRef = useRef(onCollaborationStatusChange);
2400
+ useEffect(() => {
2401
+ onCollaborationStatusChangeRef.current = onCollaborationStatusChange;
2402
+ });
2403
+ useEffect(() => {
2404
+ onCollaborationStatusChangeRef.current?.(collabResources.connectionStatus);
2405
+ }, [collabResources.connectionStatus]);
2406
+ const [editorInstance, setEditorInstance] = useState(null);
2407
+ const wrappedOnEditorReady = useCallback(
2408
+ (editor2) => {
2409
+ setEditorInstance((prev) => prev === editor2 ? prev : editor2);
2410
+ onEditorReady?.(editor2);
2411
+ },
2412
+ [onEditorReady]
2413
+ );
2414
+ const editor = editorInstance && !editorInstance.isDestroyed ? editorInstance : null;
2415
+ const refApi = useEditorRefApi({ editor, ydoc: collabResources.ydoc, outline, registry });
2416
+ useImperativeHandle(ref, () => refApi, [refApi]);
2417
+ const editorBodyKey = effectiveCollaboration ? `${collabResources.resourcesKey}::${templateRevision}::${registry.revision}` : `local::${resolvedDocumentId}::${templateRevision}::${registry.revision}`;
2418
+ const showToolbar = resolvedMode === "readonly" ? false : resolvedMode === "fill" ? toolbar?.visible === true : toolbar?.visible !== false;
2419
+ const { styles, cx } = useEditorStyles();
2420
+ return /* @__PURE__ */ jsx(CollaborationProvider, { resources: collabResources, children: editorReady ? /* @__PURE__ */ jsx(
2421
+ EditorBody,
2422
+ {
2423
+ registry,
2424
+ content,
2425
+ editable: effectiveEditable,
2426
+ mode: resolvedMode,
2427
+ collabExtensions,
2428
+ onUpdate,
2429
+ onEditorReady: wrappedOnEditorReady,
2430
+ showToolbar,
2431
+ toolbar,
2432
+ collaboration: effectiveCollaboration,
2433
+ className,
2434
+ style
2435
+ },
2436
+ editorBodyKey
2437
+ ) : /* @__PURE__ */ jsx("div", { className: cx(styles.editorWrapper, className), style, children: /* @__PURE__ */ jsx(EditorStatusBar, { editor: null, collaborationEnabled: !!collabConfig }) }) });
2438
+ });
2439
+
2440
+ export { CollaborationProvider, EditorContext, RichEditor, useCollaboration, useEditorContext, usePluginRegistry };
2441
+ //# sourceMappingURL=chunk-GGIOCI2I.mjs.map
2442
+ //# sourceMappingURL=chunk-GGIOCI2I.mjs.map