foldkit-richtext 0.2.0 → 0.4.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.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
- import { Equal, Schema } from "effect";
2
+ import { Equal, Match, Schema } from "effect";
3
3
  //#region src/document.ts
4
4
  /** Caller-assigned identity, unique across blocks and text runs in a document. */
5
5
  const NodeId = Schema.NonEmptyString.pipe(Schema.brand("foldkit-richtext/NodeId"));
@@ -221,6 +221,22 @@ const locateBlock = (document, node) => {
221
221
  });
222
222
  return found;
223
223
  };
224
+ /**
225
+ * The blocks either side of a block in its own container, which a handle's up and down move it
226
+ * past; both absent when the document does not hold it.
227
+ */
228
+ const siblingsOf = (document, node) => {
229
+ const found = locateBlock(document, node);
230
+ if (found === void 0) return {};
231
+ const index = found.path[found.path.length - 1];
232
+ const container = found.path.slice(0, -1);
233
+ const parent = container.length === 0 ? void 0 : blockAtPath(document, container);
234
+ const blocks = parent?.type === "Node" ? parent.blocks ?? [] : document.children;
235
+ return {
236
+ previous: blocks[index - 1],
237
+ next: blocks[index + 1]
238
+ };
239
+ };
224
240
  /** The run with this identity, wherever it sits. */
225
241
  const locateRun = (document, node) => {
226
242
  let found;
@@ -602,31 +618,75 @@ const sameMarkSet = (left, right) => left.length === right.length && left.every(
602
618
  * for `apply` to diagnose. Never invents runs: mixed-mark edges stay put.
603
619
  */
604
620
  const resolveInsertion = (document, position, registry = shippedRegistry) => {
605
- for (const block of document.children) {
621
+ let resolved = position;
622
+ eachBlock(document.children, (block) => {
606
623
  const index = block.children.findIndex((run) => run.id === position.node);
607
624
  const run = block.children[index];
608
- if (run === void 0) continue;
625
+ if (run === void 0) return;
609
626
  const leavingLeft = position.affinity === "before" && position.offset === 0;
610
627
  const leavingRight = position.affinity === "after" && position.offset === run.text.length;
611
- if (!leavingLeft && !leavingRight) return position;
628
+ if (!leavingLeft && !leavingRight) return;
612
629
  const neighbor = leavingLeft ? block.children[index - 1] : block.children[index + 1];
613
- if (neighbor === void 0) return position;
614
- const direction = leavingLeft ? "before" : "after";
615
- const desired = run.marks.filter((mark) => {
616
- const expand = registry.expansionOf(markName(mark));
617
- return expand === "both" || expand === direction;
618
- });
619
- if (!sameMarkSet(desired, neighbor.marks)) return position;
620
- return {
630
+ if (neighbor === void 0) return;
631
+ const desired = extending(run.marks, leavingLeft ? "before" : "after", registry);
632
+ if (!sameMarkSet(desired, neighbor.marks)) return;
633
+ resolved = {
621
634
  node: neighbor.id,
622
635
  offset: leavingLeft ? neighbor.text.length : 0,
623
636
  affinity: position.affinity
624
637
  };
625
- }
626
- return position;
638
+ });
639
+ return resolved;
640
+ };
641
+ /** The marks of a run that extend past its edge in this direction. */
642
+ const extending = (marks, direction, registry) => marks.filter((mark) => {
643
+ const expand = registry.expansionOf(markName(mark));
644
+ return expand === "both" || expand === direction;
645
+ });
646
+ /**
647
+ * The marks text typed at the outer edge of a block should carry, when they differ from its run's:
648
+ * a mark that does not extend past that edge (a link, a footnote reference) stops there. There is
649
+ * no neighbouring run to type into instead, as `resolveInsertion` finds inside a block, so the
650
+ * text needs a run of its own. Undefined anywhere else, and where every mark extends.
651
+ */
652
+ const edgeMarks = (document, position, registry = shippedRegistry) => {
653
+ let found;
654
+ eachBlock(document.children, (block) => {
655
+ const index = block.children.findIndex((run) => run.id === position.node);
656
+ const run = block.children[index];
657
+ if (run === void 0 || run.text.length === 0) return;
658
+ const atEnd = index === block.children.length - 1 && position.offset === run.text.length;
659
+ const atStart = index === 0 && position.offset === 0;
660
+ if (!atEnd && !atStart) return;
661
+ const desired = extending(run.marks, atEnd ? "after" : "before", registry);
662
+ if (desired.length !== run.marks.length) found = desired;
663
+ });
664
+ return found;
627
665
  };
628
666
  //#endregion
629
667
  //#region src/rendering.ts
668
+ /** The attribute that marks an element as an adornment, which every interpreter skips as content. */
669
+ const ADORNMENT_ATTRIBUTE = "data-adornment";
670
+ /** The attribute naming the prop an adornment's click flips. */
671
+ const TOGGLES_ATTRIBUTE = "data-toggles";
672
+ /** The attribute naming what an adornment's click asks the application for. */
673
+ const ACTION_ATTRIBUTE = "data-action";
674
+ /** An adornment's attributes as every interpreter writes them: its own, then the markers. */
675
+ const adornmentAttributes = (adornment) => [
676
+ ...Object.entries(adornment.attributes).filter(([name]) => name !== "data-adornment" && name !== "data-toggles" && name !== "data-action"),
677
+ [ADORNMENT_ATTRIBUTE, ""],
678
+ ...adornment.toggles === void 0 ? [] : [[TOGGLES_ATTRIBUTE, adornment.toggles]],
679
+ ...adornment.action === void 0 ? [] : [[ACTION_ATTRIBUTE, adornment.action]]
680
+ ];
681
+ /** Whether two renderings draw the same element: tag, attributes, holder and adornments. */
682
+ const sameElementRendering = (left, right) => left.tag === right.tag && left.inner === right.inner && sameRecord(left.attributes, right.attributes) && (left.adornments ?? []).length === (right.adornments ?? []).length && (left.adornments ?? []).every((adornment, at) => {
683
+ const other = right.adornments[at];
684
+ return adornment.tag === other.tag && adornment.text === other.text && adornment.toggles === other.toggles && adornment.action === other.action && sameRecord(adornment.attributes, other.attributes);
685
+ });
686
+ const sameRecord = (left, right) => {
687
+ const names = Object.keys(left);
688
+ return names.length === Object.keys(right).length && names.every((name) => Object.hasOwn(right, name) && left[name] === right[name]);
689
+ };
630
690
  /** The nesting the shipped marks get, innermost first. */
631
691
  const BUILT_IN_MARK_TAGS = [
632
692
  ["Bold", "strong"],
@@ -766,7 +826,11 @@ const renderBlock = (block, renderer) => {
766
826
  tag: blockTag(block),
767
827
  attributes: block.type === "Node" ? { "data-node": block.kind } : {}
768
828
  };
769
- return renderElement(element, element.inner === void 0 ? `${runs}${nested}` : `${runs}${renderElement({
829
+ const adornment = (element.adornments ?? []).map((piece) => renderElement({
830
+ tag: piece.tag,
831
+ attributes: Object.fromEntries(adornmentAttributes(piece))
832
+ }, escapeText(piece.text ?? ""))).join("");
833
+ return renderElement(element, element.inner === void 0 ? `${adornment}${runs}${nested}` : `${adornment}${runs}${renderElement({
770
834
  tag: element.inner,
771
835
  attributes: {}
772
836
  }, nested)}`);
@@ -1040,7 +1104,9 @@ const node = (name, options = {}) => ({
1040
1104
  props: options.Props,
1041
1105
  isolating: options.isolating ?? false,
1042
1106
  splitProps: options.splitProps,
1043
- within: options.within
1107
+ within: options.within,
1108
+ lineBreaks: options.lineBreaks ?? false,
1109
+ indents: options.indents ?? false
1044
1110
  });
1045
1111
  const kit = (definition) => Object.freeze({
1046
1112
  nodes: [...definition.nodes],
@@ -2275,6 +2341,410 @@ const apply = (state, transaction, transforms = defaultTransforms) => {
2275
2341
  };
2276
2342
  };
2277
2343
  //#endregion
2344
+ //#region src/indent.ts
2345
+ /**
2346
+ * Indentation in a kind whose lines are indented, as code's are (`node(…, { indents })`):
2347
+ * Tab indents, Shift+Tab outdents, and Enter starts the new line as indented as the one it
2348
+ * broke. A line is the text between two breaks of one block.
2349
+ */
2350
+ /** What one level of indentation is: two spaces. */
2351
+ const INDENT = " ";
2352
+ const textOf$1 = (block) => block.children.map((run) => run.text).join("");
2353
+ /** A position's offset into its block's whole text, or undefined when it is not the block's. */
2354
+ const offsetIn = (block, position) => {
2355
+ let consumed = 0;
2356
+ for (const run of block.children) {
2357
+ if (run.id === position.node) return consumed + position.offset;
2358
+ consumed += run.text.length;
2359
+ }
2360
+ };
2361
+ const lineStart = (text, offset) => text.lastIndexOf("\n", offset - 1) + 1;
2362
+ /** The leading spaces and tabs of the line `offset` is on, up to `offset`. */
2363
+ const indentationAt = (text, offset) => /^[ \t]*/.exec(text.slice(lineStart(text, offset), offset))?.[0] ?? "";
2364
+ /**
2365
+ * The starts of the lines a range covers, last first, so editing each leaves the offsets of the
2366
+ * ones before it as they were. A line the range only reaches the start of is not covered.
2367
+ */
2368
+ const linesCovered = (text, from, to) => {
2369
+ const starts = [lineStart(text, from)];
2370
+ for (let at = text.indexOf("\n", from); at !== -1 && at + 1 < to; at = text.indexOf("\n", at + 1)) starts.push(at + 1);
2371
+ return starts.reverse();
2372
+ };
2373
+ /** The selection's ends as offsets into the block's text, in order, or undefined. */
2374
+ const span = (state, block) => {
2375
+ const selection = state.selection;
2376
+ if (selection?.type !== "Range") return void 0;
2377
+ const anchor = offsetIn(block, selection.anchor);
2378
+ const focus = offsetIn(block, selection.focus);
2379
+ if (anchor === void 0 || focus === void 0) return void 0;
2380
+ return {
2381
+ from: Math.min(anchor, focus),
2382
+ to: Math.max(anchor, focus)
2383
+ };
2384
+ };
2385
+ /**
2386
+ * Tab: at a caret, a level of indentation where the caret is; over a range, a level at the start
2387
+ * of every line it covers, so a block of code moves right together.
2388
+ */
2389
+ const indent = (state, block) => {
2390
+ const ends = span(state, block);
2391
+ if (ends === void 0) return {
2392
+ ok: false,
2393
+ error: "InvalidSelection"
2394
+ };
2395
+ const text = textOf$1(block);
2396
+ const at = (offset) => positionInBlock(block, offset);
2397
+ if (ends.from === ends.to) {
2398
+ const caret = at(ends.from);
2399
+ if (caret === void 0) return {
2400
+ ok: false,
2401
+ error: "InvalidSelection"
2402
+ };
2403
+ const after = {
2404
+ node: caret.node,
2405
+ offset: caret.offset + 2,
2406
+ affinity: "after"
2407
+ };
2408
+ return apply(state, [Edit.insertText(caret, " "), Edit.setSelection({
2409
+ type: "Range",
2410
+ anchor: after,
2411
+ focus: after
2412
+ })]);
2413
+ }
2414
+ const operations = [];
2415
+ for (const start of linesCovered(text, ends.from, ends.to)) {
2416
+ const position = at(start);
2417
+ if (position !== void 0) operations.push(Edit.insertText(position, " "));
2418
+ }
2419
+ return apply(state, operations);
2420
+ };
2421
+ /** Shift+Tab: up to a level of indentation off the start of every line the selection is on. */
2422
+ const outdent = (state, block) => {
2423
+ const ends = span(state, block);
2424
+ if (ends === void 0) return {
2425
+ ok: false,
2426
+ error: "InvalidSelection"
2427
+ };
2428
+ const text = textOf$1(block);
2429
+ const starts = ends.from === ends.to ? [lineStart(text, ends.from)] : linesCovered(text, ends.from, ends.to);
2430
+ const operations = [];
2431
+ for (const start of starts) {
2432
+ const leading = /^(?: {1,2}|\t)/.exec(text.slice(start))?.[0].length ?? 0;
2433
+ const from = positionInBlock(block, start);
2434
+ if (leading === 0 || from === void 0 || from.offset + leading > runLength(block, from)) continue;
2435
+ operations.push(Edit.deleteText(from.node, from.offset, from.offset + leading));
2436
+ }
2437
+ return apply(state, operations);
2438
+ };
2439
+ const runLength = (block, position) => block.children.find((run) => run.id === position.node)?.text.length ?? 0;
2440
+ //#endregion
2441
+ //#region src/search.ts
2442
+ /**
2443
+ * Search: every occurrence of a query in a document's text, as matches a find bar steps through
2444
+ * and as decorations a renderer draws, without changing anything. The producer lives here rather
2445
+ * than in an application because it is a pure read of a document and nothing else, and the
2446
+ * interpreter that draws the result is the caller's choice — the read-only view renders these as
2447
+ * `span[data-decoration="search"]` (§126), and the editable one takes them when its overlay lands.
2448
+ *
2449
+ * A match never spans two blocks, because what a document has between blocks is a structural
2450
+ * boundary rather than text. It may span two *runs*, though, which is why a block's runs are
2451
+ * read as one string and the endpoints are mapped back to positions.
2452
+ */
2453
+ /** The kind a search decoration carries, which is what a stylesheet reaches it by. */
2454
+ const SEARCH_DECORATION = "search";
2455
+ /** The kind the match a find bar is on carries instead, so it can be drawn apart. */
2456
+ const SEARCH_CURRENT_DECORATION = "search-current";
2457
+ /**
2458
+ * Text as it is compared: lowercased when case does not count, unless lowercasing would change
2459
+ * its length (a dotted capital I does), which would put every offset after it out of step.
2460
+ */
2461
+ const comparable = (text, caseSensitive) => {
2462
+ if (caseSensitive) return text;
2463
+ const lower = text.toLowerCase();
2464
+ return lower.length === text.length ? lower : text;
2465
+ };
2466
+ /** Every occurrence of `query`, in document order; none for an empty query. */
2467
+ const findMatches = (document, query, options = {}) => {
2468
+ const found = [];
2469
+ if (query.length === 0) return found;
2470
+ const caseSensitive = options.caseSensitive === true;
2471
+ const needle = comparable(query, caseSensitive);
2472
+ eachBlock(document.children, (block) => {
2473
+ if (block.type === "Unknown" || block.children.length === 0) return;
2474
+ const text = comparable(block.children.map((run) => run.text).join(""), caseSensitive);
2475
+ for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + needle.length)) {
2476
+ const from = positionInBlock(block, at);
2477
+ const to = positionInBlock(block, at + needle.length);
2478
+ if (from !== void 0 && to !== void 0) found.push({
2479
+ block: block.id,
2480
+ at,
2481
+ length: needle.length,
2482
+ from,
2483
+ to
2484
+ });
2485
+ }
2486
+ });
2487
+ return found;
2488
+ };
2489
+ /**
2490
+ * Every occurrence of `query` in the document, as decorations a renderer can draw; the one at
2491
+ * index `current`, when given, carries `search-current` instead of `search`.
2492
+ */
2493
+ const searchDecorations = (document, query, options = {}) => findMatches(document, query, options).map((match, index) => ({
2494
+ from: match.from,
2495
+ to: match.to,
2496
+ kind: index === options.current ? SEARCH_CURRENT_DECORATION : SEARCH_DECORATION
2497
+ }));
2498
+ //#endregion
2499
+ //#region src/footnote.ts
2500
+ /**
2501
+ * Footnotes: a reference in the text and a definition at the end of the document, tied by a
2502
+ * label. The reference is a mark on the run that shows the label, so it moves, splits and undoes
2503
+ * with the text; the definition is a block holding blocks, so its note is ordinary editable text.
2504
+ * Nothing else ties them: a definition no reference names, or a reference with no definition, is
2505
+ * what `footnotesOf` reports, not an invalid document.
2506
+ */
2507
+ const Label = Schema.Struct({ label: Schema.String });
2508
+ /** Where a footnote is referred to: the run showing its label carries this mark. */
2509
+ const FootnoteRef = mark("FootnoteRef", {
2510
+ Props: Label,
2511
+ expand: "none"
2512
+ });
2513
+ /** A footnote's note, under the label its references carry. */
2514
+ const FootnoteDefinition = node("FootnoteDefinition", {
2515
+ Props: Label,
2516
+ children: blockContent
2517
+ });
2518
+ const labelOf = (props) => {
2519
+ if (typeof props !== "object" || props === null || !("label" in props)) return void 0;
2520
+ return typeof props.label === "string" ? props.label : void 0;
2521
+ };
2522
+ /** The label of the footnote a run refers to, if it carries a reference. */
2523
+ const referenceLabel = (run) => {
2524
+ const reference = run.marks.find((each) => markName(each) === FootnoteRef.name);
2525
+ return reference === void 0 ? void 0 : labelOf(markProps(reference));
2526
+ };
2527
+ const textOf = (blocks) => {
2528
+ const lines = [];
2529
+ eachBlock(blocks, (block) => {
2530
+ if (block.children.length > 0) lines.push(block.children.map((run) => run.text).join(""));
2531
+ });
2532
+ return lines.join("\n");
2533
+ };
2534
+ /**
2535
+ * Every footnote, in the order its first reference appears; a definition nothing refers to comes
2536
+ * after them, in document order.
2537
+ */
2538
+ const footnotesOf = (document) => {
2539
+ const references = /* @__PURE__ */ new Map();
2540
+ const definitions = /* @__PURE__ */ new Map();
2541
+ eachBlock(document.children, (block) => {
2542
+ if (block.type === "Node" && block.kind === FootnoteDefinition.name) {
2543
+ const label = labelOf(block.props);
2544
+ if (label !== void 0 && !definitions.has(label)) definitions.set(label, {
2545
+ node: block.id,
2546
+ text: textOf(block.blocks ?? [])
2547
+ });
2548
+ }
2549
+ for (const run of block.children) {
2550
+ const label = referenceLabel(run);
2551
+ if (label === void 0) continue;
2552
+ const held = references.get(label);
2553
+ if (held === void 0) references.set(label, [run.id]);
2554
+ else held.push(run.id);
2555
+ }
2556
+ });
2557
+ return [...references.keys(), ...[...definitions.keys()].filter((l) => !references.has(l))].map((label) => ({
2558
+ label,
2559
+ definition: definitions.get(label)?.node,
2560
+ references: references.get(label) ?? [],
2561
+ text: definitions.get(label)?.text ?? ""
2562
+ }));
2563
+ };
2564
+ /**
2565
+ * The label of the footnote whose reference the selection starts in or right beside. A reference
2566
+ * is a character or two, and its mark does not extend, so a click on one usually leaves the caret
2567
+ * at its edge, in the run next to it; that caret counts as at the reference.
2568
+ */
2569
+ const footnoteAt = (document, selection) => {
2570
+ if (selection?.type !== "Range") return void 0;
2571
+ const start = rangeStart(document, selection);
2572
+ if (start === void 0) return void 0;
2573
+ let found;
2574
+ eachBlock(document.children, (block) => {
2575
+ const index = block.children.findIndex((each) => each.id === start.node);
2576
+ if (index < 0) return;
2577
+ const run = block.children[index];
2578
+ let beside;
2579
+ if (start.offset === 0) beside = block.children[index - 1];
2580
+ else if (start.offset === run.text.length) beside = block.children[index + 1];
2581
+ found = referenceLabel(run) ?? (beside === void 0 ? void 0 : referenceLabel(beside));
2582
+ });
2583
+ return found;
2584
+ };
2585
+ /** The smallest whole number no footnote uses as its label, as text: the next note's label. */
2586
+ const nextFootnoteLabel = (document) => {
2587
+ const used = new Set(footnotesOf(document).map((each) => each.label));
2588
+ let n = 1;
2589
+ while (used.has(String(n))) n++;
2590
+ return String(n);
2591
+ };
2592
+ //#endregion
2593
+ //#region src/table.ts
2594
+ /**
2595
+ * Editing a table as a grid: rows and columns added and removed beside the caret's cell, and the
2596
+ * caret moved from cell to cell, as Tab and Shift+Tab do. A table is the standard vocabulary's
2597
+ * `Table` of `TableRow`s of `TableCell`s, each cell holding blocks; a column is the cells at one
2598
+ * index across the rows, which may be ragged, so a column that a short row lacks is skipped
2599
+ * rather than refused. Each change is one transaction, so it is one undo step.
2600
+ */
2601
+ const isKind = (block, kind) => block?.type === "Node" && block.kind === kind;
2602
+ /** The cells of a row, which are its nested blocks. */
2603
+ const cellsOf = (row) => row.blocks ?? [];
2604
+ /**
2605
+ * The table cell the selection starts in, the innermost one when tables nest, or undefined
2606
+ * outside a table. A range is read from its start, as the other block commands read it.
2607
+ */
2608
+ const tableAt = (document, selection) => {
2609
+ if (selection?.type !== "Range") return void 0;
2610
+ const start = rangeStart(document, selection);
2611
+ const run = start === void 0 ? void 0 : locateRun(document, start.node);
2612
+ if (run === void 0) return void 0;
2613
+ for (let depth = run.path.length - 1; depth >= 3; depth--) {
2614
+ const cell = blockAtPath(document, run.path.slice(0, depth));
2615
+ const row = blockAtPath(document, run.path.slice(0, depth - 1));
2616
+ const table = blockAtPath(document, run.path.slice(0, depth - 2));
2617
+ if (isKind(cell, "TableCell") && isKind(row, "TableRow") && isKind(table, "Table")) return {
2618
+ table,
2619
+ rows: (table.blocks ?? []).filter((candidate) => candidate.type === "Node"),
2620
+ row: run.path[depth - 2],
2621
+ column: run.path[depth - 1]
2622
+ };
2623
+ }
2624
+ };
2625
+ /** An empty cell, under placeholder identities a caller freshens. */
2626
+ const emptyCell = () => ({
2627
+ type: "Node",
2628
+ kind: "TableCell",
2629
+ id: NodeId.make("cell"),
2630
+ props: {},
2631
+ children: [],
2632
+ blocks: [{
2633
+ type: "Paragraph",
2634
+ id: NodeId.make("paragraph"),
2635
+ children: [{
2636
+ type: "Text",
2637
+ id: NodeId.make("text"),
2638
+ text: "",
2639
+ marks: []
2640
+ }]
2641
+ }]
2642
+ });
2643
+ const fresh = (block, mint) => withFreshIds({
2644
+ version: 1,
2645
+ blocks: [block]
2646
+ }, mint).blocks[0];
2647
+ const firstRun = (block) => {
2648
+ if (block === void 0) return void 0;
2649
+ let found;
2650
+ eachBlock([block], (inner) => {
2651
+ found ??= inner.children[0];
2652
+ });
2653
+ return found;
2654
+ };
2655
+ /** The selection at the start of a cell's first text, or the selection as it was. */
2656
+ const caretIn = (cell, otherwise) => {
2657
+ const run = firstRun(cell);
2658
+ if (run === void 0) return otherwise;
2659
+ const at = {
2660
+ node: run.id,
2661
+ offset: 0,
2662
+ affinity: "after"
2663
+ };
2664
+ return {
2665
+ type: "Range",
2666
+ anchor: at,
2667
+ focus: at
2668
+ };
2669
+ };
2670
+ /** The widest row's cell count: what a new row is given so the grid stays as wide. */
2671
+ const widthOf = (rows) => Math.max(1, ...rows.map((row) => cellsOf(row).length));
2672
+ /** A row as wide as the table, under fresh identities, and the operation that puts it there. */
2673
+ const newRow = (at, index, mint) => {
2674
+ const row = fresh({
2675
+ type: "Node",
2676
+ kind: "TableRow",
2677
+ id: NodeId.make("row"),
2678
+ props: {},
2679
+ children: [],
2680
+ blocks: Array.from({ length: widthOf(at.rows) }, emptyCell)
2681
+ }, mint);
2682
+ return {
2683
+ row,
2684
+ operation: Edit.insertBlock(row, index, at.table.id)
2685
+ };
2686
+ };
2687
+ /** A row above or below the caret's, as wide as the table; the caret goes to it, same column. */
2688
+ const insertRow = (state, at, where, mint) => {
2689
+ const { row, operation } = newRow(at, at.row + (where === "after" ? 1 : 0), mint);
2690
+ const cells = row.type === "Node" ? row.blocks ?? [] : [];
2691
+ return apply(state, [operation, Edit.setSelection(caretIn(cells[Math.min(at.column, cells.length - 1)], state.selection))]);
2692
+ };
2693
+ /**
2694
+ * A cell beside the caret's in every row, before or after it; a row too short to have that
2695
+ * column gets its cell at its end. The caret goes to the new cell in its own row.
2696
+ */
2697
+ const insertColumn = (state, at, where, mint) => {
2698
+ const index = at.column + (where === "after" ? 1 : 0);
2699
+ let caretCell;
2700
+ const operations = at.rows.map((row, rowIndex) => {
2701
+ const cell = fresh(emptyCell(), mint);
2702
+ if (rowIndex === at.row) caretCell = cell;
2703
+ return Edit.insertBlock(cell, Math.min(index, cellsOf(row).length), row.id);
2704
+ });
2705
+ return apply(state, [...operations, Edit.setSelection(caretIn(caretCell, state.selection))]);
2706
+ };
2707
+ /** The caret's row, gone; the caret goes to the same column of the row after it, or before. */
2708
+ const deleteRow = (state, at) => {
2709
+ if (at.rows.length === 1) return { deleteTable: at.table.id };
2710
+ const next = at.rows[at.row + 1] ?? at.rows[at.row - 1];
2711
+ const cells = cellsOf(next);
2712
+ return apply(state, [Edit.deleteBlock(at.rows[at.row].id), Edit.setSelection(caretIn(cells[Math.min(at.column, cells.length - 1)], state.selection))]);
2713
+ };
2714
+ /**
2715
+ * The caret's column, gone from every row that has it; a row it leaves empty goes too. The
2716
+ * caret goes to the cell that takes the column's place in its row, or the one before it.
2717
+ */
2718
+ const deleteColumn = (state, at) => {
2719
+ if (at.rows.every((row) => cellsOf(row).length <= 1)) return { deleteTable: at.table.id };
2720
+ const operations = [];
2721
+ for (const row of at.rows) {
2722
+ const cells = cellsOf(row);
2723
+ const cell = cells[at.column];
2724
+ if (cell === void 0) continue;
2725
+ operations.push(Edit.deleteBlock(cells.length === 1 ? row.id : cell.id));
2726
+ }
2727
+ const own = cellsOf(at.rows[at.row]);
2728
+ const landing = own.length === 1 ? void 0 : own[at.column + 1] ?? own[at.column - 1];
2729
+ return apply(state, [...operations, ...landing === void 0 ? [] : [Edit.setSelection(caretIn(landing, state.selection))]]);
2730
+ };
2731
+ /**
2732
+ * The caret to the start of the next cell, across rows, or the previous one: Tab and Shift+Tab.
2733
+ * Tab in the last cell adds a row and goes to it; Shift+Tab in the first stays where it is.
2734
+ */
2735
+ const moveToCell = (state, at, direction, mint) => {
2736
+ const order = at.rows.flatMap((row, rowIndex) => cellsOf(row).map((cell, column) => ({
2737
+ cell,
2738
+ rowIndex,
2739
+ column
2740
+ })));
2741
+ const target = order[order.findIndex((entry) => entry.rowIndex === at.row && entry.column === at.column) + (direction === "next" ? 1 : -1)];
2742
+ if (target !== void 0) return apply(state, [Edit.setSelection(caretIn(target.cell, state.selection))]);
2743
+ if (direction === "previous") return apply(state, []);
2744
+ const { row, operation } = newRow(at, at.rows.length, mint);
2745
+ return apply(state, [operation, Edit.setSelection(caretIn(row, state.selection))]);
2746
+ };
2747
+ //#endregion
2278
2748
  //#region src/command.ts
2279
2749
  /** Where `MoveBlock` puts a block: before or after a sibling, named by identity. */
2280
2750
  const Beside = Schema.Union([Schema.Struct({
@@ -2332,6 +2802,15 @@ const declaresText = (nodes, kind) => {
2332
2802
  const declared = nodes?.definitionFor(kind);
2333
2803
  return declared?.kind === "node" && declared.children === "text";
2334
2804
  };
2805
+ /**
2806
+ * Whether a block is an atom, holding neither text nor blocks, as an image is. Without a
2807
+ * vocabulary, a node with nothing in it is one.
2808
+ */
2809
+ const isAtom = (nodes, block) => {
2810
+ if (block.type !== "Node") return false;
2811
+ const declared = nodes?.definitionFor(block.kind);
2812
+ return declared === void 0 ? block.blocks === void 0 && block.children.length === 0 : declared.kind === "atom";
2813
+ };
2335
2814
  /** Whether the vocabulary names `itemKind` among the kinds `listKind` holds, as `List` names `ListItem`. */
2336
2815
  const holdsItem = (nodes, listKind, itemKind) => {
2337
2816
  const declared = nodes.definitionFor(listKind);
@@ -2586,6 +3065,117 @@ const blocksAt = (document, selection) => {
2586
3065
  const path = startPath(document, selection) ?? [];
2587
3066
  return path.map((_, depth) => blockAtPath(document, path.slice(0, depth + 1)));
2588
3067
  };
3068
+ /** Whether `prefix` is a path to one of the blocks `path` lies inside, or `path` itself. */
3069
+ const startsWith = (path, prefix) => prefix.length <= path.length && prefix.every((index, at) => path[at] === index);
3070
+ /** Document order of two block paths: a container comes before what it holds. */
3071
+ const pathOrder = (left, right) => {
3072
+ for (let at = 0; at < Math.min(left.length, right.length); at++) if (left[at] !== right[at]) return left[at] - right[at];
3073
+ return left.length - right.length;
3074
+ };
3075
+ /** Whether two blocks can be joined into one: what `JoinNode` accepts. */
3076
+ const joinable = (survivor, removed) => {
3077
+ if (survivor.type === "Unknown" || removed.type === "Unknown") return false;
3078
+ if (nestedBlocks(survivor) !== void 0 || nestedBlocks(removed) !== void 0) return false;
3079
+ if (survivor.type !== "Node" && removed.type !== "Node") return true;
3080
+ return survivor.type === "Node" && removed.type === "Node" && survivor.kind === removed.kind && Equal.equals(survivor.props, removed.props);
3081
+ };
3082
+ const nestedBlocks = (block) => block.type === "Node" && block.blocks !== void 0 ? block.blocks : void 0;
3083
+ /** Whether going from one block to another leaves an isolating container, as a table cell is. */
3084
+ const crossesIsolating = (document, from, to, nodes) => [from, to].some((path, side) => {
3085
+ const other = side === 0 ? to : from;
3086
+ for (let depth = 1; depth < path.length; depth++) {
3087
+ const container = path.slice(0, depth);
3088
+ if (startsWith(other, container)) continue;
3089
+ const block = blockAtPath(document, container);
3090
+ const declared = block?.type === "Node" ? nodes?.definitionFor(block.kind) : void 0;
3091
+ if (declared?.kind === "node" && declared.isolating === true) return true;
3092
+ }
3093
+ return false;
3094
+ });
3095
+ /** The innermost first or last block inside the block at `path`: itself when it holds none. */
3096
+ const edgeLeaf = (document, path, last) => {
3097
+ let at = path;
3098
+ for (;;) {
3099
+ const held = nestedBlocks(blockAtPath(document, at));
3100
+ if (held === void 0 || held.length === 0) return at;
3101
+ at = [...at, last ? held.length - 1 : 0];
3102
+ }
3103
+ };
3104
+ /** The first block after the one at `path` that holds no blocks, in document order. */
3105
+ const nextLeaf = (document, path) => {
3106
+ let found;
3107
+ eachBlock(document.children, (block, at) => {
3108
+ if (found !== void 0 || pathOrder(at, path) <= 0 || startsWith(path, at)) return;
3109
+ if ((nestedBlocks(block) ?? []).length === 0) found = at;
3110
+ });
3111
+ return found;
3112
+ };
3113
+ /** One result followed by another, as one: what `runAction` does for two commands. */
3114
+ const followedBy = (first, second) => !first.ok || !second.ok ? second.ok ? first : second : {
3115
+ ok: true,
3116
+ state: second.state,
3117
+ changeSet: unionChangeSet(first.changeSet, second.changeSet),
3118
+ positionMap: [...first.positionMap, ...second.positionMap],
3119
+ transactions: [...first.transactions, ...second.transactions]
3120
+ };
3121
+ /**
3122
+ * Deletes a range that leaves its container, as selecting from one kind of block into another
3123
+ * (or everything) and pressing Delete does: the text after `start` in its block and before
3124
+ * `end` in its block goes, every block wholly between them goes, and the block `end` is in
3125
+ * comes up beside the one `start` is in, joining it when the two can be one. A container it
3126
+ * leaves empty goes too. A range that leaves a table cell (an isolating container) only loses
3127
+ * its text: the cells stay, as a table's structure is not a selection's to remove. The caret
3128
+ * ends at `start`.
3129
+ */
3130
+ const clearRange = (state, start, end, options) => {
3131
+ const document = state.document;
3132
+ const startAt = locate(document, start.node);
3133
+ const endAt = locate(document, end.node);
3134
+ if (startAt === void 0 || endAt === void 0) return failure("MissingText");
3135
+ const startPath = startAt.path;
3136
+ const endPath = endAt.path;
3137
+ const spans = covered(document, start, end);
3138
+ 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))]);
3139
+ const ends = spans.filter((span) => pathKey$1(span.run.path) === pathKey$1(startPath) || pathKey$1(span.run.path) === pathKey$1(endPath));
3140
+ const between = [];
3141
+ eachBlock(document.children, (block, path) => {
3142
+ if (pathOrder(path, startPath) <= 0 || pathOrder(path, endPath) >= 0) return;
3143
+ if (startsWith(endPath, path) || startsWith(startPath, path)) return;
3144
+ if (between.some((outer) => startsWith(path, outer.path))) return;
3145
+ between.push({
3146
+ id: block.id,
3147
+ path
3148
+ });
3149
+ });
3150
+ const first = apply(state, [
3151
+ ...ends.map((span) => Edit.deleteText(span.run.id, span.from, span.to)),
3152
+ ...between.map((block) => Edit.deleteBlock(block.id)),
3153
+ Edit.setSelection(caretAt(start))
3154
+ ]);
3155
+ if (!first.ok) return first;
3156
+ const startBlock = blockAtPath(document, startPath);
3157
+ const endBlock = blockAtPath(document, endPath);
3158
+ const now = first.state.document;
3159
+ const survivorAt = locateBlock(now, startBlock.id);
3160
+ const removedAt = locateBlock(now, endBlock.id);
3161
+ if (survivorAt === void 0 || removedAt === void 0) return first;
3162
+ const operations = [];
3163
+ const parentPath = survivorAt.path.slice(0, -1);
3164
+ const parent = parentPath.length === 0 ? void 0 : blockAtPath(now, parentPath);
3165
+ const index = survivorAt.path[survivorAt.path.length - 1];
3166
+ const siblings = pathKey$1(removedAt.path.slice(0, -1)) === pathKey$1(parentPath);
3167
+ if (!siblings && parentPath.length > 0 && !acceptsChild(now, parentPath, blockKind(removedAt.block), options.nodes)) return first;
3168
+ if (!siblings) operations.push(Edit.moveBlock(endBlock.id, index + 1, parent?.id));
3169
+ if ((siblings ? removedAt.path[removedAt.path.length - 1] === index + 1 : true) && joinable(survivorAt.block, removedAt.block)) operations.push(Edit.joinBlocks(startBlock.id, endBlock.id));
3170
+ if (!siblings) for (let depth = removedAt.path.length - 1; depth > 0; depth--) {
3171
+ const container = blockAtPath(now, removedAt.path.slice(0, depth));
3172
+ if (container === void 0 || startsWith(survivorAt.path, removedAt.path.slice(0, depth))) break;
3173
+ if ((nestedBlocks(container) ?? []).length > 1) break;
3174
+ operations.push(Edit.deleteBlock(container.id));
3175
+ }
3176
+ if (operations.length === 0) return first;
3177
+ return followedBy(first, apply(first.state, [...operations, Edit.setSelection(caretAt(start))]));
3178
+ };
2589
3179
  /** The last run in a block's subtree, or undefined when it holds none. */
2590
3180
  const lastRunOf = (block) => {
2591
3181
  if (block.type === "Node" && block.blocks !== void 0) for (let index = block.blocks.length - 1; index >= 0; index--) {
@@ -2619,10 +3209,12 @@ const deleteRange = (document, start, end) => {
2619
3209
  const blocks = containerBlocks(document, containerPath);
2620
3210
  const from = startAt.path[startAt.path.length - 1];
2621
3211
  const to = endAt.path[endAt.path.length - 1];
2622
- const survivor = blocks[from].id;
3212
+ const survivor = blocks[from];
2623
3213
  for (let index = from + 1; index <= to; index++) {
2624
3214
  const block = blocks[index];
2625
- if (block !== void 0) deletions.push(Edit.joinBlocks(survivor, block.id));
3215
+ if (block === void 0) continue;
3216
+ if (!joinable(survivor, block)) return void 0;
3217
+ deletions.push(Edit.joinBlocks(survivor.id, block.id));
2626
3218
  }
2627
3219
  return deletions;
2628
3220
  };
@@ -2883,6 +3475,15 @@ const runBlockCommand = (state, command, starting, ids, options) => {
2883
3475
  */
2884
3476
  const run = (state, command, ids, options = {}) => {
2885
3477
  const declared = options.marks ?? shippedRegistry;
3478
+ const range = state.selection;
3479
+ if ((command.type === "InsertText" || command.type === "DeleteBackward" || command.type === "DeleteForward" || command.type === "SplitBlock" || command.type === "Paste") && range?.type === "Range" && !isCollapsed(range)) {
3480
+ const span = ordered(state.document, range);
3481
+ if (span !== void 0 && deleteRange(state.document, span.start, span.end) === void 0) {
3482
+ const cleared = clearRange(state, span.start, span.end, options);
3483
+ if (!cleared.ok || command.type === "DeleteBackward" || command.type === "DeleteForward") return cleared;
3484
+ return followedBy(cleared, run(cleared.state, command, ids, options));
3485
+ }
3486
+ }
2886
3487
  if (command.type === "SetSelection") return apply(state, [Edit.setSelection(command.selection)]);
2887
3488
  if (command.type === "SetProps") {
2888
3489
  const target = locateBlock(state.document, command.node)?.block;
@@ -2897,6 +3498,109 @@ const run = (state, command, ids, options = {}) => {
2897
3498
  }) && !refuses(target.props)) return failure("InvalidInput");
2898
3499
  return apply(state, [Edit.setProps(command.node, command.props)]);
2899
3500
  }
3501
+ if (command.type === "InsertRow" || command.type === "InsertColumn" || command.type === "DeleteRow" || command.type === "DeleteColumn") {
3502
+ const at = tableAt(state.document, state.selection);
3503
+ if (at === void 0) return failure("InvalidSelection");
3504
+ const edited = Match.value(command).pipe(Match.discriminatorsExhaustive("type")({
3505
+ InsertRow: ({ where }) => insertRow(state, at, where, ids.mint),
3506
+ InsertColumn: ({ where }) => insertColumn(state, at, where, ids.mint),
3507
+ DeleteRow: () => deleteRow(state, at),
3508
+ DeleteColumn: () => deleteColumn(state, at)
3509
+ }));
3510
+ return "deleteTable" in edited ? run(state, {
3511
+ type: "DeleteBlock",
3512
+ node: edited.deleteTable
3513
+ }, ids, options) : edited;
3514
+ }
3515
+ if (command.type === "Indent" || command.type === "Outdent") {
3516
+ const code = linesHolder(state, options.nodes);
3517
+ if (code !== void 0) return command.type === "Indent" ? indent(state, code) : outdent(state, code);
3518
+ const item = itemAtCaret(state, options.nodes);
3519
+ const at = tableAt(state.document, state.selection);
3520
+ const tableDepth = at === void 0 ? -1 : locateBlock(state.document, at.table.id)?.path.length ?? -1;
3521
+ if (item !== void 0 && item.containerPath.length > tableDepth) return command.type === "Indent" ? sinkItem(state, item, ids, options) : liftItem(state, item, ids, options);
3522
+ if (at === void 0) return failure("InvalidSelection");
3523
+ return moveToCell(state, at, command.type === "Indent" ? "next" : "previous", ids.mint);
3524
+ }
3525
+ if (command.type === "Replace") {
3526
+ const matches = findMatches(state.document, command.query, command);
3527
+ const chosen = command.at === void 0 ? matches : matches.slice(command.at, command.at + 1);
3528
+ return replaceMatches(state, chosen, command.replacement, ids, options);
3529
+ }
3530
+ if (command.type === "InsertFootnote") return insertFootnote(state, command.text ?? "", ids, options);
3531
+ if (command.type === "RenameFootnote") return renameFootnote(state, command.from, command.to.trim(), ids, options);
3532
+ if (command.type === "InsertBlock") {
3533
+ const to = command.to ?? besideCaret(state);
3534
+ if (to === void 0) return failure("InvalidSelection");
3535
+ const beside = locateBlock(state.document, "before" in to ? to.before : to.after);
3536
+ if (beside === void 0) return failure("InvalidInput");
3537
+ const containerPath = beside.path.slice(0, -1);
3538
+ const holder = containerPath.length === 0 ? void 0 : blockAtPath(state.document, containerPath);
3539
+ const kind = blockKind(command.block);
3540
+ 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");
3541
+ const [inserted] = withFreshIds({
3542
+ version: 1,
3543
+ blocks: [command.block]
3544
+ }, ids.mint).blocks;
3545
+ const at = beside.path[beside.path.length - 1] + ("after" in to ? 1 : 0);
3546
+ const first = firstRunIn([inserted]);
3547
+ return apply(state, [Edit.insertBlock(inserted, at, holder?.id), ...first === void 0 ? [] : [Edit.setSelection(caretAt({
3548
+ node: first.id,
3549
+ offset: 0,
3550
+ affinity: "after"
3551
+ }))]]);
3552
+ }
3553
+ if (command.type === "DeleteBlock") {
3554
+ const deleting = locateBlock(state.document, command.node);
3555
+ if (deleting === void 0) return failure("InvalidInput");
3556
+ const target = emptiedBy(state.document, deleting.path.slice(0, -1), [-1]) ?? command.node;
3557
+ const gone = locateBlock(state.document, target);
3558
+ const inside = (path) => gone.path.every((index, depth) => path[depth] === index);
3559
+ const runs = [];
3560
+ eachBlock(state.document.children, (block, path) => {
3561
+ for (const run of block.children) runs.push({
3562
+ run,
3563
+ inside: inside(path),
3564
+ after: pathOrder(path, gone.path) > 0
3565
+ });
3566
+ });
3567
+ const selection = state.selection;
3568
+ 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)));
3569
+ const following = runs.find((entry) => entry.after && !entry.inside);
3570
+ const preceding = [...runs].reverse().find((entry) => !entry.after && !entry.inside);
3571
+ const landing = following !== void 0 ? {
3572
+ node: following.run.id,
3573
+ offset: 0,
3574
+ affinity: "after"
3575
+ } : preceding !== void 0 ? {
3576
+ node: preceding.run.id,
3577
+ offset: preceding.run.text.length,
3578
+ affinity: "after"
3579
+ } : void 0;
3580
+ if (gone.path.length === 1 && state.document.children.length === 1) {
3581
+ const textId = NodeId.make(ids.mint());
3582
+ const paragraph = {
3583
+ type: "Paragraph",
3584
+ id: NodeId.make(ids.mint()),
3585
+ children: [{
3586
+ type: "Text",
3587
+ id: textId,
3588
+ text: "",
3589
+ marks: []
3590
+ }]
3591
+ };
3592
+ return apply(state, [
3593
+ Edit.insertBlock(paragraph, 1),
3594
+ Edit.deleteBlock(target),
3595
+ Edit.setSelection(caretAt({
3596
+ node: textId,
3597
+ offset: 0,
3598
+ affinity: "after"
3599
+ }))
3600
+ ]);
3601
+ }
3602
+ return apply(state, [Edit.deleteBlock(target), ...holds ? [Edit.setSelection(landing === void 0 ? null : caretAt(landing))] : []]);
3603
+ }
2900
3604
  if (command.type === "MoveBlock") {
2901
3605
  const moving = locateBlock(state.document, command.node);
2902
3606
  const beside = locateBlock(state.document, "before" in command.to ? command.to.before : command.to.after);
@@ -2925,9 +3629,39 @@ const run = (state, command, ids, options = {}) => {
2925
3629
  ]);
2926
3630
  }
2927
3631
  const selection = state.selection;
3632
+ if (selection?.type === "Node") {
3633
+ const after = {
3634
+ type: "InsertBlock",
3635
+ block: {
3636
+ type: "Paragraph",
3637
+ id: NodeId.make("paragraph"),
3638
+ children: [{
3639
+ type: "Text",
3640
+ id: NodeId.make("text"),
3641
+ text: "",
3642
+ marks: []
3643
+ }]
3644
+ },
3645
+ to: { after: selection.node }
3646
+ };
3647
+ if (command.type === "DeleteBackward" || command.type === "DeleteForward") return run(state, {
3648
+ type: "DeleteBlock",
3649
+ node: selection.node
3650
+ }, ids, options);
3651
+ if (command.type === "SplitBlock") return run(state, after, ids, options);
3652
+ if (command.type === "InsertText") return runAction(state, [
3653
+ after,
3654
+ {
3655
+ type: "DeleteBlock",
3656
+ node: selection.node
3657
+ },
3658
+ command
3659
+ ], ids, options);
3660
+ }
2928
3661
  if (selection === null || selection.type === "Node") return failure("InvalidSelection");
2929
3662
  if (command.type === "InsertText") {
2930
- const stored = command.marks;
3663
+ const edge = command.marks === void 0 && isCollapsed(selection) ? edgeMarks(state.document, selection.anchor, options.marks) : void 0;
3664
+ const stored = command.marks ?? edge;
2931
3665
  const target = isCollapsed(selection) ? stored === void 0 ? resolveInsertion(state.document, selection.anchor, options.marks) : selection.anchor : ordered(state.document, selection)?.start;
2932
3666
  if (target === void 0) return failure("InvalidSelection");
2933
3667
  const at = locate(state.document, target.node);
@@ -2935,7 +3669,7 @@ const run = (state, command, ids, options = {}) => {
2935
3669
  const marks = [];
2936
3670
  if (stored !== void 0) {
2937
3671
  for (const mark of stored) {
2938
- if (!declared.accepts(mark)) return failure("InvalidInput");
3672
+ if (edge === void 0 && !declared.accepts(mark)) return failure("InvalidInput");
2939
3673
  marks.push(mark);
2940
3674
  }
2941
3675
  if (marks.length > 0 && forbidsMarks(state.document, at.path, options.nodes)) return failure("ForbiddenMark");
@@ -2987,14 +3721,44 @@ const run = (state, command, ids, options = {}) => {
2987
3721
  type: "RetypeBlock",
2988
3722
  to: { type: "Paragraph" }
2989
3723
  }, ids, options);
3724
+ if (backward && block.type === "Heading") return run(state, {
3725
+ type: "RetypeBlock",
3726
+ to: { type: "Paragraph" }
3727
+ }, ids, options);
2990
3728
  const containerPath = at.path.slice(0, -1);
2991
3729
  const siblings = containerBlocks(state.document, containerPath);
2992
3730
  const index = at.path[at.path.length - 1];
2993
3731
  const neighborBlock = siblings[backward ? index - 1 : index + 1];
2994
- if (neighborBlock === void 0) {
2995
- const lifted = backward && containerPath.length > 0 && options.nodes !== void 0 ? liftOperations(state.document, siblings[index].id, ids, options.nodes) : void 0;
3732
+ if (neighborBlock !== void 0 && isAtom(options.nodes, neighborBlock)) return apply(state, [...textOfBlock(block) === "" ? [Edit.deleteBlock(block.id)] : [], Edit.setSelection({
3733
+ type: "Node",
3734
+ node: neighborBlock.id
3735
+ })]);
3736
+ if (neighborBlock === void 0 && backward) {
3737
+ const lifted = containerPath.length > 0 && options.nodes !== void 0 ? liftOperations(state.document, siblings[index].id, ids, options.nodes) : void 0;
2996
3738
  return apply(state, lifted ?? []);
2997
3739
  }
3740
+ if (neighborBlock === void 0 || !joinable(backward ? neighborBlock : block, backward ? block : neighborBlock)) {
3741
+ const leafPath = neighborBlock === void 0 ? nextLeaf(state.document, at.path) : edgeLeaf(state.document, [...containerPath, index + (backward ? -1 : 1)], backward);
3742
+ const leaf = leafPath === void 0 ? void 0 : blockAtPath(state.document, leafPath);
3743
+ if (leafPath === void 0 || leaf === void 0) return apply(state, []);
3744
+ const empty = textOfBlock(block) === "";
3745
+ if (isAtom(options.nodes, leaf)) return apply(state, [Edit.setSelection({
3746
+ type: "Node",
3747
+ node: leaf.id
3748
+ })]);
3749
+ const first = leaf.children[0];
3750
+ const last = leaf.children[leaf.children.length - 1];
3751
+ const target = backward ? last : first;
3752
+ if (target === void 0) return apply(state, []);
3753
+ const edge = {
3754
+ node: target.id,
3755
+ offset: backward ? target.text.length : 0,
3756
+ affinity: "after"
3757
+ };
3758
+ if (!(empty && neighborBlock !== void 0) && (backward ? joinable(leaf, block) : joinable(block, leaf))) return backward ? clearRange(state, edge, caret, options) : clearRange(state, caret, edge, options);
3759
+ if (neighborBlock === void 0 || !backward && !empty) return apply(state, []);
3760
+ return apply(state, [...empty ? [Edit.deleteBlock(block.id)] : [], Edit.setSelection(caretAt(edge))]);
3761
+ }
2998
3762
  const survivor = backward ? neighborBlock : siblings[index];
2999
3763
  const removed = backward ? siblings[index] : neighborBlock;
3000
3764
  const lastRun = lastRunOf(survivor) ?? lastRunOf(removed);
@@ -3016,6 +3780,28 @@ const run = (state, command, ids, options = {}) => {
3016
3780
  if (at === void 0) return failure("MissingText");
3017
3781
  const deletions = span === void 0 ? [] : deleteRange(state.document, span.start, span.end);
3018
3782
  if (deletions === void 0) return failure("InvalidParent");
3783
+ const holder = blockAtPath(state.document, at.path);
3784
+ const definition = holder?.type === "Node" ? options.nodes?.definitionFor(holder.kind) : void 0;
3785
+ if (holder !== void 0 && definition?.kind === "node" && definition.lineBreaks === true) {
3786
+ const last = holder.children[holder.children.length - 1];
3787
+ 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" }, {
3788
+ type: "InsertBlock",
3789
+ block: {
3790
+ type: "Paragraph",
3791
+ id: NodeId.make("paragraph"),
3792
+ children: [{
3793
+ type: "Text",
3794
+ id: NodeId.make("text"),
3795
+ text: "",
3796
+ marks: []
3797
+ }]
3798
+ },
3799
+ to: { after: holder.id }
3800
+ }], ids, options) : run(state, {
3801
+ type: "InsertText",
3802
+ text: definition.indents === true ? `\n${indentationAt(textOfBlock(holder), offsetIn(holder, caret) ?? 0)}` : "\n"
3803
+ }, ids, options);
3804
+ }
3019
3805
  const item = itemAround(state.document, at.path, options.nodes);
3020
3806
  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);
3021
3807
  const textId = ids.mint();
@@ -3041,7 +3827,7 @@ const run = (state, command, ids, options = {}) => {
3041
3827
  span = ordered(state.document, extent.selection);
3042
3828
  }
3043
3829
  if (span === void 0) return failure("InvalidSelection");
3044
- const spans = covered(state.document, span.start, span.end);
3830
+ 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)));
3045
3831
  if (spans.length === 0) return apply(state, []);
3046
3832
  const adding = command.type === "SetMark" || command.type === "ToggleMark" && !spans.every((entry) => entry.run.marks.some((held) => markName(held) === name));
3047
3833
  const operations = [];
@@ -3066,12 +3852,19 @@ const run = (state, command, ids, options = {}) => {
3066
3852
  return apply(state, operations);
3067
3853
  }
3068
3854
  if (command.type === "Paste") {
3069
- if (command.slice.blocks.length === 0) return apply(state, []);
3855
+ const content = command.slice.blocks;
3856
+ if (content.length === 0) return apply(state, []);
3070
3857
  const span = isCollapsed(selection) ? void 0 : ordered(state.document, selection);
3071
3858
  if (!isCollapsed(selection) && span === void 0) return failure("InvalidSelection");
3072
3859
  const caret = span?.start ?? selection.anchor;
3073
3860
  const at = locate(state.document, caret.node);
3074
3861
  if (at === void 0) return failure("MissingText");
3862
+ const into = blockAtPath(state.document, at.path);
3863
+ const holds = into?.type === "Node" ? options.nodes?.definitionFor(into.kind) : void 0;
3864
+ if (holds?.kind === "node" && holds.lineBreaks === true) return run(state, {
3865
+ type: "InsertText",
3866
+ text: toText(content)
3867
+ }, ids, options);
3075
3868
  const index = at.path[at.path.length - 1];
3076
3869
  const containerPath = at.path.slice(0, -1);
3077
3870
  const parent = containerPath.length === 0 ? void 0 : blockAtPath(state.document, containerPath)?.id;
@@ -3083,47 +3876,254 @@ const run = (state, command, ids, options = {}) => {
3083
3876
  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");
3084
3877
  const block = blockAtPath(state.document, at.path);
3085
3878
  if (block === void 0) return failure("MissingText");
3086
- const atBlockStart = at.runIndex === 0 && caret.offset === 0;
3087
- const atBlockEnd = at.runIndex === block.children.length - 1 && caret.offset === at.text.length;
3088
- let trailingRun;
3089
- if (atBlockStart) for (const [offset, piece] of inserted.entries()) operations.push(Edit.insertBlock(piece, index + offset, parent));
3090
- else if (atBlockEnd) for (const [offset, piece] of inserted.entries()) operations.push(Edit.insertBlock(piece, index + 1 + offset, parent));
3091
- else {
3092
- const textId = ids.mint();
3093
- operations.push(Edit.splitBlock(at.blockId, at.id, caret.offset, ids.mint(), textId));
3094
- trailingRun = NodeId.make(textId);
3095
- for (const [offset, piece] of inserted.entries()) operations.push(Edit.insertBlock(piece, index + 1 + offset, parent));
3096
- }
3097
- const landing = landingAfter(inserted, trailingRun, containerBlocks(state.document, containerPath), index, atBlockEnd);
3098
- if (landing !== void 0) operations.push(Edit.setSelection(caretAt(landing)));
3879
+ const end = span?.end ?? caret;
3880
+ const endBlock = blockAtPath(state.document, locate(state.document, end.node)?.path ?? at.path);
3881
+ const beforeEmpty = offsetIn(block, caret) === 0;
3882
+ const afterEmpty = endBlock === void 0 || offsetIn(endBlock, end) === textOfBlock(endBlock).length;
3883
+ const tailText = NodeId.make(ids.mint());
3884
+ const tail = NodeId.make(ids.mint());
3885
+ operations.push(Edit.splitBlock(at.blockId, at.id, caret.offset, tail, tailText));
3886
+ for (const [offset, piece] of inserted.entries()) operations.push(Edit.insertBlock(piece, index + 1 + offset, parent));
3887
+ const first = inserted[0];
3888
+ const last = inserted[inserted.length - 1];
3889
+ const lastRun = last.children[last.children.length - 1];
3890
+ operations.push(Edit.setSelection(caretAt(lastRun === void 0 ? {
3891
+ node: tailText,
3892
+ offset: 0,
3893
+ affinity: "after"
3894
+ } : {
3895
+ node: lastRun.id,
3896
+ offset: lastRun.text.length,
3897
+ affinity: "after"
3898
+ })));
3899
+ const joinsHead = joinable(block, first);
3900
+ const joinsTail = joinable(last, block);
3901
+ if (joinsHead) operations.push(Edit.joinBlocks(at.blockId, first.id));
3902
+ if (joinsTail) operations.push(Edit.joinBlocks(joinsHead && last === first ? at.blockId : last.id, tail));
3903
+ if (!joinsHead && beforeEmpty) operations.push(Edit.deleteBlock(at.blockId));
3904
+ if (!joinsTail && afterEmpty && lastRun !== void 0) operations.push(Edit.deleteBlock(tail));
3099
3905
  return apply(state, operations);
3100
3906
  }
3101
3907
  return apply(state, []);
3102
3908
  };
3909
+ /** Where an `InsertBlock` without a place goes: beside the caret's block, before it when empty. */
3910
+ const besideCaret = (state) => {
3911
+ if (state.selection?.type !== "Range") return void 0;
3912
+ const run = locateRun(state.document, ordered(state.document, state.selection)?.start.node ?? state.selection.anchor.node);
3913
+ const block = run === void 0 ? void 0 : blockAtPath(state.document, run.path);
3914
+ if (block === void 0) return void 0;
3915
+ return block.children.every((child) => child.text === "") ? { before: block.id } : { after: block.id };
3916
+ };
3917
+ const textOfBlock = (block) => block.children.map((run) => run.text).join("");
3918
+ /** The block the selection starts in when its kind indents its lines, as code does. */
3919
+ const linesHolder = (state, nodes) => {
3920
+ if (state.selection?.type !== "Range") return void 0;
3921
+ const start = ordered(state.document, state.selection)?.start;
3922
+ const run = start === void 0 ? void 0 : locateRun(state.document, start.node);
3923
+ const block = run === void 0 ? void 0 : blockAtPath(state.document, run.path);
3924
+ if (block?.type !== "Node") return void 0;
3925
+ const definition = nodes?.definitionFor(block.kind);
3926
+ return definition?.kind === "node" && definition.indents === true ? block : void 0;
3927
+ };
3103
3928
  /**
3104
- * Where the caret goes after a paste: the end of the last inserted run, or the
3105
- * start of what follows when the inserted content ends without text — the
3106
- * trailing half a split created, then the next sibling.
3929
+ * Whether Tab means something where the selection is: in code, or in a table cell. An editor
3930
+ * takes Tab only there, so anywhere else it still moves focus out of the editor.
3107
3931
  */
3108
- const landingAfter = (inserted, trailingRun, siblings, index, atBlockEnd) => {
3109
- const last = inserted[inserted.length - 1];
3110
- const lastRun = last.children[last.children.length - 1];
3111
- if (lastRun !== void 0) return {
3112
- node: lastRun.id,
3113
- offset: lastRun.text.length,
3114
- affinity: "after"
3115
- };
3116
- if (trailingRun !== void 0) return {
3117
- node: trailingRun,
3118
- offset: 0,
3119
- affinity: "after"
3120
- };
3121
- const followingRun = siblings[index + (atBlockEnd ? 1 : 0)]?.children[0];
3122
- return followingRun === void 0 ? void 0 : {
3123
- node: followingRun.id,
3124
- offset: 0,
3125
- affinity: "after"
3932
+ const takesTab = (document, selection, nodes) => linesHolder({
3933
+ document,
3934
+ selection
3935
+ }, nodes) !== void 0 || itemAtCaret({
3936
+ document,
3937
+ selection
3938
+ }, nodes) !== void 0 || tableAt(document, selection) !== void 0;
3939
+ /** The list item the selection starts in, when the vocabulary says its list holds it. */
3940
+ const itemAtCaret = (state, nodes) => {
3941
+ if (state.selection?.type !== "Range") return void 0;
3942
+ const start = ordered(state.document, state.selection)?.start;
3943
+ const run = start === void 0 ? void 0 : locateRun(state.document, start.node);
3944
+ return run === void 0 ? void 0 : itemAround(state.document, run.path, nodes);
3945
+ };
3946
+ /** Whether two props hold the same values, for a list that two items may share. */
3947
+ const sameProps = (left, right) => {
3948
+ const keys = Object.keys(left);
3949
+ return keys.length === Object.keys(right).length && keys.every((key) => Object.hasOwn(right, key) && Equal.equals(left[key], right[key]));
3950
+ };
3951
+ /**
3952
+ * Tab in a list item: the item moves under the item before it, as the last item of the list
3953
+ * that item ends with, or of a new one like its own when it ends with none. It keeps its
3954
+ * identity, and the caret with it. The first item has nothing to go under, and stays.
3955
+ */
3956
+ const sinkItem = (state, item, ids, options) => {
3957
+ if (item.list.type !== "Node") return apply(state, []);
3958
+ const list = item.list;
3959
+ const index = item.containerPath[item.containerPath.length - 1];
3960
+ const previous = (list.blocks ?? [])[index - 1];
3961
+ if (previous?.type !== "Node") return apply(state, []);
3962
+ const nested = previous.blocks?.at(-1);
3963
+ const last = nested?.type === "Node" ? nested.blocks?.at(-1) : void 0;
3964
+ if (nested?.type === "Node" && nested.kind === list.kind && sameProps(nested.props, list.props) && last !== void 0) return run(state, {
3965
+ type: "MoveBlock",
3966
+ node: item.container.id,
3967
+ to: { after: last.id }
3968
+ }, ids, options);
3969
+ const created = NodeId.make(ids.mint());
3970
+ return apply(state, [Edit.insertBlock({
3971
+ type: "Node",
3972
+ kind: list.kind,
3973
+ id: created,
3974
+ props: list.props,
3975
+ children: [],
3976
+ blocks: []
3977
+ }, (previous.blocks ?? []).length, previous.id), Edit.moveBlock(item.container.id, 0, created)]);
3978
+ };
3979
+ /**
3980
+ * Shift+Tab in a list item: a nested item moves out to follow the item its list is in, and an
3981
+ * item at the top level leaves its list, as `LiftBlock` takes it. A list the move empties goes.
3982
+ */
3983
+ const liftItem = (state, item, ids, options) => {
3984
+ const listPath = item.containerPath.slice(0, -1);
3985
+ const outerItem = blockAtPath(state.document, listPath.slice(0, -1));
3986
+ const outerList = blockAtPath(state.document, listPath.slice(0, -2));
3987
+ return outerItem?.type === "Node" && outerList?.type === "Node" && options.nodes !== void 0 && holdsItem(options.nodes, outerList.kind, outerItem.kind) ? run(state, {
3988
+ type: "MoveBlock",
3989
+ node: item.container.id,
3990
+ to: { after: outerItem.id }
3991
+ }, ids, options) : run(state, { type: "LiftBlock" }, ids, options);
3992
+ };
3993
+ /**
3994
+ * Replaces matches, last first, each read again from its block's offset in the state the one
3995
+ * after it left: a replacement later in a block leaves an earlier match's offset alone, though
3996
+ * the runs it touched may have merged or split, so positions found before it would not do.
3997
+ */
3998
+ const replaceMatches = (state, matches, replacement, ids, options) => {
3999
+ let done = apply(state, []);
4000
+ for (const match of [...matches].reverse()) {
4001
+ if (!done.ok) return done;
4002
+ const block = locateBlock(done.state.document, match.block)?.block;
4003
+ const from = block === void 0 ? void 0 : positionInBlock(block, match.at);
4004
+ const to = block === void 0 ? void 0 : positionInBlock(block, match.at + match.length);
4005
+ if (from === void 0 || to === void 0) return failure("MissingText");
4006
+ const step = runAction(done.state, [{
4007
+ type: "SetSelection",
4008
+ selection: {
4009
+ type: "Range",
4010
+ anchor: from,
4011
+ focus: to
4012
+ }
4013
+ }, {
4014
+ type: "InsertText",
4015
+ text: replacement
4016
+ }], ids, options);
4017
+ if (!step.ok) return step;
4018
+ done = {
4019
+ ok: true,
4020
+ state: step.state,
4021
+ changeSet: unionChangeSet(done.changeSet, step.changeSet),
4022
+ positionMap: [...done.positionMap, ...step.positionMap],
4023
+ transactions: [...done.transactions, ...step.transactions]
4024
+ };
4025
+ }
4026
+ return done;
4027
+ };
4028
+ const insertFootnote = (state, text, ids, options) => {
4029
+ const selection = state.selection;
4030
+ if (selection?.type !== "Range") return failure("InvalidSelection");
4031
+ const start = rangeStart(state.document, selection);
4032
+ const last = state.document.children[state.document.children.length - 1];
4033
+ if (start === void 0 || last === void 0) return failure("InvalidSelection");
4034
+ const end = start === selection.anchor ? selection.focus : selection.anchor;
4035
+ const label = nextFootnoteLabel(state.document);
4036
+ const definition = {
4037
+ type: "Node",
4038
+ kind: FootnoteDefinition.name,
4039
+ id: NodeId.make("footnote"),
4040
+ props: { label },
4041
+ children: [],
4042
+ blocks: [{
4043
+ type: "Paragraph",
4044
+ id: NodeId.make("footnote-text"),
4045
+ children: [{
4046
+ type: "Text",
4047
+ id: NodeId.make("footnote-run"),
4048
+ text,
4049
+ marks: []
4050
+ }]
4051
+ }]
3126
4052
  };
4053
+ return runAction(state, [
4054
+ {
4055
+ type: "SetSelection",
4056
+ selection: {
4057
+ type: "Range",
4058
+ anchor: end,
4059
+ focus: end
4060
+ }
4061
+ },
4062
+ {
4063
+ type: "InsertText",
4064
+ text: label,
4065
+ marks: [FootnoteRef.of({ label })]
4066
+ },
4067
+ {
4068
+ type: "InsertBlock",
4069
+ block: definition,
4070
+ to: { after: last.id }
4071
+ }
4072
+ ], ids, options);
4073
+ };
4074
+ const renameFootnote = (state, from, to, ids, options) => {
4075
+ const notes = footnotesOf(state.document);
4076
+ const note = notes.find((each) => each.label === from);
4077
+ if (note === void 0 || to === "" || to !== from && notes.some((each) => each.label === to)) return failure("InvalidInput");
4078
+ const relabelled = FootnoteRef.of({ label: to });
4079
+ const references = [];
4080
+ eachBlock(state.document.children, (block) => {
4081
+ for (const run of block.children) {
4082
+ if (referenceLabel(run) !== from) continue;
4083
+ references.push({
4084
+ type: "SetSelection",
4085
+ selection: {
4086
+ type: "Range",
4087
+ anchor: {
4088
+ node: run.id,
4089
+ offset: 0,
4090
+ affinity: "after"
4091
+ },
4092
+ focus: {
4093
+ node: run.id,
4094
+ offset: run.text.length,
4095
+ affinity: "before"
4096
+ }
4097
+ }
4098
+ }, {
4099
+ type: "InsertText",
4100
+ text: run.text === from ? to : run.text,
4101
+ marks: run.marks.map((each) => markName(each) === FootnoteRef.name ? relabelled : each)
4102
+ });
4103
+ }
4104
+ });
4105
+ const selection = state.selection;
4106
+ const inReference = selection?.type === "Range" && (note.references.includes(selection.anchor.node) || note.references.includes(selection.focus.node));
4107
+ return runAction(state, [
4108
+ ...note.definition === void 0 ? [] : [{
4109
+ type: "SetProps",
4110
+ node: note.definition,
4111
+ props: { label: to }
4112
+ }],
4113
+ ...references,
4114
+ ...inReference || selection === null ? [] : [{
4115
+ type: "SetSelection",
4116
+ selection
4117
+ }]
4118
+ ], ids, options);
4119
+ };
4120
+ /** The first run anywhere in these blocks, nested ones included, in document order. */
4121
+ const firstRunIn = (blocks) => {
4122
+ let found;
4123
+ eachBlock(blocks, (block) => {
4124
+ found ??= block.children[0];
4125
+ });
4126
+ return found;
3127
4127
  };
3128
4128
  /**
3129
4129
  * A composed action's invalidation summary is the union of its commands': an identity
@@ -3181,20 +4181,28 @@ const runAction = (state, commands, ids, options = {}) => {
3181
4181
  * A rule that claims to consume more than it was shown throws: those deletes would run past
3182
4182
  * the block's start and join it to the one before, which no rule means.
3183
4183
  */
3184
- const applyInputRules = (rules, input) => {
4184
+ const applyInputRules = (rules, input) => resolveInputRules(rules, input).action;
4185
+ /**
4186
+ * `applyInputRules`, with the marks the matching rule says the next typed text carries, which an
4187
+ * editor keeps as its stored marks.
4188
+ */
4189
+ const resolveInputRules = (rules, input) => {
3185
4190
  const typed = `${input.textBefore}${input.text}`;
3186
4191
  for (const rule of rules) {
3187
4192
  const matched = rule.match(typed, input.within ?? []);
3188
4193
  if (matched === void 0) continue;
3189
4194
  if (!Number.isInteger(matched.remove) || matched.remove < 0 || matched.remove > typed.length) throw new RangeError(`Input rule "${rule.name}" removes ${matched.remove} characters of the ${typed.length} it was shown`);
3190
4195
  const consumed = Array.from({ length: matched.remove }, () => ({ type: "DeleteBackward" }));
3191
- return [
3192
- input.insertion,
3193
- ...consumed,
3194
- ...matched.commands
3195
- ];
4196
+ return {
4197
+ action: [
4198
+ input.insertion,
4199
+ ...consumed,
4200
+ ...matched.commands
4201
+ ],
4202
+ storedMarks: matched.storedMarks
4203
+ };
3196
4204
  }
3197
- return [input.insertion];
4205
+ return { action: [input.insertion] };
3198
4206
  };
3199
4207
  //#endregion
3200
4208
  //#region src/history.ts
@@ -3367,43 +4375,6 @@ const runPieces = (text, spans) => {
3367
4375
  return pieces;
3368
4376
  };
3369
4377
  //#endregion
3370
- //#region src/search.ts
3371
- /**
3372
- * Search highlights, as decorations (§64): every occurrence of a query in a document's text,
3373
- * without changing it. The producer lives here rather than in an application because it is a
3374
- * pure read of a document and nothing else, and the interpreter that draws the result is the
3375
- * caller's choice — the read-only view renders these as `span[data-decoration="search"]`
3376
- * (§126), and the editable one takes them when its overlay lands.
3377
- *
3378
- * A match is exact: a caller that wants case-insensitive search lowercases both sides. It
3379
- * never spans two blocks, because what a document has between blocks is a structural
3380
- * boundary rather than text. It may span two *runs*, though, which is why a block's runs are
3381
- * read as one string and the endpoints are mapped back to positions.
3382
- */
3383
- /** The kind a search decoration carries, which is what a stylesheet reaches it by. */
3384
- const SEARCH_DECORATION = "search";
3385
- /** Every occurrence of `query` in the document, as decorations a renderer can draw. */
3386
- const searchDecorations = (document, query) => {
3387
- const found = [];
3388
- if (query.length === 0) return found;
3389
- eachBlock(document.children, (block) => {
3390
- if (block.type === "Unknown" || block.children.length === 0) return;
3391
- const text = block.children.map((run) => run.text).join("");
3392
- let at = text.indexOf(query);
3393
- while (at >= 0) {
3394
- const anchor = positionInBlock(block, at);
3395
- const focus = positionInBlock(block, at + query.length);
3396
- if (anchor !== void 0 && focus !== void 0) found.push({
3397
- from: anchor,
3398
- to: focus,
3399
- kind: SEARCH_DECORATION
3400
- });
3401
- at = text.indexOf(query, at + query.length);
3402
- }
3403
- });
3404
- return found;
3405
- };
3406
- //#endregion
3407
4378
  //#region src/code.ts
3408
4379
  /**
3409
4380
  * Code highlighting, as decorations (§124 §7, §130): the document holds a `CodeBlock`'s
@@ -3563,12 +4534,21 @@ const standardNodes = [
3563
4534
  node("CodeBlock", {
3564
4535
  Props: Schema.Struct({ language: Schema.optional(Schema.String) }),
3565
4536
  children: textContent,
3566
- marks: "none"
4537
+ marks: "none",
4538
+ lineBreaks: true,
4539
+ indents: true
3567
4540
  }),
3568
4541
  atom("ThematicBreak"),
3569
4542
  atom("Image", { Props: Schema.Struct({
3570
4543
  src: Schema.String,
3571
- alt: Schema.optional(Schema.String)
4544
+ alt: Schema.optional(Schema.String),
4545
+ caption: Schema.optional(Schema.String),
4546
+ width: Schema.optional(Schema.Number.check(Schema.isGreaterThan(0))),
4547
+ align: Schema.optional(Schema.Literals([
4548
+ "start",
4549
+ "center",
4550
+ "end"
4551
+ ]))
3572
4552
  }) }),
3573
4553
  node("Table", { children: blocksOf("TableRow") }),
3574
4554
  node("TableRow", {
@@ -5528,6 +6508,183 @@ const resolve = (state, selection) => {
5528
6508
  };
5529
6509
  };
5530
6510
  //#endregion
5531
- export { Beside, Block, Bold, Code, Container, DefaultDocumentLimits, Document, DocumentLimits, Edit, EditorState, Heading, History, Italic, Link, MAX_NORMALIZATION_PASSES, Mark, MarkValue, Node, NodeBlock, NodeId, Operation, Paragraph, Position, replicated_exports as Replicated, RetypeTarget, RunMark, SEARCH_DECORATION, Selection, Slice, Strikethrough, Text, TextBlock, Transaction, UnknownBlock, apply, applyInputRules, atom, block, blockAtPath, blockContent, blockKind, blocksAt, blocksOf, canRedo, canUndo, codeDecorations, commit, count, coversText, decodeDocument, decorationsIn, defaultTransforms, deserializeSlice, documentToHtml, documentToText, emptyHistory, emptySlice, findUnknownMarks, findUnknownNodes, groupFor, inspect, inspectHistory, inspectKit, isBlank, kit, linkAt, locateBlock, locateRun, mapPosition, mark, markExtent, markName, markProps, markRegistry, marksInRange, mergeAdjacentRuns, migrate, migration, moveTargets, noRendering, node, nodeProps, nodeRegistry, nodeRendering, plainTextOf, positionInBlock, promoteUnknown, rangeStart, redo, rendering, renderingOver, resolveInsertion, run, runAction, runPieces, runRendering, safeUrl, sameMark, sameMarkSet, searchDecorations, selectionIsValid, serializeSlice, shippedMarks, shippedRegistry, sliceFromText, sliceOf, standardMarks, standardNodes, standardRendering, textBefore, textBlockAt, textContent, textRangeBefore, toHtml, toText, unchanged, undo, unionChangeSet, validate, withFreshIds };
6511
+ //#region src/outline.ts
6512
+ /**
6513
+ * The document's outline: its headings in document order, which a table of contents draws, and
6514
+ * the section a selection is in. Both are reads; nothing here changes the document.
6515
+ */
6516
+ /** Every heading with text, in document order, inside containers too. */
6517
+ const outlineOf = (document) => {
6518
+ const entries = [];
6519
+ eachBlock(document.children, (block) => {
6520
+ if (block.type !== "Heading") return;
6521
+ const text = block.children.map((run) => run.text).join("");
6522
+ if (text.trim() !== "") entries.push({
6523
+ node: block.id,
6524
+ level: block.level,
6525
+ text
6526
+ });
6527
+ });
6528
+ return entries;
6529
+ };
6530
+ /**
6531
+ * The heading of the section the selection starts in: the last heading with text at or before
6532
+ * its block. Undefined with no selection, or before the first heading.
6533
+ */
6534
+ const sectionAt = (document, selection) => {
6535
+ if (selection?.type !== "Range") return void 0;
6536
+ const start = rangeStart(document, selection);
6537
+ if (start === void 0) return void 0;
6538
+ let last;
6539
+ let found;
6540
+ eachBlock(document.children, (block) => {
6541
+ if (block.type === "Heading" && block.children.some((run) => run.text.trim() !== "")) last = block.id;
6542
+ if (block.children.some((run) => run.id === start.node)) found = last;
6543
+ });
6544
+ return found;
6545
+ };
6546
+ //#endregion
6547
+ //#region src/media.ts
6548
+ /**
6549
+ * Media beside the standard `Image`: a video and a sound played with the browser's own controls,
6550
+ * and a file to download. Opt-in vocabulary like footnotes: add `mediaNodes` to a kit and draw
6551
+ * them with `mediaRendering` under the rendering. Each is an atom holding where its media is
6552
+ * (`src`); where that is, a `data:` URL read from a file or a URL an upload returned, is the
6553
+ * application's to decide.
6554
+ */
6555
+ const Width = Schema.optional(Schema.Number.check(Schema.isGreaterThan(0)));
6556
+ /** A video, played with the browser's controls, at `width` CSS pixels when it says. */
6557
+ const Video = atom("Video", { Props: Schema.Struct({
6558
+ src: Schema.String,
6559
+ title: Schema.optional(Schema.String),
6560
+ width: Width
6561
+ }) });
6562
+ /** A sound, played with the browser's controls. */
6563
+ const Audio = atom("Audio", { Props: Schema.Struct({
6564
+ src: Schema.String,
6565
+ title: Schema.optional(Schema.String)
6566
+ }) });
6567
+ /** A file to download, under its name, with its size and type when they are known. */
6568
+ const Attachment = atom("Attachment", { Props: Schema.Struct({
6569
+ src: Schema.String,
6570
+ name: Schema.String,
6571
+ size: Schema.optional(Schema.Number.check(Schema.isGreaterThanOrEqualTo(0))),
6572
+ type: Schema.optional(Schema.String)
6573
+ }) });
6574
+ const mediaNodes = [
6575
+ Video,
6576
+ Audio,
6577
+ Attachment
6578
+ ];
6579
+ /** Types a page could run as script or markup if one were ever opened rather than saved. */
6580
+ const ACTIVE = /^(text\/html|application\/xhtml\+xml|image\/svg\+xml|text\/xml|application\/xml)\b/i;
6581
+ /**
6582
+ * Where a media element may load from: what the URL policy allows, or a `data:` URL whose type
6583
+ * `accepts` admits. The policy refuses `data:` in general, since a link to one could carry a
6584
+ * page; a video's own bytes cannot.
6585
+ */
6586
+ const mediaUrl = (value, accepts) => {
6587
+ if (typeof value !== "string") return void 0;
6588
+ const data = /^data:([^;,]*)[;,]/i.exec(value.trim());
6589
+ if (data === null) return safeUrl(value);
6590
+ return accepts(data[1] ?? "") ? value.trim() : void 0;
6591
+ };
6592
+ const text = (value) => typeof value === "string" ? value : "";
6593
+ /** A size as a reader says it: `820 B`, `12 KB`, `3.4 MB`. */
6594
+ const fileSize = (bytes) => {
6595
+ if (bytes < 1024) return `${bytes} B`;
6596
+ if (bytes < 1048576) return `${Math.round(bytes / 1024)} KB`;
6597
+ return `${(bytes / 1048576).toFixed(1)} MB`;
6598
+ };
6599
+ /**
6600
+ * How media draws: a `video` or `audio` with `controls`, which loads only its metadata until it
6601
+ * is played, and an attachment as a download link showing its name and size. A source the policy
6602
+ * refuses leaves the element without one, so it draws nothing playable.
6603
+ */
6604
+ const mediaRendering = rendering({ nodes: {
6605
+ Video: (block) => {
6606
+ const src = mediaUrl(block.props.src, (type) => type.toLowerCase().startsWith("video/"));
6607
+ const width = block.props.width;
6608
+ return {
6609
+ tag: "video",
6610
+ attributes: {
6611
+ ...src === void 0 ? {} : { src },
6612
+ controls: "",
6613
+ preload: "metadata",
6614
+ title: text(block.props.title),
6615
+ ...typeof width === "number" ? { width: String(width) } : {}
6616
+ }
6617
+ };
6618
+ },
6619
+ Audio: (block) => {
6620
+ const src = mediaUrl(block.props.src, (type) => type.toLowerCase().startsWith("audio/"));
6621
+ return {
6622
+ tag: "audio",
6623
+ attributes: {
6624
+ ...src === void 0 ? {} : { src },
6625
+ controls: "",
6626
+ preload: "metadata",
6627
+ title: text(block.props.title)
6628
+ }
6629
+ };
6630
+ },
6631
+ Attachment: (block) => {
6632
+ const href = mediaUrl(block.props.src, (type) => !ACTIVE.test(type));
6633
+ const name = text(block.props.name);
6634
+ const size = block.props.size;
6635
+ return {
6636
+ tag: "a",
6637
+ attributes: {
6638
+ ...href === void 0 ? {} : { href },
6639
+ download: name,
6640
+ "data-attachment": ""
6641
+ },
6642
+ adornments: [{
6643
+ tag: "span",
6644
+ attributes: { "data-attachment-name": "" },
6645
+ text: name
6646
+ }, ...typeof size === "number" ? [{
6647
+ tag: "span",
6648
+ attributes: { "data-attachment-size": "" },
6649
+ text: fileSize(size)
6650
+ }] : []]
6651
+ };
6652
+ }
6653
+ } });
6654
+ /**
6655
+ * The block for a file a reader added: an `Image`, `Video` or `Audio` when its type is one, and
6656
+ * an `Attachment` otherwise. Its identity is a placeholder, which `InsertBlock` replaces.
6657
+ */
6658
+ const mediaBlock = (file) => {
6659
+ const family = file.type.toLowerCase().split("/")[0];
6660
+ const title = file.name.replace(/\.[^.]+$/, "");
6661
+ const node = (kind, props) => ({
6662
+ type: "Node",
6663
+ kind,
6664
+ id: NodeId.make("media"),
6665
+ props,
6666
+ children: []
6667
+ });
6668
+ if (family === "image") return node("Image", {
6669
+ src: file.src,
6670
+ alt: title
6671
+ });
6672
+ if (family === "video") return node("Video", {
6673
+ src: file.src,
6674
+ title
6675
+ });
6676
+ if (family === "audio") return node("Audio", {
6677
+ src: file.src,
6678
+ title
6679
+ });
6680
+ return node("Attachment", {
6681
+ src: file.src,
6682
+ name: file.name,
6683
+ size: file.size,
6684
+ ...file.type === "" ? {} : { type: file.type }
6685
+ });
6686
+ };
6687
+ //#endregion
6688
+ export { ACTION_ATTRIBUTE, ADORNMENT_ATTRIBUTE, Attachment, Audio, Beside, Block, Bold, Code, Container, DefaultDocumentLimits, Document, DocumentLimits, Edit, EditorState, FootnoteDefinition, FootnoteRef, Heading, History, INDENT, Italic, Link, MAX_NORMALIZATION_PASSES, Mark, MarkValue, Node, NodeBlock, NodeId, Operation, Paragraph, Position, replicated_exports as Replicated, RetypeTarget, RunMark, SEARCH_CURRENT_DECORATION, SEARCH_DECORATION, Selection, Slice, Strikethrough, TOGGLES_ATTRIBUTE, Text, TextBlock, Transaction, UnknownBlock, Video, adornmentAttributes, apply, applyInputRules, atom, block, blockAtPath, blockContent, blockKind, blocksAt, blocksOf, canRedo, canUndo, codeDecorations, commit, count, coversText, decodeDocument, decorationsIn, defaultTransforms, deserializeSlice, documentToHtml, documentToText, eachBlock, emptyHistory, emptySlice, fileSize, findMatches, findUnknownMarks, findUnknownNodes, footnoteAt, footnotesOf, groupFor, inspect, inspectHistory, inspectKit, isAtom, isBlank, kit, linkAt, locateBlock, locateRun, mapPosition, mark, markExtent, markName, markProps, markRegistry, marksInRange, mediaBlock, mediaNodes, mediaRendering, mergeAdjacentRuns, migrate, migration, moveTargets, nextFootnoteLabel, noRendering, node, nodeProps, nodeRegistry, nodeRendering, outlineOf, plainTextOf, positionInBlock, promoteUnknown, rangeStart, redo, referenceLabel, rendering, renderingOver, resolveInputRules, resolveInsertion, run, runAction, runPieces, runRendering, safeUrl, sameElementRendering, sameMark, sameMarkSet, searchDecorations, sectionAt, selectionIsValid, serializeSlice, shippedMarks, shippedRegistry, siblingsOf, sliceFromText, sliceOf, standardMarks, standardNodes, standardRendering, tableAt, takesTab, textBefore, textBlockAt, textContent, textRangeBefore, toHtml, toText, unchanged, undo, unionChangeSet, validate, withFreshIds };
5532
6689
 
5533
6690
  //# sourceMappingURL=index.mjs.map