@haklex/rich-editor 0.58.0 → 0.59.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 (115) hide show
  1. package/README.md +35 -0
  2. package/dist/{AlertQuoteEditNode-DQt5pIZ8.js → AlertQuoteEditNode-Ck4v29Wg.js} +9 -20
  3. package/dist/BlockIdPlugin-Cwv8aV9g.js +106 -0
  4. package/dist/{ColorSchemeContext-RLg0uDRt.js → ColorSchemeContext-Dc_HebHd.js} +5 -4
  5. package/dist/ContentEditable.css--lQ6ekTS.js +7 -0
  6. package/dist/EditorBlockContext-DytAx9Tg.js +9 -0
  7. package/dist/{ExtraNodesContext-DdU7MZwS.js → ExtraNodesContext-xQ2RNsqH.js} +1 -1
  8. package/dist/{MermaidPlugin-BpoGXa9D.js → MermaidPlugin-BCoGsdi3.js} +3 -3
  9. package/dist/NestedEditorPluginsContext-D78UZkmx.js +16 -0
  10. package/dist/{RubyRenderer-CnTFvt0b.js → RubyRenderer-8HMSMaZz.js} +1 -1
  11. package/dist/VirtualizationPlugin-C8TJ4HJN.js +178 -0
  12. package/dist/{SubmitShortcutPlugin-BuRxU6WD.js → VirtualizationPlugin-Crc0cLUx.js} +969 -532
  13. package/dist/VirtualizedEditor-CIGYcIfr.js +818 -0
  14. package/dist/command-registry-entry.d.ts +3 -0
  15. package/dist/command-registry-entry.d.ts.map +1 -0
  16. package/dist/command-registry-entry.mjs +343 -0
  17. package/dist/commands/registry.d.ts +24 -0
  18. package/dist/commands/registry.d.ts.map +1 -0
  19. package/dist/commands-entry.mjs +2 -2
  20. package/dist/components/EditorSurfaceHost.d.ts +3 -0
  21. package/dist/components/EditorSurfaceHost.d.ts.map +1 -0
  22. package/dist/components/RichEditor.d.ts.map +1 -1
  23. package/dist/components/RichEditorShell.d.ts +3 -1
  24. package/dist/components/RichEditorShell.d.ts.map +1 -1
  25. package/dist/components/VirtualizationFromProps.d.ts +6 -0
  26. package/dist/components/VirtualizationFromProps.d.ts.map +1 -0
  27. package/dist/components/decorators/GridEditDecorator.d.ts.map +1 -1
  28. package/dist/components/renderers/ImageRenderer.d.ts +1 -0
  29. package/dist/components/renderers/ImageRenderer.d.ts.map +1 -1
  30. package/dist/context/EditorBlockContext.d.ts +12 -0
  31. package/dist/context/EditorBlockContext.d.ts.map +1 -0
  32. package/dist/context/EditorSurfaceContext.d.ts +42 -0
  33. package/dist/context/EditorSurfaceContext.d.ts.map +1 -0
  34. package/dist/defineProperty-BYhxpJwd.js +39 -0
  35. package/dist/{grid.css-CUb_icKZ.js → grid.css-DJWKdYpz.js} +2 -1
  36. package/dist/index.d.ts +5 -0
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.mjs +95 -43
  39. package/dist/{katex.css-9tq8FN8h.js → katex.css-9crOcnIa.js} +2 -1
  40. package/dist/{node-registry-CH2oHfO4.js → node-registry-jRE4LqH-.js} +37 -21
  41. package/dist/nodes/ImageNode.d.ts +7 -1
  42. package/dist/nodes/ImageNode.d.ts.map +1 -1
  43. package/dist/nodes/RichQuoteNode.d.ts +4 -1
  44. package/dist/nodes/RichQuoteNode.d.ts.map +1 -1
  45. package/dist/nodes-entry.mjs +4 -4
  46. package/dist/plugins/FileUploadPlugin.d.ts.map +1 -1
  47. package/dist/plugins/ImageDialog.d.ts +13 -0
  48. package/dist/plugins/ImageDialog.d.ts.map +1 -0
  49. package/dist/plugins/ImageDialogReview.d.ts +13 -0
  50. package/dist/plugins/ImageDialogReview.d.ts.map +1 -0
  51. package/dist/plugins/ImageDialogSource.d.ts +12 -0
  52. package/dist/plugins/ImageDialogSource.d.ts.map +1 -0
  53. package/dist/plugins/ImagePlugin.d.ts.map +1 -1
  54. package/dist/plugins/ImageUploadPlugin.d.ts +1 -1
  55. package/dist/plugins/ImageUploadPlugin.d.ts.map +1 -1
  56. package/dist/plugins/VideoUploadPlugin.d.ts +1 -1
  57. package/dist/plugins/VideoUploadPlugin.d.ts.map +1 -1
  58. package/dist/plugins/VirtualizationPlugin.d.ts +2 -0
  59. package/dist/plugins/VirtualizationPlugin.d.ts.map +1 -0
  60. package/dist/plugins/image-dialog-model.d.ts +65 -0
  61. package/dist/plugins/image-dialog-model.d.ts.map +1 -0
  62. package/dist/plugins/image-dialog.css.d.ts +30 -0
  63. package/dist/plugins/image-dialog.css.d.ts.map +1 -0
  64. package/dist/plugins/image-upload-toast.d.ts +2 -0
  65. package/dist/plugins/image-upload-toast.d.ts.map +1 -0
  66. package/dist/plugins/image-upload.css.d.ts +0 -23
  67. package/dist/plugins/image-upload.css.d.ts.map +1 -1
  68. package/dist/plugins/insertion-cursor.d.ts +20 -0
  69. package/dist/plugins/insertion-cursor.d.ts.map +1 -0
  70. package/dist/plugins/present-image-dialog.d.ts +14 -0
  71. package/dist/plugins/present-image-dialog.d.ts.map +1 -0
  72. package/dist/plugins-entry.d.ts +5 -0
  73. package/dist/plugins-entry.d.ts.map +1 -1
  74. package/dist/plugins-entry.mjs +7 -5
  75. package/dist/recycler-entry.d.ts +8 -0
  76. package/dist/recycler-entry.d.ts.map +1 -0
  77. package/dist/recycler-entry.mjs +3 -0
  78. package/dist/renderers-entry.mjs +4 -4
  79. package/dist/rich-editor.css +1 -1
  80. package/dist/static-entry.d.ts +1 -0
  81. package/dist/static-entry.d.ts.map +1 -1
  82. package/dist/static-entry.mjs +10 -9
  83. package/dist/styles/grid.css.d.ts.map +1 -1
  84. package/dist/styles/shared.css.d.ts.map +1 -1
  85. package/dist/styles-entry.mjs +3 -3
  86. package/dist/{theme-Blq1EG_t.js → theme-DH4xzxU-.js} +63 -48
  87. package/dist/{thumbhash-DHHqtr0c.js → thumbhash-GjK8OYAb.js} +1 -1
  88. package/dist/types.d.ts +3 -0
  89. package/dist/types.d.ts.map +1 -1
  90. package/dist/{utils-CdxPji5z.js → utils-E6qVk-NR.js} +1 -0
  91. package/dist/viewport-BvO92tse.js +210 -0
  92. package/dist/virtualization/VirtualizationPlugin.d.ts +5 -0
  93. package/dist/virtualization/VirtualizationPlugin.d.ts.map +1 -0
  94. package/dist/virtualization/VirtualizedEditor.d.ts +6 -0
  95. package/dist/virtualization/VirtualizedEditor.d.ts.map +1 -0
  96. package/dist/virtualization/controller.d.ts +73 -0
  97. package/dist/virtualization/controller.d.ts.map +1 -0
  98. package/dist/virtualization/document.d.ts +26 -0
  99. package/dist/virtualization/document.d.ts.map +1 -0
  100. package/dist/virtualization/layout.d.ts +42 -0
  101. package/dist/virtualization/layout.d.ts.map +1 -0
  102. package/dist/virtualization/preserve.d.ts +21 -0
  103. package/dist/virtualization/preserve.d.ts.map +1 -0
  104. package/dist/virtualization/style.css.d.ts +4 -0
  105. package/dist/virtualization/style.css.d.ts.map +1 -0
  106. package/dist/virtualization/sync.d.ts +4 -0
  107. package/dist/virtualization/sync.d.ts.map +1 -0
  108. package/dist/virtualization/types.d.ts +13 -0
  109. package/dist/virtualization/types.d.ts.map +1 -0
  110. package/dist/virtualization/viewport.d.ts +3 -0
  111. package/dist/virtualization/viewport.d.ts.map +1 -0
  112. package/dist/virtualization-entry.d.ts +3 -0
  113. package/dist/virtualization-entry.d.ts.map +1 -0
  114. package/dist/virtualization-entry.mjs +1 -0
  115. package/package.json +17 -5
@@ -0,0 +1,818 @@
1
+ import { t as _defineProperty } from "./defineProperty-BYhxpJwd.js";
2
+ import { n as useNestedEditorPlugins } from "./NestedEditorPluginsContext-D78UZkmx.js";
3
+ import { n as blockIdState } from "./BlockIdPlugin-Cwv8aV9g.js";
4
+ import { t as EditorBlockContext } from "./EditorBlockContext-DytAx9Tg.js";
5
+ import { n as contentWrapper, t as content } from "./ContentEditable.css--lQ6ekTS.js";
6
+ import { a as PreserveNodeManager, i as slot, l as estimateHeight, n as canvas, o as HeightIndex, s as TypePool, t as resolveScrollContainer, u as occupiedHeight } from "./viewport-BvO92tse.js";
7
+ import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
8
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
9
+ import { $exportNodeJSON, $getNodeByKey, $getRoot, $getSelection, $getSlot, $getSlotNames, $getState, $isElementNode, $isRangeSelection, $parseSerializedNode, $setSelection, $setState, COMMAND_PRIORITY_CRITICAL, KEY_ARROW_DOWN_COMMAND, KEY_ARROW_UP_COMMAND, KEY_BACKSPACE_COMMAND, KEY_DELETE_COMMAND, REDO_COMMAND, SKIP_DOM_SELECTION_TAG, SKIP_SCROLL_INTO_VIEW_TAG, UNDO_COMMAND, createEditor } from "lexical";
10
+ import { createPortal, flushSync } from "react-dom";
11
+ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
12
+ import { ContentEditable } from "@lexical/react/LexicalContentEditable";
13
+ import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary";
14
+ import { LexicalNestedComposer } from "@lexical/react/LexicalNestedComposer";
15
+ import { RichTextPlugin } from "@lexical/react/LexicalRichTextPlugin";
16
+ import { nanoid } from "nanoid";
17
+ //#region src/virtualization/document.ts
18
+ function $serializeBlock(node) {
19
+ const data = $exportNodeJSON(node);
20
+ if ($isElementNode(node)) data.children = node.getChildren().map($serializeBlock);
21
+ for (const name of $getSlotNames(node)) {
22
+ data.$slots ?? (data.$slots = {});
23
+ data.$slots[name] = $serializeBlock($getSlot(node, name));
24
+ }
25
+ return data;
26
+ }
27
+ var VirtualDocument = class {
28
+ constructor(editor) {
29
+ _defineProperty(this, "editor", void 0);
30
+ _defineProperty(this, "rows", []);
31
+ _defineProperty(this, "onChange", void 0);
32
+ _defineProperty(this, "unsubscribe", void 0);
33
+ _defineProperty(this, "lastEdit", void 0);
34
+ this.editor = editor;
35
+ this.read();
36
+ this.unsubscribe = editor.registerUpdateListener(({ dirtyElements, dirtyLeaves, tags }) => {
37
+ if (!dirtyElements.size && !dirtyLeaves.size) return;
38
+ this.read(/* @__PURE__ */ new Set([...dirtyElements.keys(), ...dirtyLeaves]));
39
+ const source = [...tags].find((tag) => tag.startsWith("virtual-island:"));
40
+ if (!source) this.lastEdit = void 0;
41
+ this.onChange?.(source);
42
+ });
43
+ }
44
+ read(dirty) {
45
+ const previous = new Map(this.rows.map((row) => [row.key, row]));
46
+ this.rows = this.editor.getEditorState().read(() => $getRoot().getChildren().map((node) => {
47
+ const key = node.getKey();
48
+ const old = previous.get(key);
49
+ if (old?.node === node && !dirty?.has(key)) return old;
50
+ const data = $serializeBlock(node);
51
+ return {
52
+ data,
53
+ key,
54
+ node,
55
+ id: $getState(node, blockIdState) || key,
56
+ pool: `${data.type}:${data.url ?? data.tag ?? data.listType ?? ""}`
57
+ };
58
+ }));
59
+ }
60
+ replace(ids, children, source) {
61
+ const first = this.rows.findIndex((row) => row.id === ids[0]);
62
+ if (first < 0 || ids.some((id, i) => this.rows[first + i]?.id !== id)) throw new Error("Virtual editor island is stale or noncontiguous");
63
+ const keys = this.rows.slice(first, first + ids.length).map((row) => row.key);
64
+ const now = Date.now();
65
+ const merge = this.lastEdit?.source === source && this.lastEdit.ids === ids.join(",") && this.lastEdit.count === children.length && children.length === ids.length && now - this.lastEdit.time < 600;
66
+ this.editor.update(() => {
67
+ const original = keys.map((key) => $getNodeByKey(key));
68
+ if (original.some((node) => !node)) throw new Error("Virtual editor block was removed");
69
+ let tail;
70
+ for (const data of children) {
71
+ const node = $parseSerializedNode(data);
72
+ if (tail) tail.insertAfter(node);
73
+ else original[0].insertBefore(node);
74
+ tail = node;
75
+ }
76
+ for (const node of original) node.remove();
77
+ }, {
78
+ discrete: true,
79
+ tag: [merge ? "history-merge" : "history-push", `virtual-island:${source}`]
80
+ });
81
+ this.lastEdit = {
82
+ source,
83
+ ids: ids.join(","),
84
+ time: now,
85
+ count: children.length
86
+ };
87
+ }
88
+ dispose() {
89
+ this.unsubscribe();
90
+ }
91
+ };
92
+ //#endregion
93
+ //#region src/virtualization/sync.ts
94
+ var reusable = /* @__PURE__ */ new Set([
95
+ "paragraph",
96
+ "text",
97
+ "heading",
98
+ "quote",
99
+ "list",
100
+ "listitem",
101
+ "details",
102
+ "dynamic"
103
+ ]);
104
+ function $syncChildren(parent, data) {
105
+ const previous = parent.getChildren();
106
+ data.forEach((next, index) => {
107
+ const node = previous[index];
108
+ if (node?.getType() === next.type && reusable.has(next.type)) {
109
+ node.updateFromJSON(next);
110
+ if (next.type === "details") {
111
+ const details = node;
112
+ details.setOpen(Boolean(next.open));
113
+ details.setSummary(next.summary);
114
+ } else if (next.type === "dynamic") {
115
+ const dynamic = node;
116
+ dynamic.setUrl(next.url);
117
+ dynamic.setProps(next.props);
118
+ dynamic.setInitialHeight(next.initialHeight);
119
+ }
120
+ if ($isElementNode(node)) $syncChildren(node, next.children ?? []);
121
+ } else {
122
+ const replacement = $parseSerializedNode(next);
123
+ if (node) node.replace(replacement);
124
+ else parent.append(replacement);
125
+ }
126
+ });
127
+ for (const node of previous.slice(data.length)) node.remove();
128
+ }
129
+ //#endregion
130
+ //#region src/virtualization/controller.ts
131
+ var EditorRecycler = class {
132
+ constructor(master, canvas, options) {
133
+ _defineProperty(this, "master", void 0);
134
+ _defineProperty(this, "canvas", void 0);
135
+ _defineProperty(this, "options", void 0);
136
+ _defineProperty(this, "document", void 0);
137
+ _defineProperty(this, "pool", new TypePool());
138
+ _defineProperty(this, "islands", /* @__PURE__ */ new Map());
139
+ _defineProperty(this, "states", /* @__PURE__ */ new Map());
140
+ _defineProperty(this, "viewport", void 0);
141
+ _defineProperty(this, "preserve", void 0);
142
+ _defineProperty(this, "heights", void 0);
143
+ _defineProperty(this, "revision", 0);
144
+ _defineProperty(this, "indices", /* @__PURE__ */ new Map());
145
+ _defineProperty(this, "listeners", /* @__PURE__ */ new Set());
146
+ _defineProperty(this, "observer", void 0);
147
+ _defineProperty(this, "frame", 0);
148
+ _defineProperty(this, "dead", false);
149
+ _defineProperty(this, "width", void 0);
150
+ _defineProperty(this, "metrics", /* @__PURE__ */ new Map());
151
+ _defineProperty(this, "firstParagraph", -1);
152
+ _defineProperty(this, "previousRows", []);
153
+ _defineProperty(this, "onScroll", () => this.refresh());
154
+ this.master = master;
155
+ this.canvas = canvas;
156
+ this.options = options;
157
+ this.viewport = resolveScrollContainer(canvas, options.scrollContainer);
158
+ this.preserve = new PreserveNodeManager(options.preserveCapacity ?? 32, (id) => {
159
+ this.pool.slots.find((slot) => slot.id === id)?.beforeRelease?.();
160
+ });
161
+ if (options.overscan !== void 0 && (!Number.isFinite(options.overscan) || options.overscan < 0)) throw new Error("Virtual editor overscan must be a nonnegative number");
162
+ this.document = new VirtualDocument(master);
163
+ this.indices = new Map(this.rows.map((row, index) => [row.id, index]));
164
+ this.firstParagraph = this.rows.findIndex((row) => row.data.type === "paragraph");
165
+ master.update(() => $getRoot().markDirty(), {
166
+ discrete: true,
167
+ tag: "history-merge"
168
+ });
169
+ this.width = canvas.clientWidth;
170
+ try {
171
+ this.heights = this.buildHeights();
172
+ } catch (error) {
173
+ this.document.dispose();
174
+ throw error;
175
+ }
176
+ canvas.style.height = `${this.heights.total}px`;
177
+ this.document.onChange = (source) => {
178
+ this.reconcileDocument(source);
179
+ };
180
+ this.previousRows = this.rows.map((row) => ({
181
+ id: row.id,
182
+ data: row.data
183
+ }));
184
+ this.observer = new ResizeObserver(() => this.queueMeasure());
185
+ this.observer.observe(canvas);
186
+ if (this.viewport instanceof HTMLElement) this.observer.observe(this.viewport);
187
+ this.viewport.addEventListener("scroll", this.onScroll, { passive: true });
188
+ window.addEventListener("resize", this.onScroll);
189
+ this.refresh(false);
190
+ }
191
+ get rows() {
192
+ return this.document.rows;
193
+ }
194
+ get scrollTop() {
195
+ return this.viewport instanceof HTMLElement ? this.viewport.scrollTop : window.scrollY;
196
+ }
197
+ setScrollTop(top) {
198
+ if (this.viewport instanceof HTMLElement) this.viewport.scrollTop = top;
199
+ else window.scrollTo(window.scrollX, top);
200
+ }
201
+ viewportTop() {
202
+ return this.viewport instanceof HTMLElement ? this.viewport.getBoundingClientRect().top + this.viewport.clientTop : 0;
203
+ }
204
+ viewportHeight() {
205
+ return this.viewport instanceof HTMLElement ? this.viewport.clientHeight : window.innerHeight;
206
+ }
207
+ canvasTop() {
208
+ return this.canvas.getBoundingClientRect().top - this.viewportTop() + this.scrollTop;
209
+ }
210
+ buildHeights() {
211
+ return new HeightIndex(this.rows.map((row) => this.estimate(row.data)));
212
+ }
213
+ estimate(data) {
214
+ const height = this.options.estimateBlockHeight?.(data, this.width) ?? estimateHeight(data, this.width);
215
+ if (!Number.isFinite(height) || height <= 0) throw new Error("Virtual editor estimated height must be positive and finite");
216
+ return Math.max(24, height);
217
+ }
218
+ reconcileDocument(source) {
219
+ const anchor = this.anchor();
220
+ const previous = new Map(this.previousRows.map((row, index) => [row.id, {
221
+ ...row,
222
+ height: this.heights.values[index]
223
+ }]));
224
+ if (this.rows.length !== this.previousRows.length || this.rows.some((row, i) => row.id !== this.previousRows[i].id)) this.heights = new HeightIndex(this.rows.map((row) => previous.get(row.id)?.height ?? this.estimate(row.data)));
225
+ const indices = new Map(this.rows.map((row, index) => [row.id, index]));
226
+ this.indices = indices;
227
+ this.firstParagraph = this.rows.findIndex((row) => row.data.type === "paragraph");
228
+ for (const id of this.metrics.keys()) if (!indices.has(id)) this.metrics.delete(id);
229
+ for (const slot of this.pool.slots) {
230
+ const island = this.islands.get(slot.id);
231
+ if (!island) continue;
232
+ island.ids = island.ids.filter((id) => indices.has(id));
233
+ island.source = source === `virtual-island:${slot.id}`;
234
+ if (island.ids.length) {
235
+ slot.index = indices.get(island.ids[0]);
236
+ slot.pool = this.rows[slot.index].pool;
237
+ } else {
238
+ slot.beforeRelease?.();
239
+ slot.active = false;
240
+ }
241
+ }
242
+ this.pool.slots = this.pool.slots.filter((slot) => {
243
+ const island = this.islands.get(slot.id);
244
+ if (!island || island.ids.length) return true;
245
+ island.unsubscribe();
246
+ this.preserve.forget(slot.id);
247
+ this.islands.delete(slot.id);
248
+ this.pool.disposed++;
249
+ return false;
250
+ });
251
+ this.previousRows = this.rows.map((row) => ({
252
+ id: row.id,
253
+ data: row.data
254
+ }));
255
+ this.restore(anchor);
256
+ this.refresh(false);
257
+ this.publish();
258
+ this.queueMeasure();
259
+ }
260
+ subscribe(listener) {
261
+ this.listeners.add(listener);
262
+ return () => {
263
+ this.listeners.delete(listener);
264
+ };
265
+ }
266
+ publish(sync = true) {
267
+ if (this.dead || !this.listeners.size) return;
268
+ this.revision++;
269
+ const notify = () => this.listeners.forEach((listener) => listener());
270
+ if (sync) flushSync(notify);
271
+ else notify();
272
+ }
273
+ refresh(sync = true) {
274
+ if (this.dead || !this.rows.length) return;
275
+ const y = Math.max(0, this.scrollTop - this.canvasTop());
276
+ const buffer = this.options.overscan ?? this.viewportHeight() * 1.5;
277
+ const first = this.heights.find(Math.max(0, y - buffer));
278
+ const last = this.heights.find(y + this.viewportHeight() + buffer);
279
+ const covered = /* @__PURE__ */ new Set();
280
+ const groupHeads = [];
281
+ const pinned = /* @__PURE__ */ new Set();
282
+ for (const slot of this.pool.slots) {
283
+ const island = this.islands.get(slot.id);
284
+ if (!island || !slot.active && !this.preserve.has(slot.id)) continue;
285
+ if (island.retained || island.editor.isComposing() || slot.element?.contains(document.activeElement)) pinned.add(slot.id);
286
+ for (let i = 1; i < island.ids.length; i++) covered.add(slot.index + i);
287
+ if (island.ids.length > 1 && slot.index < first && slot.index + island.ids.length > first) groupHeads.push(slot.index);
288
+ }
289
+ const indices = [...groupHeads, ...Array.from({ length: last - first + 1 }, (_, i) => first + i)].filter((i) => !covered.has(i));
290
+ const wanted = new Set(indices);
291
+ const resumed = /* @__PURE__ */ new Set();
292
+ for (const slot of this.pool.slots) if ((wanted.has(slot.index) || pinned.has(slot.id)) && this.preserve.activate(slot.id)) resumed.add(slot.id);
293
+ for (const slot of this.pool.slots) if (slot.active && !wanted.has(slot.index) && !pinned.has(slot.id)) this.preserve.park(slot.id, this.islands.get(slot.id)?.ids.join(",") ?? "");
294
+ const protectedSlots = /* @__PURE__ */ new Set([...this.preserve.ids(), ...resumed]);
295
+ const changed = this.pool.update(indices, (i) => this.rows[i].pool, pinned, protectedSlots);
296
+ for (const [id, island] of this.islands) if (!this.pool.slots.some((slot) => slot.id === id)) {
297
+ island.unsubscribe();
298
+ island.editor.setRootElement(null);
299
+ this.preserve.forget(id);
300
+ this.islands.delete(id);
301
+ }
302
+ if (changed) this.publish(sync);
303
+ }
304
+ island(slot) {
305
+ let island = this.islands.get(slot.id);
306
+ if (island) return island;
307
+ const editor = this.master.read(() => createEditor());
308
+ island = {
309
+ editor,
310
+ ids: [],
311
+ generation: -1,
312
+ loading: false,
313
+ source: false,
314
+ data: "",
315
+ unsubscribe: () => {},
316
+ retained: 0
317
+ };
318
+ this.islands.set(slot.id, island);
319
+ island.unsubscribe = editor.registerUpdateListener(({ editorState, dirtyElements, dirtyLeaves, tags }) => {
320
+ if (island.loading || !island.ids.length || tags.has("virtual-bind") || !dirtyElements.size && !dirtyLeaves.size) return;
321
+ const children = editorState.toJSON().root.children;
322
+ if (JSON.stringify(children) === island.data) return;
323
+ const used = /* @__PURE__ */ new Set();
324
+ children.forEach((data, i) => {
325
+ let id = data.$?.blockId;
326
+ if (!id || used.has(id)) id = i === 0 ? island.ids[0] : nanoid(8);
327
+ data.$ = {
328
+ ...data.$,
329
+ blockId: id
330
+ };
331
+ used.add(id);
332
+ });
333
+ const oldIds = [...island.ids];
334
+ island.ids = children.map((data) => data.$.blockId);
335
+ island.data = JSON.stringify(children);
336
+ editor.update(() => $getRoot().getChildren().forEach((node, i) => $setState(node, blockIdState, island.ids[i])), { tag: "virtual-bind" });
337
+ this.document.replace(oldIds, children, String(slot.id));
338
+ });
339
+ return island;
340
+ }
341
+ bind(slot) {
342
+ const island = this.island(slot);
343
+ const rebound = island.generation !== slot.generation;
344
+ if (rebound) island.ids = [this.rows[slot.index].id];
345
+ const rows = island.ids.map((id) => this.rows[this.indices.get(id) ?? -1]).filter((row) => !!row);
346
+ if (!rows.length) return;
347
+ const children = rows.map((row) => row.data);
348
+ const data = JSON.stringify(children);
349
+ if (!rebound && (island.source || data === island.data)) {
350
+ island.source = false;
351
+ island.data = data;
352
+ return;
353
+ }
354
+ island.generation = slot.generation;
355
+ island.data = data;
356
+ island.loading = true;
357
+ try {
358
+ island.editor.update(() => {
359
+ $syncChildren($getRoot(), children);
360
+ if (rebound) $setSelection(null);
361
+ }, {
362
+ discrete: true,
363
+ tag: rebound ? ["virtual-bind", SKIP_DOM_SELECTION_TAG] : "virtual-bind"
364
+ });
365
+ } finally {
366
+ island.loading = false;
367
+ }
368
+ this.restorePanels(slot);
369
+ this.queueMeasure();
370
+ }
371
+ attach(slot, element) {
372
+ if (slot.element) this.observer.unobserve(slot.element);
373
+ slot.element = element ?? void 0;
374
+ if (element) this.observer.observe(element);
375
+ }
376
+ mount(slot, host) {
377
+ const next = this.pool.slots.filter((other) => other.active && other.index > slot.index).sort((a, b) => a.index - b.index).map((other) => this.preserve.host(other.id)).find((element) => element?.parentElement === this.canvas);
378
+ this.preserve.mount(slot.id, host, slot.active ? this.canvas : null, next ?? null);
379
+ }
380
+ state(id) {
381
+ let state = this.states.get(id);
382
+ if (!state) {
383
+ state = /* @__PURE__ */ new Map();
384
+ this.states.set(id, state);
385
+ }
386
+ return state;
387
+ }
388
+ nodeState(slot, key, expectedId) {
389
+ const island = this.island(slot);
390
+ const scope = island.editor.getEditorState().read(() => {
391
+ let node = key ? $getNodeByKey(key) : $getRoot().getFirstChild();
392
+ const path = [];
393
+ while (node?.getParent() && node.getParent().getType() !== "root") {
394
+ path.unshift(node.getIndexWithinParent());
395
+ node = node.getParent();
396
+ }
397
+ const index = node?.getIndexWithinParent() ?? 0;
398
+ return `${index === 0 ? expectedId : island.ids[index] ?? expectedId}:${path.join(".")}`;
399
+ });
400
+ return this.state(scope);
401
+ }
402
+ capturePanels(slot) {
403
+ const id = this.islands.get(slot.id)?.ids[0];
404
+ if (!id) return;
405
+ this.state(id).set("details", this.panels(slot).map(({ panel }) => panel.open));
406
+ }
407
+ restorePanels(slot) {
408
+ const saved = this.state(this.island(slot).ids[0]).get("details");
409
+ this.panels(slot).forEach(({ panel, initialOpen }, i) => {
410
+ panel.open = saved?.[i] ?? initialOpen;
411
+ });
412
+ }
413
+ panels(slot) {
414
+ const editor = this.island(slot).editor;
415
+ return editor.getEditorState().read(() => {
416
+ const panels = [];
417
+ const walk = (node) => {
418
+ if (node.getType() === "details") {
419
+ const panel = editor.getElementByKey(node.getKey());
420
+ if (panel instanceof HTMLDetailsElement) panels.push({
421
+ panel,
422
+ initialOpen: node.getOpen()
423
+ });
424
+ }
425
+ if ($isElementNode(node)) node.getChildren().forEach(walk);
426
+ };
427
+ walk($getRoot());
428
+ return panels;
429
+ });
430
+ }
431
+ anchor() {
432
+ const bounds = this.canvas.getBoundingClientRect();
433
+ const target = document.elementFromPoint(bounds.left + bounds.width / 2, Math.max(this.viewportTop() + 8, bounds.top + 1))?.closest("[data-virtual-editor-slot]");
434
+ const index = this.pool.slots.find((item) => item.active && item.element === target)?.index ?? this.heights.find(Math.max(0, this.scrollTop - this.canvasTop()));
435
+ return {
436
+ id: this.previousRows[index]?.id ?? this.rows[index]?.id,
437
+ offset: this.scrollTop - this.canvasTop() - this.blockOffset(index)
438
+ };
439
+ }
440
+ restore(anchor) {
441
+ this.canvas.style.height = `${this.heights.total + this.leadingMargin}px`;
442
+ const index = anchor.id ? this.indices.get(anchor.id) ?? -1 : -1;
443
+ if (index >= 0) this.setScrollTop(this.canvasTop() + this.blockOffset(index) + anchor.offset);
444
+ }
445
+ queueMeasure() {
446
+ if (!this.dead && !this.frame) this.frame = requestAnimationFrame(() => this.measure());
447
+ }
448
+ slotOffset(slot) {
449
+ return this.blockOffset(slot.index) - (this.metrics.get(this.rows[slot.index]?.id)?.top ?? 0);
450
+ }
451
+ get leadingMargin() {
452
+ return this.metrics.get(this.rows[0]?.id)?.top ?? 0;
453
+ }
454
+ blockOffset(index) {
455
+ return this.heights.offset(index) + this.leadingMargin;
456
+ }
457
+ commitLayout() {
458
+ cancelAnimationFrame(this.frame);
459
+ this.measure(false);
460
+ }
461
+ measure(sync = true) {
462
+ this.frame = 0;
463
+ if (this.dead) return;
464
+ const anchor = this.anchor();
465
+ let changed = false;
466
+ if (Math.abs(this.canvas.clientWidth - this.width) > .5) {
467
+ this.width = this.canvas.clientWidth;
468
+ this.metrics.clear();
469
+ this.heights = this.buildHeights();
470
+ changed = true;
471
+ }
472
+ const measured = /* @__PURE__ */ new Set();
473
+ for (const slot of this.pool.slots) {
474
+ if (!slot.active) continue;
475
+ const island = this.islands.get(slot.id);
476
+ const root = island?.editor.getRootElement();
477
+ if (!root || !island?.ids.length) continue;
478
+ const elements = island.editor.getEditorState().read(() => $getRoot().getChildren().map((node) => island.editor.getElementByKey(node.getKey())));
479
+ elements.forEach((element, i) => {
480
+ if (!element) return;
481
+ const index = this.indices.get(island.ids[i]) ?? -1;
482
+ const previous = this.rows[index - 1]?.data;
483
+ element.toggleAttribute("data-document-first", index === 0 && element === root.firstElementChild);
484
+ element.toggleAttribute("data-document-last", index === this.rows.length - 1 && element === root.lastElementChild);
485
+ element.toggleAttribute("data-document-first-paragraph", index === this.firstParagraph);
486
+ element.dataset.documentPrevTag = previous?.type === "heading" ? previous.tag : previous?.type === "horizontalrule" ? "hr" : "";
487
+ });
488
+ const bounds = root.getBoundingClientRect();
489
+ const rects = elements.map((element) => element?.getBoundingClientRect());
490
+ island.ids.forEach((id, i) => {
491
+ const index = this.indices.get(id) ?? -1;
492
+ const element = elements[i];
493
+ if (index < 0 || !element) return;
494
+ element.dataset.blockId = id;
495
+ const rect = rects[i];
496
+ const style = getComputedStyle(element);
497
+ const top = i === 0 ? rect.top - bounds.top : parseFloat(style.marginTop) || 0;
498
+ const bottom = i === island.ids.length - 1 ? bounds.bottom - rect.bottom : parseFloat(style.marginBottom) || 0;
499
+ if (Math.abs(top - (this.metrics.get(id)?.top ?? 0)) > .1) changed = true;
500
+ this.metrics.set(id, {
501
+ height: rect.height,
502
+ top,
503
+ bottom,
504
+ gap: rects[i + 1] ? rects[i + 1].top - rect.bottom : void 0
505
+ });
506
+ measured.add(index);
507
+ if (index > 0) measured.add(index - 1);
508
+ });
509
+ }
510
+ for (const index of measured) {
511
+ const metrics = this.metrics.get(this.rows[index].id);
512
+ if (!metrics) continue;
513
+ const height = Math.max(1, occupiedHeight(metrics, this.metrics.get(this.rows[index + 1]?.id)));
514
+ if (Math.abs(height - this.heights.values[index]) > .1) {
515
+ this.heights.update(index, height);
516
+ changed = true;
517
+ }
518
+ }
519
+ if (changed) {
520
+ this.restore(anchor);
521
+ this.refresh(false);
522
+ this.publish(sync);
523
+ }
524
+ }
525
+ scrollTo(index) {
526
+ this.setScrollTop(this.canvasTop() + this.blockOffset(Math.max(0, Math.min(index, this.rows.length - 1))));
527
+ this.refresh();
528
+ }
529
+ focusBlock(index, end = false, scroll = true) {
530
+ if (index < 0 || index >= this.rows.length) return;
531
+ if (scroll) this.scrollTo(index);
532
+ requestAnimationFrame(() => {
533
+ const slot = this.pool.slots.find((item) => item.active && this.islands.get(item.id)?.ids.includes(this.rows[index]?.id));
534
+ if (!slot) return;
535
+ this.island(slot).editor.update(() => {
536
+ if (end) $getRoot().selectEnd();
537
+ else $getRoot().selectStart();
538
+ }, { tag: scroll ? void 0 : SKIP_SCROLL_INTO_VIEW_TAG });
539
+ });
540
+ }
541
+ joinNeighbor(slot, backward) {
542
+ const island = this.island(slot);
543
+ const index = backward ? slot.index - 1 : slot.index + island.ids.length;
544
+ const row = this.rows[index];
545
+ if (!row) return false;
546
+ for (const other of this.pool.slots) if (other !== slot && this.islands.get(other.id)?.ids.includes(row.id)) {
547
+ other.beforeRelease?.();
548
+ other.active = false;
549
+ }
550
+ island.ids = backward ? [row.id, ...island.ids] : [...island.ids, row.id];
551
+ if (backward) slot.index = index;
552
+ island.editor.update(() => {
553
+ const node = $parseSerializedNode(row.data);
554
+ if (backward) $getRoot().getFirstChild().insertBefore(node);
555
+ else $getRoot().append(node);
556
+ const selection = $getSelection();
557
+ if ($isRangeSelection(selection)) selection.deleteCharacter(backward);
558
+ }, { discrete: true });
559
+ return true;
560
+ }
561
+ dispose() {
562
+ this.dead = true;
563
+ this.document.dispose();
564
+ this.observer.disconnect();
565
+ cancelAnimationFrame(this.frame);
566
+ this.viewport.removeEventListener("scroll", this.onScroll);
567
+ window.removeEventListener("resize", this.onScroll);
568
+ for (const island of this.islands.values()) island.unsubscribe();
569
+ this.listeners.clear();
570
+ this.preserve.clear();
571
+ }
572
+ };
573
+ //#endregion
574
+ //#region src/virtualization/VirtualizedEditor.tsx
575
+ function IslandPlugins({ controller, slot }) {
576
+ const [editor] = useLexicalComposerContext();
577
+ useEffect(() => {
578
+ const edge = (end) => {
579
+ const selection = $getSelection();
580
+ if (!$isRangeSelection(selection) || !selection.isCollapsed()) return false;
581
+ const node = end ? $getRoot().getLastDescendant() : $getRoot().getFirstDescendant();
582
+ return !!node && selection.anchor.key === node.getKey() && selection.anchor.offset === (end ? node.getTextContentSize() : 0);
583
+ };
584
+ const unregister = [
585
+ editor.registerCommand(UNDO_COMMAND, () => {
586
+ controller.master.dispatchCommand(UNDO_COMMAND, void 0);
587
+ return true;
588
+ }, COMMAND_PRIORITY_CRITICAL),
589
+ editor.registerCommand(REDO_COMMAND, () => {
590
+ controller.master.dispatchCommand(REDO_COMMAND, void 0);
591
+ return true;
592
+ }, COMMAND_PRIORITY_CRITICAL),
593
+ editor.registerCommand(KEY_BACKSPACE_COMMAND, (event) => {
594
+ if (!edge(false) || !controller.joinNeighbor(slot, true)) return false;
595
+ event?.preventDefault();
596
+ return true;
597
+ }, COMMAND_PRIORITY_CRITICAL),
598
+ editor.registerCommand(KEY_DELETE_COMMAND, (event) => {
599
+ if (!edge(true) || !controller.joinNeighbor(slot, false)) return false;
600
+ event?.preventDefault();
601
+ return true;
602
+ }, COMMAND_PRIORITY_CRITICAL),
603
+ editor.registerCommand(KEY_ARROW_UP_COMMAND, (event) => {
604
+ if (!edge(false) || event?.shiftKey || slot.index === 0) return false;
605
+ event?.preventDefault();
606
+ controller.focusBlock(slot.index - 1, true);
607
+ return true;
608
+ }, COMMAND_PRIORITY_CRITICAL),
609
+ editor.registerCommand(KEY_ARROW_DOWN_COMMAND, (event) => {
610
+ if (!edge(true) || event?.shiftKey) return false;
611
+ const index = slot.index + controller.island(slot).ids.length;
612
+ if (index >= controller.rows.length) return false;
613
+ event?.preventDefault();
614
+ controller.focusBlock(index);
615
+ return true;
616
+ }, COMMAND_PRIORITY_CRITICAL)
617
+ ];
618
+ return () => unregister.forEach((fn) => fn());
619
+ }, [
620
+ controller,
621
+ editor,
622
+ slot
623
+ ]);
624
+ return null;
625
+ }
626
+ function EditorSlot({ controller, slot: slot$1, plugins: surfacePlugins, onActiveEditorChange, onRelease, retainSurface, placeholder: placeholder$1 }) {
627
+ const island = controller.island(slot$1);
628
+ const row = controller.rows[slot$1.index];
629
+ const binding = `${slot$1.generation}:${slot$1.active}`;
630
+ const [settled, setSettled] = useState("");
631
+ const [host] = useState(() => {
632
+ const element = document.createElement("div");
633
+ element.style.display = "contents";
634
+ return element;
635
+ });
636
+ const mounted = slot$1.active || controller.preserve.has(slot$1.id);
637
+ const plugins = useNestedEditorPlugins();
638
+ const value = useMemo(() => ({
639
+ blockId: row.id,
640
+ active: slot$1.active,
641
+ editor: island.editor,
642
+ nodeState: (key) => controller.nodeState(slot$1, key, row.id),
643
+ retain: () => {
644
+ island.retained++;
645
+ const releaseSurface = retainSurface();
646
+ let released = false;
647
+ return () => {
648
+ if (released) return;
649
+ released = true;
650
+ island.retained--;
651
+ releaseSurface();
652
+ controller.refresh(false);
653
+ };
654
+ }
655
+ }), [
656
+ controller,
657
+ island.editor,
658
+ retainSurface,
659
+ row.id,
660
+ slot$1,
661
+ slot$1.active,
662
+ slot$1.generation
663
+ ]);
664
+ const ref = useCallback((element) => controller.attach(slot$1, element), [controller, slot$1]);
665
+ useLayoutEffect(() => {
666
+ controller.mount(slot$1, host);
667
+ if (mounted) controller.bind(slot$1);
668
+ else island.generation = -1;
669
+ slot$1.beforeRelease = () => {
670
+ controller.capturePanels(slot$1);
671
+ onRelease(island.editor);
672
+ };
673
+ });
674
+ useLayoutEffect(() => () => host.remove(), [host]);
675
+ useLayoutEffect(() => {
676
+ let frame = requestAnimationFrame(() => {
677
+ frame = requestAnimationFrame(() => setSettled(binding));
678
+ });
679
+ return () => cancelAnimationFrame(frame);
680
+ }, [binding]);
681
+ return createPortal(/* @__PURE__ */ jsx("div", {
682
+ className: slot,
683
+ "data-pool": slot$1.pool,
684
+ "data-restoring": settled !== binding ? "" : void 0,
685
+ "data-virtual-editor-block": slot$1.active ? row.id : void 0,
686
+ "data-virtual-editor-slot": slot$1.id,
687
+ ref,
688
+ style: {
689
+ display: slot$1.active ? void 0 : "none",
690
+ transform: `translateY(${controller.slotOffset(slot$1)}px)`
691
+ },
692
+ onFocusCapture: () => onActiveEditorChange(island.editor),
693
+ children: /* @__PURE__ */ jsx(EditorBlockContext, {
694
+ value,
695
+ children: mounted && /* @__PURE__ */ jsxs(LexicalNestedComposer, {
696
+ skipCollabChecks: true,
697
+ initialEditor: island.editor,
698
+ children: [
699
+ /* @__PURE__ */ jsx(RichTextPlugin, {
700
+ ErrorBoundary: LexicalErrorBoundary,
701
+ contentEditable: /* @__PURE__ */ jsx(ContentEditable, {
702
+ "aria-label": "Document block",
703
+ "aria-placeholder": placeholder$1 ?? "",
704
+ className: `rich-editor__content qi8t62`,
705
+ "data-virtual-editor-content": "",
706
+ placeholder: /* @__PURE__ */ jsx("div", {
707
+ className: "b94s952",
708
+ style: {
709
+ top: 0,
710
+ left: 0,
711
+ display: placeholder$1 ? void 0 : "none"
712
+ },
713
+ children: placeholder$1
714
+ })
715
+ })
716
+ }),
717
+ slot$1.active && surfacePlugins,
718
+ /* @__PURE__ */ jsx(IslandPlugins, {
719
+ controller,
720
+ slot: slot$1
721
+ }),
722
+ slot$1.active && plugins
723
+ ]
724
+ })
725
+ })
726
+ }), host, String(slot$1.id));
727
+ }
728
+ function Contents({ controller, plugins, onActiveEditorChange, onRelease, retainSurface, placeholder }) {
729
+ const [, update] = useState(0);
730
+ useLayoutEffect(() => controller.subscribe(() => update((value) => value + 1)), [controller]);
731
+ useLayoutEffect(() => controller.commitLayout());
732
+ return /* @__PURE__ */ jsx(Fragment$1, { children: controller.pool.slots.map((slot) => /* @__PURE__ */ jsx(EditorSlot, {
733
+ controller,
734
+ plugins,
735
+ retainSurface,
736
+ slot,
737
+ placeholder: controller.rows.length === 1 && controller.rows[0].data.type === "paragraph" && !(controller.rows[0].data.children ?? []).some((child) => child.type !== "text" || child.text) ? placeholder : void 0,
738
+ onActiveEditorChange,
739
+ onRelease
740
+ }, slot.id)) });
741
+ }
742
+ function VirtualizedEditor({ options, className, plugins, autoFocus, hasHeader, onActiveEditorChange, retainSurface, placeholder }) {
743
+ const [editor] = useLexicalComposerContext();
744
+ const { scrollContainer, overscan, estimateBlockHeight, preserveCapacity } = options;
745
+ const stableOptions = useMemo(() => ({
746
+ scrollContainer,
747
+ overscan,
748
+ estimateBlockHeight,
749
+ preserveCapacity
750
+ }), [
751
+ scrollContainer,
752
+ overscan,
753
+ estimateBlockHeight,
754
+ preserveCapacity
755
+ ]);
756
+ const active = useRef(null);
757
+ const selectEditor = useCallback((editor) => {
758
+ active.current = editor;
759
+ onActiveEditorChange(editor);
760
+ }, [onActiveEditorChange]);
761
+ const releaseEditor = useCallback((editor) => {
762
+ if (active.current === editor) selectEditor(null);
763
+ }, [selectEditor]);
764
+ const canvas$1 = useRef(null);
765
+ const [controller, setController] = useState(null);
766
+ const [error, setError] = useState("");
767
+ useEffect(() => {
768
+ setController(null);
769
+ setError("");
770
+ const element = canvas$1.current;
771
+ let instance;
772
+ try {
773
+ instance = new EditorRecycler(editor, element, stableOptions);
774
+ setController(instance);
775
+ Object.assign(element, { virtualEditor: instance });
776
+ } catch (reason) {
777
+ setError(String(reason));
778
+ return;
779
+ }
780
+ return () => {
781
+ selectEditor(null);
782
+ instance.dispose();
783
+ Reflect.deleteProperty(element, "virtualEditor");
784
+ };
785
+ }, [
786
+ editor,
787
+ selectEditor,
788
+ stableOptions
789
+ ]);
790
+ useEffect(() => {
791
+ if (controller && autoFocus) controller.focusBlock(0, false, false);
792
+ }, [autoFocus, controller]);
793
+ return /* @__PURE__ */ jsxs("div", {
794
+ className: `rich-editor__content-wrapper ${contentWrapper}`,
795
+ style: { "--ce-padding-top": `${hasHeader ? 40 : 12}px` },
796
+ children: [error && /* @__PURE__ */ jsx("p", {
797
+ role: "alert",
798
+ children: error
799
+ }), /* @__PURE__ */ jsx("div", {
800
+ className: `${content} ${className ?? ""}`,
801
+ children: /* @__PURE__ */ jsx("div", {
802
+ className: canvas,
803
+ "data-virtual-editor": "",
804
+ ref: canvas$1,
805
+ children: controller && /* @__PURE__ */ jsx(Contents, {
806
+ controller,
807
+ placeholder,
808
+ plugins,
809
+ retainSurface,
810
+ onActiveEditorChange: selectEditor,
811
+ onRelease: releaseEditor
812
+ })
813
+ })
814
+ })]
815
+ });
816
+ }
817
+ //#endregion
818
+ export { VirtualizedEditor };