plitejs 0.0.1 → 54.0.0-beta.3

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 (61) hide show
  1. package/LICENSE +4 -1
  2. package/README.md +83 -0
  3. package/dist/annotation-store-metrics-Ccjkef45.js +12 -0
  4. package/dist/annotations/index.d.ts +2 -0
  5. package/dist/annotations/index.js +2 -0
  6. package/dist/authored/index.d.ts +596 -0
  7. package/dist/authored/index.js +18558 -0
  8. package/dist/authored-veto-DSnQcHGR.js +6 -0
  9. package/dist/browser-protocol-pvt4HFF7.js +5 -0
  10. package/dist/comparison-plan-CEQL0ooW.js +1338 -0
  11. package/dist/comparison-types-Dt-unJZY.d.ts +179 -0
  12. package/dist/create-editor-CkHtPWXV.js +1107 -0
  13. package/dist/diff/index.d.ts +32 -0
  14. package/dist/diff/index.js +1748 -0
  15. package/dist/dom/index.d.ts +2 -0
  16. package/dist/dom/index.js +2 -0
  17. package/dist/dom-Cgfscvnm.js +9220 -0
  18. package/dist/editor-owner-IUmkTeXz.js +171 -0
  19. package/dist/editor-view-lifetime-GJKa_QGh.js +23 -0
  20. package/dist/history/index.d.ts +170 -0
  21. package/dist/history/index.js +6718 -0
  22. package/dist/hyperscript/index.d.ts +2 -0
  23. package/dist/hyperscript/index.js +2 -0
  24. package/dist/hyperscript-FPuoArEi.js +299 -0
  25. package/dist/index-BpQx2UG4.d.ts +1093 -0
  26. package/dist/index-Cw-oC2ps.d.ts +190 -0
  27. package/dist/index-DPWyk3lG.d.ts +65 -0
  28. package/dist/index-DpltOCot.d.ts +9753 -0
  29. package/dist/index-HPYawTae.d.ts +119 -0
  30. package/dist/index-K0Za9YXc.d.ts +1246 -0
  31. package/dist/index.d.ts +2 -0
  32. package/dist/index.js +5 -0
  33. package/dist/internal/index.d.ts +2 -0
  34. package/dist/internal/index.js +156 -0
  35. package/dist/mapped-view-store-ld-6uxEU.js +120 -0
  36. package/dist/native-grouping-input-DMNcsIaW.js +8 -0
  37. package/dist/pagination/index.d.ts +169 -0
  38. package/dist/pagination/index.js +2 -0
  39. package/dist/pagination/react.d.ts +33 -0
  40. package/dist/pagination/react.js +1509 -0
  41. package/dist/pagination-D_A8iPJP.js +1021 -0
  42. package/dist/plugin-DWzkJbnJ.js +50999 -0
  43. package/dist/range-geometry-BLAHRE11.d.ts +38 -0
  44. package/dist/range-geometry-BjeLHOnl.js +486 -0
  45. package/dist/react/index.d.ts +5 -0
  46. package/dist/react/index.js +7 -0
  47. package/dist/react/virtualized.d.ts +13 -0
  48. package/dist/react/virtualized.js +209 -0
  49. package/dist/react-DZ15gmz2.js +1018 -0
  50. package/dist/retraction-BMem8Rfk.js +109 -0
  51. package/dist/src-cT1OTKP_.js +1386 -0
  52. package/dist/store-Cz2mXyDe.js +704 -0
  53. package/dist/testing/index.d.ts +183 -0
  54. package/dist/testing/index.js +96 -0
  55. package/dist/use-editor-dom-scope-BbMDSCpW.js +28354 -0
  56. package/dist/yjs/index.d.ts +2 -0
  57. package/dist/yjs/index.js +2 -0
  58. package/dist/yjs/react/index.d.ts +26 -0
  59. package/dist/yjs/react/index.js +85 -0
  60. package/dist/yjs-DOK-m7kl.js +13413 -0
  61. package/package.json +191 -43
@@ -0,0 +1,1018 @@
1
+ import { Ki as subscribeRootViewPresentation, Kn as getCurrentSelectionRoot, Lr as readEditorHistoryHeadRoots, Y as deleteFragment, Yc as toInternalRoot, Yu as DocumentChange, at as getNodeKey, bc as keyMovedAt, cd as getInternalDocumentChangeRootKeys, ct as getSelection, eu as failInvariant, ft as hasPath, it as getLastCommit, iu as SelectionApi, l as definePlugin, lt as getSnapshot, mu as RangeApi, ot as getPathByNodeKey, rn as string, to as setShownSelectionAsView, vt as insertText, xu as PathApi, ys as getSelectionDOMRange, za as getPlacementGeneration } from "./plugin-DWzkJbnJ.js";
2
+ import { i as transfer } from "./src-cT1OTKP_.js";
3
+ import { a as createEditor$1, d as assertEditorOptions, f as readEditorOptions, i as createDormantEditor, u as EDITOR_OPTION_KEYS } from "./create-editor-CkHtPWXV.js";
4
+ import { t as createEditorOwner } from "./editor-owner-IUmkTeXz.js";
5
+ import { n as createDormantPliteAnnotationStoreOwner } from "./store-Cz2mXyDe.js";
6
+ import { D as DOMEditor, L as resolveWrittenDOMRange, Vt as findEditorDOMRootRuntime, Xn as EDITOR_TO_PENDING_SELECTION, ht as subscribeDropIndicator, mt as readDropIndicator, on as enableKernelTraceRetention, v as dom, yr as getSelection$1 } from "./dom-Cgfscvnm.js";
7
+ import { t as BROWSER_HANDLE_KEY } from "./browser-protocol-pvt4HFF7.js";
8
+ import { $ as applyEditableCommand, At as resolvePliteViewBoundarySegmentEndpoint, Ct as ReactUpdatePolicy, Dt as readPliteViewSelection, Et as isPliteViewSelectionCollapsed, F as useEditorViewState, Ft as ElementContext, G as getPliteNodeElementByPath, J as useEditorSelector, Mt as getPliteViewBoundaryOwnerKey, O as useOptionalPliteRuntimeContext, Ot as subscribePliteViewSelection, Pt as PliteContentRootOwnerContext, Q as getMountedEditableDOMRuntime, Tt as createPliteViewSelection, U as registerBrowserHandle, Ut as useEditorContext, W as didSyncTextPathToDOM, X as useGenericSelector, Y as useEditorState, _t as readPathByNodeKey, at as getEditableKernelTrace, bt as readRuntimeSelection, dt as subscribeTypedText, et as applyModelOwnedHistoryIntent, ft as executeEditableSelectionImport, gt as syncEditorSelectionFromDOM, ht as syncEditableDOMSelectionToEditor, it as clearEditableKernelTrace, jt as createPliteViewBoundaryGraph, kt as writePliteViewSelection, mt as setEditableModelSelectionPreference, nt as shouldForceRenderAfterModelOwnedHistory, ot as recordEditableKernelTrace, pt as isEditableModelSelectionPreferred, q as callShouldUpdate, rt as beginEditableEventFrame, tt as readHistoryGate, vt as readRuntimeText, wt as withPliteReactPreservedSelection, xt as ReactEditor, yt as getHistoryDirectionFromNativeEvent } from "./use-editor-dom-scope-BbMDSCpW.js";
9
+ import { a as useRangeGeometryOwner, n as cutRects, o as useIsomorphicLayoutEffect, t as createRangeGeometryOwner } from "./range-geometry-BjeLHOnl.js";
10
+ import { useCallback, useContext, useEffect, useInsertionEffect, useMemo, useRef, useSyncExternalStore } from "react";
11
+ //#region src/react/editable/projected-native-affordance.ts
12
+ const PROJECTED_NATIVE_AFFORDANCE_MATRIX = Object.freeze({
13
+ clipboard: {
14
+ proof: "Model-owned projected selection writes text/plain, text/html, and editor fragment payloads.",
15
+ status: "supported"
16
+ },
17
+ find: {
18
+ proof: "Browser find indexes mounted DOM text, not private projected ViewSelection spans.",
19
+ status: "degraded"
20
+ },
21
+ ime: {
22
+ proof: "Collapsed root-local IME remains native; expanded projected composition has no native-span proof.",
23
+ status: "degraded"
24
+ },
25
+ mobileSelection: {
26
+ proof: "No raw-device mobile handle proof exists for expanded projected selection.",
27
+ status: "unsupported"
28
+ },
29
+ screenReader: {
30
+ proof: "Private projected selection is model-owned and has no cross-root announcement proof.",
31
+ status: "degraded"
32
+ },
33
+ spellcheck: {
34
+ proof: "Browser spellcheck remains root-local to mounted editable DOM, not projected spans.",
35
+ status: "degraded"
36
+ }
37
+ });
38
+ const getProjectedNativeAffordanceMatrix = () => PROJECTED_NATIVE_AFFORDANCE_MATRIX;
39
+ //#endregion
40
+ //#region src/react/editable/browser-handle.ts
41
+ const cloneRange = (range) => range ? {
42
+ anchor: {
43
+ ...range.anchor,
44
+ path: [...range.anchor.path]
45
+ },
46
+ focus: {
47
+ ...range.focus,
48
+ path: [...range.focus.path]
49
+ }
50
+ } : null;
51
+ const getPublicDocumentChangeRoots = (change) => [
52
+ ...getInternalDocumentChangeRootKeys(change).map((root) => root === "main" ? null : root),
53
+ ...change.createRoots,
54
+ ...change.deleteRoots
55
+ ];
56
+ const createBrowserHandleDataTransfer = ({ html, fragment, text }) => {
57
+ const records = /* @__PURE__ */ new Map();
58
+ if (html) records.set("text/html", html);
59
+ if (text) records.set("text/plain", text);
60
+ if (fragment) records.set("application/x-editor-fragment", fragment);
61
+ return {
62
+ clearData: (format) => {
63
+ if (format) records.delete(format);
64
+ else records.clear();
65
+ },
66
+ dropEffect: "none",
67
+ effectAllowed: "all",
68
+ files: [],
69
+ getData: (format) => records.get(format) ?? "",
70
+ get types() {
71
+ return [...records.keys()];
72
+ },
73
+ items: [],
74
+ setData: (format, value) => {
75
+ records.set(format, value);
76
+ },
77
+ setDragImage: () => {}
78
+ };
79
+ };
80
+ const attachPliteBrowserHandle = ({ browserHandleNextId, browserHandleRangeAnchors, domPhaseScheduler, editor, element, inputController, forceRender, flushPendingNativeTextInput, isViewportBackedSelection, dispatchHistory, scrollPathIntoView, setExplicitViewportBackedSelection }) => {
81
+ const getCurrentHandleElement = () => {
82
+ if (element.isConnected) return element;
83
+ return editor.api.dom.resolveDOMNode(editor) ?? element;
84
+ };
85
+ const refocusHandleElement = () => {
86
+ const focusHandleElement = () => {
87
+ getCurrentHandleElement().focus({ preventScroll: true });
88
+ };
89
+ focusHandleElement();
90
+ domPhaseScheduler.schedule("dom-write", "focus-browser-handle-microtask", focusHandleElement, { timing: "microtask" });
91
+ domPhaseScheduler.schedule("dom-write", "focus-browser-handle-timeout", focusHandleElement, { timing: "timeout" });
92
+ };
93
+ const runCommand = (command, { forceRenderAfter = true } = {}) => {
94
+ const previousIsUpdatingSelection = inputController.state.isUpdatingSelection;
95
+ flushPendingNativeTextInput?.();
96
+ setEditableModelSelectionPreference({
97
+ inputController,
98
+ preferModelSelection: true,
99
+ reason: "browser-handle",
100
+ selectionSource: "model-owned"
101
+ });
102
+ inputController.state.isUpdatingSelection = true;
103
+ inputController.state.selectionChangeOrigin = "browser-handle";
104
+ const selectionBefore = readRuntimeSelection(editor);
105
+ beginEditableEventFrame(editor, {
106
+ eventFamily: "repair",
107
+ focusOwner: "editor",
108
+ inputIntent: null,
109
+ modelSelectionBefore: selectionBefore,
110
+ selectionSource: "model-owned",
111
+ targetOwner: "editor"
112
+ });
113
+ applyEditableCommand({
114
+ command,
115
+ editor,
116
+ element: getCurrentHandleElement()
117
+ });
118
+ const selectionAfter = readRuntimeSelection(editor);
119
+ const viewportBackedSelection = isViewportBackedSelection(getSelectionDOMRange(editor, selectionAfter));
120
+ if (viewportBackedSelection) setEditableModelSelectionPreference({
121
+ inputController,
122
+ preferModelSelection: true,
123
+ reason: "viewport-backed",
124
+ selectionSource: "viewport-backed"
125
+ });
126
+ setExplicitViewportBackedSelection(viewportBackedSelection);
127
+ syncEditableDOMSelectionToEditor({
128
+ editor,
129
+ editorElement: getCurrentHandleElement(),
130
+ options: { forceModelExport: true },
131
+ scrollSelectionIntoView: () => {},
132
+ viewportBackedSelection,
133
+ state: inputController.state
134
+ });
135
+ refocusHandleElement();
136
+ recordEditableKernelTrace({
137
+ editor,
138
+ trace: {
139
+ command,
140
+ eventFamily: "repair",
141
+ intent: null,
142
+ nativeAllowed: false,
143
+ ownership: "model-owned",
144
+ repair: null,
145
+ selectionChangeOrigin: "browser-handle",
146
+ selectionAfter,
147
+ selectionBefore,
148
+ selectionSource: viewportBackedSelection ? "viewport-backed" : "model-owned",
149
+ stateAfter: "model-owned",
150
+ stateBefore: "model-owned",
151
+ targetOwner: "editor"
152
+ }
153
+ });
154
+ if (forceRenderAfter) forceRender();
155
+ const clearBrowserHandleSelectionUpdate = () => {
156
+ if (inputController.state.selectionChangeOrigin === "browser-handle") inputController.state.isUpdatingSelection = previousIsUpdatingSelection;
157
+ };
158
+ domPhaseScheduler.schedule("selection-repair", "clear-browser-handle-selection-update", clearBrowserHandleSelectionUpdate, { timing: "timeout" });
159
+ };
160
+ const handle = {
161
+ applyChange: (change, policy) => {
162
+ const documentChange = DocumentChange.fromJSON(change);
163
+ if (policy) editor.update(policy, (tx) => {
164
+ tx.changes.apply(documentChange);
165
+ });
166
+ else editor.update((tx) => {
167
+ tx.changes.apply(documentChange);
168
+ });
169
+ forceRender();
170
+ },
171
+ applyValueChange: (value, policy) => {
172
+ const documentChange = DocumentChange.between(editor.read.value(), value);
173
+ if (policy) editor.update(policy, (tx) => {
174
+ tx.changes.apply(documentChange);
175
+ });
176
+ else editor.update((tx) => {
177
+ tx.changes.apply(documentChange);
178
+ });
179
+ forceRender();
180
+ },
181
+ createRangeAnchor: (selection, association) => {
182
+ const id = String(browserHandleNextId.current);
183
+ browserHandleNextId.current += 1;
184
+ const rangeAnchor = editor.anchor(selection, {
185
+ association,
186
+ deletion: "nearest"
187
+ });
188
+ browserHandleRangeAnchors.current.set(id, rangeAnchor);
189
+ return id;
190
+ },
191
+ deleteBackward: () => {
192
+ runCommand({
193
+ direction: "backward",
194
+ kind: "delete"
195
+ });
196
+ },
197
+ deleteForward: () => {
198
+ runCommand({
199
+ direction: "forward",
200
+ kind: "delete"
201
+ });
202
+ },
203
+ deleteFragment: () => {
204
+ runCommand({ kind: "delete-fragment" });
205
+ },
206
+ deleteTextAt: (range, policy) => {
207
+ if (policy) editor.update(policy, () => {
208
+ deleteFragment(editor, { at: range });
209
+ });
210
+ else deleteFragment(editor, { at: range });
211
+ forceRender();
212
+ },
213
+ clearSettledPendingNativeTextInputRepair: () => {
214
+ const pathKey = inputController.state.pendingNativeTextInputRepairPathKey;
215
+ const offset = inputController.state.pendingNativeTextInputRepairOffset;
216
+ if (!pathKey || offset == null) return true;
217
+ const modelSelection = readRuntimeSelection(editor);
218
+ if (!modelSelection || !RangeApi.isRange(modelSelection) || !RangeApi.isCollapsed(modelSelection) || modelSelection.anchor.path.join(",") !== pathKey || modelSelection.anchor.offset !== offset) return false;
219
+ const root = ReactEditor.resolveDocumentOrShadowRoot(editor);
220
+ const selection = root ? getSelection$1(root) : null;
221
+ if (!selection || selection.rangeCount === 0) return false;
222
+ const domRange = ReactEditor.resolveRange(editor, selection, { exactMatch: false });
223
+ if (!domRange || !RangeApi.isCollapsed(domRange) || domRange.anchor.path.join(",") !== pathKey || domRange.anchor.offset !== offset) return false;
224
+ const { anchorNode } = selection;
225
+ const textHost = (anchorNode && anchorNode.nodeType === Node.TEXT_NODE ? anchorNode.parentElement : anchorNode instanceof Element ? anchorNode : null)?.closest("[data-editor-node=\"text\"]");
226
+ const editorText = readRuntimeText(editor, domRange.anchor.path)?.text;
227
+ const domText = textHost?.textContent?.replace(/\uFEFF/g, "") ?? null;
228
+ if (!textHost || textHost.getAttribute("data-editor-path") !== pathKey || editorText == null || domText !== editorText) return false;
229
+ inputController.state.pendingNativeTextInputRepairOffset = null;
230
+ inputController.state.pendingNativeTextInputRepairPathKey = null;
231
+ return true;
232
+ },
233
+ focus: () => {
234
+ setEditableModelSelectionPreference({
235
+ inputController,
236
+ preferModelSelection: true,
237
+ reason: "browser-handle",
238
+ selectionSource: "model-owned"
239
+ });
240
+ inputController.state.selectionChangeOrigin = "browser-handle";
241
+ const viewRoot = toInternalRoot(editor.read((state) => state.view.root()));
242
+ if (!getSelection(editor) || getCurrentSelectionRoot(editor) !== viewRoot) {
243
+ const point = editor.read((state) => state.points.start([]));
244
+ if (point) setShownSelectionAsView(editor, point);
245
+ }
246
+ const editorElement = getCurrentHandleElement();
247
+ editorElement.focus({ preventScroll: true });
248
+ forceRender();
249
+ const viewportBackedSelection = isViewportBackedSelection(getSelectionDOMRange(editor, readRuntimeSelection(editor)));
250
+ setExplicitViewportBackedSelection(viewportBackedSelection);
251
+ syncEditableDOMSelectionToEditor({
252
+ editor,
253
+ editorElement,
254
+ options: { forceModelExport: true },
255
+ scrollSelectionIntoView: () => {},
256
+ viewportBackedSelection,
257
+ state: inputController.state
258
+ });
259
+ },
260
+ clearKernelTrace: () => clearEditableKernelTrace(editor),
261
+ getKernelTrace: () => [...getEditableKernelTrace(editor)],
262
+ getExternalTextMetrics: () => getMountedEditableDOMRuntime(editor, element)?.externalText.metrics() ?? null,
263
+ getHistory: () => editor.read((state) => {
264
+ const { history } = state;
265
+ const summarizeBatch = (batch) => {
266
+ const record = batch;
267
+ return {
268
+ change: record.change?.toJSON() ?? null,
269
+ effectCount: record.effects?.length ?? 0,
270
+ roots: record.change ? [...new Set(getPublicDocumentChangeRoots(record.change))] : []
271
+ };
272
+ };
273
+ const snapshot = history?.();
274
+ return {
275
+ redos: snapshot?.redos.map(summarizeBatch) ?? [],
276
+ undos: snapshot?.undos.map(summarizeBatch) ?? []
277
+ };
278
+ }),
279
+ getLastCommit: () => {
280
+ const commit = getLastCommit(editor);
281
+ if (!commit) return null;
282
+ const changedRoots = [...new Set(getPublicDocumentChangeRoots(commit.changes))];
283
+ return {
284
+ change: commit.changes.toJSON(),
285
+ changedRoots,
286
+ classifications: changedRoots.map((root) => ({
287
+ document: commit.changed.has("document", root ?? void 0),
288
+ properties: commit.changed.has("properties", root ?? void 0),
289
+ root,
290
+ structure: commit.changed.has("structure", root ?? void 0),
291
+ text: commit.changed.has("text", root ?? void 0)
292
+ })),
293
+ effectCount: commit.effects.length,
294
+ selectionAfter: commit.selectionAfter,
295
+ selectionBefore: commit.selectionBefore,
296
+ selectionChanged: commit.selectionChanged,
297
+ tags: commit.tags,
298
+ version: commit.version
299
+ };
300
+ },
301
+ getElementByPath: (path) => getPliteNodeElementByPath(editor, path),
302
+ getPathByNodeKey: (nodeKey) => getPathByNodeKey(editor, nodeKey),
303
+ getProjectedNativeAffordanceMatrix,
304
+ getNodeKey: (path) => getNodeKey(editor, path),
305
+ resolveDOMPoint: (point) => editor.api.dom.resolveDOMPoint(point),
306
+ getModelSelection: () => readRuntimeSelection(editor),
307
+ getSelection: () => cloneRange(editor.read.selection()),
308
+ getInputState: () => {
309
+ const selection = getSelectionDOMRange(editor, readRuntimeSelection(editor));
310
+ const modelOwnedDOMCoverageSelection = !!selection && (getMountedEditableDOMRuntime(editor, element)?.domCoverage.getBoundariesForRange(selection).some((boundary) => boundary.selectionPolicy !== "materialize") ?? false);
311
+ return {
312
+ activeIntent: inputController.state.activeIntent,
313
+ isProjectingSelection: inputController.state.isProjectingSelection,
314
+ modelOwnedTextInputGuard: inputController.state.modelOwnedTextInputGuard ?? 0,
315
+ modelSelectionPreference: inputController.state.modelSelectionPreference,
316
+ modelOwnedDOMCoverageSelection,
317
+ pendingDOMSelectionImport: inputController.state.pendingDOMSelectionImport,
318
+ pendingNativeTextInputRepairOffset: inputController.state.pendingNativeTextInputRepairOffset ?? null,
319
+ pendingNativeTextInputRepairPathKey: inputController.state.pendingNativeTextInputRepairPathKey ?? null,
320
+ preferModelSelection: inputController.preferModelSelectionForInputRef.current,
321
+ recentTextInputRepairEcho: inputController.state.recentTextInputRepairEcho ?? null,
322
+ selectionChangeOrigin: inputController.state.selectionChangeOrigin,
323
+ selectionSource: inputController.state.selectionSource
324
+ };
325
+ },
326
+ getBlockText: (index) => {
327
+ const snapshot = getSnapshot(editor);
328
+ if (index < 0 || index >= snapshot.children.length) return null;
329
+ return string(editor, [index]);
330
+ },
331
+ getBlockTexts: () => getSnapshot(editor).children.map((_child, index) => string(editor, [index])),
332
+ getDOMSelection: () => {
333
+ const root = ReactEditor.resolveDocumentOrShadowRoot(editor);
334
+ const selection = root ? getSelection$1(root) : null;
335
+ if (!selection || selection.rangeCount === 0) return null;
336
+ try {
337
+ return ReactEditor.resolveRange(editor, selection, { exactMatch: false });
338
+ } catch {
339
+ return null;
340
+ }
341
+ },
342
+ getDOMPhaseSchedulerDiagnostics: () => domPhaseScheduler?.diagnostics() ?? null,
343
+ getText: (path = []) => string(editor, path),
344
+ getValue: () => editor.read((state) => state.value()),
345
+ getViewSelection: () => readPliteViewSelection(editor),
346
+ importDOMSelection: () => {
347
+ flushPendingNativeTextInput?.();
348
+ const selectionBefore = readRuntimeSelection(editor);
349
+ executeEditableSelectionImport({
350
+ importSelection: () => {
351
+ setEditableModelSelectionPreference({
352
+ inputController,
353
+ preferModelSelection: false,
354
+ selectionSource: "dom-current"
355
+ });
356
+ writePliteViewSelection(editor, null);
357
+ inputController.state.isUpdatingSelection = false;
358
+ inputController.state.selectionChangeOrigin = "native-user";
359
+ syncEditorSelectionFromDOM({
360
+ editor,
361
+ ignoreModelSelectionPreference: true,
362
+ inputController
363
+ });
364
+ },
365
+ selectionPolicy: {
366
+ kind: "import-dom",
367
+ reason: "unknown-selection"
368
+ }
369
+ });
370
+ recordEditableKernelTrace({
371
+ editor,
372
+ trace: {
373
+ command: null,
374
+ eventFamily: "selectionchange",
375
+ intent: null,
376
+ nativeAllowed: true,
377
+ ownership: "native-allowed",
378
+ repair: null,
379
+ selectionChangeOrigin: "browser-handle",
380
+ selectionAfter: readRuntimeSelection(editor),
381
+ selectionBefore,
382
+ selectionPolicy: {
383
+ kind: "import-dom",
384
+ reason: "unknown-selection"
385
+ },
386
+ selectionSource: inputController.state.selectionSource,
387
+ stateAfter: "dom-selection",
388
+ stateBefore: "idle",
389
+ targetOwner: "editor"
390
+ }
391
+ });
392
+ return cloneRange(editor.read.selection());
393
+ },
394
+ insertBreak: () => {
395
+ runCommand({
396
+ kind: "insert-break",
397
+ variant: "paragraph"
398
+ });
399
+ },
400
+ insertData: ({ html, fragment, text }) => {
401
+ const data = createBrowserHandleDataTransfer({
402
+ html,
403
+ fragment,
404
+ text
405
+ });
406
+ runCommand({
407
+ data,
408
+ kind: "insert-data"
409
+ });
410
+ },
411
+ insertText: (text) => {
412
+ const selection = getSelectionDOMRange(editor, readRuntimeSelection(editor));
413
+ const path = selection ? RangeApi.start(selection).path : null;
414
+ runCommand({
415
+ kind: "insert-text",
416
+ text
417
+ });
418
+ if (!path || !didSyncTextPathToDOM(editor, path)) forceRender();
419
+ },
420
+ insertTextAt: (text, at, policy) => {
421
+ if (policy) editor.update(policy, () => {
422
+ insertText(editor, text, { at });
423
+ });
424
+ else insertText(editor, text, { at });
425
+ forceRender();
426
+ },
427
+ redo: () => {
428
+ dispatchHistory("redo", "none", (result) => {
429
+ if (result.status !== "applied") return;
430
+ if (shouldForceRenderAfterModelOwnedHistory(editor)) forceRender();
431
+ refocusHandleElement();
432
+ });
433
+ },
434
+ resolveRangeAnchor: (id) => {
435
+ const selection = browserHandleRangeAnchors.current.get(id)?.resolve() ?? null;
436
+ return cloneRange(selection);
437
+ },
438
+ selectAll: () => {
439
+ runCommand({ kind: "select-all" });
440
+ },
441
+ selectRange: (selection) => {
442
+ flushPendingNativeTextInput?.();
443
+ const previousIsUpdatingSelection = inputController.state.isUpdatingSelection;
444
+ const viewportBackedSelection = isViewportBackedSelection(selection);
445
+ setEditableModelSelectionPreference({
446
+ inputController,
447
+ preferModelSelection: true,
448
+ reason: "browser-handle",
449
+ selectionSource: "model-owned"
450
+ });
451
+ inputController.state.isUpdatingSelection = true;
452
+ inputController.state.selectionChangeOrigin = "browser-handle";
453
+ writePliteViewSelection(editor, null);
454
+ setShownSelectionAsView(editor, selection);
455
+ setExplicitViewportBackedSelection(viewportBackedSelection);
456
+ if (viewportBackedSelection) scrollPathIntoView?.(RangeApi.start(selection).path, "center");
457
+ getCurrentHandleElement().focus({ preventScroll: true });
458
+ const syncDOMSelection = () => {
459
+ if (!isEditableModelSelectionPreferred(inputController)) return;
460
+ syncEditableDOMSelectionToEditor({
461
+ editor,
462
+ editorElement: getCurrentHandleElement(),
463
+ options: { forceModelExport: true },
464
+ scrollSelectionIntoView: () => {},
465
+ viewportBackedSelection,
466
+ state: inputController.state
467
+ });
468
+ };
469
+ syncDOMSelection();
470
+ const clearBrowserHandleSelectionUpdate = () => {
471
+ if (inputController.state.selectionChangeOrigin === "browser-handle") inputController.state.isUpdatingSelection = previousIsUpdatingSelection;
472
+ };
473
+ domPhaseScheduler.schedule("selection-repair", "sync-browser-handle-selection-microtask", syncDOMSelection, { timing: "microtask" });
474
+ domPhaseScheduler.schedule("selection-repair", "sync-browser-handle-selection-timeout", syncDOMSelection, { timing: "timeout" });
475
+ domPhaseScheduler.schedule("selection-repair", "clear-browser-handle-selection-update", clearBrowserHandleSelectionUpdate, { timing: "timeout" });
476
+ },
477
+ setNativeDOMSelection: (selection) => {
478
+ const domRange = resolveWrittenDOMRange(editor, selection, { checkPageText: true });
479
+ if (!domRange) return false;
480
+ const currentElement = getCurrentHandleElement();
481
+ const rootNode = currentElement.getRootNode();
482
+ const ShadowRootConstructor = currentElement.ownerDocument.defaultView?.ShadowRoot;
483
+ const nativeSelection = getSelection$1(rootNode);
484
+ if (!nativeSelection) return false;
485
+ currentElement.focus({ preventScroll: true });
486
+ const documentSelection = currentElement.ownerDocument.getSelection();
487
+ const selectionCandidates = [nativeSelection, documentSelection === nativeSelection ? null : documentSelection].filter((candidate) => !!candidate);
488
+ const applyNativeSelection = (candidate) => {
489
+ candidate.removeAllRanges();
490
+ if (RangeApi.isBackward(selection) && !RangeApi.isCollapsed(selection)) {
491
+ const range = currentElement.ownerDocument.createRange();
492
+ range.setStart(domRange.endContainer, domRange.endOffset);
493
+ range.collapse(true);
494
+ candidate.addRange(range);
495
+ candidate.extend(domRange.startContainer, domRange.startOffset);
496
+ } else candidate.addRange(domRange);
497
+ return candidate.rangeCount > 0;
498
+ };
499
+ if (!selectionCandidates.some(applyNativeSelection)) return false;
500
+ currentElement.ownerDocument.dispatchEvent(new Event("selectionchange", { bubbles: true }));
501
+ if (ShadowRootConstructor && rootNode instanceof ShadowRootConstructor) rootNode.dispatchEvent(new Event("selectionchange", { bubbles: true }));
502
+ return true;
503
+ },
504
+ scrollPathIntoView: (path, align = "center") => scrollPathIntoView?.(path, align) ?? false,
505
+ setViewSelection: (selection) => {
506
+ writePliteViewSelection(editor, selection ? createPliteViewSelection(createPliteViewBoundaryGraph(selection.graph), {
507
+ anchor: selection.anchor,
508
+ focus: selection.focus
509
+ }) : null, { placedAt: getPlacementGeneration(editor) });
510
+ },
511
+ undo: () => {
512
+ dispatchHistory("undo", "none", (result) => {
513
+ if (result.status !== "applied") return;
514
+ if (shouldForceRenderAfterModelOwnedHistory(editor)) forceRender();
515
+ refocusHandleElement();
516
+ });
517
+ },
518
+ releaseRangeAnchor: (id) => {
519
+ const rangeAnchor = browserHandleRangeAnchors.current.get(id);
520
+ if (!rangeAnchor) return null;
521
+ browserHandleRangeAnchors.current.delete(id);
522
+ const selection = rangeAnchor.release();
523
+ return cloneRange(selection);
524
+ }
525
+ };
526
+ element[BROWSER_HANDLE_KEY] = handle;
527
+ return () => {
528
+ if (element["__EDITOR_BROWSER_HANDLE__"] === handle) element[BROWSER_HANDLE_KEY] = void 0;
529
+ };
530
+ };
531
+ //#endregion
532
+ //#region src/react/editable/install-browser-handle.ts
533
+ /**
534
+ * Expose the browser test handle that `@platejs/test` reads on every
535
+ * `Editable` root mounted afterwards, and keep the kernel trace it reads.
536
+ *
537
+ * Call once at module scope in a test or development entry, before the first
538
+ * editor mounts. Production entries never call it, so their bundles drop the
539
+ * handle. Calling it again changes nothing.
540
+ */
541
+ const installBrowserHandle = () => {
542
+ registerBrowserHandle(attachPliteBrowserHandle);
543
+ enableKernelTraceRetention();
544
+ };
545
+ //#endregion
546
+ //#region src/react/hooks/use-editor-runtime-state.ts
547
+ /**
548
+ * Subscribe to a derived state value from an explicit editor instance.
549
+ *
550
+ * Use this for chrome that owns or receives an editor but is outside a
551
+ * `<EditorRoot>` provider. Commit-driven selectors invalidate synchronously. Inside
552
+ * provider descendants, prefer `useEditorState`.
553
+ */
554
+ function useEditorRuntimeState(editor, selector, { equalityFn, shouldUpdate } = {}) {
555
+ const [selectedState, update] = useGenericSelector(useCallback(() => editor.read((state) => selector(state)), [editor, selector]), equalityFn);
556
+ const shouldUpdateRef = useRef(shouldUpdate);
557
+ useIsomorphicLayoutEffect(() => {
558
+ const changed = shouldUpdateRef.current !== shouldUpdate;
559
+ shouldUpdateRef.current = shouldUpdate;
560
+ if (changed) update();
561
+ }, [shouldUpdate, update]);
562
+ const updateWithCommit = useCallback((change) => {
563
+ if (!callShouldUpdate(editor, shouldUpdateRef.current, change)) return;
564
+ update();
565
+ }, [editor, update]);
566
+ useIsomorphicLayoutEffect(() => {
567
+ update();
568
+ return editor.subscribeCommit((change) => {
569
+ updateWithCommit(change);
570
+ });
571
+ }, [
572
+ editor,
573
+ update,
574
+ updateWithCommit
575
+ ]);
576
+ return selectedState;
577
+ }
578
+ //#endregion
579
+ //#region src/react/hooks/use-element-path.ts
580
+ const samePath = (left, right) => {
581
+ if (left === right) return true;
582
+ if (!left || !right || left.length !== right.length) return false;
583
+ return left.every((segment, index) => segment === right[index]);
584
+ };
585
+ /** Subscribe to the live path for the current rendered element. */
586
+ const useElementPath = () => {
587
+ const element = useContext(ElementContext);
588
+ const renderedPath = element?.path ?? null;
589
+ const nodeKey = element?.nodeKey ?? null;
590
+ const root = useEditorContext().read.view.root();
591
+ const selector = useCallback((editor) => {
592
+ const path = readPathByNodeKey(editor, nodeKey) ?? renderedPath;
593
+ return path ? [...path] : null;
594
+ }, [nodeKey, renderedPath]);
595
+ const shouldUpdate = useCallback((change) => {
596
+ if (!nodeKey || !change) return true;
597
+ return keyMovedAt(change.changed, nodeKey, root);
598
+ }, [nodeKey, root]);
599
+ return useEditorSelector(selector, {
600
+ equalityFn: samePath,
601
+ profileId: "element-path",
602
+ runtimeEventSource: "path",
603
+ nodeKey,
604
+ shouldUpdate
605
+ });
606
+ };
607
+ //#endregion
608
+ //#region src/react/hooks/use-element-selected.ts
609
+ /**
610
+ * Subscribe to whether an element path matches the current view's selection,
611
+ * including retained content in a mounted markup view.
612
+ */
613
+ const useElementSelected = ({ at, mode = "intersects" } = {}) => {
614
+ const editor = useEditorContext();
615
+ const owner = useContext(PliteContentRootOwnerContext);
616
+ const context = useContext(ElementContext);
617
+ const element = context?.element ?? null;
618
+ const contextNodeKey = context?.nodeKey ?? null;
619
+ const explicitNodeKey = typeof at === "string" ? at : null;
620
+ const explicitPath = Array.isArray(at) ? at : null;
621
+ const watchedNodeKey = explicitNodeKey ?? (explicitPath ? null : contextNodeKey);
622
+ const resolvePath = useCallback((current) => {
623
+ const path = explicitPath ?? (watchedNodeKey ? getPathByNodeKey(current, watchedNodeKey) : null) ?? (element ? ReactEditor.resolvePath(current, element) : null);
624
+ return path && hasPath(current, path) ? path : null;
625
+ }, [
626
+ element,
627
+ explicitPath,
628
+ watchedNodeKey
629
+ ]);
630
+ const selector = useCallback((current) => {
631
+ const selectedPath = resolvePath(current);
632
+ if (!selectedPath) return false;
633
+ const selection = readRuntimeSelection(current);
634
+ if (!selection) return false;
635
+ if (mode === "node" || mode === "object") return SelectionApi.isNode(selection) && (mode === "node" || selection.mode === "object") && selection.paths.some((candidatePath) => PathApi.equals(candidatePath, selectedPath));
636
+ if (mode === "text" && SelectionApi.isNode(selection)) return false;
637
+ if (mode === "collapsed" && !current.read.selection.isCollapsed()) return false;
638
+ return current.read.selection.intersects(selectedPath);
639
+ }, [mode, resolvePath]);
640
+ const readProjectedSelection = useCallback(() => {
641
+ const selection = readPliteViewSelection(editor);
642
+ if (!selection) return null;
643
+ const selectedPath = resolvePath(editor);
644
+ if (!selectedPath || mode === "node" || mode === "object" || mode === "collapsed" && !isPliteViewSelectionCollapsed(selection)) return false;
645
+ const root = editor.read.view.root() ?? "main";
646
+ const ownerKey = owner ? getPliteViewBoundaryOwnerKey(owner) : null;
647
+ const roots = { [root]: editor.read.children() };
648
+ return selection.segments.parts.some((segment) => {
649
+ if (segment.root !== root || segment.ownerKey !== ownerKey) return false;
650
+ const anchor = resolvePliteViewBoundarySegmentEndpoint(roots, segment, segment.start);
651
+ const focus = resolvePliteViewBoundarySegmentEndpoint(roots, segment, segment.end);
652
+ return !!anchor && !!focus && RangeApi.includes({
653
+ anchor,
654
+ focus
655
+ }, selectedPath);
656
+ });
657
+ }, [
658
+ editor,
659
+ mode,
660
+ owner,
661
+ resolvePath
662
+ ]);
663
+ const projected = useSyncExternalStore(useCallback((notify) => subscribePliteViewSelection(editor, notify), [editor]), readProjectedSelection, readProjectedSelection);
664
+ const shouldUpdate = useCallback((change) => {
665
+ if (explicitPath) return !change || change.selectionChanged || change.changed.hasAny("structure") || change.changed.hasAny("root-order");
666
+ if (!watchedNodeKey || !change) return true;
667
+ const root = editor.read.view.root();
668
+ return change.changed.hasNodeKey(watchedNodeKey, "selection", root) || change.changed.hasNodeKey(watchedNodeKey, "path", root);
669
+ }, [
670
+ editor,
671
+ explicitPath,
672
+ watchedNodeKey
673
+ ]);
674
+ const selected = useEditorSelector(selector, {
675
+ deferred: true,
676
+ nodeKey: explicitPath ? null : watchedNodeKey,
677
+ profileId: "element-selected",
678
+ runtimeEventSource: "selection",
679
+ shouldUpdate
680
+ });
681
+ return projected ?? selected;
682
+ };
683
+ //#endregion
684
+ //#region src/react/hooks/use-plite-annotation-store.tsx
685
+ const createAnnotationStoreOwner = (editor, annotations, options) => {
686
+ const annotationsCell = { current: annotations };
687
+ const optionsCell = { current: options };
688
+ return {
689
+ annotationsCell,
690
+ optionsCell,
691
+ storeOwner: createDormantPliteAnnotationStoreOwner(editor, () => annotationsCell.current, {
692
+ id: options.id,
693
+ onError: (error) => optionsCell.current.onError?.(error)
694
+ })
695
+ };
696
+ };
697
+ /**
698
+ * Create an annotation store from a React-owned annotation value.
699
+ *
700
+ * New array identities refresh automatically. Pass `revision` only when an
701
+ * external mutable source changes without producing a new array.
702
+ */
703
+ function useAnnotationStore(editor, annotations, options = {}) {
704
+ const sourceId = options.id;
705
+ const { annotationsCell, optionsCell, storeOwner } = useMemo(() => createAnnotationStoreOwner(editor, annotations, options), [editor, sourceId]);
706
+ const { store } = storeOwner;
707
+ const storeOwnerRef = useRef(storeOwner);
708
+ const effectVersionRef = useRef(0);
709
+ useInsertionEffect(() => {
710
+ annotationsCell.current = annotations;
711
+ optionsCell.current = options;
712
+ storeOwnerRef.current = storeOwner;
713
+ storeOwner.activate();
714
+ }, [
715
+ annotations,
716
+ annotationsCell,
717
+ options,
718
+ optionsCell,
719
+ storeOwner
720
+ ]);
721
+ useIsomorphicLayoutEffect(() => {
722
+ store.refresh();
723
+ }, [
724
+ annotations,
725
+ annotationsCell,
726
+ options.revision,
727
+ store
728
+ ]);
729
+ useIsomorphicLayoutEffect(() => {
730
+ effectVersionRef.current += 1;
731
+ const effectVersion = effectVersionRef.current;
732
+ return () => {
733
+ queueMicrotask(() => {
734
+ if (storeOwnerRef.current !== storeOwner || effectVersionRef.current === effectVersion) storeOwner.destroy();
735
+ });
736
+ };
737
+ }, [storeOwner]);
738
+ return store;
739
+ }
740
+ //#endregion
741
+ //#region src/react/hooks/use-plite-annotations.tsx
742
+ /** Read one resolved annotation by id from an explicit store. */
743
+ function useAnnotation(store, id) {
744
+ const subscribe = useCallback((listener) => store.subscribeAnnotation(id, listener), [id, store]);
745
+ const getSnapshot = useCallback(() => store.getAnnotation(id), [id, store]);
746
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
747
+ }
748
+ /** Read the current annotation snapshot from an explicit store. */
749
+ function useAnnotations(store) {
750
+ const subscribe = useCallback((listener) => store.subscribe(listener), [store]);
751
+ const getSnapshot = useCallback(() => store.getSnapshot(), [store]);
752
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
753
+ }
754
+ //#endregion
755
+ //#region src/react/plugin/with-react.ts
756
+ const createReactApi = (editor) => Object.freeze({
757
+ isComposing: () => DOMEditor.isComposing(editor),
758
+ isFocused: () => DOMEditor.isFocused(editor),
759
+ isReadOnly: () => DOMEditor.isReadOnly(editor),
760
+ settleInput: () => getMountedEditableDOMRuntime(editor)?.settleInput() ?? !DOMEditor.isComposing(editor),
761
+ subscribeTypedText: (listener) => subscribeTypedText(editor, listener)
762
+ });
763
+ const createReactPlugin = (domPlugin) => definePlugin("react", {
764
+ api: ({ editor }) => createReactApi(editor),
765
+ dependencies: [domPlugin, transfer()],
766
+ on: { commit(context) {
767
+ if (context.commit.changed.hasAny("text") && findEditorDOMRootRuntime(context.editor)?.isAndroidHost) EDITOR_TO_PENDING_SELECTION.delete(context.editor);
768
+ } }
769
+ });
770
+ /**
771
+ * Installs the DOM bridge and exposes React focus, read-only, and composition
772
+ * APIs through the editor plugin system.
773
+ */
774
+ const react = ({ dom: domPlugin }) => createReactPlugin(domPlugin);
775
+ /** @internal */
776
+ const REACT_EDITOR_OPTION_KEYS = {
777
+ ...EDITOR_OPTION_KEYS,
778
+ clipboardFormatKey: true
779
+ };
780
+ /**
781
+ * Creates a React editor with the React bridge installed before custom
782
+ * plugins. Install history explicitly when the editor needs undo/redo.
783
+ */
784
+ function createEditor(options = {}) {
785
+ return createReactEditor(options, false);
786
+ }
787
+ /** @internal */
788
+ const createDormantReactEditor = (options = {}) => createReactEditor(options, true);
789
+ const createReactEditor = (options, dormant) => {
790
+ assertEditorOptions(options, REACT_EDITOR_OPTION_KEYS);
791
+ const { clipboardFormatKey, plugins: authoredPlugins, lifecycleErrorSink, ...editorOptions } = readEditorOptions(options, REACT_EDITOR_OPTION_KEYS);
792
+ const exactDOMPlugin = dom({ clipboardFormatKey });
793
+ const installedPlugins = [react({ dom: exactDOMPlugin }), ...authoredPlugins ?? []];
794
+ const coreOptions = {
795
+ ...editorOptions,
796
+ plugins: installedPlugins,
797
+ lifecycleErrorSink
798
+ };
799
+ return dormant ? createDormantEditor(coreOptions) : createEditor$1(coreOptions);
800
+ };
801
+ //#endregion
802
+ //#region src/react/hooks/use-editor.ts
803
+ function useEditor(options = {}, deps = []) {
804
+ assertEditorOptions(options, REACT_EDITOR_OPTION_KEYS);
805
+ const owner = useMemo(() => createEditorOwner(() => createDormantReactEditor(options)), deps);
806
+ useEditorOwner(owner);
807
+ return owner.editor;
808
+ }
809
+ /** @internal */
810
+ const useEditorOwner = (owner) => {
811
+ useInsertionEffect(() => () => owner.retire(), [owner]);
812
+ useIsomorphicLayoutEffect(() => {
813
+ owner.startUnlessViewStarted();
814
+ owner.layoutConnected();
815
+ return () => owner.layoutDisconnected();
816
+ }, [owner]);
817
+ useEffect(() => {
818
+ owner.passiveConnected();
819
+ return () => owner.passiveDisconnected();
820
+ }, [owner]);
821
+ };
822
+ //#endregion
823
+ //#region src/react/hooks/use-drop-indicator.ts
824
+ /**
825
+ * This view's block drop indicator while a block drag hovers an admitted
826
+ * edge: the target key, edge, axis and the viewport line to paint.
827
+ */
828
+ const useDropIndicator = () => {
829
+ const editor = useEditorContext();
830
+ return useSyncExternalStore(useCallback((listener) => subscribeDropIndicator(editor, listener), [editor]), () => readDropIndicator(editor), () => null);
831
+ };
832
+ //#endregion
833
+ //#region src/react/hooks/use-editable-clip.tsx
834
+ const createEditableClip = (editor, editableRef) => {
835
+ const owner = createRangeGeometryOwner(editor, {
836
+ measure: () => null,
837
+ subscribe: () => () => {}
838
+ }, editableRef);
839
+ return {
840
+ clip: (rects) => {
841
+ const area = owner.readArea();
842
+ return area ? cutRects(rects, area) : [];
843
+ },
844
+ owner
845
+ };
846
+ };
847
+ /**
848
+ * Cuts viewport boxes to `RangeGeometry.clipRect` of one Editable, with the
849
+ * edge rule of `RangeGeometry.visible`. Returns [] when no part shows or no
850
+ * Editable is mounted. It reads layout, so call it where you measure. The
851
+ * returned function is stable.
852
+ */
853
+ function useEditableClip({ editableRef }) {
854
+ const editor = useEditorContext();
855
+ const { clip, owner } = useMemo(() => createEditableClip(editor, editableRef), [editableRef, editor]);
856
+ useRangeGeometryOwner(owner);
857
+ return clip;
858
+ }
859
+ //#endregion
860
+ //#region src/react/hooks/use-plite-history.ts
861
+ const EMPTY = Object.freeze({ status: "empty" });
862
+ const UNCHECKED = Object.freeze({ status: "unchecked" });
863
+ const readUncheckedAnswer = (editor, direction) => readEditorHistoryHeadRoots(editor, direction) === null ? EMPTY : UNCHECKED;
864
+ const isReady = (answer) => answer?.status === "open" || answer?.status === "unchecked";
865
+ const openView = (answer) => answer?.status === "open" ? answer.view : void 0;
866
+ const sameGateAnswer = (a, b) => a === b || a.status === b.status && openView(a) === openView(b);
867
+ const historyGatesEquality = (a, b) => a === b || a !== null && b !== null && a.presentation === b.presentation && sameGateAnswer(a.redo, b.redo) && sameGateAnswer(a.undo, b.undo);
868
+ const selectHistoryPending = (state) => state.history?.pending?.() ?? null;
869
+ /**
870
+ * Create undo/redo commands and keyboard handling.
871
+ *
872
+ * Without `editor` or `root`, they run through the shown writable view used
873
+ * last, and are on only while a shown writable `Editable` reaches every root
874
+ * the next undo or redo changes. With `editor` or `root`, they replay the next
875
+ * batch whatever roots it changes. With `root`, they are off while no view of
876
+ * it is shown. With `editor`, they can stay on while no `Editable` runs that
877
+ * editor, and a click then does nothing. They are off while their view is
878
+ * read-only or composes text.
879
+ */
880
+ function useEditorHistory({ editor: providedEditor, focusPolicy = "restore-root", root: fixedRoot } = {}) {
881
+ if (fixedRoot === "main") throw new Error("Omit root to bind history to the primary document.");
882
+ const context = useOptionalPliteRuntimeContext();
883
+ const source = providedEditor ?? context?.runtime ?? failInvariant("useEditorHistory requires an editor or an EditorRoot.");
884
+ const follows = !providedEditor && !fixedRoot;
885
+ const targetContext = fixedRoot ? context : null;
886
+ const subscribeTarget = useCallback((listener) => targetContext && fixedRoot ? targetContext.subscribeRootTarget(fixedRoot, listener) : () => {}, [fixedRoot, targetContext]);
887
+ const readTarget = useCallback(() => targetContext && fixedRoot ? targetContext.getRootTarget(fixedRoot) : null, [fixedRoot, targetContext]);
888
+ const target = useSyncExternalStore(subscribeTarget, readTarget, readTarget);
889
+ const fixedView = providedEditor ?? target?.view;
890
+ const contextScope = context?.historyScope;
891
+ const [gates, updateGates] = useGenericSelector(useCallback(() => {
892
+ if (!follows) return {
893
+ presentation: null,
894
+ redo: readUncheckedAnswer(source, "redo"),
895
+ undo: readUncheckedAnswer(source, "undo")
896
+ };
897
+ return contextScope ? {
898
+ presentation: contextScope.presentation,
899
+ redo: readHistoryGate(contextScope, "redo"),
900
+ undo: readHistoryGate(contextScope, "undo")
901
+ } : null;
902
+ }, [
903
+ contextScope,
904
+ follows,
905
+ source
906
+ ]), historyGatesEquality);
907
+ const presentation = gates?.presentation;
908
+ useEffect(() => {
909
+ const stopCommits = source.subscribeCommit(() => updateGates());
910
+ const stopNotice = presentation ? subscribeRootViewPresentation(presentation, updateGates) : void 0;
911
+ updateGates();
912
+ return () => {
913
+ stopCommits();
914
+ stopNotice?.();
915
+ };
916
+ }, [
917
+ presentation,
918
+ source,
919
+ updateGates
920
+ ]);
921
+ const historyEditor = follows ? openView(gates?.undo) ?? openView(gates?.redo) : fixedView;
922
+ const shown = providedEditor || follows ? true : target?.shown ?? false;
923
+ const readOnly = useEditorViewState(historyEditor ?? source, (view) => view.isReadOnly());
924
+ const composing = useEditorViewState(historyEditor ?? source, (view) => view.isComposing());
925
+ const pending = useEditorRuntimeState(source, selectHistoryPending);
926
+ const undoReady = isReady(gates?.undo);
927
+ const redoReady = isReady(gates?.redo);
928
+ const applyHistory = useCallback((direction) => {
929
+ const editor = follows ? contextScope && openView(readHistoryGate(contextScope, direction)) : providedEditor ?? (targetContext && fixedRoot ? targetContext.getRootTarget(fixedRoot)?.view : void 0);
930
+ return editor ? applyModelOwnedHistoryIntent({
931
+ direction,
932
+ editor,
933
+ focusPolicy,
934
+ rootCheck: follows ? "check" : "skip"
935
+ }) : false;
936
+ }, [
937
+ contextScope,
938
+ fixedRoot,
939
+ focusPolicy,
940
+ follows,
941
+ providedEditor,
942
+ targetContext
943
+ ]);
944
+ const undo = useCallback(() => {
945
+ applyHistory("undo");
946
+ }, [applyHistory]);
947
+ const redo = useCallback(() => {
948
+ applyHistory("redo");
949
+ }, [applyHistory]);
950
+ const onKeyDown = useCallback((event) => {
951
+ const direction = getHistoryDirectionFromNativeEvent(event.nativeEvent);
952
+ if (!direction || readOnly || composing) return;
953
+ if (!pending && (direction === "undo" ? !undoReady : !redoReady)) return;
954
+ if (!applyHistory(direction)) return;
955
+ event.preventDefault();
956
+ event.stopPropagation();
957
+ }, [
958
+ applyHistory,
959
+ composing,
960
+ pending,
961
+ readOnly,
962
+ redoReady,
963
+ undoReady
964
+ ]);
965
+ return useMemo(() => ({
966
+ canRedo: shown && !readOnly && !composing && pending === null && redoReady,
967
+ canUndo: shown && !readOnly && !composing && pending === null && undoReady,
968
+ onKeyDown,
969
+ pending,
970
+ redo,
971
+ undo
972
+ }), [
973
+ composing,
974
+ onKeyDown,
975
+ pending,
976
+ readOnly,
977
+ redo,
978
+ redoReady,
979
+ shown,
980
+ undo,
981
+ undoReady
982
+ ]);
983
+ }
984
+ //#endregion
985
+ //#region src/react/hooks/use-state-field.ts
986
+ /**
987
+ * Subscribe to one `defineStateField` value.
988
+ *
989
+ * The hook only re-renders when the field key appears in the committed dirty
990
+ * state keys. Use it for document meta controls such as title, page settings,
991
+ * or feature state that should not subscribe to every editor change.
992
+ */
993
+ function useStateFieldValue(field, options = {}) {
994
+ return useEditorState((state) => state.getField(field), {
995
+ ...options,
996
+ shouldUpdate: (change) => Boolean(change?.dirtyStateKeys.includes(field.key))
997
+ });
998
+ }
999
+ /**
1000
+ * Create a setter for one `defineStateField` value.
1001
+ *
1002
+ * The setter writes through `editor.update` and preserves DOM selection by
1003
+ * default so external controls can update state without stealing focus. Pass
1004
+ * an update policy when history or tags need additional control.
1005
+ */
1006
+ function useSetStateField(field) {
1007
+ const editor = useEditorContext();
1008
+ return useCallback((value, policy) => {
1009
+ if (policy) editor.update(withPliteReactPreservedSelection(policy), (tx) => {
1010
+ tx.setField(field, value);
1011
+ });
1012
+ else editor.update(ReactUpdatePolicy.preserveSelection, (tx) => {
1013
+ tx.setField(field, value);
1014
+ });
1015
+ }, [editor, field]);
1016
+ }
1017
+ //#endregion
1018
+ export { useDropIndicator as a, react as c, useAnnotationStore as d, useElementSelected as f, installBrowserHandle as h, useEditableClip as i, useAnnotation as l, useEditorRuntimeState as m, useStateFieldValue as n, useEditor as o, useElementPath as p, useEditorHistory as r, createEditor as s, useSetStateField as t, useAnnotations as u };