foldkit-richtext 0.5.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/dist/clipboard.d.ts +224 -0
  2. package/dist/clipboard.d.ts.map +1 -0
  3. package/dist/clipboard.js +208 -0
  4. package/dist/clipboard.js.map +1 -0
  5. package/dist/code.d.ts +27 -0
  6. package/dist/code.d.ts.map +1 -0
  7. package/dist/code.js +45 -0
  8. package/dist/code.js.map +1 -0
  9. package/dist/command.d.ts +300 -0
  10. package/dist/command.d.ts.map +1 -0
  11. package/dist/command.js +1438 -0
  12. package/dist/command.js.map +1 -0
  13. package/dist/decoration.d.ts +44 -0
  14. package/dist/decoration.d.ts.map +1 -0
  15. package/dist/decoration.js +96 -0
  16. package/dist/decoration.js.map +1 -0
  17. package/dist/document.d.ts +1045 -0
  18. package/dist/document.d.ts.map +1 -0
  19. package/dist/document.js +544 -0
  20. package/dist/document.js.map +1 -0
  21. package/dist/footnote.d.ts +35 -0
  22. package/dist/footnote.d.ts.map +1 -0
  23. package/dist/footnote.js +100 -0
  24. package/dist/footnote.js.map +1 -0
  25. package/dist/history.d.ts +470 -0
  26. package/dist/history.d.ts.map +1 -0
  27. package/dist/history.js +81 -0
  28. package/dist/history.js.map +1 -0
  29. package/dist/html.d.ts +27 -0
  30. package/dist/html.d.ts.map +1 -0
  31. package/dist/html.js +99 -0
  32. package/dist/html.js.map +1 -0
  33. package/dist/indent.d.ts +16 -0
  34. package/dist/indent.d.ts.map +1 -0
  35. package/dist/indent.js +101 -0
  36. package/dist/indent.js.map +1 -0
  37. package/dist/index.d.ts +24 -0
  38. package/dist/index.js +24 -0
  39. package/dist/input.d.ts +54 -0
  40. package/dist/input.d.ts.map +1 -0
  41. package/dist/input.js +37 -0
  42. package/dist/input.js.map +1 -0
  43. package/dist/kit.d.ts +179 -0
  44. package/dist/kit.d.ts.map +1 -0
  45. package/dist/kit.js +202 -0
  46. package/dist/kit.js.map +1 -0
  47. package/dist/marks.d.ts +79 -0
  48. package/dist/marks.d.ts.map +1 -0
  49. package/dist/marks.js +127 -0
  50. package/dist/marks.js.map +1 -0
  51. package/dist/media.d.ts +30 -0
  52. package/dist/media.d.ts.map +1 -0
  53. package/dist/media.js +148 -0
  54. package/dist/media.js.map +1 -0
  55. package/dist/migration.d.ts +55 -0
  56. package/dist/migration.d.ts.map +1 -0
  57. package/dist/migration.js +124 -0
  58. package/dist/migration.js.map +1 -0
  59. package/dist/outline.d.ts +15 -0
  60. package/dist/outline.d.ts.map +1 -0
  61. package/dist/outline.js +39 -0
  62. package/dist/outline.js.map +1 -0
  63. package/dist/rendering.d.ts +96 -0
  64. package/dist/rendering.d.ts.map +1 -0
  65. package/dist/rendering.js +106 -0
  66. package/dist/rendering.js.map +1 -0
  67. package/dist/replicated.d.ts +340 -0
  68. package/dist/replicated.d.ts.map +1 -0
  69. package/dist/replicated.js +1727 -0
  70. package/dist/replicated.js.map +1 -0
  71. package/dist/search.d.ts +28 -0
  72. package/dist/search.d.ts.map +1 -0
  73. package/dist/search.js +61 -0
  74. package/dist/search.js.map +1 -0
  75. package/dist/standard.d.ts +61 -0
  76. package/dist/standard.d.ts.map +1 -0
  77. package/dist/standard.js +231 -0
  78. package/dist/standard.js.map +1 -0
  79. package/dist/table.d.ts +38 -0
  80. package/dist/table.d.ts.map +1 -0
  81. package/dist/table.js +160 -0
  82. package/dist/table.js.map +1 -0
  83. package/dist/transaction.d.ts +712 -0
  84. package/dist/transaction.d.ts.map +1 -0
  85. package/dist/transaction.js +993 -0
  86. package/dist/transaction.js.map +1 -0
  87. package/dist/transform.d.ts +48 -0
  88. package/dist/transform.d.ts.map +1 -0
  89. package/dist/transform.js +94 -0
  90. package/dist/transform.js.map +1 -0
  91. package/dist/url.d.ts +16 -0
  92. package/dist/url.d.ts.map +1 -0
  93. package/dist/url.js +32 -0
  94. package/dist/url.js.map +1 -0
  95. package/package.json +7 -7
  96. package/dist/index.d.mts +0 -3787
  97. package/dist/index.d.mts.map +0 -1
  98. package/dist/index.mjs +0 -6688
  99. package/dist/index.mjs.map +0 -1
  100. package/dist/rolldown-runtime-D8jQpDG7.mjs +0 -12
@@ -0,0 +1,1438 @@
1
+ import { Equal, Match, Schema } from "effect";
2
+ import { toText } from "./html.js";
3
+ import { NodeId, blockAtPath, compareRunPlaces, eachBlock, locateBlock, locateRun, pathKey, positionInBlock, rangeStart, textContent } from "./document.js";
4
+ import { withFreshIds } from "./clipboard.js";
5
+ import { edgeMarks, markName as markName$1, propsFailure, resolveInsertion, sameMark, shippedRegistry } from "./marks.js";
6
+ import { blockKind, standsWithin } from "./kit.js";
7
+ import { indent, indentationAt, offsetIn, outdent } from "./indent.js";
8
+ import { findMatches } from "./search.js";
9
+ import { FootnoteDefinition, FootnoteRef, footnotesOf, nextFootnoteLabel, referenceLabel } from "./footnote.js";
10
+ import { deleteColumn, deleteRow, insertColumn, insertRow, moveToCell, tableAt } from "./table.js";
11
+ import { Edit, apply } from "./transaction.js";
12
+ // src/command.ts
13
+ /** Where `MoveBlock` puts a block: before or after a sibling, named by identity. */
14
+ const Beside = Schema.Union([Schema.Struct({
15
+ before: NodeId,
16
+ after: Schema.optionalKey(Schema.Never)
17
+ }), Schema.Struct({
18
+ after: NodeId,
19
+ before: Schema.optionalKey(Schema.Never)
20
+ })]);
21
+ /** A container a block is wrapped in: a node kind, and the props it starts with. */
22
+ const Container = Schema.Struct({
23
+ kind: Schema.NonEmptyString,
24
+ props: Schema.optionalKey(Schema.JsonObject)
25
+ });
26
+ /**
27
+ * Whether the block at a path is declared to carry no marks, in which case adding one
28
+ * is refused at the command layer rather than reported only by `validate` (§125). A
29
+ * preserved block is left alone: it has no declaration to read, and preserving it
30
+ * matters more than forbidding a mark on it.
31
+ */
32
+ const forbidsMarks = (document, path, nodes) => {
33
+ if (nodes === void 0) return false;
34
+ const block = blockAtPath(document, path);
35
+ if (block === void 0 || block.type === "Unknown") return false;
36
+ return kindForbidsMarks(nodes, blockKind(block));
37
+ };
38
+ const kindForbidsMarks = (nodes, kind) => {
39
+ const declared = nodes.definitionFor(kind);
40
+ return declared?.kind === "node" && declared.marks === "none";
41
+ };
42
+ /**
43
+ * Whether the block at a path accepts a child of this kind. A declaration without a
44
+ * constraint accepts any block, and a vocabulary that does not declare the parent is
45
+ * not consulted — `validate` reports an undeclared kind, and an edit should not fail
46
+ * for a reason the caller never stated.
47
+ */
48
+ const acceptsChild = (document, path, kind, nodes) => {
49
+ const parent = blockAtPath(document, path);
50
+ return parent === void 0 || kindAccepts(nodes, blockKind(parent), kind);
51
+ };
52
+ /** Whether a kind's declaration lets it hold another as a nested block; undeclared is open. */
53
+ const kindAccepts = (nodes, parentKind, childKind) => {
54
+ if (nodes === void 0) return true;
55
+ const declared = nodes.definitionFor(parentKind);
56
+ if (declared?.kind !== "node" || typeof declared.children === "string") return true;
57
+ return declared.children.of.includes(childKind);
58
+ };
59
+ /** Whether the vocabulary declares props for a new node that these do not decode as. */
60
+ const refusesProps = (nodes, container) => {
61
+ const declared = nodes?.definitionFor(container.kind);
62
+ return declared !== void 0 && declared.kind !== "block" && propsFailure(declared.props, container.props ?? {});
63
+ };
64
+ /** Whether the vocabulary declares `kind` as a node that holds runs, as `CodeBlock` is. */
65
+ const declaresText = (nodes, kind) => {
66
+ const declared = nodes?.definitionFor(kind);
67
+ return declared?.kind === "node" && declared.children === textContent;
68
+ };
69
+ /**
70
+ * Whether a block is an atom, holding neither text nor blocks, as an image is. Without a
71
+ * vocabulary, a node with nothing in it is one.
72
+ */
73
+ const isAtom = (nodes, block) => {
74
+ if (block.type !== "Node") return false;
75
+ const declared = nodes?.definitionFor(block.kind);
76
+ return declared === void 0 ? block.blocks === void 0 && block.children.length === 0 : declared.kind === "atom";
77
+ };
78
+ /** Whether the vocabulary names `itemKind` among the kinds `listKind` holds, as `List` names `ListItem`. */
79
+ const holdsItem = (nodes, listKind, itemKind) => {
80
+ const declared = nodes.definitionFor(listKind);
81
+ return declared?.kind === "node" && typeof declared.children !== "string" && declared.children.of.includes(itemKind);
82
+ };
83
+ /**
84
+ * Whether a kind can be a new container. Unlike an existing parent, a kind a wrap creates
85
+ * must be declared as holding nested blocks when there is a vocabulary: wrapping in an
86
+ * undeclared kind, or a text kind such as `CodeBlock`, would make content `validate`
87
+ * refuses.
88
+ */
89
+ const holdsBlocks = (nodes, kind) => {
90
+ if (nodes === void 0) return true;
91
+ const declared = nodes.definitionFor(kind);
92
+ return declared?.kind === "node" && declared.children !== textContent;
93
+ };
94
+ const failure = (error) => ({
95
+ ok: false,
96
+ error
97
+ });
98
+ /** Document order over a located run, by the shared place rule. */
99
+ const locatedOrder = (left, right) => compareRunPlaces({
100
+ path: left.path,
101
+ index: left.runIndex
102
+ }, {
103
+ path: right.path,
104
+ index: right.runIndex
105
+ });
106
+ const locate = (document, node) => {
107
+ const found = locateRun(document, node);
108
+ if (found === void 0) return void 0;
109
+ const block = blockAtPath(document, found.path);
110
+ if (block === void 0) return void 0;
111
+ return {
112
+ path: found.path,
113
+ runIndex: found.index,
114
+ blockId: block.id,
115
+ id: found.run.id,
116
+ text: found.run.text,
117
+ marks: found.run.marks
118
+ };
119
+ };
120
+ const isCollapsed = (selection) => selection.anchor.node === selection.focus.node && selection.anchor.offset === selection.focus.offset;
121
+ /** Whether a selection covers text: a range that is not a caret. What a mark or a link applies to. */
122
+ const coversText = (selection) => selection?.type === "Range" && !isCollapsed(selection);
123
+ /** A caret is a range whose endpoints coincide; direction is not yet meaningful. */
124
+ const caretAt = (position) => ({
125
+ type: "Range",
126
+ anchor: position,
127
+ focus: position
128
+ });
129
+ /** Orders a range's endpoints by document order without losing direction. */
130
+ const ordered = (document, selection) => {
131
+ const anchor = locate(document, selection.anchor.node);
132
+ const focus = locate(document, selection.focus.node);
133
+ if (anchor === void 0 || focus === void 0) return void 0;
134
+ const byPlace = locatedOrder(anchor, focus);
135
+ return (byPlace !== 0 ? byPlace > 0 : selection.anchor.offset > selection.focus.offset) ? {
136
+ start: selection.focus,
137
+ end: selection.anchor
138
+ } : {
139
+ start: selection.anchor,
140
+ end: selection.focus
141
+ };
142
+ };
143
+ /** Runs intersecting an ordered [start, end), with the covered sub-range. */
144
+ const covered = (document, start, end) => {
145
+ const startAt = locate(document, start.node);
146
+ const endAt = locate(document, end.node);
147
+ if (startAt === void 0 || endAt === void 0) return [];
148
+ const spans = [];
149
+ eachBlock(document.children, (block, path) => {
150
+ for (const [runIndex, run] of block.children.entries()) {
151
+ const place = {
152
+ path,
153
+ runIndex
154
+ };
155
+ if (locatedOrder(place, startAt) < 0 || locatedOrder(place, endAt) > 0) continue;
156
+ const from = locatedOrder(place, startAt) === 0 ? start.offset : 0;
157
+ const to = locatedOrder(place, endAt) === 0 ? end.offset : run.text.length;
158
+ if (from >= to) continue;
159
+ spans.push({
160
+ run: {
161
+ path,
162
+ runIndex,
163
+ blockId: block.id,
164
+ id: run.id,
165
+ text: run.text,
166
+ marks: run.marks
167
+ },
168
+ from,
169
+ to
170
+ });
171
+ }
172
+ });
173
+ return spans;
174
+ };
175
+ /** Marks every run in the list carries; empty when there are no runs. */
176
+ const sharedMarks = (runs) => {
177
+ let common;
178
+ for (const marks of runs) {
179
+ const names = new Set(marks.map(markName$1));
180
+ if (common === void 0) {
181
+ common = names;
182
+ continue;
183
+ }
184
+ for (const name of common) if (!names.has(name)) common.delete(name);
185
+ }
186
+ return common ?? /* @__PURE__ */ new Set();
187
+ };
188
+ /**
189
+ * The marks every run the selection covers carries: the ones a toggle would
190
+ * remove, which is what an "active" toolbar button means. A caret reports its
191
+ * run's marks — an empty run can carry them, which is how a caret holds a format
192
+ * — and a range is not bold when it straddles a bold run and a plain one. A node
193
+ * selection reports what its whole subtree agrees on. A read, not a command:
194
+ * nothing here changes anything.
195
+ */
196
+ const marksInRange = (document, selection) => {
197
+ if (selection === null) return /* @__PURE__ */ new Set();
198
+ if (selection.type === "Node") {
199
+ const found = locateBlock(document, selection.node);
200
+ if (found === void 0) return /* @__PURE__ */ new Set();
201
+ const runs = [];
202
+ eachBlock([found.block], (each) => {
203
+ for (const run of each.children) runs.push(run.marks);
204
+ });
205
+ return sharedMarks(runs);
206
+ }
207
+ const bounds = ordered(document, selection);
208
+ if (bounds === void 0) return /* @__PURE__ */ new Set();
209
+ if (isCollapsed(selection)) {
210
+ const caret = locate(document, selection.anchor.node);
211
+ return caret === void 0 ? /* @__PURE__ */ new Set() : sharedMarks([caret.marks]);
212
+ }
213
+ return sharedMarks(covered(document, bounds.start, bounds.end).map((span) => span.run.marks));
214
+ };
215
+ /**
216
+ * The named mark on the run a position is in, and the adjacent runs of its block carrying
217
+ * the same mark with the same props: the whole link a caret sits in, which is what a link
218
+ * editor shows and what `SetMark` and `ClearMark` act on at a caret. Undefined when that
219
+ * run does not carry the mark. A read, like `marksInRange`.
220
+ */
221
+ const markExtent = (document, position, name) => {
222
+ const found = locateRun(document, position.node);
223
+ const mark = found?.run.marks.find((held) => markName$1(held) === name);
224
+ if (found === void 0 || mark === void 0) return void 0;
225
+ const runs = blockAtPath(document, found.path).children;
226
+ const carries = (index) => runs[index]?.marks.some((held) => sameMark(held, mark)) === true;
227
+ let first = found.index;
228
+ while (carries(first - 1)) first--;
229
+ let last = found.index;
230
+ while (carries(last + 1)) last++;
231
+ const end = runs[last];
232
+ return {
233
+ mark,
234
+ selection: {
235
+ type: "Range",
236
+ anchor: {
237
+ node: runs[first].id,
238
+ offset: 0,
239
+ affinity: "after"
240
+ },
241
+ focus: {
242
+ node: end.id,
243
+ offset: end.text.length,
244
+ affinity: "before"
245
+ }
246
+ }
247
+ };
248
+ };
249
+ /**
250
+ * The text style of the block a selection starts in, in the shape `RetypeBlock` takes, so a
251
+ * style picker compares what it would send with what is there. Undefined for a node
252
+ * selection, one that resolves to nothing, or a block a retype does not reach, such as a code
253
+ * block.
254
+ */
255
+ const textBlockAt = (document, selection) => {
256
+ if (selection?.type !== "Range") return void 0;
257
+ const path = startPath(document, selection);
258
+ const block = path === void 0 ? void 0 : blockAtPath(document, path);
259
+ if (block?.type === "Paragraph") return { type: "Paragraph" };
260
+ if (block?.type === "Heading") return {
261
+ type: "Heading",
262
+ level: block.level
263
+ };
264
+ };
265
+ /**
266
+ * Why block `moving` may not move into the container at `container` (§149), or undefined when
267
+ * it may. Within its own container it always may. Elsewhere, the container must hold its kind,
268
+ * the kind must stand in the container's kind (a `ListItem` only in a `List`), it may not leave
269
+ * a container declared isolating, and it may not go inside itself.
270
+ */
271
+ const moveFailure = (document, moving, container, nodes) => {
272
+ if (moving.path.every((index, depth) => container[depth] === index)) return "InvalidParent";
273
+ const source = moving.path.slice(0, -1);
274
+ if (pathKey(source) === pathKey(container)) return void 0;
275
+ const kind = blockKind(moving.block);
276
+ const parent = container.length === 0 ? void 0 : blockAtPath(document, container);
277
+ if (!acceptsChild(document, container, kind, nodes) || !standsWithin(nodes?.definitionFor(kind), parent === void 0 ? void 0 : blockKind(parent))) return "UnexpectedChild";
278
+ for (let depth = source.length; depth > 0; depth--) {
279
+ const holder = source.slice(0, depth);
280
+ if (!holder.every((index, at) => container[at] === index) && isIsolating(document, holder, nodes)) return "InvalidParent";
281
+ }
282
+ };
283
+ const isIsolating = (document, path, nodes) => {
284
+ const block = blockAtPath(document, path);
285
+ const declared = block === void 0 ? void 0 : nodes?.definitionFor(blockKind(block));
286
+ return declared?.kind === "node" && declared.isolating === true;
287
+ };
288
+ /**
289
+ * The outermost container a block leaving `source` empties, walking up while each held nothing
290
+ * else: a list whose only item's only block moved out goes with it. Never the container it lands
291
+ * in, or one holding that. An isolating one is never reached, since a move may not leave it.
292
+ */
293
+ const emptiedBy = (document, source, container) => {
294
+ let emptied;
295
+ for (let path = source; path.length > 0; path = path.slice(0, -1)) {
296
+ const block = blockAtPath(document, path);
297
+ const holdsTarget = path.every((index, depth) => container[depth] === index);
298
+ if (block?.type !== "Node" || (block.blocks?.length ?? 0) > 1 || holdsTarget) break;
299
+ emptied = block.id;
300
+ }
301
+ return emptied;
302
+ };
303
+ /**
304
+ * The blocks `node` may move beside, in document order (§149): the blocks of every container it
305
+ * may move into, which is what a drag offers. Empty when the document does not hold it.
306
+ */
307
+ const moveTargets = (document, node, nodes) => {
308
+ const moving = locateBlock(document, node);
309
+ if (moving === void 0) return [];
310
+ const targets = [];
311
+ eachBlock(document.children, (block, path) => {
312
+ if (moveFailure(document, moving, path.slice(0, -1), nodes) === void 0) targets.push(block.id);
313
+ });
314
+ return targets;
315
+ };
316
+ /** Where a selection starts: its first run's block, or the block a node selection names. */
317
+ const startPath = (document, selection) => {
318
+ if (selection === null) return void 0;
319
+ if (selection.type === "Node") return locateBlock(document, selection.node)?.path;
320
+ const start = ordered(document, selection)?.start;
321
+ return start === void 0 ? void 0 : locateRun(document, start.node)?.path;
322
+ };
323
+ /**
324
+ * The blocks a selection starts in, outermost first: a caret in a list item's paragraph gives
325
+ * the list, the item, and the paragraph. What a block handle picks from, and a breadcrumb draws.
326
+ * Empty when the selection is null or resolves to nothing.
327
+ */
328
+ const blocksAt = (document, selection) => {
329
+ const path = startPath(document, selection) ?? [];
330
+ return path.map((_, depth) => blockAtPath(document, path.slice(0, depth + 1)));
331
+ };
332
+ /** Whether `prefix` is a path to one of the blocks `path` lies inside, or `path` itself. */
333
+ const startsWith = (path, prefix) => prefix.length <= path.length && prefix.every((index, at) => path[at] === index);
334
+ /** Document order of two block paths: a container comes before what it holds. */
335
+ const pathOrder = (left, right) => {
336
+ for (let at = 0; at < Math.min(left.length, right.length); at++) if (left[at] !== right[at]) return left[at] - right[at];
337
+ return left.length - right.length;
338
+ };
339
+ /** Whether two blocks can be joined into one: what `JoinNode` accepts. */
340
+ const joinable = (survivor, removed) => {
341
+ if (survivor.type === "Unknown" || removed.type === "Unknown") return false;
342
+ if (nestedBlocks(survivor) !== void 0 || nestedBlocks(removed) !== void 0) return false;
343
+ if (survivor.type !== "Node" && removed.type !== "Node") return true;
344
+ return survivor.type === "Node" && removed.type === "Node" && survivor.kind === removed.kind && Equal.equals(survivor.props, removed.props);
345
+ };
346
+ const nestedBlocks = (block) => block.type === "Node" && block.blocks !== void 0 ? block.blocks : void 0;
347
+ /** Whether going from one block to another leaves an isolating container, as a table cell is. */
348
+ const crossesIsolating = (document, from, to, nodes) => [from, to].some((path, side) => {
349
+ const other = side === 0 ? to : from;
350
+ for (let depth = 1; depth < path.length; depth++) {
351
+ const container = path.slice(0, depth);
352
+ if (startsWith(other, container)) continue;
353
+ const block = blockAtPath(document, container);
354
+ const declared = block?.type === "Node" ? nodes?.definitionFor(block.kind) : void 0;
355
+ if (declared?.kind === "node" && declared.isolating === true) return true;
356
+ }
357
+ return false;
358
+ });
359
+ /** The innermost first or last block inside the block at `path`: itself when it holds none. */
360
+ const edgeLeaf = (document, path, last) => {
361
+ let at = path;
362
+ for (;;) {
363
+ const held = nestedBlocks(blockAtPath(document, at));
364
+ if (held === void 0 || held.length === 0) return at;
365
+ at = [...at, last ? held.length - 1 : 0];
366
+ }
367
+ };
368
+ /** The first block after the one at `path` that holds no blocks, in document order. */
369
+ const nextLeaf = (document, path) => {
370
+ let found;
371
+ eachBlock(document.children, (block, at) => {
372
+ if (found !== void 0 || pathOrder(at, path) <= 0 || startsWith(path, at)) return;
373
+ if ((nestedBlocks(block) ?? []).length === 0) found = at;
374
+ });
375
+ return found;
376
+ };
377
+ /** One result followed by another, as one: what `runAction` does for two commands. */
378
+ const followedBy = (first, second) => !first.ok || !second.ok ? second.ok ? first : second : {
379
+ ok: true,
380
+ state: second.state,
381
+ changeSet: unionChangeSet(first.changeSet, second.changeSet),
382
+ positionMap: [...first.positionMap, ...second.positionMap],
383
+ transactions: [...first.transactions, ...second.transactions]
384
+ };
385
+ /**
386
+ * Deletes a range that leaves its container, as selecting from one kind of block into another
387
+ * (or everything) and pressing Delete does: the text after `start` in its block and before
388
+ * `end` in its block goes, every block wholly between them goes, and the block `end` is in
389
+ * comes up beside the one `start` is in, joining it when the two can be one. A container it
390
+ * leaves empty goes too. A range that leaves a table cell (an isolating container) only loses
391
+ * its text: the cells stay, as a table's structure is not a selection's to remove. The caret
392
+ * ends at `start`.
393
+ */
394
+ const clearRange = (state, start, end, options) => {
395
+ const document = state.document;
396
+ const startAt = locate(document, start.node);
397
+ const endAt = locate(document, end.node);
398
+ if (startAt === void 0 || endAt === void 0) return failure("MissingText");
399
+ const startPath = startAt.path;
400
+ const endPath = endAt.path;
401
+ const spans = covered(document, start, end);
402
+ if (crossesIsolating(document, startPath, endPath, options.nodes)) return apply(state, [...spans.map((span) => Edit.deleteText(span.run.id, span.from, span.to)), Edit.setSelection(caretAt(start))]);
403
+ const ends = spans.filter((span) => pathKey(span.run.path) === pathKey(startPath) || pathKey(span.run.path) === pathKey(endPath));
404
+ const between = [];
405
+ eachBlock(document.children, (block, path) => {
406
+ if (pathOrder(path, startPath) <= 0 || pathOrder(path, endPath) >= 0) return;
407
+ if (startsWith(endPath, path) || startsWith(startPath, path)) return;
408
+ if (between.some((outer) => startsWith(path, outer.path))) return;
409
+ between.push({
410
+ id: block.id,
411
+ path
412
+ });
413
+ });
414
+ const first = apply(state, [
415
+ ...ends.map((span) => Edit.deleteText(span.run.id, span.from, span.to)),
416
+ ...between.map((block) => Edit.deleteBlock(block.id)),
417
+ Edit.setSelection(caretAt(start))
418
+ ]);
419
+ if (!first.ok) return first;
420
+ const startBlock = blockAtPath(document, startPath);
421
+ const endBlock = blockAtPath(document, endPath);
422
+ const now = first.state.document;
423
+ const survivorAt = locateBlock(now, startBlock.id);
424
+ const removedAt = locateBlock(now, endBlock.id);
425
+ if (survivorAt === void 0 || removedAt === void 0) return first;
426
+ const operations = [];
427
+ const parentPath = survivorAt.path.slice(0, -1);
428
+ const parent = parentPath.length === 0 ? void 0 : blockAtPath(now, parentPath);
429
+ const index = survivorAt.path[survivorAt.path.length - 1];
430
+ const siblings = pathKey(removedAt.path.slice(0, -1)) === pathKey(parentPath);
431
+ if (!siblings && parentPath.length > 0 && !acceptsChild(now, parentPath, blockKind(removedAt.block), options.nodes)) return first;
432
+ if (!siblings) operations.push(Edit.moveBlock(endBlock.id, index + 1, parent?.id));
433
+ if ((siblings ? removedAt.path[removedAt.path.length - 1] === index + 1 : true) && joinable(survivorAt.block, removedAt.block)) operations.push(Edit.joinBlocks(startBlock.id, endBlock.id));
434
+ if (!siblings) for (let depth = removedAt.path.length - 1; depth > 0; depth--) {
435
+ const container = blockAtPath(now, removedAt.path.slice(0, depth));
436
+ if (container === void 0 || startsWith(survivorAt.path, removedAt.path.slice(0, depth))) break;
437
+ if ((nestedBlocks(container) ?? []).length > 1) break;
438
+ operations.push(Edit.deleteBlock(container.id));
439
+ }
440
+ if (operations.length === 0) return first;
441
+ return followedBy(first, apply(first.state, [...operations, Edit.setSelection(caretAt(start))]));
442
+ };
443
+ /** The last run in a block's subtree, or undefined when it holds none. */
444
+ const lastRunOf = (block) => {
445
+ if (block.type === "Node" && block.blocks !== void 0) for (let index = block.blocks.length - 1; index >= 0; index--) {
446
+ const found = lastRunOf(block.blocks[index]);
447
+ if (found !== void 0) return found;
448
+ }
449
+ return block.children[block.children.length - 1];
450
+ };
451
+ /** The block list a path lives in: the document's, or a container's nested blocks. */
452
+ const containerBlocks = (document, containerPath) => {
453
+ if (containerPath.length === 0) return document.children;
454
+ const container = blockAtPath(document, containerPath);
455
+ return container?.type === "Node" && container.blocks !== void 0 ? container.blocks : [];
456
+ };
457
+ /**
458
+ * Deletes an ordered [start, end): one operation per covered run, then the
459
+ * blocks the range spanned are joined, so selecting across a paragraph boundary
460
+ * and deleting removes the boundary too. The first block survives, which is
461
+ * where the caret already is. Returns undefined when the range needs a join this
462
+ * version cannot express — one across containers, which has no boundary to
463
+ * remove — so the caller refuses rather than deleting half of what was selected.
464
+ */
465
+ const deleteRange = (document, start, end) => {
466
+ const startAt = locate(document, start.node);
467
+ const endAt = locate(document, end.node);
468
+ const deletions = covered(document, start, end).map((span) => Edit.deleteText(span.run.id, span.from, span.to));
469
+ if (startAt === void 0 || endAt === void 0) return deletions;
470
+ if (pathKey(startAt.path) === pathKey(endAt.path)) return deletions;
471
+ const containerPath = startAt.path.slice(0, -1);
472
+ if (pathKey(containerPath) !== pathKey(endAt.path.slice(0, -1))) return void 0;
473
+ const blocks = containerBlocks(document, containerPath);
474
+ const from = startAt.path[startAt.path.length - 1];
475
+ const to = endAt.path[endAt.path.length - 1];
476
+ const survivor = blocks[from];
477
+ for (let index = from + 1; index <= to; index++) {
478
+ const block = blocks[index];
479
+ if (block === void 0) continue;
480
+ if (!joinable(survivor, block)) return void 0;
481
+ deletions.push(Edit.joinBlocks(survivor.id, block.id));
482
+ }
483
+ return deletions;
484
+ };
485
+ const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
486
+ /** A caret uses UTF-16 offsets, while a deletion removes a whole grapheme. */
487
+ const graphemeDeletion = (block, caret, runIndex, backward) => {
488
+ const starts = [];
489
+ let length = 0;
490
+ for (const run of block.children) {
491
+ starts.push(length);
492
+ length += run.text.length;
493
+ }
494
+ const at = starts[runIndex] + caret.offset;
495
+ if (backward ? at === 0 : at === length) return void 0;
496
+ const text = block.children.map((run) => run.text).join("");
497
+ let from = 0;
498
+ let to = 0;
499
+ for (const segment of segmenter.segment(text)) {
500
+ const end = segment.index + segment.segment.length;
501
+ if (backward ? end >= at : end > at) {
502
+ from = segment.index;
503
+ to = end;
504
+ break;
505
+ }
506
+ }
507
+ const operations = [];
508
+ let graphemeStart;
509
+ for (const [index, run] of block.children.entries()) {
510
+ const start = starts[index];
511
+ const localFrom = Math.max(0, from - start);
512
+ const localTo = Math.min(run.text.length, to - start);
513
+ if (localFrom >= localTo) continue;
514
+ graphemeStart ??= {
515
+ node: run.id,
516
+ offset: localFrom,
517
+ affinity: "after"
518
+ };
519
+ operations.push(Edit.deleteText(run.id, localFrom, localTo));
520
+ }
521
+ if (graphemeStart === void 0) return void 0;
522
+ return {
523
+ operations,
524
+ caret: backward ? graphemeStart : caret
525
+ };
526
+ };
527
+ /**
528
+ * The operations that lift a block out of its container, or `undefined` when it is at the
529
+ * top level with nothing to leave. One step moves it into the container's parent: before
530
+ * the container when it was first, after it when it was last, and between the two halves
531
+ * of a split container when it was in the middle. A container it leaves empty is deleted.
532
+ * Steps repeat while the vocabulary says the new parent does not hold the block's kind;
533
+ * without a vocabulary, one step is taken. A container the vocabulary declares isolating is
534
+ * never left, so a lift that would start by leaving one lifts nothing.
535
+ *
536
+ * Each step is computed against the document the steps before it produced, applied with no
537
+ * normalization, because a split or a deletion moves the indices the next step reads.
538
+ */
539
+ const liftOperations = (document, node, ids, nodes) => {
540
+ const operations = [];
541
+ let current = document;
542
+ for (;;) {
543
+ const found = locateBlock(current, node);
544
+ if (found === void 0 || found.path.length === 1) break;
545
+ const containerPath = found.path.slice(0, -1);
546
+ const container = blockAtPath(current, containerPath);
547
+ if (container?.type !== "Node" || container.blocks === void 0) break;
548
+ const declared = nodes?.definitionFor(container.kind);
549
+ if (declared?.kind === "node" && declared.isolating === true) break;
550
+ const parentPath = containerPath.slice(0, -1);
551
+ const parent = parentPath.length === 0 ? void 0 : blockAtPath(current, parentPath);
552
+ const at = containerPath[containerPath.length - 1];
553
+ const index = found.path[found.path.length - 1];
554
+ const siblings = container.blocks;
555
+ const step = [];
556
+ if (index === 0) {
557
+ step.push(Edit.moveBlock(node, at, parent?.id));
558
+ if (siblings.length === 1) step.push(Edit.deleteBlock(container.id));
559
+ } else if (index === siblings.length - 1) step.push(Edit.moveBlock(node, at + 1, parent?.id));
560
+ else {
561
+ const rest = NodeId.make(ids.mint());
562
+ step.push(Edit.insertBlock({
563
+ ...container,
564
+ id: rest,
565
+ children: [],
566
+ blocks: []
567
+ }, at + 1, parent?.id), ...siblings.slice(index + 1).map((sibling, offset) => Edit.moveBlock(sibling.id, offset, rest)), Edit.moveBlock(node, at + 1, parent?.id));
568
+ }
569
+ const stepped = apply({
570
+ document: current,
571
+ selection: null
572
+ }, step, []);
573
+ if (!stepped.ok) throw new Error(`liftOperations: a lift step was refused (${stepped.error})`);
574
+ operations.push(...step);
575
+ current = stepped.state.document;
576
+ if (parent === void 0 || kindAccepts(nodes, blockKind(parent), blockKind(found.block))) break;
577
+ }
578
+ return operations.length === 0 ? void 0 : operations;
579
+ };
580
+ /**
581
+ * The item a block sits in, when the vocabulary says its container is one: a kind its own
582
+ * parent declares it holds, as a `List` declares `ListItem`, and not isolating, as a table
583
+ * cell is. Enter treats such a container as the unit it splits.
584
+ */
585
+ const itemAround = (document, path, nodes) => {
586
+ if (nodes === void 0) return void 0;
587
+ const containerPath = path.slice(0, -1);
588
+ const container = blockAtPath(document, containerPath);
589
+ const list = blockAtPath(document, containerPath.slice(0, -1));
590
+ if (container?.type !== "Node" || list?.type !== "Node") return void 0;
591
+ const declaredItem = nodes.definitionFor(container.kind);
592
+ const isolating = declaredItem?.kind === "node" && declaredItem.isolating === true;
593
+ return holdsItem(nodes, list.kind, container.kind) && !isolating ? {
594
+ container,
595
+ containerPath,
596
+ list
597
+ } : void 0;
598
+ };
599
+ /**
600
+ * Whether Enter in the block at `path`, over to `end`, leaves no heading text after the caret,
601
+ * so the new block is a paragraph: what follows a title is text. Mid-heading, both halves stay
602
+ * the heading they were. Over a range, what follows is what the removal leaves: the heading's
603
+ * own rest when the range ends inside it, or the next block's text, which was never the
604
+ * heading's, when it ends there.
605
+ */
606
+ const endsHeading = (document, path, end) => {
607
+ const block = blockAtPath(document, path);
608
+ const endAt = locate(document, end.node);
609
+ return block?.type === "Heading" && endAt !== void 0 && (pathKey(endAt.path) !== pathKey(path) || end.offset >= endAt.text.length && block.children.slice(endAt.runIndex + 1).every((run) => run.text.length === 0));
610
+ };
611
+ /**
612
+ * Enter inside a list item. An empty block that is the item's whole content leaves the list,
613
+ * as Backspace does. Otherwise the block splits and the second half, with every block after
614
+ * it in the item, becomes a new item of the same kind and props right after this one.
615
+ */
616
+ const splitItem = (state, at, offset, { container, containerPath, list }, ids, nodes) => {
617
+ const blocks = container.blocks ?? [];
618
+ const index = at.path[at.path.length - 1];
619
+ if (blockAtPath(state.document, at.path)?.children.every((run) => run.text === "") === true && blocks.length === 1) return apply(state, liftOperations(state.document, at.blockId, ids, nodes) ?? []);
620
+ const textId = ids.mint();
621
+ const blockId = ids.mint();
622
+ const itemId = NodeId.make(ids.mint());
623
+ const declared = nodes?.definitionFor(container.kind);
624
+ const props = {
625
+ ...container.props,
626
+ ...declared?.kind === "node" ? declared.splitProps : {}
627
+ };
628
+ if (declared?.kind === "node" && propsFailure(declared.props, props)) return failure("InvalidInput");
629
+ return apply(state, [
630
+ Edit.splitBlock(at.blockId, at.id, offset, blockId, textId),
631
+ ...endsHeading(state.document, at.path, {
632
+ node: at.id,
633
+ offset,
634
+ affinity: "after"
635
+ }) ? [Edit.retypeBlock(NodeId.make(blockId), { type: "Paragraph" })] : [],
636
+ Edit.insertBlock({
637
+ ...container,
638
+ id: itemId,
639
+ props,
640
+ children: [],
641
+ blocks: []
642
+ }, containerPath[containerPath.length - 1] + 1, list.id),
643
+ Edit.moveBlock(NodeId.make(blockId), 0, itemId),
644
+ ...blocks.slice(index + 1).map((later, position) => Edit.moveBlock(later.id, position + 1, itemId)),
645
+ Edit.setSelection(caretAt({
646
+ node: NodeId.make(textId),
647
+ offset: 0,
648
+ affinity: "after"
649
+ }))
650
+ ]);
651
+ };
652
+ /**
653
+ * A block-level intent acts on the block the selection starts in: the caret's own block,
654
+ * or the first block of a range. Acting on every block a range covers would be a surprise,
655
+ * and a menu or a marker is typed at a caret anyway.
656
+ */
657
+ const startingBlock = (document, selection) => {
658
+ const start = isCollapsed(selection) ? selection.anchor : ordered(document, selection)?.start;
659
+ if (start === void 0) return { error: "InvalidSelection" };
660
+ const at = locate(document, start.node);
661
+ const block = at === void 0 ? void 0 : blockAtPath(document, at.path);
662
+ if (at === void 0 || block === void 0) return { error: "MissingText" };
663
+ const parentPath = at.path.slice(0, -1);
664
+ return {
665
+ block,
666
+ path: at.path,
667
+ parentPath,
668
+ parent: parentPath.length === 0 ? void 0 : blockAtPath(document, parentPath),
669
+ selection
670
+ };
671
+ };
672
+ /**
673
+ * Retype, wrap, convert, retype a container, and lift: each reshapes the starting block, or
674
+ * the container holding it, where it stands.
675
+ */
676
+ const runBlockCommand = (state, command, starting, ids, options) => {
677
+ const { block, path, parentPath, parent } = starting;
678
+ const index = path[path.length - 1];
679
+ if (command.type === "LiftBlock") {
680
+ const lifted = liftOperations(state.document, block.id, ids, options.nodes);
681
+ return lifted === void 0 ? failure("InvalidInput") : apply(state, lifted);
682
+ }
683
+ if (command.type === "RetypeContainer") {
684
+ if (parent?.type !== "Node" || parent.blocks === void 0 || index !== 0) return failure("InvalidInput");
685
+ const { kind } = command.to;
686
+ if (refusesProps(options.nodes, command.to)) return failure("InvalidInput");
687
+ const outerPath = parentPath.slice(0, -1);
688
+ const outer = outerPath.length === 0 ? void 0 : blockAtPath(state.document, outerPath);
689
+ const declared = options.nodes?.definitionFor(kind);
690
+ if (!(holdsBlocks(options.nodes, kind) && acceptsChild(state.document, outerPath, kind, options.nodes) && standsWithin(declared, outer === void 0 ? void 0 : blockKind(outer)) && parent.blocks.every((child) => kindAccepts(options.nodes, kind, blockKind(child)) && standsWithin(options.nodes?.definitionFor(blockKind(child)), kind)))) return failure("UnexpectedChild");
691
+ return apply(state, [Edit.retypeBlock(parent.id, {
692
+ type: "Node",
693
+ kind,
694
+ props: command.to.props ?? {}
695
+ })]);
696
+ }
697
+ if (command.type === "RetypeBlock") {
698
+ if (!acceptsChild(state.document, parentPath, command.to.type, options.nodes)) return failure("UnexpectedChild");
699
+ if (block.type !== "Paragraph" && block.type !== "Heading" && (block.type !== "Node" || !declaresText(options.nodes, block.kind))) return failure("InvalidInput");
700
+ return apply(state, [Edit.retypeBlock(block.id, command.to)]);
701
+ }
702
+ if (command.type === "WrapBlock") {
703
+ const [outer] = command.containers;
704
+ if (outer === void 0) return failure("InvalidInput");
705
+ if (command.containers.some((container) => refusesProps(options.nodes, container))) return failure("InvalidInput");
706
+ const kinds = [...command.containers.map((container) => container.kind), blockKind(block)];
707
+ const parentKind = parent === void 0 ? void 0 : blockKind(parent);
708
+ if (!(acceptsChild(state.document, parentPath, outer.kind, options.nodes) && command.containers.every((container, at) => holdsBlocks(options.nodes, container.kind) && kindAccepts(options.nodes, container.kind, kinds[at + 1])) && kinds.every((kind, at) => standsWithin(options.nodes?.definitionFor(kind), at === 0 ? parentKind : kinds[at - 1])))) return failure("UnexpectedChild");
709
+ const before = (parent === void 0 ? state.document.children : parent.type === "Node" ? parent.blocks ?? [] : [])[index - 1];
710
+ const item = command.containers[1];
711
+ const joins = options.nodes !== void 0 && item !== void 0 && holdsItem(options.nodes, outer.kind, item.kind) && before?.type === "Node" && before.kind === outer.kind && Equal.equals(before.props, outer.props ?? {});
712
+ const created = joins ? command.containers.slice(1) : command.containers;
713
+ const containerIds = created.map(() => NodeId.make(ids.mint()));
714
+ const chain = created.reduceRight((inner, container, at) => ({
715
+ type: "Node",
716
+ kind: container.kind,
717
+ id: containerIds[at],
718
+ props: container.props ?? {},
719
+ children: [],
720
+ blocks: inner === void 0 ? [] : [inner]
721
+ }), void 0);
722
+ return apply(state, [joins ? Edit.insertBlock(chain, before.blocks?.length ?? 0, before.id) : Edit.insertBlock(chain, index, parent?.id), Edit.moveBlock(block.id, 0, containerIds[containerIds.length - 1])]);
723
+ }
724
+ if (block.type !== "Paragraph" && block.type !== "Heading") return failure("InvalidInput");
725
+ const kind = command.to.kind;
726
+ if (refusesProps(options.nodes, command.to)) return failure("InvalidInput");
727
+ if (!(options.nodes === void 0 || declaresText(options.nodes, kind)) || !acceptsChild(state.document, parentPath, kind, options.nodes)) return failure("UnexpectedChild");
728
+ if (options.nodes !== void 0 && kindForbidsMarks(options.nodes, kind) && block.children.some((run) => run.marks.length > 0)) return failure("ForbiddenMark");
729
+ return apply(state, [Edit.retypeBlock(block.id, {
730
+ type: "Node",
731
+ kind,
732
+ props: command.to.props ?? {}
733
+ })]);
734
+ };
735
+ /**
736
+ * Resolves one intent into a transaction and applies it atomically. Commands
737
+ * describe intent; the returned `positionMap` and `ChangeSet` describe the
738
+ * document effect, and rejection returns no partially edited state.
739
+ */
740
+ const run = (state, command, ids, options = {}) => {
741
+ const declared = options.marks ?? shippedRegistry;
742
+ const range = state.selection;
743
+ if ((command.type === "InsertText" || command.type === "DeleteBackward" || command.type === "DeleteForward" || command.type === "SplitBlock" || command.type === "Paste") && range?.type === "Range" && !isCollapsed(range)) {
744
+ const span = ordered(state.document, range);
745
+ if (span !== void 0 && deleteRange(state.document, span.start, span.end) === void 0) {
746
+ const cleared = clearRange(state, span.start, span.end, options);
747
+ if (!cleared.ok || command.type === "DeleteBackward" || command.type === "DeleteForward") return cleared;
748
+ return followedBy(cleared, run(cleared.state, command, ids, options));
749
+ }
750
+ }
751
+ if (command.type === "SetSelection") return apply(state, [Edit.setSelection(command.selection)]);
752
+ if (command.type === "SetProps") {
753
+ const target = locateBlock(state.document, command.node)?.block;
754
+ if (target?.type !== "Node") return failure("InvalidInput");
755
+ const refuses = (props) => refusesProps(options.nodes, {
756
+ kind: target.kind,
757
+ props
758
+ });
759
+ if (refuses({
760
+ ...target.props,
761
+ ...command.props
762
+ }) && !refuses(target.props)) return failure("InvalidInput");
763
+ return apply(state, [Edit.setProps(command.node, command.props)]);
764
+ }
765
+ if (command.type === "InsertRow" || command.type === "InsertColumn" || command.type === "DeleteRow" || command.type === "DeleteColumn") {
766
+ const at = tableAt(state.document, state.selection);
767
+ if (at === void 0) return failure("InvalidSelection");
768
+ const edited = Match.value(command).pipe(Match.discriminatorsExhaustive("type")({
769
+ InsertRow: ({ where }) => insertRow(state, at, where, ids.mint),
770
+ InsertColumn: ({ where }) => insertColumn(state, at, where, ids.mint),
771
+ DeleteRow: () => deleteRow(state, at),
772
+ DeleteColumn: () => deleteColumn(state, at)
773
+ }));
774
+ return "deleteTable" in edited ? run(state, {
775
+ type: "DeleteBlock",
776
+ node: edited.deleteTable
777
+ }, ids, options) : edited;
778
+ }
779
+ if (command.type === "Indent" || command.type === "Outdent") {
780
+ const code = linesHolder(state, options.nodes);
781
+ if (code !== void 0) return command.type === "Indent" ? indent(state, code) : outdent(state, code);
782
+ const item = itemAtCaret(state, options.nodes);
783
+ const at = tableAt(state.document, state.selection);
784
+ const tableDepth = at === void 0 ? -1 : locateBlock(state.document, at.table.id)?.path.length ?? -1;
785
+ if (item !== void 0 && item.containerPath.length > tableDepth) return command.type === "Indent" ? sinkItem(state, item, ids, options) : liftItem(state, item, ids, options);
786
+ if (at === void 0) return failure("InvalidSelection");
787
+ return moveToCell(state, at, command.type === "Indent" ? "next" : "previous", ids.mint);
788
+ }
789
+ if (command.type === "Replace") {
790
+ const matches = findMatches(state.document, command.query, command);
791
+ const chosen = command.at === void 0 ? matches : matches.slice(command.at, command.at + 1);
792
+ return replaceMatches(state, chosen, command.replacement, ids, options);
793
+ }
794
+ if (command.type === "InsertFootnote") return insertFootnote(state, command.text ?? "", ids, options);
795
+ if (command.type === "RenameFootnote") return renameFootnote(state, command.from, command.to.trim(), ids, options);
796
+ if (command.type === "InsertBlock") {
797
+ const to = command.to ?? besideCaret(state);
798
+ if (to === void 0) return failure("InvalidSelection");
799
+ const beside = locateBlock(state.document, "before" in to ? to.before : to.after);
800
+ if (beside === void 0) return failure("InvalidInput");
801
+ const containerPath = beside.path.slice(0, -1);
802
+ const holder = containerPath.length === 0 ? void 0 : blockAtPath(state.document, containerPath);
803
+ const kind = blockKind(command.block);
804
+ if (holder !== void 0 && !acceptsChild(state.document, containerPath, kind, options.nodes) || !standsWithin(options.nodes?.definitionFor(kind), holder === void 0 ? void 0 : blockKind(holder))) return failure("UnexpectedChild");
805
+ const [inserted] = withFreshIds({
806
+ version: 1,
807
+ blocks: [command.block]
808
+ }, ids.mint).blocks;
809
+ const at = beside.path[beside.path.length - 1] + ("after" in to ? 1 : 0);
810
+ const first = firstRunIn([inserted]);
811
+ return apply(state, [Edit.insertBlock(inserted, at, holder?.id), ...first === void 0 ? [] : [Edit.setSelection(caretAt({
812
+ node: first.id,
813
+ offset: 0,
814
+ affinity: "after"
815
+ }))]]);
816
+ }
817
+ if (command.type === "DeleteBlock") {
818
+ const deleting = locateBlock(state.document, command.node);
819
+ if (deleting === void 0) return failure("InvalidInput");
820
+ const target = emptiedBy(state.document, deleting.path.slice(0, -1), [-1]) ?? command.node;
821
+ const gone = locateBlock(state.document, target);
822
+ const inside = (path) => gone.path.every((index, depth) => path[depth] === index);
823
+ const runs = [];
824
+ eachBlock(state.document.children, (block, path) => {
825
+ for (const run of block.children) runs.push({
826
+ run,
827
+ inside: inside(path),
828
+ after: pathOrder(path, gone.path) > 0
829
+ });
830
+ });
831
+ const selection = state.selection;
832
+ const holds = selection !== null && (selection.type === "Node" ? locateBlock(state.document, selection.node) !== void 0 && inside(locateBlock(state.document, selection.node).path) : [selection.anchor, selection.focus].some((end) => runs.some((entry) => entry.inside && entry.run.id === end.node)));
833
+ const following = runs.find((entry) => entry.after && !entry.inside);
834
+ const preceding = [...runs].reverse().find((entry) => !entry.after && !entry.inside);
835
+ const landing = following !== void 0 ? {
836
+ node: following.run.id,
837
+ offset: 0,
838
+ affinity: "after"
839
+ } : preceding !== void 0 ? {
840
+ node: preceding.run.id,
841
+ offset: preceding.run.text.length,
842
+ affinity: "after"
843
+ } : void 0;
844
+ if (gone.path.length === 1 && state.document.children.length === 1) {
845
+ const textId = NodeId.make(ids.mint());
846
+ const paragraph = {
847
+ type: "Paragraph",
848
+ id: NodeId.make(ids.mint()),
849
+ children: [{
850
+ type: "Text",
851
+ id: textId,
852
+ text: "",
853
+ marks: []
854
+ }]
855
+ };
856
+ return apply(state, [
857
+ Edit.insertBlock(paragraph, 1),
858
+ Edit.deleteBlock(target),
859
+ Edit.setSelection(caretAt({
860
+ node: textId,
861
+ offset: 0,
862
+ affinity: "after"
863
+ }))
864
+ ]);
865
+ }
866
+ return apply(state, [Edit.deleteBlock(target), ...holds ? [Edit.setSelection(landing === void 0 ? null : caretAt(landing))] : []]);
867
+ }
868
+ if (command.type === "MoveBlock") {
869
+ const moving = locateBlock(state.document, command.node);
870
+ const beside = locateBlock(state.document, "before" in command.to ? command.to.before : command.to.after);
871
+ if (moving === void 0 || beside === void 0) return failure("InvalidInput");
872
+ const container = beside.path.slice(0, -1);
873
+ const refused = moveFailure(state.document, moving, container, options.nodes);
874
+ if (refused !== void 0) return failure(refused);
875
+ const source = moving.path.slice(0, -1);
876
+ const within = pathKey(source) === pathKey(container);
877
+ const from = moving.path[moving.path.length - 1];
878
+ const place = beside.path[beside.path.length - 1] + ("after" in command.to ? 1 : 0);
879
+ const to = within && from < place ? place - 1 : place;
880
+ const parent = container.length === 0 ? void 0 : blockAtPath(state.document, container)?.id;
881
+ const emptied = emptiedBy(state.document, source, container);
882
+ const gone = emptied === void 0 ? void 0 : locateBlock(state.document, emptied);
883
+ const selected = state.selection?.type === "Node" ? locateBlock(state.document, state.selection.node) : void 0;
884
+ const inside = (path, holder) => holder.every((index, depth) => path[depth] === index);
885
+ const lost = gone !== void 0 && selected !== void 0 && inside(selected.path, gone.path) && !inside(selected.path, moving.path);
886
+ return apply(state, [
887
+ Edit.moveBlock(command.node, to, parent),
888
+ ...emptied === void 0 ? [] : [Edit.deleteBlock(emptied)],
889
+ ...lost ? [Edit.setSelection({
890
+ type: "Node",
891
+ node: command.node
892
+ })] : []
893
+ ]);
894
+ }
895
+ const selection = state.selection;
896
+ if (selection?.type === "Node") {
897
+ const after = {
898
+ type: "InsertBlock",
899
+ block: {
900
+ type: "Paragraph",
901
+ id: NodeId.make("paragraph"),
902
+ children: [{
903
+ type: "Text",
904
+ id: NodeId.make("text"),
905
+ text: "",
906
+ marks: []
907
+ }]
908
+ },
909
+ to: { after: selection.node }
910
+ };
911
+ if (command.type === "DeleteBackward" || command.type === "DeleteForward") return run(state, {
912
+ type: "DeleteBlock",
913
+ node: selection.node
914
+ }, ids, options);
915
+ if (command.type === "SplitBlock") return run(state, after, ids, options);
916
+ if (command.type === "InsertText") return runAction(state, [
917
+ after,
918
+ {
919
+ type: "DeleteBlock",
920
+ node: selection.node
921
+ },
922
+ command
923
+ ], ids, options);
924
+ }
925
+ if (selection === null || selection.type === "Node") return failure("InvalidSelection");
926
+ if (command.type === "InsertText") {
927
+ const edge = command.marks === void 0 && isCollapsed(selection) ? edgeMarks(state.document, selection.anchor, options.marks) : void 0;
928
+ const stored = command.marks ?? edge;
929
+ const target = isCollapsed(selection) ? stored === void 0 ? resolveInsertion(state.document, selection.anchor, options.marks) : selection.anchor : ordered(state.document, selection)?.start;
930
+ if (target === void 0) return failure("InvalidSelection");
931
+ const at = locate(state.document, target.node);
932
+ if (at === void 0) return failure("MissingText");
933
+ const marks = [];
934
+ if (stored !== void 0) {
935
+ for (const mark of stored) {
936
+ if (edge === void 0 && !declared.accepts(mark)) return failure("InvalidInput");
937
+ marks.push(mark);
938
+ }
939
+ if (marks.length > 0 && forbidsMarks(state.document, at.path, options.nodes)) return failure("ForbiddenMark");
940
+ }
941
+ const deletions = isCollapsed(selection) ? [] : deleteRange(state.document, target, ordered(state.document, selection).end);
942
+ if (deletions === void 0) return failure("InvalidParent");
943
+ if (command.text.length === 0) return apply(state, deletions.length === 0 ? [] : [...deletions, Edit.setSelection(caretAt(target))]);
944
+ if (stored === void 0) return apply(state, [
945
+ ...deletions,
946
+ Edit.insertText(target, command.text),
947
+ Edit.setSelection(caretAt({
948
+ ...target,
949
+ offset: target.offset + command.text.length,
950
+ affinity: "after"
951
+ }))
952
+ ]);
953
+ const span = isCollapsed(selection) ? void 0 : ordered(state.document, selection);
954
+ const tailFrom = span === void 0 ? target.offset : span.end.node === target.node ? span.end.offset : at.text.length;
955
+ const operations = [...deletions, Edit.insertText(target, command.text)];
956
+ const end = target.offset + command.text.length;
957
+ if (tailFrom < at.text.length) operations.push(Edit.splitRun(target.node, end, ids.mint()));
958
+ const piece = target.offset > 0 ? NodeId.make(ids.mint()) : target.node;
959
+ if (target.offset > 0) operations.push(Edit.splitRun(target.node, target.offset, piece));
960
+ for (const mark of marks) if (!at.marks.some((existing) => sameMark(existing, mark))) operations.push(Edit.addMark(piece, mark));
961
+ for (const mark of at.marks) if (!marks.some((kept) => markName$1(kept) === markName$1(mark))) operations.push(Edit.removeMark(piece, markName$1(mark)));
962
+ return apply(state, operations);
963
+ }
964
+ if (command.type === "RetypeBlock" || command.type === "WrapBlock" || command.type === "ConvertBlock" || command.type === "RetypeContainer" || command.type === "LiftBlock") {
965
+ const target = startingBlock(state.document, selection);
966
+ return "error" in target ? failure(target.error) : runBlockCommand(state, command, target, ids, options);
967
+ }
968
+ if (command.type === "DeleteBackward" || command.type === "DeleteForward") {
969
+ if (!isCollapsed(selection)) {
970
+ const span = ordered(state.document, selection);
971
+ if (span === void 0) return failure("InvalidSelection");
972
+ const deletions = deleteRange(state.document, span.start, span.end);
973
+ if (deletions === void 0) return failure("InvalidParent");
974
+ return apply(state, [...deletions, Edit.setSelection(caretAt(span.start))]);
975
+ }
976
+ const caret = selection.anchor;
977
+ const at = locate(state.document, caret.node);
978
+ if (at === void 0) return failure("MissingText");
979
+ const backward = command.type === "DeleteBackward";
980
+ const block = blockAtPath(state.document, at.path);
981
+ if (block === void 0) return failure("MissingText");
982
+ const deletion = graphemeDeletion(block, caret, at.runIndex, backward);
983
+ if (deletion !== void 0) return apply(state, [...deletion.operations, Edit.setSelection(caretAt(deletion.caret))]);
984
+ if (backward && block.type === "Node" && declaresText(options.nodes, block.kind)) return run(state, {
985
+ type: "RetypeBlock",
986
+ to: { type: "Paragraph" }
987
+ }, ids, options);
988
+ if (backward && block.type === "Heading") return run(state, {
989
+ type: "RetypeBlock",
990
+ to: { type: "Paragraph" }
991
+ }, ids, options);
992
+ const containerPath = at.path.slice(0, -1);
993
+ const siblings = containerBlocks(state.document, containerPath);
994
+ const index = at.path[at.path.length - 1];
995
+ const neighborBlock = siblings[backward ? index - 1 : index + 1];
996
+ if (neighborBlock !== void 0 && isAtom(options.nodes, neighborBlock)) return apply(state, [...textOfBlock(block) === "" ? [Edit.deleteBlock(block.id)] : [], Edit.setSelection({
997
+ type: "Node",
998
+ node: neighborBlock.id
999
+ })]);
1000
+ if (neighborBlock === void 0 && backward) {
1001
+ const lifted = containerPath.length > 0 && options.nodes !== void 0 ? liftOperations(state.document, siblings[index].id, ids, options.nodes) : void 0;
1002
+ return apply(state, lifted ?? []);
1003
+ }
1004
+ if (neighborBlock === void 0 || !joinable(backward ? neighborBlock : block, backward ? block : neighborBlock)) {
1005
+ const leafPath = neighborBlock === void 0 ? nextLeaf(state.document, at.path) : edgeLeaf(state.document, [...containerPath, index + (backward ? -1 : 1)], backward);
1006
+ const leaf = leafPath === void 0 ? void 0 : blockAtPath(state.document, leafPath);
1007
+ if (leafPath === void 0 || leaf === void 0) return apply(state, []);
1008
+ const empty = textOfBlock(block) === "";
1009
+ if (isAtom(options.nodes, leaf)) return apply(state, [Edit.setSelection({
1010
+ type: "Node",
1011
+ node: leaf.id
1012
+ })]);
1013
+ const first = leaf.children[0];
1014
+ const last = leaf.children[leaf.children.length - 1];
1015
+ const target = backward ? last : first;
1016
+ if (target === void 0) return apply(state, []);
1017
+ const edge = {
1018
+ node: target.id,
1019
+ offset: backward ? target.text.length : 0,
1020
+ affinity: "after"
1021
+ };
1022
+ if (!(empty && neighborBlock !== void 0) && (backward ? joinable(leaf, block) : joinable(block, leaf))) return backward ? clearRange(state, edge, caret, options) : clearRange(state, caret, edge, options);
1023
+ if (neighborBlock === void 0 || !backward && !empty) return apply(state, []);
1024
+ return apply(state, [...empty ? [Edit.deleteBlock(block.id)] : [], Edit.setSelection(caretAt(edge))]);
1025
+ }
1026
+ const survivor = backward ? neighborBlock : siblings[index];
1027
+ const removed = backward ? siblings[index] : neighborBlock;
1028
+ const lastRun = lastRunOf(survivor) ?? lastRunOf(removed);
1029
+ return apply(state, [Edit.joinBlocks(survivor.id, removed.id), Edit.setSelection(caretAt(lastRun === void 0 ? {
1030
+ node: survivor.id,
1031
+ offset: 0,
1032
+ affinity: "after"
1033
+ } : {
1034
+ node: lastRun.id,
1035
+ offset: lastRun.text.length,
1036
+ affinity: "after"
1037
+ }))]);
1038
+ }
1039
+ if (command.type === "SplitBlock") {
1040
+ const span = isCollapsed(selection) ? void 0 : ordered(state.document, selection);
1041
+ if (!isCollapsed(selection) && span === void 0) return failure("InvalidSelection");
1042
+ const caret = span?.start ?? selection.anchor;
1043
+ const at = locate(state.document, caret.node);
1044
+ if (at === void 0) return failure("MissingText");
1045
+ const deletions = span === void 0 ? [] : deleteRange(state.document, span.start, span.end);
1046
+ if (deletions === void 0) return failure("InvalidParent");
1047
+ const holder = blockAtPath(state.document, at.path);
1048
+ const definition = holder?.type === "Node" ? options.nodes?.definitionFor(holder.kind) : void 0;
1049
+ if (holder !== void 0 && definition?.kind === "node" && definition.lineBreaks === true) {
1050
+ const last = holder.children[holder.children.length - 1];
1051
+ return span === void 0 && last?.id === at.id && caret.offset === at.text.length && holder.children.map((run) => run.text).join("").endsWith("\n") ? runAction(state, [{ type: "DeleteBackward" }, {
1052
+ type: "InsertBlock",
1053
+ block: {
1054
+ type: "Paragraph",
1055
+ id: NodeId.make("paragraph"),
1056
+ children: [{
1057
+ type: "Text",
1058
+ id: NodeId.make("text"),
1059
+ text: "",
1060
+ marks: []
1061
+ }]
1062
+ },
1063
+ to: { after: holder.id }
1064
+ }], ids, options) : run(state, {
1065
+ type: "InsertText",
1066
+ text: definition.indents === true ? `\n${indentationAt(textOfBlock(holder), offsetIn(holder, caret) ?? 0)}` : "\n"
1067
+ }, ids, options);
1068
+ }
1069
+ const item = itemAround(state.document, at.path, options.nodes);
1070
+ if (item !== void 0) return span === void 0 ? splitItem(state, at, caret.offset, item, ids, options.nodes) : runAction(state, [{ type: "DeleteBackward" }, { type: "SplitBlock" }], ids, options);
1071
+ const textId = ids.mint();
1072
+ const blockId = ids.mint();
1073
+ return apply(state, [
1074
+ ...deletions,
1075
+ Edit.splitBlock(at.blockId, at.id, caret.offset, blockId, textId),
1076
+ ...endsHeading(state.document, at.path, span?.end ?? caret) ? [Edit.retypeBlock(NodeId.make(blockId), { type: "Paragraph" })] : [],
1077
+ Edit.setSelection(caretAt({
1078
+ node: NodeId.make(textId),
1079
+ offset: 0,
1080
+ affinity: "after"
1081
+ }))
1082
+ ]);
1083
+ }
1084
+ if (command.type === "ToggleMark" || command.type === "SetMark" || command.type === "ClearMark") {
1085
+ const mark = command.mark;
1086
+ const name = markName$1(mark);
1087
+ let span = ordered(state.document, selection);
1088
+ if (isCollapsed(selection)) {
1089
+ const extent = command.type === "ToggleMark" ? void 0 : markExtent(state.document, selection.anchor, name);
1090
+ if (extent === void 0) return apply(state, []);
1091
+ span = ordered(state.document, extent.selection);
1092
+ }
1093
+ if (span === void 0) return failure("InvalidSelection");
1094
+ const spans = covered(state.document, span.start, span.end).filter((entry) => command.type !== "ClearMark" || typeof mark === "string" || entry.run.marks.some((held) => sameMark(held, mark)));
1095
+ if (spans.length === 0) return apply(state, []);
1096
+ const adding = command.type === "SetMark" || command.type === "ToggleMark" && !spans.every((entry) => entry.run.marks.some((held) => markName$1(held) === name));
1097
+ const operations = [];
1098
+ const targets = [];
1099
+ for (const [index, entry] of spans.entries()) {
1100
+ let target = entry.run.id;
1101
+ let base = 0;
1102
+ if (index === 0 && entry.from > 0) {
1103
+ const textId = ids.mint();
1104
+ operations.push(Edit.splitRun(target, entry.from, textId));
1105
+ target = NodeId.make(textId);
1106
+ base = entry.from;
1107
+ }
1108
+ if (index === spans.length - 1 && entry.to < entry.run.text.length) operations.push(Edit.splitRun(target, entry.to - base, ids.mint()));
1109
+ targets.push(target);
1110
+ }
1111
+ if (adding) {
1112
+ if (!declared.accepts(mark)) return failure("InvalidInput");
1113
+ if (spans.some((entry) => forbidsMarks(state.document, entry.run.path, options.nodes))) return failure("ForbiddenMark");
1114
+ for (const target of targets) operations.push(Edit.addMark(target, mark));
1115
+ } else for (const target of targets) operations.push(Edit.removeMark(target, name));
1116
+ return apply(state, operations);
1117
+ }
1118
+ if (command.type === "Paste") {
1119
+ const content = command.slice.blocks;
1120
+ if (content.length === 0) return apply(state, []);
1121
+ const span = isCollapsed(selection) ? void 0 : ordered(state.document, selection);
1122
+ if (!isCollapsed(selection) && span === void 0) return failure("InvalidSelection");
1123
+ const caret = span?.start ?? selection.anchor;
1124
+ const at = locate(state.document, caret.node);
1125
+ if (at === void 0) return failure("MissingText");
1126
+ const into = blockAtPath(state.document, at.path);
1127
+ const holds = into?.type === "Node" ? options.nodes?.definitionFor(into.kind) : void 0;
1128
+ if (holds?.kind === "node" && holds.lineBreaks === true) return run(state, {
1129
+ type: "InsertText",
1130
+ text: toText(content)
1131
+ }, ids, options);
1132
+ const index = at.path[at.path.length - 1];
1133
+ const containerPath = at.path.slice(0, -1);
1134
+ const parent = containerPath.length === 0 ? void 0 : blockAtPath(state.document, containerPath)?.id;
1135
+ const replacements = span === void 0 ? [] : deleteRange(state.document, span.start, span.end);
1136
+ if (replacements === void 0) return failure("InvalidParent");
1137
+ const operations = [...replacements];
1138
+ const inserted = withFreshIds(command.slice, ids.mint).blocks;
1139
+ const holder = containerPath.length === 0 ? void 0 : blockAtPath(state.document, containerPath);
1140
+ if (inserted.some((piece) => containerPath.length > 0 && !acceptsChild(state.document, containerPath, blockKind(piece), options.nodes) || !standsWithin(options.nodes?.definitionFor(blockKind(piece)), holder === void 0 ? void 0 : blockKind(holder)))) return failure("UnexpectedChild");
1141
+ const block = blockAtPath(state.document, at.path);
1142
+ if (block === void 0) return failure("MissingText");
1143
+ const end = span?.end ?? caret;
1144
+ const endBlock = blockAtPath(state.document, locate(state.document, end.node)?.path ?? at.path);
1145
+ const beforeEmpty = offsetIn(block, caret) === 0;
1146
+ const afterEmpty = endBlock === void 0 || offsetIn(endBlock, end) === textOfBlock(endBlock).length;
1147
+ const tailText = NodeId.make(ids.mint());
1148
+ const tail = NodeId.make(ids.mint());
1149
+ operations.push(Edit.splitBlock(at.blockId, at.id, caret.offset, tail, tailText));
1150
+ for (const [offset, piece] of inserted.entries()) operations.push(Edit.insertBlock(piece, index + 1 + offset, parent));
1151
+ const first = inserted[0];
1152
+ const last = inserted[inserted.length - 1];
1153
+ const lastRun = last.children[last.children.length - 1];
1154
+ operations.push(Edit.setSelection(caretAt(lastRun === void 0 ? {
1155
+ node: tailText,
1156
+ offset: 0,
1157
+ affinity: "after"
1158
+ } : {
1159
+ node: lastRun.id,
1160
+ offset: lastRun.text.length,
1161
+ affinity: "after"
1162
+ })));
1163
+ const joinsHead = joinable(block, first);
1164
+ const joinsTail = joinable(last, block);
1165
+ if (joinsHead) operations.push(Edit.joinBlocks(at.blockId, first.id));
1166
+ if (joinsTail) operations.push(Edit.joinBlocks(joinsHead && last === first ? at.blockId : last.id, tail));
1167
+ if (!joinsHead && beforeEmpty) operations.push(Edit.deleteBlock(at.blockId));
1168
+ if (!joinsTail && afterEmpty && lastRun !== void 0) operations.push(Edit.deleteBlock(tail));
1169
+ return apply(state, operations);
1170
+ }
1171
+ return apply(state, []);
1172
+ };
1173
+ /** Where an `InsertBlock` without a place goes: beside the caret's block, before it when empty. */
1174
+ const besideCaret = (state) => {
1175
+ if (state.selection?.type !== "Range") return void 0;
1176
+ const run = locateRun(state.document, ordered(state.document, state.selection)?.start.node ?? state.selection.anchor.node);
1177
+ const block = run === void 0 ? void 0 : blockAtPath(state.document, run.path);
1178
+ if (block === void 0) return void 0;
1179
+ return block.children.every((child) => child.text === "") ? { before: block.id } : { after: block.id };
1180
+ };
1181
+ const textOfBlock = (block) => block.children.map((run) => run.text).join("");
1182
+ /** The block the selection starts in when its kind indents its lines, as code does. */
1183
+ const linesHolder = (state, nodes) => {
1184
+ if (state.selection?.type !== "Range") return void 0;
1185
+ const start = ordered(state.document, state.selection)?.start;
1186
+ const run = start === void 0 ? void 0 : locateRun(state.document, start.node);
1187
+ const block = run === void 0 ? void 0 : blockAtPath(state.document, run.path);
1188
+ if (block?.type !== "Node") return void 0;
1189
+ const definition = nodes?.definitionFor(block.kind);
1190
+ return definition?.kind === "node" && definition.indents === true ? block : void 0;
1191
+ };
1192
+ /**
1193
+ * Whether Tab means something where the selection is: in code, or in a table cell. An editor
1194
+ * takes Tab only there, so anywhere else it still moves focus out of the editor.
1195
+ */
1196
+ const takesTab = (document, selection, nodes) => linesHolder({
1197
+ document,
1198
+ selection
1199
+ }, nodes) !== void 0 || itemAtCaret({
1200
+ document,
1201
+ selection
1202
+ }, nodes) !== void 0 || tableAt(document, selection) !== void 0;
1203
+ /** The list item the selection starts in, when the vocabulary says its list holds it. */
1204
+ const itemAtCaret = (state, nodes) => {
1205
+ if (state.selection?.type !== "Range") return void 0;
1206
+ const start = ordered(state.document, state.selection)?.start;
1207
+ const run = start === void 0 ? void 0 : locateRun(state.document, start.node);
1208
+ return run === void 0 ? void 0 : itemAround(state.document, run.path, nodes);
1209
+ };
1210
+ /** Whether two props hold the same values, for a list that two items may share. */
1211
+ const sameProps = (left, right) => {
1212
+ const keys = Object.keys(left);
1213
+ return keys.length === Object.keys(right).length && keys.every((key) => Object.hasOwn(right, key) && Equal.equals(left[key], right[key]));
1214
+ };
1215
+ /**
1216
+ * Tab in a list item: the item moves under the item before it, as the last item of the list
1217
+ * that item ends with, or of a new one like its own when it ends with none. It keeps its
1218
+ * identity, and the caret with it. The first item has nothing to go under, and stays.
1219
+ */
1220
+ const sinkItem = (state, item, ids, options) => {
1221
+ if (item.list.type !== "Node") return apply(state, []);
1222
+ const list = item.list;
1223
+ const index = item.containerPath[item.containerPath.length - 1];
1224
+ const previous = (list.blocks ?? [])[index - 1];
1225
+ if (previous?.type !== "Node") return apply(state, []);
1226
+ const nested = previous.blocks?.at(-1);
1227
+ const last = nested?.type === "Node" ? nested.blocks?.at(-1) : void 0;
1228
+ if (nested?.type === "Node" && nested.kind === list.kind && sameProps(nested.props, list.props) && last !== void 0) return run(state, {
1229
+ type: "MoveBlock",
1230
+ node: item.container.id,
1231
+ to: { after: last.id }
1232
+ }, ids, options);
1233
+ const created = NodeId.make(ids.mint());
1234
+ return apply(state, [Edit.insertBlock({
1235
+ type: "Node",
1236
+ kind: list.kind,
1237
+ id: created,
1238
+ props: list.props,
1239
+ children: [],
1240
+ blocks: []
1241
+ }, (previous.blocks ?? []).length, previous.id), Edit.moveBlock(item.container.id, 0, created)]);
1242
+ };
1243
+ /**
1244
+ * Shift+Tab in a list item: a nested item moves out to follow the item its list is in, and an
1245
+ * item at the top level leaves its list, as `LiftBlock` takes it. A list the move empties goes.
1246
+ */
1247
+ const liftItem = (state, item, ids, options) => {
1248
+ const listPath = item.containerPath.slice(0, -1);
1249
+ const outerItem = blockAtPath(state.document, listPath.slice(0, -1));
1250
+ const outerList = blockAtPath(state.document, listPath.slice(0, -2));
1251
+ return outerItem?.type === "Node" && outerList?.type === "Node" && options.nodes !== void 0 && holdsItem(options.nodes, outerList.kind, outerItem.kind) ? run(state, {
1252
+ type: "MoveBlock",
1253
+ node: item.container.id,
1254
+ to: { after: outerItem.id }
1255
+ }, ids, options) : run(state, { type: "LiftBlock" }, ids, options);
1256
+ };
1257
+ /**
1258
+ * Replaces matches, last first, each read again from its block's offset in the state the one
1259
+ * after it left: a replacement later in a block leaves an earlier match's offset alone, though
1260
+ * the runs it touched may have merged or split, so positions found before it would not do.
1261
+ */
1262
+ const replaceMatches = (state, matches, replacement, ids, options) => {
1263
+ let done = apply(state, []);
1264
+ for (const match of [...matches].reverse()) {
1265
+ if (!done.ok) return done;
1266
+ const block = locateBlock(done.state.document, match.block)?.block;
1267
+ const from = block === void 0 ? void 0 : positionInBlock(block, match.at);
1268
+ const to = block === void 0 ? void 0 : positionInBlock(block, match.at + match.length);
1269
+ if (from === void 0 || to === void 0) return failure("MissingText");
1270
+ const step = runAction(done.state, [{
1271
+ type: "SetSelection",
1272
+ selection: {
1273
+ type: "Range",
1274
+ anchor: from,
1275
+ focus: to
1276
+ }
1277
+ }, {
1278
+ type: "InsertText",
1279
+ text: replacement
1280
+ }], ids, options);
1281
+ if (!step.ok) return step;
1282
+ done = {
1283
+ ok: true,
1284
+ state: step.state,
1285
+ changeSet: unionChangeSet(done.changeSet, step.changeSet),
1286
+ positionMap: [...done.positionMap, ...step.positionMap],
1287
+ transactions: [...done.transactions, ...step.transactions]
1288
+ };
1289
+ }
1290
+ return done;
1291
+ };
1292
+ const insertFootnote = (state, text, ids, options) => {
1293
+ const selection = state.selection;
1294
+ if (selection?.type !== "Range") return failure("InvalidSelection");
1295
+ const start = rangeStart(state.document, selection);
1296
+ const last = state.document.children[state.document.children.length - 1];
1297
+ if (start === void 0 || last === void 0) return failure("InvalidSelection");
1298
+ const end = start === selection.anchor ? selection.focus : selection.anchor;
1299
+ const label = nextFootnoteLabel(state.document);
1300
+ const definition = {
1301
+ type: "Node",
1302
+ kind: FootnoteDefinition.name,
1303
+ id: NodeId.make("footnote"),
1304
+ props: { label },
1305
+ children: [],
1306
+ blocks: [{
1307
+ type: "Paragraph",
1308
+ id: NodeId.make("footnote-text"),
1309
+ children: [{
1310
+ type: "Text",
1311
+ id: NodeId.make("footnote-run"),
1312
+ text,
1313
+ marks: []
1314
+ }]
1315
+ }]
1316
+ };
1317
+ return runAction(state, [
1318
+ {
1319
+ type: "SetSelection",
1320
+ selection: {
1321
+ type: "Range",
1322
+ anchor: end,
1323
+ focus: end
1324
+ }
1325
+ },
1326
+ {
1327
+ type: "InsertText",
1328
+ text: label,
1329
+ marks: [FootnoteRef.of({ label })]
1330
+ },
1331
+ {
1332
+ type: "InsertBlock",
1333
+ block: definition,
1334
+ to: { after: last.id }
1335
+ }
1336
+ ], ids, options);
1337
+ };
1338
+ const renameFootnote = (state, from, to, ids, options) => {
1339
+ const notes = footnotesOf(state.document);
1340
+ const note = notes.find((each) => each.label === from);
1341
+ if (note === void 0 || to === "" || to !== from && notes.some((each) => each.label === to)) return failure("InvalidInput");
1342
+ const relabelled = FootnoteRef.of({ label: to });
1343
+ const references = [];
1344
+ eachBlock(state.document.children, (block) => {
1345
+ for (const run of block.children) {
1346
+ if (referenceLabel(run) !== from) continue;
1347
+ references.push({
1348
+ type: "SetSelection",
1349
+ selection: {
1350
+ type: "Range",
1351
+ anchor: {
1352
+ node: run.id,
1353
+ offset: 0,
1354
+ affinity: "after"
1355
+ },
1356
+ focus: {
1357
+ node: run.id,
1358
+ offset: run.text.length,
1359
+ affinity: "before"
1360
+ }
1361
+ }
1362
+ }, {
1363
+ type: "InsertText",
1364
+ text: run.text === from ? to : run.text,
1365
+ marks: run.marks.map((each) => markName$1(each) === FootnoteRef.name ? relabelled : each)
1366
+ });
1367
+ }
1368
+ });
1369
+ const selection = state.selection;
1370
+ const inReference = selection?.type === "Range" && (note.references.includes(selection.anchor.node) || note.references.includes(selection.focus.node));
1371
+ return runAction(state, [
1372
+ ...note.definition === void 0 ? [] : [{
1373
+ type: "SetProps",
1374
+ node: note.definition,
1375
+ props: { label: to }
1376
+ }],
1377
+ ...references,
1378
+ ...inReference || selection === null ? [] : [{
1379
+ type: "SetSelection",
1380
+ selection
1381
+ }]
1382
+ ], ids, options);
1383
+ };
1384
+ /** The first run anywhere in these blocks, nested ones included, in document order. */
1385
+ const firstRunIn = (blocks) => {
1386
+ let found;
1387
+ eachBlock(blocks, (block) => {
1388
+ found ??= block.children[0];
1389
+ });
1390
+ return found;
1391
+ };
1392
+ /**
1393
+ * A composed action's invalidation summary is the union of its commands': an identity
1394
+ * one command retired and a later one restored appears in both sets, and a patch reads
1395
+ * that as "remove it, then render it", so it never under-invalidates.
1396
+ */
1397
+ const unionChangeSet = (left, right) => ({
1398
+ dirtyNodes: /* @__PURE__ */ new Set([...left.dirtyNodes, ...right.dirtyNodes]),
1399
+ insertedNodes: /* @__PURE__ */ new Set([...left.insertedNodes, ...right.insertedNodes]),
1400
+ removedNodes: /* @__PURE__ */ new Set([...left.removedNodes, ...right.removedNodes]),
1401
+ textChanged: /* @__PURE__ */ new Set([...left.textChanged, ...right.textChanged]),
1402
+ structureChanged: left.structureChanged || right.structureChanged,
1403
+ selectionChanged: left.selectionChanged || right.selectionChanged
1404
+ });
1405
+ /**
1406
+ * Resolves commands in order and commits them as one action: one resulting state, one
1407
+ * composed ChangeSet, and one identity stream, so a caller can treat "remove the query,
1408
+ * then apply the choice" as a single transition. It stops at the first refusal and
1409
+ * returns that command's error; state is a value, so nothing partial escapes.
1410
+ */
1411
+ const runAction = (state, commands, ids, options = {}) => {
1412
+ const [first, ...rest] = commands;
1413
+ if (first === void 0) return apply(state, []);
1414
+ const started = run(state, first, ids, options);
1415
+ if (!started.ok) return started;
1416
+ let current = started.state;
1417
+ let changeSet = started.changeSet;
1418
+ let positionMap = started.positionMap;
1419
+ let transactions = started.transactions;
1420
+ for (const command of rest) {
1421
+ const result = run(current, command, ids, options);
1422
+ if (!result.ok) return result;
1423
+ current = result.state;
1424
+ changeSet = unionChangeSet(changeSet, result.changeSet);
1425
+ positionMap = [...positionMap, ...result.positionMap];
1426
+ transactions = [...transactions, ...result.transactions];
1427
+ }
1428
+ return {
1429
+ ok: true,
1430
+ state: current,
1431
+ changeSet,
1432
+ positionMap,
1433
+ transactions
1434
+ };
1435
+ };
1436
+ export { Beside, Container, blocksAt, coversText, isAtom, markExtent, marksInRange, moveTargets, run, runAction, takesTab, textBlockAt, unionChangeSet };
1437
+
1438
+ //# sourceMappingURL=command.js.map