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,1386 @@
1
+ import { $i as trackDraftSpans, Af as decodeVersionedValue, Ai as planPaste, B as NodeApi, Bf as defineEffect, Eu as getEditorSchema, Gr as replaceSliceAtBlockBoundary, Ic as readAuthoredView, Is as EditorSchemaValidationError, Mf as encodeVersionedValue, Pf as normalizeEditorValuePersistence, Qi as readDraftTrackAt, Rl as resolveCompiledSchemaProperty, Rn as getAppliedSpecLanding, Sn as applyTransactionSpec, Tu as getEditorRuntimeRoot, Vd as canonicalJsonKey, Vl as toCompiledNodeContext, Wl as uniquePropertiesOf, Yi as getContentSlice, Zf as countCoreWork, Zi as readDraftTrack, _l as markDefinedStateField, au as ElementApi, ba as editorReads, bi as withDraftMove, ca as deleteText, co as createEditorViewRuntime, da as removeNodes, dl as getCompiledEditorSchema, fl as getConfiguredPluginRegistry, hu as PointApi, i as compilePlugin, ip as getDefined, iu as SelectionApi, jc as isDocumentView, ji as writePaste, jn as finalizeTransactionRepresentation, l as definePlugin, ms as withFitLanding, mu as RangeApi, nr as getEditorStateView, pl as getPluginContributions, ps as payloadKeyOf, rc as ContentSlice, rp as cloneFrozen, ta as registerEditorDraftGuard, tu as definePluginPoint, ua as resolveDeletedRange, vr as getTransactionSnapshot, wi as withEditorUpdateRootScope, wu as getEditorRuntimeOwner, xu as PathApi, ya as executeEditorRead } from "./plugin-DWzkJbnJ.js";
2
+ import { _ as screenReaderAnnouncementEffect } from "./create-editor-CkHtPWXV.js";
3
+ //#region src/core/landing.ts
4
+ /** Contribute a veto that refuses a landing on its final edge. */
5
+ const transferVeto = definePluginPoint("transfer.veto");
6
+ var TransferRefusalError = class extends Error {
7
+ reason;
8
+ constructor(reason) {
9
+ super(`Transfer refused: ${reason}`);
10
+ this.name = "TransferRefusalError";
11
+ this.reason = reason;
12
+ }
13
+ };
14
+ const refuse = (reason) => {
15
+ throw new TransferRefusalError(reason);
16
+ };
17
+ const reachableRoots = (editor, value, nodes) => {
18
+ const roots = /* @__PURE__ */ new Set();
19
+ const visit = (children) => {
20
+ for (const node of children) {
21
+ if (!ElementApi.isElement(node)) continue;
22
+ for (const root of Object.values(editor.read.schema.getElementContentRoots(node))) {
23
+ if (roots.has(root)) continue;
24
+ roots.add(root);
25
+ visit(value.roots?.[root] ?? []);
26
+ }
27
+ visit(node.children);
28
+ }
29
+ };
30
+ visit(nodes);
31
+ return roots;
32
+ };
33
+ const liveTarget = (editor, { key }) => {
34
+ const entry = editor.read.nodes.get(key);
35
+ if (!entry || !ElementApi.isElement(entry[0])) refuse("policy");
36
+ return entry;
37
+ };
38
+ const insertionPath = (path, edge) => [...path.slice(0, -1), path.at(-1) + (edge === "after" ? 1 : 0)];
39
+ const insertionIndex = (edge, targetPath) => insertionPath(targetPath, edge.edge).at(-1);
40
+ const checkInside = (editor, { moving }, targetPath) => {
41
+ if (!moving) return;
42
+ const targetRoot = getEditorRuntimeRoot(editor);
43
+ if (moving.root === targetRoot && moving.entries.some(([, path]) => PathApi.equals(path, targetPath) || PathApi.isAncestor(path, targetPath))) refuse("inside-source");
44
+ if (targetRoot !== "main" && reachableRoots(editor, editor.read.value(), moving.entries.map(([node]) => node)).has(targetRoot)) refuse("inside-source");
45
+ };
46
+ const checkIdentity = (editor, request, edge, targetPath) => {
47
+ checkInside(editor, request, targetPath);
48
+ const { moving } = request;
49
+ if (!moving || moving.root !== getEditorRuntimeRoot(editor)) return;
50
+ const parentPath = targetPath.slice(0, -1);
51
+ const index = insertionIndex(edge, targetPath);
52
+ const indices = moving.entries.map(([, path]) => path.at(-1));
53
+ if (moving.entries.every(([, path]) => PathApi.equals(path.slice(0, -1), parentPath)) && indices.every((value, i) => i === 0 || value === indices[i - 1] + 1) && index >= indices[0] && index <= indices.at(-1) + 1) refuse("no-op");
54
+ };
55
+ const checkPlacement = (editor, { fit, intent, moving }, edge, targetPath, replacing = []) => {
56
+ const parentPath = targetPath.slice(0, -1);
57
+ const parent = parentPath.length === 0 ? null : editor.read.nodes.get(parentPath)?.[0];
58
+ const root = getEditorRuntimeRoot(editor);
59
+ const removing = moving?.root === root ? moving.entries.filter(([, path]) => PathApi.equals(path.slice(0, -1), parentPath)).map(([, path]) => path.at(-1)) : [];
60
+ if (!getEditorSchema(editor).canPlaceAt(parent, parent ? parent.children : editor.read.children(), fit, insertionIndex(edge, targetPath), {
61
+ removing: [...removing, ...replacing],
62
+ root,
63
+ strict: intent === "copy"
64
+ })) refuse("schema");
65
+ };
66
+ const runVetoes = (editor, input) => {
67
+ for (const veto of getPluginContributions(editor, transferVeto)) if (veto(input, editor)) refuse("policy");
68
+ };
69
+ const landingInput = (request, edge, target) => ({
70
+ edge: edge.edge,
71
+ from: request.from,
72
+ intent: request.intent,
73
+ payload: request.payload,
74
+ relation: request.relation,
75
+ target
76
+ });
77
+ const readLanding = (editor, input, edge) => executeEditorRead(editor, editorReads.transfer.landing, input, () => edge, editor);
78
+ const sameEdge = (a, b) => a.key === b.key && a.edge === b.edge;
79
+ /** @internal */
80
+ const landingMetrics = { copiedEntries: 0 };
81
+ const copyChildren = (node) => {
82
+ landingMetrics.copiedEntries += node.children.length;
83
+ return {
84
+ ...node,
85
+ children: [...node.children]
86
+ };
87
+ };
88
+ const patchAt = (roots, path, properties, owned) => {
89
+ let siblings = roots;
90
+ for (const [depth, index] of path.entries()) {
91
+ const found = siblings[index];
92
+ const node = ElementApi.isElement(found) ? found : refuse("policy");
93
+ const copy = owned.has(node) ? node : copyChildren(node);
94
+ const next = depth === path.length - 1 ? Object.fromEntries(Object.entries({
95
+ ...copy,
96
+ ...properties
97
+ }).filter(([, value]) => value !== void 0)) : copy;
98
+ owned.add(next);
99
+ siblings[index] = next;
100
+ siblings = next.children;
101
+ }
102
+ };
103
+ const adoptAt = (editor, { fit, intent, payload }, { input }) => {
104
+ if (payload.kind !== "nodes") return null;
105
+ const patches = executeEditorRead(editor, editorReads.transfer.adopt, {
106
+ ...input,
107
+ payload
108
+ }, () => [], editor);
109
+ if (patches.length === 0) return null;
110
+ const schema = getEditorSchema(editor);
111
+ const root = getEditorRuntimeRoot(editor);
112
+ const [, targetPath] = input.target;
113
+ const destination = targetPath.slice(0, -1).map((_, depth) => editor.read.nodes.get(targetPath.slice(0, depth + 1))?.[0]).filter((node) => ElementApi.isElement(node)).reverse();
114
+ const fitted = [...fit];
115
+ const nodes = [...payload.nodes];
116
+ const owned = /* @__PURE__ */ new WeakSet();
117
+ landingMetrics.copiedEntries += fitted.length + nodes.length;
118
+ for (const { at, properties } of patches) {
119
+ const ancestors = [];
120
+ let children = nodes;
121
+ let element;
122
+ for (const index of at) {
123
+ if (element) ancestors.unshift(element);
124
+ const node = children[index];
125
+ if (!ElementApi.isElement(node)) return refuse("policy");
126
+ element = node;
127
+ ({children} = node);
128
+ }
129
+ if (!element || intent === "move" && Object.values(properties).includes(null) || Object.keys(properties).some((key) => schema.elementPropertyLanding(element, key, [...ancestors, ...destination], root) !== "adopt")) return refuse("policy");
130
+ patchAt(nodes, at, properties, owned);
131
+ patchAt(fitted, at, properties, owned);
132
+ }
133
+ return {
134
+ fit: fitted,
135
+ patches,
136
+ payload: {
137
+ ...payload,
138
+ nodes
139
+ }
140
+ };
141
+ };
142
+ const judgeLanding = (editor, request, { edge, input, target: [, path] }, adopted) => {
143
+ checkPlacement(editor, adopted ? {
144
+ ...request,
145
+ fit: adopted.fit
146
+ } : request, edge, path);
147
+ runVetoes(editor, adopted ? {
148
+ ...input,
149
+ payload: adopted.payload
150
+ } : input);
151
+ return {
152
+ adopted,
153
+ edge
154
+ };
155
+ };
156
+ const resolveLanding = (editor, request, edge) => {
157
+ const target = liveTarget(editor, edge);
158
+ checkIdentity(editor, request, edge, target[1]);
159
+ const to = readLanding(editor, landingInput(request, edge, target), edge);
160
+ const redirected = !sameEdge(to, edge);
161
+ const final = redirected ? liveTarget(editor, to) : target;
162
+ const input = landingInput(request, to, final);
163
+ if (redirected) {
164
+ if (!sameEdge(readLanding(editor, input, to), to)) refuse("policy");
165
+ checkIdentity(editor, request, to, final[1]);
166
+ }
167
+ return {
168
+ edge: to,
169
+ input,
170
+ target: final
171
+ };
172
+ };
173
+ const landAt = (editor, request, edge) => {
174
+ const resolved = resolveLanding(editor, request, edge);
175
+ return judgeLanding(editor, request, resolved, adoptAt(editor, request, resolved));
176
+ };
177
+ const withSlot = (shell, slot, children) => {
178
+ if (slot.length === 0) return {
179
+ ...shell,
180
+ children: [...children]
181
+ };
182
+ const [index, ...rest] = slot;
183
+ return {
184
+ ...shell,
185
+ children: shell.children.map((child, i) => i === index ? withSlot(child, rest, children) : child)
186
+ };
187
+ };
188
+ const slotIn = (shell, slot) => {
189
+ const element = slot.length === 0 ? shell : NodeApi.getIf(shell, slot);
190
+ return ElementApi.isElement(element) && element.children.length === 0 ? element : null;
191
+ };
192
+ const checkSlot = (editor, slot, fit) => {
193
+ if (!getEditorSchema(editor).canPlaceAt(slot, [], fit, 0, { root: getEditorRuntimeRoot(editor) })) refuse("schema");
194
+ };
195
+ /**
196
+ * A wrap that takes the target's place moves the target alone, so a target
197
+ * whose feature family reaches past it refuses.
198
+ */
199
+ const landBeside = (editor, request, moving, side) => {
200
+ const target = liveTarget(editor, side);
201
+ const [targetNode, targetPath] = target;
202
+ checkInside(editor, request, targetPath);
203
+ const wrap = executeEditorRead(editor, editorReads.transfer.side, {
204
+ from: request.from,
205
+ intent: request.intent,
206
+ payload: request.payload,
207
+ relation: request.relation,
208
+ side: side.side,
209
+ target
210
+ }, () => null, editor);
211
+ const payloadSlot = wrap && slotIn(wrap.shell, wrap.payload);
212
+ const targetSlot = wrap && "target" in wrap ? slotIn(wrap.shell, wrap.target) : null;
213
+ if (!wrap || !payloadSlot || "target" in wrap && (!targetSlot || PathApi.equals(wrap.target, wrap.payload))) return refuse("policy");
214
+ let anchor;
215
+ let replaced = null;
216
+ if ("target" in wrap) {
217
+ if (moving.entries.some(([, path]) => PathApi.isAncestor(targetPath, path))) refuse("inside-source");
218
+ if (executeEditorRead(editor, editorReads.transfer.source, { selection: SelectionApi.nodes([targetPath], { mode: "block" }) }, ({ selection }) => selection, editor).paths.some((path) => !PathApi.equals(path, targetPath))) return refuse("policy");
219
+ anchor = {
220
+ edge: "before",
221
+ key: side.key
222
+ };
223
+ replaced = {
224
+ key: side.key,
225
+ node: targetNode,
226
+ slot: wrap.target
227
+ };
228
+ } else {
229
+ const key = wrap.ancestor >= 0 && wrap.ancestor < targetPath.length ? editor.key(targetPath.slice(0, targetPath.length - wrap.ancestor)) : null;
230
+ if (!key) return refuse("policy");
231
+ anchor = {
232
+ edge: wrap.edge,
233
+ key
234
+ };
235
+ }
236
+ const anchorEntry = liveTarget(editor, anchor);
237
+ const [, anchorPath] = anchorEntry;
238
+ const filled = withSlot(wrap.shell, wrap.payload, request.fit);
239
+ checkPlacement(editor, {
240
+ ...request,
241
+ fit: [replaced ? withSlot(filled, replaced.slot, [targetNode]) : filled]
242
+ }, anchor, anchorPath, replaced ? [anchorPath.at(-1)] : []);
243
+ checkSlot(editor, payloadSlot, request.fit);
244
+ if (targetSlot) checkSlot(editor, targetSlot, [targetNode]);
245
+ const input = {
246
+ ...landingInput(request, anchor, anchorEntry),
247
+ wrap
248
+ };
249
+ runVetoes(editor, input);
250
+ if (replaced) {
251
+ const parentPath = targetPath.slice(0, -1);
252
+ runVetoes(editor, {
253
+ ...input,
254
+ from: editor,
255
+ intent: "move",
256
+ payload: {
257
+ kind: "nodes",
258
+ nodes: [targetNode],
259
+ parentKeys: [parentPath.length > 0 ? editor.key(parentPath) : null]
260
+ },
261
+ relation: "document"
262
+ });
263
+ }
264
+ return {
265
+ anchor,
266
+ payload: wrap.payload,
267
+ replaced,
268
+ shell: wrap.shell
269
+ };
270
+ };
271
+ //#endregion
272
+ //#region src/core/transfer-guard.ts
273
+ const rootChildren = (value, root) => root === "main" ? value.children : value.roots?.[root] ?? [];
274
+ const childrenAt = (children, path) => {
275
+ let current = children;
276
+ for (const index of path) {
277
+ const node = current[index];
278
+ if (!node || !ElementApi.isElement(node)) return null;
279
+ ({children: current} = node);
280
+ }
281
+ return current;
282
+ };
283
+ const nodeAt = (children, path) => path.length === 0 ? null : childrenAt(children, path.slice(0, -1))?.[path.at(-1)] ?? null;
284
+ /** The elements above `path` in `children`, nearest first. */
285
+ const ancestorsAt = (children, path) => {
286
+ const ancestors = [];
287
+ let current = children;
288
+ for (const index of path.slice(0, -1)) {
289
+ const node = current[index];
290
+ if (!node || !ElementApi.isElement(node)) break;
291
+ ancestors.unshift(node);
292
+ ({children: current} = node);
293
+ }
294
+ return ancestors;
295
+ };
296
+ /**
297
+ * Visits each node of `nodes`, the fragment of a range that starts at `start`,
298
+ * with its path in the children the range was read from.
299
+ */
300
+ const eachFragmentNode = (nodes, start, visit) => {
301
+ const walk = (list, parent, onStartEdge) => {
302
+ list.forEach((node, at) => {
303
+ const path = [...parent, onStartEdge ? start[parent.length] + at : at];
304
+ visit(node, path);
305
+ if (ElementApi.isElement(node)) walk(node.children, path, onStartEdge && at === 0);
306
+ });
307
+ };
308
+ walk(nodes, [], true);
309
+ };
310
+ const NO_KEYS = /* @__PURE__ */ new Set();
311
+ const noDroppedKeys = () => NO_KEYS;
312
+ /** The drops `steps` recorded, by the node each value was carried from. */
313
+ const droppedKeysOf = (steps) => {
314
+ const keys = /* @__PURE__ */ new Map();
315
+ for (const step of steps) for (const { key, place } of step.drops ?? []) {
316
+ const entry = place?.document.nodeStartingAt(place.at);
317
+ if (!place || entry?.from !== place.at) continue;
318
+ const node = place.document.node(entry.path);
319
+ const found = keys.get(node) ?? /* @__PURE__ */ new Set();
320
+ found.add(key);
321
+ keys.set(node, found);
322
+ }
323
+ return keys.size === 0 ? noDroppedKeys : (source) => keys.get(source) ?? NO_KEYS;
324
+ };
325
+ const withoutDropped = (expected, landed, dropped) => dropped.size === 0 ? expected : Object.fromEntries(Object.entries(expected).filter(([key]) => !dropped.has(key) || Object.hasOwn(landed, key)));
326
+ const sameContent = (a, aRoots, b, bRoots, dropped = noDroppedKeys) => {
327
+ if (NodeApi.isText(a) || NodeApi.isText(b)) return canonicalJsonKey(withoutDropped(a, b, dropped(a))) === canonicalJsonKey(b);
328
+ const { children: aChildren, childRoots: aChildRoots, ...aProps } = a;
329
+ const { children: bChildren, childRoots: bChildRoots, ...bProps } = b;
330
+ if (canonicalJsonKey(withoutDropped(aProps, bProps, dropped(a))) !== canonicalJsonKey(bProps)) return false;
331
+ if (aChildren.length !== bChildren.length) return false;
332
+ const aRootNames = Object.keys(aChildRoots ?? {}).sort();
333
+ const bRootNames = Object.keys(bChildRoots ?? {}).sort();
334
+ if (aRootNames.join(",") !== bRootNames.join(",")) return false;
335
+ for (const slot of aRootNames) {
336
+ const aRoot = aRoots?.[aChildRoots?.[slot]] ?? [];
337
+ const bRoot = bRoots?.[bChildRoots?.[slot]] ?? [];
338
+ if (aRoot.length !== bRoot.length || aRoot.some((node, i) => !sameContent(node, aRoots, bRoot[i], bRoots, dropped))) return false;
339
+ }
340
+ return aChildren.every((child, i) => sameContent(child, aRoots, bChildren[i], bRoots, dropped));
341
+ };
342
+ const firstOf = (list) => list[0];
343
+ const lastOf = (list) => list.at(-1);
344
+ const nonEmpty = (nodes) => nodes.filter((node) => !NodeApi.isText(node) || node.text !== "");
345
+ const edgeDepth = (nodes, edge) => {
346
+ let depth = 0;
347
+ for (let node = edge(nonEmpty(nodes)); node && ElementApi.isElement(node); node = edge(nonEmpty(node.children))) depth += 1;
348
+ return depth;
349
+ };
350
+ const closedEdges = ({ content, openEnd, openStart }) => ({
351
+ end: edgeDepth(content, lastOf) - openEnd,
352
+ start: edgeDepth(content, firstOf) - openStart
353
+ });
354
+ const openAtEdge = (node, atStart, atEnd, closed) => !!closed && (atStart && edgeDepth([node], firstOf) > closed.start || atEnd && edgeDepth([node], lastOf) > closed.end);
355
+ const textTokens = (fragment, closed, kind) => {
356
+ const tokens = [];
357
+ const visit = (nodes, onStart, onEnd) => {
358
+ const list = nonEmpty(nodes);
359
+ list.forEach((node, index) => {
360
+ if (NodeApi.isText(node)) {
361
+ tokens.push(canonicalJsonKey(node));
362
+ return;
363
+ }
364
+ const atStart = onStart && index === 0;
365
+ const atEnd = onEnd && index === list.length - 1;
366
+ const open = openAtEdge(node, atStart, atEnd, closed);
367
+ if (!open) {
368
+ const { children: _children, ...props } = node;
369
+ tokens.push(`<${canonicalJsonKey(props)}>`);
370
+ }
371
+ if (kind(node) === "void") for (const child of node.children) tokens.push(canonicalJsonKey(child));
372
+ else visit(node.children, atStart, atEnd);
373
+ if (!open) tokens.push("</>");
374
+ });
375
+ };
376
+ visit(fragment, true, true);
377
+ return tokens.join("\0");
378
+ };
379
+ const headChain = (nodes, kind) => {
380
+ const chain = [];
381
+ let node = nodes[0];
382
+ while (node && ElementApi.isElement(node) && kind(node) === "block") {
383
+ chain.push(node);
384
+ node = node.children[0];
385
+ }
386
+ return chain;
387
+ };
388
+ const openPrefix = (slice, chain) => {
389
+ let nodes = slice.content;
390
+ let count = 0;
391
+ while (count < slice.openStart && count < chain.length && nodes[0] === chain[count]) {
392
+ nodes = chain[count].children;
393
+ count += 1;
394
+ }
395
+ return count;
396
+ };
397
+ const payloadItems = (nodes, exempt) => {
398
+ const items = [];
399
+ const visit = (list, ancestors) => {
400
+ for (const node of list) {
401
+ if (NodeApi.isText(node)) {
402
+ if (node.text !== "") items.push({ text: node });
403
+ continue;
404
+ }
405
+ const shown = !exempt.has(node);
406
+ if (shown) items.push({
407
+ ancestors,
408
+ element: node
409
+ });
410
+ visit(node.children, [node, ...ancestors]);
411
+ if (shown) items.push("</>");
412
+ }
413
+ };
414
+ visit(nodes, []);
415
+ return items;
416
+ };
417
+ const belowCarried = (nodes, kind, carried) => {
418
+ const chain = headChain(nodes, kind);
419
+ const atDrop = chain.length - carried;
420
+ return atDrop < 0 ? null : {
421
+ head: chain[atDrop] ?? null,
422
+ items: payloadItems(nodes, new Set(chain.slice(0, atDrop)))
423
+ };
424
+ };
425
+ const shellOf = (element, skip) => {
426
+ const { children: _children, ...props } = element;
427
+ return canonicalJsonKey(Object.fromEntries(Object.entries(props).filter(([key]) => !skip(key))));
428
+ };
429
+ const carryMove = ({ followsDrop, kind, moved, replaced, sources = /* @__PURE__ */ new Map(), written }) => {
430
+ const movedChain = headChain(moved.content, kind);
431
+ const writtenChain = headChain(written.content, kind);
432
+ const uncarried = movedChain.length - writtenChain.length + openPrefix(written, writtenChain);
433
+ const addsShell = uncarried < 0;
434
+ const losesShell = uncarried > openPrefix(moved, movedChain);
435
+ if (addsShell || losesShell) return null;
436
+ const head = movedChain[uncarried] ?? null;
437
+ return {
438
+ carried: movedChain.length - uncarried,
439
+ followsDrop,
440
+ head,
441
+ inherited: head && replaced ? Object.fromEntries(Object.entries(replaced).filter(([key]) => !(key in head))) : null,
442
+ items: payloadItems(moved.content, new Set(movedChain.slice(0, uncarried))),
443
+ kind,
444
+ sources
445
+ };
446
+ };
447
+ const landsMoved = (landed, { carried, followsDrop, head, inherited, items, kind, sources }, dropped = noDroppedKeys) => {
448
+ const below = belowCarried(landed, kind, carried);
449
+ if (!below) return false;
450
+ const droppedFrom = (node) => {
451
+ const source = sources.get(node);
452
+ return source ? dropped(source) : NO_KEYS;
453
+ };
454
+ const inheritedBy = (element, isHead) => (key) => isHead && !!inherited && Object.hasOwn(inherited, key) && canonicalJsonKey(element[key]) === canonicalJsonKey(inherited[key]);
455
+ return below.items.length === items.length && below.items.every((item, index) => {
456
+ const expected = items[index];
457
+ if (typeof item === "string" || typeof expected === "string") return item === expected;
458
+ if ("text" in item || "text" in expected) {
459
+ if (!("text" in item) || !("text" in expected)) return false;
460
+ return canonicalJsonKey(withoutDropped(expected.text, item.text, droppedFrom(expected.text))) === canonicalJsonKey(item.text);
461
+ }
462
+ const skip = followsDrop(item.element, item.ancestors);
463
+ const landedInherits = inheritedBy(item.element, item.element === below.head);
464
+ const expectedInherits = inheritedBy(expected.element, expected.element === head);
465
+ const dropsHere = droppedFrom(expected.element);
466
+ return shellOf(item.element, (key) => skip(key) || landedInherits(key)) === shellOf(expected.element, (key) => skip(key) || expectedInherits(key) || dropsHere.has(key) && !Object.hasOwn(item.element, key));
467
+ });
468
+ };
469
+ const selectionRange = (from, to) => ({
470
+ anchor: from,
471
+ focus: to
472
+ });
473
+ const trackedRange = (index, { from, to }) => {
474
+ const start = index.pointAt(from, 1);
475
+ const end = index.pointAt(to, -1);
476
+ return start && end ? selectionRange({
477
+ offset: start.offset,
478
+ path: [...start.path]
479
+ }, {
480
+ offset: end.offset,
481
+ path: [...end.path]
482
+ }) : null;
483
+ };
484
+ const childRootNames = (element) => {
485
+ const { childRoots } = element;
486
+ return childRoots ? Object.keys(childRoots).sort().map((slot) => childRoots[slot]) : [];
487
+ };
488
+ const PLACE_MARK = "\0";
489
+ const apartFromPlaces = (name) => name.startsWith(PLACE_MARK) ? `${PLACE_MARK}${name}` : void 0;
490
+ const copyNormalizer = (schema, copyChildren, root) => {
491
+ const unique = uniquePropertiesOf(schema);
492
+ const referenced = new Set([...schema.properties.byId.values()].flatMap(({ references }) => references && unique.has(references.key) ? [references.key] : []));
493
+ return (nodes, roots, { closed, nearestAncestorsOf = () => [] } = {}) => {
494
+ const places = /* @__PURE__ */ new Map();
495
+ const walked = /* @__PURE__ */ new Set();
496
+ const inputs = /* @__PURE__ */ new WeakMap();
497
+ const placeHolders = (list, rootPlace, edges) => {
498
+ let carried = 0;
499
+ const visit = (children, onStart, onEnd) => {
500
+ const kept = nonEmpty(children);
501
+ kept.forEach((node, index) => {
502
+ if (!ElementApi.isElement(node)) return;
503
+ const atStart = onStart && index === 0;
504
+ const atEnd = onEnd && index === kept.length - 1;
505
+ if (!openAtEdge(node, atStart, atEnd, edges)) {
506
+ const place = `${rootPlace}.${carried += 1}`;
507
+ for (const key of referenced) {
508
+ if (node[key] === void 0) continue;
509
+ const byValue = places.get(key) ?? /* @__PURE__ */ new Map();
510
+ const value = canonicalJsonKey(node[key]);
511
+ places.set(key, byValue);
512
+ if (!byValue.has(value)) byValue.set(value, place);
513
+ }
514
+ }
515
+ visit(node.children, atStart, atEnd);
516
+ for (const name of childRootNames(node)) {
517
+ if (walked.has(name)) continue;
518
+ walked.add(name);
519
+ placeHolders(roots?.[name] ?? [], `${PLACE_MARK}${walked.size}`);
520
+ }
521
+ });
522
+ };
523
+ visit(list, true, true);
524
+ };
525
+ placeHolders(nodes, `${PLACE_MARK}0`, closed);
526
+ const nameByPlace = (list, ancestors, at) => {
527
+ const out = list.map((node) => {
528
+ if (!ElementApi.isElement(node)) return node;
529
+ const context = toCompiledNodeContext(node, ancestors, at);
530
+ const renamed = {};
531
+ for (const [key, value] of Object.entries(node)) {
532
+ const references = resolveCompiledSchemaProperty(schema, "element", key, context)?.references;
533
+ const byValue = references && places.get(references.key);
534
+ if (!references || !byValue) continue;
535
+ const mapped = references.map(value, (name) => byValue.get(canonicalJsonKey(name)) ?? apartFromPlaces(name));
536
+ if (canonicalJsonKey(mapped) !== canonicalJsonKey(value)) renamed[key] = mapped;
537
+ }
538
+ const element = Object.keys(renamed).length === 0 ? node : {
539
+ ...node,
540
+ ...renamed
541
+ };
542
+ const children = nameByPlace(node.children, [element, ...ancestors], at);
543
+ return element === node && children === node.children ? node : {
544
+ ...element,
545
+ children
546
+ };
547
+ });
548
+ return out.every((node, index) => node === list[index]) ? list : out;
549
+ };
550
+ const copyRecordingInputs = (list, ancestors, at) => {
551
+ const result = copyChildren(places.size === 0 ? list : nameByPlace(list, ancestors, at), at, ancestors);
552
+ const trace = (out, input) => {
553
+ out.forEach((node, index) => {
554
+ const from = input[index];
555
+ if (node === from) return;
556
+ inputs.set(node, from);
557
+ if (ElementApi.isElement(node) && ElementApi.isElement(from)) trace(node.children, from.children);
558
+ });
559
+ };
560
+ trace(result, list);
561
+ return result;
562
+ };
563
+ return {
564
+ nodes: nodes.flatMap((node, index) => copyRecordingInputs([node], nearestAncestorsOf(index), root)),
565
+ roots: roots && {
566
+ ...roots,
567
+ ...Object.fromEntries([...walked].map((name) => [name, copyRecordingInputs(roots[name] ?? [], [], name)]))
568
+ },
569
+ inputOf: (node) => inputs.get(node) ?? node
570
+ };
571
+ };
572
+ };
573
+ const fragmentOf = (children, range) => NodeApi.fragment({
574
+ children,
575
+ type: ""
576
+ }, range);
577
+ const trackedPaths = (index, spans) => spans.map(({ from, to }) => {
578
+ const entry = index.nodeStartingAt(from);
579
+ return entry && entry.to === to ? [...entry.path] : null;
580
+ });
581
+ const landingHolds = (expected, { children, dropped, index, roots, spans }, copy) => {
582
+ const asCopied = (nodes, from, of) => copy ? copy(nodes, from, of) : {
583
+ inputOf: (node) => node,
584
+ nodes,
585
+ roots: from
586
+ };
587
+ if (expected.kind === "nodes") {
588
+ const paths = trackedPaths(index, spans);
589
+ const nodes = paths.map((path) => path && nodeAt(children, path));
590
+ if (paths.length !== expected.content.length || nodes.some((node) => !node)) return false;
591
+ const of = { nearestAncestorsOf: (at) => ancestorsAt(children, paths[at]) };
592
+ const want = asCopied(expected.content, expected.roots, of);
593
+ const landed = asCopied(nodes, roots, of);
594
+ return landed.nodes.every((node, i) => sameContent(want.nodes[i], want.roots, node, landed.roots, (source) => dropped(want.inputOf(source))));
595
+ }
596
+ const [span] = spans;
597
+ const range = span && trackedRange(index, span);
598
+ if (!range) return false;
599
+ const landed = fragmentOf(children, range);
600
+ if (expected.kind === "range-move") return landsMoved(landed, expected.moved, dropped);
601
+ const { closed, landedKind } = expected;
602
+ return textTokens(asCopied(landed, roots, { closed }).nodes, closed, landedKind) === textTokens(asCopied(expected.content, expected.roots, { closed }).nodes, closed, landedKind);
603
+ };
604
+ /**
605
+ * What a command frame's draft must hold: the landing as the projection the
606
+ * frame started from shows it, or `null` when the projection cannot place the
607
+ * landing.
608
+ */
609
+ const rebaseLanding = ({ expected, track }, frame, root) => {
610
+ const start = readDraftTrackAt(track, frame);
611
+ if (!start) return null;
612
+ const { value } = frame.start;
613
+ const children = rootChildren(value, root);
614
+ if (expected.kind === "nodes") {
615
+ const content = [];
616
+ for (const path of trackedPaths(start.index, start.spans)) {
617
+ const node = path && nodeAt(children, path);
618
+ if (!path || !node) return null;
619
+ content.push(node);
620
+ }
621
+ return {
622
+ content,
623
+ kind: "nodes",
624
+ roots: value.roots
625
+ };
626
+ }
627
+ const [span] = start.spans;
628
+ const range = span && trackedRange(start.index, span);
629
+ if (!range) return null;
630
+ const started = fragmentOf(children, range);
631
+ if (expected.kind === "range-copy") return {
632
+ ...expected,
633
+ content: started,
634
+ roots: value.roots
635
+ };
636
+ const { moved } = expected;
637
+ const below = belowCarried(started, moved.kind, moved.carried);
638
+ if (!below) return null;
639
+ const sources = /* @__PURE__ */ new Map();
640
+ eachFragmentNode(started, range.anchor.path, (node, path) => {
641
+ const source = nodeAt(children, path);
642
+ if (source) sources.set(node, source);
643
+ });
644
+ return {
645
+ kind: "range-move",
646
+ moved: {
647
+ ...moved,
648
+ ...below,
649
+ sources
650
+ }
651
+ };
652
+ };
653
+ const guardLanding = (editor, copy, draft, check, diagnostics) => registerEditorDraftGuard(editor, (written, frame) => {
654
+ const landing = draft.current;
655
+ if (!landing || check(landing, written, frame)) return;
656
+ draft.current = null;
657
+ if (!copy) throw new TransferRefusalError("lossy");
658
+ diagnostics.push({
659
+ impact: "lossy",
660
+ message: "Some dragged content does not fit here."
661
+ });
662
+ }, "plain", "transaction");
663
+ //#endregion
664
+ //#region src/core/transfer.ts
665
+ const targetOf = (landing) => landing.kind === "edge" ? landing.edge : landing.kind === "point" ? { point: landing.point } : landing.side;
666
+ const authoredIdentity = (editor) => {
667
+ const view = readAuthoredView(editor);
668
+ return view && "preview" in view ? view.preview : "native";
669
+ };
670
+ const relationOf = (from, to) => {
671
+ if (getEditorRuntimeOwner(from) !== getEditorRuntimeOwner(to)) return "independent";
672
+ return isDocumentView(from) || isDocumentView(to) || authoredIdentity(from) !== authoredIdentity(to) ? "identity" : "document";
673
+ };
674
+ const pruneAndSort = (entries) => {
675
+ const sorted = [...entries].sort(([, a], [, b]) => PathApi.compare(a, b));
676
+ const kept = [];
677
+ for (const entry of sorted) {
678
+ const previous = kept.at(-1);
679
+ if (previous && PathApi.isAncestor(previous[1], entry[1])) continue;
680
+ kept.push(entry);
681
+ }
682
+ return kept;
683
+ };
684
+ const expandSource = (from, paths) => {
685
+ const expanded = executeEditorRead(from, editorReads.transfer.source, { selection: SelectionApi.nodes(paths, { mode: "block" }) }, ({ selection }) => selection, from);
686
+ return pruneAndSort(expanded.paths.flatMap((path) => {
687
+ const entry = from.read.nodes.get(path);
688
+ return entry ? [entry] : [];
689
+ }));
690
+ };
691
+ const transferEntries = (editor, node) => {
692
+ const selected = editor.read.selection.nodes().map(([, path]) => path);
693
+ const path = node === void 0 ? void 0 : editor.read.nodes.path(node);
694
+ if (node !== void 0 && !path) return [];
695
+ const paths = path ? selected.some((candidate) => PathApi.equals(candidate, path)) ? selected : [path] : selected.length > 0 ? selected : editor.read.nodes.blocks().map(([, blockPath]) => blockPath);
696
+ return paths.length === 0 ? [] : expandSource(editor, paths).filter((entry) => ElementApi.isElement(entry[0]));
697
+ };
698
+ const resolveSource = (from, input) => {
699
+ const root = getEditorRuntimeRoot(from);
700
+ if (input.range) {
701
+ if (RangeApi.isCollapsed(input.range)) refuse("source-missing");
702
+ return {
703
+ deleted: resolveDeletedRange(from, input.range),
704
+ kind: "text",
705
+ range: input.range,
706
+ root
707
+ };
708
+ }
709
+ const found = input.nodes?.map((key) => from.read.nodes.get(key));
710
+ if (found && (found.length === 0 || found.some((entry) => !entry))) refuse("source-missing");
711
+ const entries = found ? expandSource(from, found.map(([, path]) => path)) : transferEntries(from);
712
+ if (entries.length === 0) refuse("source-missing");
713
+ return {
714
+ entries,
715
+ kind: "nodes",
716
+ root
717
+ };
718
+ };
719
+ const payloadOf = (from, source) => source.kind === "text" ? { kind: "text" } : {
720
+ kind: "nodes",
721
+ nodes: source.entries.map(([node]) => node),
722
+ parentKeys: source.entries.map(([, path]) => path.length > 1 ? from.key(path.slice(0, -1)) : null)
723
+ };
724
+ /**
725
+ * Where each node of a moved range's payload came from, so its landing can
726
+ * judge a value the node carried. An open edge block merges into the
727
+ * landing's block instead of landing as itself, so it gets no source.
728
+ */
729
+ const payloadSourcesOf = (index, range, slice, inline) => {
730
+ const open = /* @__PURE__ */ new Set();
731
+ const edges = [[slice.openStart, (list) => list[0]], [slice.openEnd, (list) => list.at(-1)]];
732
+ for (const [depth, edge] of edges) {
733
+ let list = slice.content;
734
+ for (let level = 0; level < depth; level += 1) {
735
+ const node = edge(list);
736
+ if (!node || !ElementApi.isElement(node)) break;
737
+ if (!inline(node)) open.add(node);
738
+ list = node.children;
739
+ }
740
+ }
741
+ const [start] = RangeApi.edges(range);
742
+ const landing = [];
743
+ const nodes = /* @__PURE__ */ new Map();
744
+ eachFragmentNode(slice.content, start.path, (node, path) => {
745
+ if (NodeApi.isText(node) ? node.text === "" : open.has(node)) return;
746
+ countCoreWork("landingSources");
747
+ landing.push({
748
+ at: index.nodeRange(path).from,
749
+ document: index,
750
+ kind: NodeApi.isText(node) ? "text" : "element",
751
+ payload: payloadKeyOf(node)
752
+ });
753
+ nodes.set(node, index.node(path));
754
+ });
755
+ return {
756
+ landing,
757
+ nodes
758
+ };
759
+ };
760
+ const checkTextLanding = (editor, admission, point) => {
761
+ const { source, intent, relation } = admission;
762
+ if (source.kind !== "text" || intent !== "move" || relation !== "document" || source.root !== getEditorRuntimeRoot(editor)) return;
763
+ const [selectedStart, selectedEnd] = RangeApi.edges(source.range);
764
+ const [deletedStart, deletedEnd] = RangeApi.edges(source.deleted ?? source.range);
765
+ if ([
766
+ selectedStart,
767
+ selectedEnd,
768
+ deletedStart,
769
+ deletedEnd
770
+ ].some((edge) => PointApi.equals(point, edge))) refuse("no-op");
771
+ const start = PointApi.isBefore(deletedStart, selectedStart) ? deletedStart : selectedStart;
772
+ const end = PointApi.isAfter(deletedEnd, selectedEnd) ? deletedEnd : selectedEnd;
773
+ if (PointApi.isAfter(point, start) && PointApi.isBefore(point, end)) refuse("inside-source");
774
+ };
775
+ const requestOf = (from, intent, payload, relation, source, slice) => ({
776
+ fit: source.kind !== "nodes" ? [] : slice ? slice.content : source.entries.map(([node]) => node),
777
+ from,
778
+ intent,
779
+ moving: source.kind === "nodes" && intent === "move" && relation === "document" ? {
780
+ entries: source.entries,
781
+ root: source.root
782
+ } : null,
783
+ payload,
784
+ relation
785
+ });
786
+ const resolveStep = (editor, request, source, direction) => {
787
+ if (source.kind !== "nodes" || source.root !== getEditorRuntimeRoot(editor)) return refuse("policy");
788
+ const parent = source.entries[0][1].slice(0, -1);
789
+ if (source.entries.some(([, path]) => !PathApi.equals(path.slice(0, -1), parent))) return refuse("policy");
790
+ const next = direction === "next";
791
+ const [, anchorPath] = next ? source.entries.at(-1) : source.entries[0];
792
+ const anchorKey = request.from.key(anchorPath);
793
+ const payload = new Set(source.entries.map(([node]) => node));
794
+ let path = anchorKey ? editor.read.nodes.path(anchorKey) : void 0;
795
+ let reason = "no-op";
796
+ while (path) {
797
+ path = next ? PathApi.next(path) : PathApi.hasPrevious(path) ? PathApi.previous(path) : void 0;
798
+ const entry = path && editor.read.nodes.get(path);
799
+ const key = path && editor.key(path);
800
+ if (!entry || !key) break;
801
+ if (payload.has(entry[0])) continue;
802
+ try {
803
+ const resolved = resolveLanding(editor, request, {
804
+ edge: next ? "after" : "before",
805
+ key
806
+ });
807
+ judgeLanding(editor, request, resolved, null);
808
+ const landed = editor.read.nodes.path(resolved.edge.key);
809
+ if (landed && PathApi.equals(landed.slice(0, -1), parent)) {
810
+ const adopted = adoptAt(editor, request, resolved);
811
+ return adopted ? judgeLanding(editor, request, resolved, adopted) : {
812
+ adopted,
813
+ edge: resolved.edge
814
+ };
815
+ }
816
+ reason = "policy";
817
+ } catch (error) {
818
+ if (!(error instanceof TransferRefusalError)) throw error;
819
+ ({reason} = error);
820
+ }
821
+ }
822
+ return refuse(reason);
823
+ };
824
+ const sameKey = (left, right) => left.every((part, i) => Object.is(part, right[i]));
825
+ const SOURCES = /* @__PURE__ */ new WeakMap();
826
+ const resolvePayload = (from, input) => {
827
+ const key = [
828
+ input.nodes?.join("\0") ?? (input.range ? JSON.stringify(input.range) : from.read.selection()),
829
+ from.read.runtime.snapshot(),
830
+ getConfiguredPluginRegistry(from).configurationRevision
831
+ ];
832
+ const cached = SOURCES.get(from);
833
+ if (cached && sameKey(cached.key, key)) return cached;
834
+ const source = resolveSource(from, input);
835
+ const resolved = {
836
+ key,
837
+ payload: payloadOf(from, source),
838
+ slices: {},
839
+ source
840
+ };
841
+ SOURCES.set(from, resolved);
842
+ return resolved;
843
+ };
844
+ const admit = (editor, input, method) => {
845
+ const from = input.from ?? editor;
846
+ const { payload, slices, source } = resolvePayload(from, input);
847
+ const relation = relationOf(from, editor);
848
+ const intent = method === "copy" || relation !== "document" || from.read.view.isReadOnly() ? "copy" : "move";
849
+ if (editor.read.view.isReadOnly()) refuse("read-only-target");
850
+ if (source.kind === "text" && intent === "move") {
851
+ const { deleted } = source;
852
+ if (!deleted) refuse("lossy");
853
+ else if (RangeApi.isCollapsed(deleted)) refuse("no-op");
854
+ }
855
+ const slice = source.kind === "nodes" && intent === "move" && source.root === getEditorRuntimeRoot(editor) ? null : slices[intent] ??= getContentSlice(from, source.kind === "text" ? intent === "move" && source.deleted || source.range : SelectionApi.nodes(source.entries.map(([, path]) => path), { mode: "block" }), void 0, intent);
856
+ const request = requestOf(from, intent, payload, relation, source, slice);
857
+ const admitted = (landing) => ({
858
+ relocatedAdoption: null,
859
+ intent,
860
+ landing,
861
+ relation,
862
+ slice,
863
+ source
864
+ });
865
+ const admittedEdge = ({ adopted, edge }) => ({
866
+ ...admitted({
867
+ edge,
868
+ kind: "edge"
869
+ }),
870
+ relocatedAdoption: slice ? null : adopted,
871
+ slice: adopted && slice ? ContentSlice.withContent(slice, adopted.fit, { open: "preserve" }) : slice
872
+ });
873
+ if (typeof input.to === "string") return admittedEdge(resolveStep(editor, request, source, input.to));
874
+ if ("point" in input.to) {
875
+ if (source.kind === "nodes") refuse("schema");
876
+ const admission = admitted({
877
+ kind: "point",
878
+ point: input.to.point
879
+ });
880
+ checkTextLanding(editor, admission, input.to.point);
881
+ return admission;
882
+ }
883
+ if ("side" in input.to) {
884
+ if (source.kind !== "nodes" || slice || !request.moving) return refuse("policy");
885
+ return admitted({
886
+ keys: source.entries.map(([, path]) => from.key(path)),
887
+ kind: "wrap",
888
+ side: input.to,
889
+ wrap: landBeside(editor, request, request.moving, input.to)
890
+ });
891
+ }
892
+ return admittedEdge(landAt(editor, request, input.to));
893
+ };
894
+ const runTransfer = (editor, input, method) => {
895
+ const from = input.from ?? editor;
896
+ const diagnostics = [];
897
+ let admission;
898
+ try {
899
+ admission = admit(editor, input, method);
900
+ } catch (error) {
901
+ if (error instanceof TransferRefusalError) return {
902
+ reason: error.reason,
903
+ status: "refused"
904
+ };
905
+ throw error;
906
+ }
907
+ const { intent, landing, relation, relocatedAdoption, slice, source } = admission;
908
+ const copy = intent === "copy";
909
+ const targetRoot = getEditorRuntimeRoot(editor);
910
+ const before = from.read.value();
911
+ const relocate = !slice;
912
+ const carried = landing.kind === "wrap" && landing.wrap.replaced ? [landing.wrap.replaced] : [];
913
+ const content = slice ? slice.content : source.kind === "nodes" ? [...relocatedAdoption?.payload.nodes ?? source.entries.map(([node]) => node), ...carried.map(({ node }) => node)] : [];
914
+ const schema = getEditorSchema(editor);
915
+ const normalize = copy ? copyNormalizer(getCompiledEditorSchema(editor), schema.copyChildren, targetRoot) : null;
916
+ const draft = { current: null };
917
+ const runtime = getEditorRuntimeOwner(editor);
918
+ const trackNodes = (paths) => {
919
+ const snapshot = getDefined(getTransactionSnapshot(runtime));
920
+ const index = snapshot.builder.getIndex(targetRoot);
921
+ return {
922
+ expected: {
923
+ content,
924
+ kind: "nodes",
925
+ roots: slice ? slice.roots : before.roots
926
+ },
927
+ track: trackDraftSpans(snapshot, snapshot.builder, targetRoot, paths.map((path) => index.nodeRange(path)))
928
+ };
929
+ };
930
+ const followsDrop = (element, ancestors) => (key) => schema.elementPropertyLanding(element, key, ancestors, targetRoot) !== "preserve";
931
+ const release = guardLanding(editor, copy, draft, (drafted, after, frame) => {
932
+ const builder = getTransactionSnapshot(runtime)?.builder;
933
+ const spans = builder?.value === after ? readDraftTrack(drafted.track, after, frame) : null;
934
+ if (!builder || !spans) return false;
935
+ const expected = frame ? rebaseLanding(drafted, frame, targetRoot) : drafted.expected;
936
+ return !!expected && landingHolds(expected, {
937
+ children: rootChildren(after, targetRoot),
938
+ dropped: droppedKeysOf(builder.draftSteps),
939
+ index: builder.getIndex(targetRoot),
940
+ roots: after.roots,
941
+ spans
942
+ }, normalize);
943
+ }, diagnostics);
944
+ let landed = null;
945
+ const select = typeof input.to !== "string";
946
+ let held = null;
947
+ const hold = (range) => {
948
+ const [start, end] = RangeApi.edges(range);
949
+ held = {
950
+ end: editor.anchor(end, {
951
+ association: "backward",
952
+ deletion: "nearest"
953
+ }),
954
+ kind: "range",
955
+ start: editor.anchor(start, {
956
+ association: "forward",
957
+ deletion: "nearest"
958
+ })
959
+ };
960
+ };
961
+ const holdNodes = (nodes) => {
962
+ held = {
963
+ first: editor.anchor(nodes.anchorPath, { deletion: "nearest" }),
964
+ kind: "nodes",
965
+ last: editor.anchor(nodes.focusPath, { deletion: "nearest" })
966
+ };
967
+ };
968
+ const asMove = (role, run) => copy ? run() : withDraftMove(getEditorRuntimeOwner(editor), { role }, run);
969
+ let accepted;
970
+ try {
971
+ accepted = editor.update((tx) => {
972
+ if (input.announce) tx.effects.emit(screenReaderAnnouncementEffect, input.announce);
973
+ const pathOf = (key) => tx.nodes.get(key)?.[1] ?? refuse("source-missing");
974
+ const besidePath = (anchor, edge, leaving) => {
975
+ const index = anchor.at(-1);
976
+ const shifted = PathApi.equals(leaving.slice(0, -1), anchor.slice(0, -1)) && leaving.at(-1) < index ? index - 1 : index;
977
+ return [...anchor.slice(0, -1), edge === "before" ? shifted : shifted + 1];
978
+ };
979
+ const moveChain = (keys, first) => {
980
+ keys.forEach((key, index) => {
981
+ const at = pathOf(key);
982
+ tx.nodes.move({
983
+ at,
984
+ to: index === 0 ? first() : besidePath(pathOf(keys[index - 1]), "after", at)
985
+ });
986
+ });
987
+ };
988
+ const selectLanded = (keys) => {
989
+ const paths = keys.map(pathOf);
990
+ const nodes = SelectionApi.nodes(paths, { mode: "block" });
991
+ landed = nodes;
992
+ draft.current = trackNodes([...paths, ...carried.map(({ key }) => pathOf(key))]);
993
+ holdNodes(nodes);
994
+ if (select) tx.selection.set(nodes);
995
+ };
996
+ if (landing.kind === "wrap") {
997
+ const { anchor, payload, replaced, shell } = landing.wrap;
998
+ const shellPath = insertionPath(pathOf(anchor.key), anchor.edge);
999
+ tx.nodes.insert(shell, { at: shellPath });
1000
+ const shellKey = tx.key(shellPath) ?? refuse("schema");
1001
+ const slot = (path, index) => [
1002
+ ...pathOf(shellKey),
1003
+ ...path,
1004
+ index
1005
+ ];
1006
+ if (replaced) tx.nodes.move({
1007
+ at: pathOf(replaced.key),
1008
+ to: slot(replaced.slot, 0)
1009
+ });
1010
+ moveChain(landing.keys, () => slot(payload, 0));
1011
+ selectLanded(landing.keys);
1012
+ return true;
1013
+ }
1014
+ if (relocate && source.kind === "nodes" && landing.kind === "edge") {
1015
+ const keys = source.entries.map(([, path]) => from.key(path));
1016
+ const { edge } = landing;
1017
+ moveChain(keys, () => besidePath(pathOf(edge.key), edge.edge, pathOf(keys[0])));
1018
+ for (const { at, properties } of relocatedAdoption?.patches ?? []) {
1019
+ const [index, ...rest] = at;
1020
+ tx.nodes.set(properties, {
1021
+ at: [...pathOf(keys[index]), ...rest],
1022
+ voids: true
1023
+ });
1024
+ }
1025
+ selectLanded(keys);
1026
+ return true;
1027
+ }
1028
+ const removeSource = () => {
1029
+ if (copy) return;
1030
+ asMove("source", removeSourceSteps);
1031
+ };
1032
+ const removeSourceSteps = () => {
1033
+ if (source.root === targetRoot) {
1034
+ if (source.kind === "text") tx.text.delete({ at: source.range });
1035
+ else for (const [, path] of [...source.entries].reverse()) tx.nodes.remove({ at: path });
1036
+ return;
1037
+ }
1038
+ const owner = getEditorRuntimeOwner(editor);
1039
+ withEditorUpdateRootScope(owner, source.root, () => {
1040
+ if (source.kind === "text") deleteText(owner, { at: source.range });
1041
+ else for (const [, path] of [...source.entries].reverse()) removeNodes(owner, { at: path });
1042
+ });
1043
+ };
1044
+ const landedKind = (element) => {
1045
+ const behavior = schema.getElementBehavior(element);
1046
+ return behavior.void ? "void" : behavior.inline ? "inline" : "block";
1047
+ };
1048
+ const landAsPaste = (at, copied, sources = null) => {
1049
+ const plan = planPaste(editor, getEditorStateView(editor), {
1050
+ options: { at },
1051
+ slice: copied
1052
+ }, intent, { drop: true });
1053
+ if (!plan) return null;
1054
+ if (!copy && (plan.inputCut || plan.landingCut)) refuse("lossy");
1055
+ const written = withFitLanding(copy ? { kind: "paste" } : {
1056
+ kind: "move",
1057
+ sources: sources?.landing ?? []
1058
+ }, () => writePaste(editor, plan, { landing: true }));
1059
+ if (!written) return null;
1060
+ if (written.lossy) diagnostics.push({
1061
+ impact: "lossy",
1062
+ message: "Some dragged content does not fit here."
1063
+ });
1064
+ applyTransactionSpec(getEditorRuntimeOwner(editor), written.spec);
1065
+ return {
1066
+ expected: copy ? {
1067
+ closed: closedEdges(written.written),
1068
+ content: written.written.content,
1069
+ kind: "range-copy",
1070
+ landedKind,
1071
+ roots: written.written.roots
1072
+ } : {
1073
+ kind: "range-move",
1074
+ moved: carryMove({
1075
+ followsDrop,
1076
+ kind: landedKind,
1077
+ moved: copied,
1078
+ replaced: written.written === plan.emptyBlockReplacement ? plan.site.target.block?.[0] ?? null : null,
1079
+ sources: sources?.nodes,
1080
+ written: written.written
1081
+ }) ?? refuse("lossy")
1082
+ },
1083
+ spec: written.spec
1084
+ };
1085
+ };
1086
+ if (landing.kind === "point") {
1087
+ const drop = tx.anchor(landing.point, {
1088
+ association: "backward",
1089
+ deletion: "nearest"
1090
+ });
1091
+ const { builder: moving } = getDefined(getTransactionSnapshot(runtime));
1092
+ const sources = moving.tracksPlaces && !copy && slice && source.kind === "text" && source.root === targetRoot ? payloadSourcesOf(moving.getIndex(targetRoot), source.deleted ?? source.range, slice, (element) => schema.getElementBehavior(element).inline) : null;
1093
+ removeSource();
1094
+ finalizeTransactionRepresentation(getEditorRuntimeOwner(editor));
1095
+ const point = drop.resolve();
1096
+ const pasted = point && slice && asMove("landing", () => landAsPaste(point, slice, sources)) || refuse("schema");
1097
+ const track = getAppliedSpecLanding(pasted.spec) ?? refuse("schema");
1098
+ const { builder } = getDefined(getTransactionSnapshot(runtime));
1099
+ const [span] = readDraftTrack(track, builder.value) ?? [];
1100
+ const index = builder.getIndex(targetRoot);
1101
+ const range = (span && trackedRange(index, span)) ?? refuse("schema");
1102
+ const nodeAtPath = (path) => index.find(path);
1103
+ const beside = (edge, step) => {
1104
+ const at = edge.path.slice(0, -1);
1105
+ const node = nodeAtPath(at);
1106
+ const behavior = node && ElementApi.isElement(node) && schema.getElementBehavior(node);
1107
+ const path = [...at.slice(0, -1), at.at(-1) + step];
1108
+ const text = behavior && behavior.void && behavior.inline && nodeAtPath(path);
1109
+ return text && NodeApi.isText(text) ? {
1110
+ offset: step < 0 ? text.text.length : 0,
1111
+ path
1112
+ } : edge;
1113
+ };
1114
+ landed = selectionRange(beside(range.anchor, -1), beside(range.focus, 1));
1115
+ draft.current = {
1116
+ expected: pasted.expected,
1117
+ track
1118
+ };
1119
+ hold(landed);
1120
+ if (select) tx.selection.set(landed);
1121
+ return true;
1122
+ }
1123
+ removeSource();
1124
+ const target = tx.nodes.get(landing.edge.key);
1125
+ if (!target || !slice) refuse("policy");
1126
+ const [, targetPath] = target;
1127
+ const boundary = insertionPath(targetPath, landing.edge.edge);
1128
+ if (!asMove("landing", () => replaceSliceAtBlockBoundary(getEditorRuntimeOwner(editor), slice, boundary, { drop: true }))) refuse("schema");
1129
+ const first = boundary.at(-1);
1130
+ const paths = content.map((_, i) => [...boundary.slice(0, -1), first + i]);
1131
+ const nodes = SelectionApi.nodes(paths, { mode: "block" });
1132
+ landed = nodes;
1133
+ draft.current = trackNodes(paths);
1134
+ holdNodes(nodes);
1135
+ if (select) tx.selection.set(nodes);
1136
+ return true;
1137
+ });
1138
+ } catch (error) {
1139
+ releaseHeld(held);
1140
+ if (error instanceof TransferRefusalError) return {
1141
+ reason: error.reason,
1142
+ status: "refused"
1143
+ };
1144
+ if (error instanceof EditorSchemaValidationError) return {
1145
+ reason: "schema",
1146
+ status: "refused"
1147
+ };
1148
+ throw error;
1149
+ } finally {
1150
+ release();
1151
+ }
1152
+ if (!accepted) {
1153
+ releaseHeld(held);
1154
+ return {
1155
+ reason: "policy",
1156
+ status: "refused"
1157
+ };
1158
+ }
1159
+ const at = readHeld(held, landed);
1160
+ if (!at) return {
1161
+ reason: "schema",
1162
+ status: "refused"
1163
+ };
1164
+ if (!copy) return {
1165
+ at,
1166
+ status: "moved"
1167
+ };
1168
+ return {
1169
+ at,
1170
+ diagnostics,
1171
+ reason: method === "copy" ? "intent" : relation === "independent" ? "independent" : relation === "identity" ? "identity" : "read-only-source",
1172
+ status: "copied"
1173
+ };
1174
+ };
1175
+ const releaseHeld = (held) => {
1176
+ if (held?.kind === "range") {
1177
+ held.start.release();
1178
+ held.end.release();
1179
+ } else if (held) {
1180
+ held.first.release();
1181
+ held.last.release();
1182
+ }
1183
+ };
1184
+ const readHeld = (held, landed) => {
1185
+ if (!held || !landed) return landed;
1186
+ const edges = held.kind === "range" ? [held.start.resolve(), held.end.resolve()] : [held.first.resolve(), held.last.resolve()];
1187
+ releaseHeld(held);
1188
+ const [start, end] = edges;
1189
+ if (!start || !end) return landed;
1190
+ if (held.kind === "range") return selectionRange(start, end);
1191
+ const first = start;
1192
+ const parent = first.slice(0, -1);
1193
+ const from = first.at(-1);
1194
+ const to = end.at(-1);
1195
+ const rest = Array.from({ length: Math.max(0, to - from) }, (_, offset) => [...parent, from + offset + 1]);
1196
+ return SelectionApi.nodes([first, ...rest], { mode: "block" });
1197
+ };
1198
+ const CHECKS = /* @__PURE__ */ new WeakMap();
1199
+ const checkKey = (editor, input, method) => {
1200
+ const from = input.from ?? editor;
1201
+ return [
1202
+ from,
1203
+ method,
1204
+ input.nodes?.join("\0") ?? JSON.stringify(input.range ?? null),
1205
+ editor.read.runtime.snapshot(),
1206
+ from.read.runtime.snapshot(),
1207
+ editor.read.view.isReadOnly(),
1208
+ from.read.view.isReadOnly(),
1209
+ authoredIdentity(editor),
1210
+ authoredIdentity(from),
1211
+ getConfiguredPluginRegistry(editor).configurationRevision
1212
+ ];
1213
+ };
1214
+ const checkTransfer = (editor, input, method) => {
1215
+ const key = checkKey(editor, input, method);
1216
+ const kept = CHECKS.get(editor);
1217
+ const cached = kept && sameKey(kept.key, key) ? kept : {
1218
+ checks: /* @__PURE__ */ new Map(),
1219
+ key
1220
+ };
1221
+ const to = JSON.stringify(input.to);
1222
+ const known = cached.checks.get(to);
1223
+ if (known) return known;
1224
+ let check;
1225
+ try {
1226
+ check = {
1227
+ admitted: true,
1228
+ to: targetOf(admit(editor, input, method).landing)
1229
+ };
1230
+ } catch (error) {
1231
+ if (!(error instanceof TransferRefusalError)) throw error;
1232
+ check = {
1233
+ admitted: false,
1234
+ reason: error.reason
1235
+ };
1236
+ }
1237
+ cached.checks.set(to, check);
1238
+ CHECKS.set(editor, cached);
1239
+ return check;
1240
+ };
1241
+ const checkFilesLanding = (editor, types, fit, to) => {
1242
+ try {
1243
+ if (editor.read.view.isReadOnly()) refuse("read-only-target");
1244
+ return {
1245
+ admitted: true,
1246
+ to: landAt(editor, {
1247
+ fit,
1248
+ from: editor,
1249
+ intent: "copy",
1250
+ moving: null,
1251
+ payload: {
1252
+ kind: "files",
1253
+ types
1254
+ },
1255
+ relation: "independent"
1256
+ }, to).edge
1257
+ };
1258
+ } catch (error) {
1259
+ if (!(error instanceof TransferRefusalError)) throw error;
1260
+ return {
1261
+ admitted: false,
1262
+ reason: error.reason
1263
+ };
1264
+ }
1265
+ };
1266
+ const selectionReader = (from) => {
1267
+ const selection = from.read.selection();
1268
+ const root = selection && SelectionApi.root(selection);
1269
+ return !root || root === getEditorRuntimeRoot(from) ? from : createEditorViewRuntime(from, { root });
1270
+ };
1271
+ const fromSelectionRoot = (editor, input) => input.nodes || input.range ? input : {
1272
+ ...input,
1273
+ from: selectionReader(input.from ?? editor)
1274
+ };
1275
+ const TRANSFER_PLUGIN = definePlugin("transfer", {
1276
+ read: ({ editor }) => ({
1277
+ check: (input) => checkTransfer(editor, fromSelectionRoot(editor, input), "move"),
1278
+ nodes: (options) => {
1279
+ const reader = options?.node === void 0 ? selectionReader(editor) : editor;
1280
+ return transferEntries(reader, options?.node).flatMap(([node]) => reader.key(node) ?? []);
1281
+ }
1282
+ }),
1283
+ api: ({ editor }) => ({
1284
+ copy: (input) => runTransfer(editor, fromSelectionRoot(editor, input), "copy"),
1285
+ move: (input) => runTransfer(editor, fromSelectionRoot(editor, input), "move")
1286
+ })
1287
+ });
1288
+ /** The drag-and-drop and keyboard move action; React editors install it. */
1289
+ const transfer = () => TRANSFER_PLUGIN;
1290
+ //#endregion
1291
+ //#region src/core/state-field.ts
1292
+ /**
1293
+ * Creates an editor-scoped state field from a keyed descriptor.
1294
+ *
1295
+ * State fields register when their plugin is installed and are read through
1296
+ * the editor state API.
1297
+ */
1298
+ const defineStateField = (descriptor) => {
1299
+ if (!descriptor.key) throw new Error("State field key cannot be empty.");
1300
+ if (descriptor.key === "__proto__") throw new Error("State field key cannot be \"__proto__\".");
1301
+ const normalizedDescriptor = Object.freeze({
1302
+ ...descriptor,
1303
+ compare: descriptor.compare ?? Object.is,
1304
+ ...descriptor.persist ? { persist: normalizeEditorValuePersistence(descriptor.persist) } : {},
1305
+ ...descriptor.initial !== void 0 && typeof descriptor.initial !== "function" ? { initial: cloneFrozen(descriptor.initial) } : {}
1306
+ });
1307
+ if (normalizedDescriptor.collab === "shared" && !normalizedDescriptor.persist) throw new Error(`Shared state field "${normalizedDescriptor.key}" requires persistence.`);
1308
+ if (normalizedDescriptor.collab === "shared" && normalizedDescriptor.reduce) throw new Error(`Shared state field "${normalizedDescriptor.key}" cannot define reduce. Set it with tx.setField so every peer receives the value.`);
1309
+ const transitionCodec = normalizedDescriptor.persist ? normalizeEditorValuePersistence({
1310
+ decode(value) {
1311
+ if (typeof value !== "object" || value === null || !Object.hasOwn(value, "previousValue") || !Object.hasOwn(value, "value")) throw new Error(`Invalid state field "${descriptor.key}" transition.`);
1312
+ return Object.freeze({
1313
+ previousValue: getDefined(normalizedDescriptor.persist).decode(value.previousValue),
1314
+ value: getDefined(normalizedDescriptor.persist).decode(value.value)
1315
+ });
1316
+ },
1317
+ encode: ({ previousValue, value }) => ({
1318
+ previousValue: getDefined(normalizedDescriptor.persist).encode(previousValue),
1319
+ value: getDefined(normalizedDescriptor.persist).encode(value)
1320
+ }),
1321
+ ...normalizedDescriptor.persist.legacyDecoders ? { legacyDecoders: Object.fromEntries(Object.entries(normalizedDescriptor.persist.legacyDecoders).map(([version, decode]) => [version, (value) => {
1322
+ if (typeof value !== "object" || value === null || !Object.hasOwn(value, "previousValue") || !Object.hasOwn(value, "value")) throw new Error(`Invalid state field "${descriptor.key}" transition.`);
1323
+ return Object.freeze({
1324
+ previousValue: decode(value.previousValue),
1325
+ value: decode(value.value)
1326
+ });
1327
+ }])) } : {},
1328
+ version: normalizedDescriptor.persist.version
1329
+ }) : void 0;
1330
+ const effectOptions = {
1331
+ history: normalizedDescriptor.history,
1332
+ key: `state:${normalizedDescriptor.key}`
1333
+ };
1334
+ let field;
1335
+ const effect = normalizedDescriptor.collab === "shared" ? defineEffect({
1336
+ ...effectOptions,
1337
+ persist: getDefined(transitionCodec),
1338
+ collab: "shared",
1339
+ collabReplay: "latest",
1340
+ collabSnapshot: (state) => {
1341
+ const value = state.getField(field);
1342
+ return {
1343
+ previousValue: value,
1344
+ value
1345
+ };
1346
+ },
1347
+ invert: ({ previousValue, value }) => ({
1348
+ previousValue: value,
1349
+ value: previousValue
1350
+ })
1351
+ }) : defineEffect({
1352
+ ...effectOptions,
1353
+ ...transitionCodec ? { persist: transitionCodec } : {},
1354
+ collab: "local",
1355
+ invert: ({ previousValue, value }) => ({
1356
+ previousValue: value,
1357
+ value: previousValue
1358
+ })
1359
+ });
1360
+ const definition = {
1361
+ ...normalizedDescriptor,
1362
+ deserialize(value) {
1363
+ if (!normalizedDescriptor.persist) throw new Error(`State field "${normalizedDescriptor.key}" does not define persistence.`);
1364
+ return decodeVersionedValue(normalizedDescriptor.persist, value, `state field "${normalizedDescriptor.key}"`);
1365
+ },
1366
+ effectTypes: Object.freeze([effect]),
1367
+ effect,
1368
+ stateFields: [],
1369
+ name: `state-field:${normalizedDescriptor.key}`,
1370
+ reduce(value, nextEffect) {
1371
+ if (nextEffect.type === effect) return nextEffect.value.value;
1372
+ return normalizedDescriptor.reduce?.(value, nextEffect) ?? value;
1373
+ },
1374
+ serialize(value) {
1375
+ if (!normalizedDescriptor.persist) throw new Error(`State field "${normalizedDescriptor.key}" does not define persistence.`);
1376
+ return encodeVersionedValue(normalizedDescriptor.persist, value, `state field "${normalizedDescriptor.key}"`);
1377
+ }
1378
+ };
1379
+ field = definition;
1380
+ definition.stateFields = Object.freeze([field]);
1381
+ field = compilePlugin(definition);
1382
+ markDefinedStateField(field);
1383
+ return field;
1384
+ };
1385
+ //#endregion
1386
+ export { transferEntries as a, transfer as i, checkFilesLanding as n, transferVeto as o, checkTransfer as r, defineStateField as t };