foldkit-richtext 0.1.0 → 0.2.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/README.md +440 -23
- package/dist/index.d.mts +964 -100
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3337 -240
- package/dist/index.mjs.map +1 -1
- package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
- package/package.json +3 -2
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
|
|
1
2
|
import { Equal, Schema } from "effect";
|
|
2
3
|
//#region src/document.ts
|
|
3
4
|
/** Caller-assigned identity, unique across blocks and text runs in a document. */
|
|
@@ -196,6 +197,8 @@ const compareRunPlaces = (left, right) => {
|
|
|
196
197
|
if (left.path.length !== right.path.length) return left.path.length - right.path.length;
|
|
197
198
|
return left.index - right.index;
|
|
198
199
|
};
|
|
200
|
+
/** Document order over position places: the run first, then the offset within it. */
|
|
201
|
+
const comparePositionPlaces = (left, right) => compareRunPlaces(left, right) || left.offset - right.offset;
|
|
199
202
|
/** The block a path addresses, or undefined when the path does not resolve. */
|
|
200
203
|
const blockAtPath = (document, path) => {
|
|
201
204
|
let blocks = document.children;
|
|
@@ -232,6 +235,91 @@ const locateRun = (document, node) => {
|
|
|
232
235
|
});
|
|
233
236
|
return found;
|
|
234
237
|
};
|
|
238
|
+
/**
|
|
239
|
+
* Whether a reader would see nothing: no blocks, or a lone paragraph or heading whose runs
|
|
240
|
+
* hold no text. What an editor shows its placeholder for; a lone empty list or code block is
|
|
241
|
+
* content a writer made, so it is not blank.
|
|
242
|
+
*/
|
|
243
|
+
const isBlank = (document) => {
|
|
244
|
+
const first = document.children[0];
|
|
245
|
+
if (first === void 0) return true;
|
|
246
|
+
return document.children.length === 1 && (first.type === "Paragraph" || first.type === "Heading") && first.children.every((run) => run.text.length === 0);
|
|
247
|
+
};
|
|
248
|
+
/**
|
|
249
|
+
* The text of the block a position addresses, up to that position, in run order.
|
|
250
|
+
* A menu reads this: what a query is typed into is the block's text between its
|
|
251
|
+
* start and the caret, and a query never spans blocks. Affinity is not consulted — a
|
|
252
|
+
* prefix ends between characters whatever side the caret leans to — an offset past a
|
|
253
|
+
* run's end clamps to it, a negative one reads as none of it, and a position that
|
|
254
|
+
* resolves to nothing gives an empty string.
|
|
255
|
+
*/
|
|
256
|
+
const textBefore = (document, position) => {
|
|
257
|
+
const found = locateRun(document, position.node);
|
|
258
|
+
if (found === void 0) return "";
|
|
259
|
+
const block = blockAtPath(document, found.path);
|
|
260
|
+
if (block === void 0) return "";
|
|
261
|
+
return block.children.slice(0, found.index).map((earlier) => earlier.text).join("") + found.run.text.slice(0, Math.max(0, position.offset));
|
|
262
|
+
};
|
|
263
|
+
/**
|
|
264
|
+
* Whichever end of a range comes first in the document, whatever direction it was made in,
|
|
265
|
+
* or `undefined` when either end does not resolve. What replaces a range starts here, so a
|
|
266
|
+
* read of the text before an edit reads from this end rather than the anchor.
|
|
267
|
+
*/
|
|
268
|
+
const rangeStart = (document, range) => {
|
|
269
|
+
const anchor = locateRun(document, range.anchor.node);
|
|
270
|
+
const focus = locateRun(document, range.focus.node);
|
|
271
|
+
if (anchor === void 0 || focus === void 0) return void 0;
|
|
272
|
+
return comparePositionPlaces({
|
|
273
|
+
...anchor,
|
|
274
|
+
offset: range.anchor.offset
|
|
275
|
+
}, {
|
|
276
|
+
...focus,
|
|
277
|
+
offset: range.focus.offset
|
|
278
|
+
}) <= 0 ? range.anchor : range.focus;
|
|
279
|
+
};
|
|
280
|
+
/**
|
|
281
|
+
* The position a block's text offset addresses, or `undefined` when it is negative or past
|
|
282
|
+
* the end. The inverse of `textBefore` for one block: a rule, a search match, or any producer
|
|
283
|
+
* working in a block's own text needs it to say where what it found is.
|
|
284
|
+
*/
|
|
285
|
+
const positionInBlock = (block, offset) => {
|
|
286
|
+
if (offset < 0) return void 0;
|
|
287
|
+
let consumed = 0;
|
|
288
|
+
for (const run of block.children) {
|
|
289
|
+
const next = consumed + run.text.length;
|
|
290
|
+
if (offset <= next) return {
|
|
291
|
+
node: run.id,
|
|
292
|
+
offset: offset - consumed,
|
|
293
|
+
affinity: offset === next ? "after" : "before"
|
|
294
|
+
};
|
|
295
|
+
consumed = next;
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
/**
|
|
299
|
+
* The range covering the `length` characters before `position` in its block, or
|
|
300
|
+
* `undefined` when the position does not resolve, `length` is not positive, or fewer
|
|
301
|
+
* characters precede it. The inverse of `textBefore`: an input rule or a menu deletes
|
|
302
|
+
* what it matched with this range, so removing the match and acting on it commit as one
|
|
303
|
+
* action (§124 §5). Endpoints land at run boundaries with `after` affinity, which is
|
|
304
|
+
* where a caret that typed that character would sit.
|
|
305
|
+
*/
|
|
306
|
+
const textRangeBefore = (document, position, length) => {
|
|
307
|
+
if (length <= 0) return void 0;
|
|
308
|
+
const found = locateRun(document, position.node);
|
|
309
|
+
if (found === void 0) return void 0;
|
|
310
|
+
const block = blockAtPath(document, found.path);
|
|
311
|
+
if (block === void 0) return void 0;
|
|
312
|
+
const end = block.children.slice(0, found.index).reduce((total, run) => total + run.text.length, 0) + Math.min(found.run.text.length, Math.max(0, position.offset));
|
|
313
|
+
const start = end - length;
|
|
314
|
+
if (start < 0) return void 0;
|
|
315
|
+
const anchor = positionInBlock(block, start);
|
|
316
|
+
const focus = positionInBlock(block, end);
|
|
317
|
+
return anchor === void 0 || focus === void 0 ? void 0 : {
|
|
318
|
+
type: "Range",
|
|
319
|
+
anchor,
|
|
320
|
+
focus
|
|
321
|
+
};
|
|
322
|
+
};
|
|
235
323
|
/** Every node a block subtree owns, block and run alike, keyed by identity. */
|
|
236
324
|
const indexNodes = (blocks, nodes) => {
|
|
237
325
|
eachBlock(blocks, (block) => {
|
|
@@ -297,11 +385,38 @@ const Selection = Schema.Union([Schema.Struct({
|
|
|
297
385
|
type: Schema.Literal("Node"),
|
|
298
386
|
node: NodeId
|
|
299
387
|
})]);
|
|
388
|
+
const nodeIndexes = /* @__PURE__ */ new WeakMap();
|
|
389
|
+
/** The document's `NodeIndex`, built once per document: documents are immutable. */
|
|
390
|
+
const nodeIndex = (document) => {
|
|
391
|
+
const cached = nodeIndexes.get(document);
|
|
392
|
+
if (cached !== void 0) return cached;
|
|
393
|
+
const nodes = /* @__PURE__ */ new Map();
|
|
394
|
+
const blockOf = /* @__PURE__ */ new Map();
|
|
395
|
+
const parentOf = /* @__PURE__ */ new Map();
|
|
396
|
+
const visit = (blocks, parent) => {
|
|
397
|
+
for (const block of blocks) {
|
|
398
|
+
nodes.set(block.id, block);
|
|
399
|
+
parentOf.set(block.id, parent);
|
|
400
|
+
for (const run of block.children) {
|
|
401
|
+
nodes.set(run.id, run);
|
|
402
|
+
blockOf.set(run.id, block);
|
|
403
|
+
}
|
|
404
|
+
if (block.type === "Node" && block.blocks !== void 0) visit(block.blocks, block.id);
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
visit(document.children, null);
|
|
408
|
+
const index = {
|
|
409
|
+
nodes,
|
|
410
|
+
blockOf,
|
|
411
|
+
parentOf
|
|
412
|
+
};
|
|
413
|
+
nodeIndexes.set(document, index);
|
|
414
|
+
return index;
|
|
415
|
+
};
|
|
300
416
|
/** Validates references without sorting range endpoints or changing direction. */
|
|
301
417
|
const selectionIsValid = (document, selection) => {
|
|
302
418
|
if (selection === null) return true;
|
|
303
|
-
const nodes =
|
|
304
|
-
indexNodes(document.children, nodes);
|
|
419
|
+
const { nodes } = nodeIndex(document);
|
|
305
420
|
if (selection.type === "Node") return nodes.has(selection.node);
|
|
306
421
|
return [selection.anchor, selection.focus].every((position) => {
|
|
307
422
|
const node = nodes.get(position.node);
|
|
@@ -312,6 +427,62 @@ const EditorState = Schema.Struct({
|
|
|
312
427
|
document: Document,
|
|
313
428
|
selection: Schema.NullOr(Selection)
|
|
314
429
|
}).check(Schema.makeFilter((state) => selectionIsValid(state.document, state.selection) || "Unresolved selection"));
|
|
430
|
+
const decodeBlock = Schema.decodeUnknownSync(Block, { onExcessProperty: "error" });
|
|
431
|
+
const decodeSelection = Schema.decodeUnknownSync(Schema.NullOr(Selection), { onExcessProperty: "error" });
|
|
432
|
+
/**
|
|
433
|
+
* Blocks and documents that have passed validation. They are immutable, and an edit copies
|
|
434
|
+
* only the blocks on the path to what it touches, so a keystroke re-validates that path
|
|
435
|
+
* rather than the document or a whole container.
|
|
436
|
+
*/
|
|
437
|
+
const validBlocks = /* @__PURE__ */ new WeakSet();
|
|
438
|
+
const validDocuments = /* @__PURE__ */ new WeakSet();
|
|
439
|
+
/**
|
|
440
|
+
* Throws unless `block` decodes as a `Block`, caching every block that passes, nested ones
|
|
441
|
+
* included. A block's validity does not depend on where it sits (the codec has no placement
|
|
442
|
+
* or depth rules; identity is checked document-wide by the caller), so a node block is valid
|
|
443
|
+
* exactly when its own fields are and each nested block is: those are checked separately, the
|
|
444
|
+
* fields by decoding the block with its nested blocks emptied.
|
|
445
|
+
*/
|
|
446
|
+
const assertBlock = (block) => {
|
|
447
|
+
if (typeof block !== "object" || block === null) return void decodeBlock(block);
|
|
448
|
+
if (validBlocks.has(block)) return;
|
|
449
|
+
const nested = Object.getOwnPropertyDescriptor(block, "blocks");
|
|
450
|
+
if (block.type === "Node" && Array.isArray(nested?.value)) {
|
|
451
|
+
decodeBlock(Object.create(Object.getPrototypeOf(block), {
|
|
452
|
+
...Object.getOwnPropertyDescriptors(block),
|
|
453
|
+
blocks: {
|
|
454
|
+
...nested,
|
|
455
|
+
value: []
|
|
456
|
+
}
|
|
457
|
+
}));
|
|
458
|
+
for (const child of nested.value) assertBlock(child);
|
|
459
|
+
} else decodeBlock(block);
|
|
460
|
+
validBlocks.add(block);
|
|
461
|
+
};
|
|
462
|
+
const hasOnlyKeys = (value, keys) => Object.keys(value).every((key) => keys.includes(key));
|
|
463
|
+
/**
|
|
464
|
+
* Whether `input` decodes as an `EditorState`, with no excess properties, as
|
|
465
|
+
* `Schema.decodeUnknownSync(EditorState, { onExcessProperty: 'error' })` decides, but
|
|
466
|
+
* remembering each block and document that passed. Throws on invalid input.
|
|
467
|
+
*/
|
|
468
|
+
const assertEditorState = (input) => {
|
|
469
|
+
if (typeof input !== "object" || input === null || !hasOnlyKeys(input, ["document", "selection"])) throw new Error("Invalid editor state");
|
|
470
|
+
const { document, selection } = input;
|
|
471
|
+
if (typeof document !== "object" || document === null) throw new Error("Invalid document");
|
|
472
|
+
if (!validDocuments.has(document)) {
|
|
473
|
+
const { version, children } = document;
|
|
474
|
+
if (version !== 1 || !Array.isArray(children) || !hasOnlyKeys(document, ["version", "children"])) throw new Error("Invalid document");
|
|
475
|
+
for (const block of children) assertBlock(block);
|
|
476
|
+
const ids = /* @__PURE__ */ new Set();
|
|
477
|
+
for (const block of children) for (const id of subtreeIds(block)) {
|
|
478
|
+
if (ids.has(id)) throw new Error("Duplicate node identity");
|
|
479
|
+
ids.add(id);
|
|
480
|
+
}
|
|
481
|
+
validDocuments.add(document);
|
|
482
|
+
}
|
|
483
|
+
decodeSelection(selection);
|
|
484
|
+
if (!selectionIsValid(document, selection)) throw new Error("Unresolved selection");
|
|
485
|
+
};
|
|
315
486
|
/**
|
|
316
487
|
* Counts semantic nodes and UTF-16 text units, and reports nesting depth. Depth
|
|
317
488
|
* counts levels of content: an empty document is 0, blocks are 1, runs inside a
|
|
@@ -332,6 +503,27 @@ const inspect = (document) => {
|
|
|
332
503
|
depth
|
|
333
504
|
};
|
|
334
505
|
};
|
|
506
|
+
const words = new Intl.Segmenter(void 0, { granularity: "word" });
|
|
507
|
+
const graphemes = new Intl.Segmenter(void 0, { granularity: "grapheme" });
|
|
508
|
+
/**
|
|
509
|
+
* What a reader would count: words and user-perceived characters, as `Intl.Segmenter` splits
|
|
510
|
+
* them in the default locale, so a word in a script without spaces still counts. Runs are
|
|
511
|
+
* joined within a block, so a word that changes mark midway is one word, and blocks never
|
|
512
|
+
* join, so the last word of one block and the first of the next are two.
|
|
513
|
+
*/
|
|
514
|
+
const count = (document) => {
|
|
515
|
+
let wordCount = 0;
|
|
516
|
+
let characterCount = 0;
|
|
517
|
+
eachBlock(document.children, (block) => {
|
|
518
|
+
const text = block.children.map((run) => run.text).join("");
|
|
519
|
+
for (const segment of words.segment(text)) if (segment.isWordLike) wordCount += 1;
|
|
520
|
+
for (const _ of graphemes.segment(text)) characterCount += 1;
|
|
521
|
+
});
|
|
522
|
+
return {
|
|
523
|
+
words: wordCount,
|
|
524
|
+
characters: characterCount
|
|
525
|
+
};
|
|
526
|
+
};
|
|
335
527
|
//#endregion
|
|
336
528
|
//#region src/marks.ts
|
|
337
529
|
const decodeJsonProps = Schema.decodeUnknownSync(Schema.JsonObject);
|
|
@@ -365,11 +557,29 @@ const shippedMarks = [
|
|
|
365
557
|
Italic,
|
|
366
558
|
Code
|
|
367
559
|
];
|
|
560
|
+
/**
|
|
561
|
+
* Whether props fail to decode against a node's or a mark's declared schema. The
|
|
562
|
+
* diagnostic is deliberately stable: a schema's own message can name internals
|
|
563
|
+
* an API boundary should not leak, so only the verdict travels.
|
|
564
|
+
*/
|
|
565
|
+
const propsFailure = (props, value) => {
|
|
566
|
+
if (props === void 0) return false;
|
|
567
|
+
try {
|
|
568
|
+
Schema.decodeUnknownSync(props, { onExcessProperty: "error" })(value);
|
|
569
|
+
return false;
|
|
570
|
+
} catch {
|
|
571
|
+
return true;
|
|
572
|
+
}
|
|
573
|
+
};
|
|
368
574
|
const markRegistry = (definitions) => {
|
|
369
|
-
const byName = new Map(definitions.map((definition) => [definition.name, definition
|
|
575
|
+
const byName = new Map(definitions.map((definition) => [definition.name, definition]));
|
|
370
576
|
return {
|
|
371
|
-
expansionOf: (name) => byName.get(name) ?? "both",
|
|
372
|
-
declares: (name) => byName.has(name)
|
|
577
|
+
expansionOf: (name) => byName.get(name)?.expand ?? "both",
|
|
578
|
+
declares: (name) => byName.has(name),
|
|
579
|
+
accepts: (mark) => {
|
|
580
|
+
const definition = byName.get(markName(mark));
|
|
581
|
+
return definition !== void 0 && !propsFailure(definition.Props, markProps(mark));
|
|
582
|
+
}
|
|
373
583
|
};
|
|
374
584
|
};
|
|
375
585
|
/** The policy of the shipped vocabulary. */
|
|
@@ -428,7 +638,7 @@ const BUILT_IN_MARK_TAGS = [
|
|
|
428
638
|
* hand-built `Rendering` must not let `__proto__` resolve to a prototype.
|
|
429
639
|
*/
|
|
430
640
|
const entryFor = (entries, name) => Object.hasOwn(entries, name) ? entries[name] : void 0;
|
|
431
|
-
const resolve = (entry, value) => typeof entry === "function" ? entry(value) : entry;
|
|
641
|
+
const resolve$1 = (entry, value) => typeof entry === "function" ? entry(value) : entry;
|
|
432
642
|
/** A name's own entry map, with no prototype for a content-chosen name to reach. */
|
|
433
643
|
const entryMap = (entries) => {
|
|
434
644
|
const map = Object.create(null);
|
|
@@ -441,6 +651,21 @@ const rendering = (definition = {}) => Object.freeze({
|
|
|
441
651
|
});
|
|
442
652
|
/** The behaviour without a renderer: shipped tags for shipped marks, names otherwise. */
|
|
443
653
|
const noRendering = rendering();
|
|
654
|
+
/**
|
|
655
|
+
* A registry built over another: an entry named here wins, and every name the base
|
|
656
|
+
* renders keeps its entry, so an application extends a vocabulary like the standard one
|
|
657
|
+
* without restating it.
|
|
658
|
+
*/
|
|
659
|
+
const renderingOver = (base, definition = {}) => rendering({
|
|
660
|
+
marks: {
|
|
661
|
+
...base.marks,
|
|
662
|
+
...definition.marks
|
|
663
|
+
},
|
|
664
|
+
nodes: {
|
|
665
|
+
...base.nodes,
|
|
666
|
+
...definition.nodes
|
|
667
|
+
}
|
|
668
|
+
});
|
|
444
669
|
const byName = (left, right) => left < right ? -1 : left > right ? 1 : 0;
|
|
445
670
|
/**
|
|
446
671
|
* Resolves a run's marks to elements. Order is the vocabulary's, then names
|
|
@@ -458,7 +683,7 @@ const runRendering = (definition, run) => {
|
|
|
458
683
|
nest.push(entry === void 0 ? {
|
|
459
684
|
tag,
|
|
460
685
|
attributes: {}
|
|
461
|
-
} : resolve(entry, mark) ?? {
|
|
686
|
+
} : resolve$1(entry, mark) ?? {
|
|
462
687
|
tag,
|
|
463
688
|
attributes: {}
|
|
464
689
|
});
|
|
@@ -467,7 +692,7 @@ const runRendering = (definition, run) => {
|
|
|
467
692
|
for (const mark of others) {
|
|
468
693
|
const name = markName(mark);
|
|
469
694
|
const entry = entryFor(definition.marks, name);
|
|
470
|
-
const element = entry === void 0 ? void 0 : resolve(entry, mark);
|
|
695
|
+
const element = entry === void 0 ? void 0 : resolve$1(entry, mark);
|
|
471
696
|
if (element === void 0) unrendered.push(name);
|
|
472
697
|
else nest.push(element);
|
|
473
698
|
}
|
|
@@ -479,7 +704,7 @@ const runRendering = (definition, run) => {
|
|
|
479
704
|
/** The element a node kind renders as, or undefined when no entry applies. */
|
|
480
705
|
const nodeRendering = (definition, block) => {
|
|
481
706
|
const entry = entryFor(definition.nodes, block.kind);
|
|
482
|
-
return entry === void 0 ? void 0 : resolve(entry, block);
|
|
707
|
+
return entry === void 0 ? void 0 : resolve$1(entry, block);
|
|
483
708
|
};
|
|
484
709
|
//#endregion
|
|
485
710
|
//#region src/html.ts
|
|
@@ -488,6 +713,26 @@ const escapeAttribute = (value) => escapeText(value).replace(/"/g, """).rep
|
|
|
488
713
|
const TAG = /^[A-Za-z][-A-Za-z0-9]*$/;
|
|
489
714
|
const ATTRIBUTE = /^[A-Za-z_:][-A-Za-z0-9_:.]*$/;
|
|
490
715
|
/**
|
|
716
|
+
* HTML void elements: they have no closing tag, so a rendering that names one — a
|
|
717
|
+
* standard `Image` is an `img`, a `ThematicBreak` an `hr` — writes one tag and no
|
|
718
|
+
* children rather than `<img></img>`.
|
|
719
|
+
*/
|
|
720
|
+
const VOID_ELEMENTS = /* @__PURE__ */ new Set([
|
|
721
|
+
"area",
|
|
722
|
+
"base",
|
|
723
|
+
"br",
|
|
724
|
+
"col",
|
|
725
|
+
"embed",
|
|
726
|
+
"hr",
|
|
727
|
+
"img",
|
|
728
|
+
"input",
|
|
729
|
+
"link",
|
|
730
|
+
"meta",
|
|
731
|
+
"source",
|
|
732
|
+
"track",
|
|
733
|
+
"wbr"
|
|
734
|
+
]);
|
|
735
|
+
/**
|
|
491
736
|
* Writes an element. An attribute *value* is content and is escaped; a tag or
|
|
492
737
|
* attribute *name* is refused rather than written when malformed, because a name
|
|
493
738
|
* cannot be escaped — one holding a quote, a space, or `>` would end the attribute
|
|
@@ -500,6 +745,7 @@ const renderElement = (element, inner) => {
|
|
|
500
745
|
if (!ATTRIBUTE.test(name)) throw new Error(`RichText.toHtml: invalid attribute name "${name}"`);
|
|
501
746
|
return ` ${name}="${escapeAttribute(value)}"`;
|
|
502
747
|
}).join("");
|
|
748
|
+
if (VOID_ELEMENTS.has(element.tag.toLowerCase())) return `<${element.tag}${attributes}>`;
|
|
503
749
|
return `<${element.tag}${attributes}>${inner}</${element.tag}>`;
|
|
504
750
|
};
|
|
505
751
|
const renderRun = (run, renderer) => {
|
|
@@ -520,7 +766,10 @@ const renderBlock = (block, renderer) => {
|
|
|
520
766
|
tag: blockTag(block),
|
|
521
767
|
attributes: block.type === "Node" ? { "data-node": block.kind } : {}
|
|
522
768
|
};
|
|
523
|
-
return renderElement(element, `${runs}${nested}`
|
|
769
|
+
return renderElement(element, element.inner === void 0 ? `${runs}${nested}` : `${runs}${renderElement({
|
|
770
|
+
tag: element.inner,
|
|
771
|
+
attributes: {}
|
|
772
|
+
}, nested)}`);
|
|
524
773
|
};
|
|
525
774
|
/** Serializes blocks as HTML, with text and attributes escaped. */
|
|
526
775
|
const toHtml = (blocks, renderer = noRendering) => blocks.map((block) => renderBlock(block, renderer)).join("");
|
|
@@ -668,7 +917,7 @@ const sliceOf = (document, selection) => {
|
|
|
668
917
|
...focus,
|
|
669
918
|
offset: selection.focus.offset
|
|
670
919
|
};
|
|
671
|
-
const span =
|
|
920
|
+
const span = comparePositionPlaces(anchorPlace, focusPlace) <= 0 ? {
|
|
672
921
|
start: anchorPlace,
|
|
673
922
|
end: focusPlace
|
|
674
923
|
} : {
|
|
@@ -753,6 +1002,202 @@ const deserializeSlice = (input) => {
|
|
|
753
1002
|
}
|
|
754
1003
|
};
|
|
755
1004
|
//#endregion
|
|
1005
|
+
//#region src/kit.ts
|
|
1006
|
+
/** Declares that a node holds nested blocks, only of the named kinds. */
|
|
1007
|
+
const blocksOf = (...kinds) => Object.freeze({
|
|
1008
|
+
mode: blockContent,
|
|
1009
|
+
of: [...kinds]
|
|
1010
|
+
});
|
|
1011
|
+
/** Declares a block node kind: a top-level node containing text runs. */
|
|
1012
|
+
const block = (name) => ({
|
|
1013
|
+
name,
|
|
1014
|
+
kind: "block",
|
|
1015
|
+
children: "text"
|
|
1016
|
+
});
|
|
1017
|
+
/**
|
|
1018
|
+
* Declares an atom: an addressable node with no text content. Its optional props
|
|
1019
|
+
* decode at the same boundary as a `node`'s, so an `Image` is an atom carrying a
|
|
1020
|
+
* source rather than a run holder.
|
|
1021
|
+
*/
|
|
1022
|
+
const atom = (name, options = {}) => ({
|
|
1023
|
+
name,
|
|
1024
|
+
kind: "atom",
|
|
1025
|
+
children: "none",
|
|
1026
|
+
props: options.Props
|
|
1027
|
+
});
|
|
1028
|
+
/**
|
|
1029
|
+
* Declares an application node kind: a `Node` block whose props this schema
|
|
1030
|
+
* validates and whose content the `children` declaration states — a mode, or block
|
|
1031
|
+
* content restricted to the kinds `blocksOf` names. `marks: 'none'` forbids marks on
|
|
1032
|
+
* its runs. The document codec keeps those props as JSON; the Kit is where an
|
|
1033
|
+
* application's types meet them.
|
|
1034
|
+
*/
|
|
1035
|
+
const node = (name, options = {}) => ({
|
|
1036
|
+
name,
|
|
1037
|
+
kind: "node",
|
|
1038
|
+
children: options.children ?? "text",
|
|
1039
|
+
marks: options.marks ?? "all",
|
|
1040
|
+
props: options.Props,
|
|
1041
|
+
isolating: options.isolating ?? false,
|
|
1042
|
+
splitProps: options.splitProps,
|
|
1043
|
+
within: options.within
|
|
1044
|
+
});
|
|
1045
|
+
const kit = (definition) => Object.freeze({
|
|
1046
|
+
nodes: [...definition.nodes],
|
|
1047
|
+
marks: [...definition.marks]
|
|
1048
|
+
});
|
|
1049
|
+
/** Whether a block is held as a built-in block or as an application node. */
|
|
1050
|
+
const heldShape = (block) => block.type === "Node" ? "node" : "block";
|
|
1051
|
+
/**
|
|
1052
|
+
* The content a block actually holds. An empty application node is `either`: the
|
|
1053
|
+
* document cannot say whether it is an atom or a run holder that happens to have
|
|
1054
|
+
* no runs, so a declaration of either kind agrees with it.
|
|
1055
|
+
*/
|
|
1056
|
+
const heldContent = (block) => {
|
|
1057
|
+
if (block.type !== "Node") return "text";
|
|
1058
|
+
if (block.blocks !== void 0) return "blocks";
|
|
1059
|
+
return block.children.length > 0 ? "text" : "either";
|
|
1060
|
+
};
|
|
1061
|
+
/** The content mode a declaration names, or `'none'` for an atom. */
|
|
1062
|
+
const declaredContent = (definition) => definition.kind === "atom" ? "none" : typeof definition.children === "string" ? definition.children : blockContent;
|
|
1063
|
+
/**
|
|
1064
|
+
* Whether a declared definition agrees with the block it is declared for, and
|
|
1065
|
+
* why not. A `block` declaration expects a built-in block and a `node` or `atom`
|
|
1066
|
+
* one expects an application node; then the declared content mode must match what
|
|
1067
|
+
* the block holds, which is what makes an atom's no-children rule real.
|
|
1068
|
+
*/
|
|
1069
|
+
const definitionMismatch = (definition, block) => {
|
|
1070
|
+
const expected = definition.kind === "block" ? "block" : "node";
|
|
1071
|
+
const held = heldShape(block);
|
|
1072
|
+
if (held !== expected) return `"${definition.name}" is declared as ${definition.kind}, but the document holds it as ${held}`;
|
|
1073
|
+
const declared = declaredContent(definition);
|
|
1074
|
+
const content = heldContent(block);
|
|
1075
|
+
return (content === "either" ? declared !== "blocks" : declared === content) ? void 0 : `"${definition.name}" is declared to hold ${declared}, but the document holds ${content}`;
|
|
1076
|
+
};
|
|
1077
|
+
/**
|
|
1078
|
+
* A block's semantic kind: an application node's declared kind, a preserved node's
|
|
1079
|
+
* original type, or a built-in block's own type. This is what a `blocksOf`
|
|
1080
|
+
* constraint names, and what a `NodeRegistry` is looked up by.
|
|
1081
|
+
*/
|
|
1082
|
+
const blockKind = (block) => block.type === "Node" ? block.kind : block.type === "Unknown" ? block.originalType : block.type;
|
|
1083
|
+
/**
|
|
1084
|
+
* The children a constrained kind does not accept. A declaration without a
|
|
1085
|
+
* constraint accepts any block, and a block that holds runs has no children to
|
|
1086
|
+
* check; `definitionMismatch` is what reports the mode itself.
|
|
1087
|
+
*/
|
|
1088
|
+
const childKindDiagnostics = (definition, block) => {
|
|
1089
|
+
if (definition.kind !== "node" || typeof definition.children === "string") return [];
|
|
1090
|
+
if (block.type !== "Node" || block.blocks === void 0) return [];
|
|
1091
|
+
const allowed = definition.children.of;
|
|
1092
|
+
const permitted = new Set(allowed);
|
|
1093
|
+
return block.blocks.filter((child) => !permitted.has(blockKind(child))).map((child) => ({
|
|
1094
|
+
code: "UnexpectedChild",
|
|
1095
|
+
node: child.id,
|
|
1096
|
+
detail: blockKind(child),
|
|
1097
|
+
message: `"${block.kind}" accepts only ${allowed.join(", ")}`
|
|
1098
|
+
}));
|
|
1099
|
+
};
|
|
1100
|
+
/**
|
|
1101
|
+
* Whether a kind may stand in a parent of `parentKind`, or at the top level when that is
|
|
1102
|
+
* undefined: anywhere, unless its declaration names where (§149).
|
|
1103
|
+
*/
|
|
1104
|
+
const standsWithin = (declared, parentKind) => declared?.kind !== "node" || declared.within === void 0 || parentKind !== void 0 && declared.within.includes(parentKind);
|
|
1105
|
+
/** Structural summary of a Kit, for tooling and tests. */
|
|
1106
|
+
const inspectKit = (definition) => ({
|
|
1107
|
+
blocks: definition.nodes.filter((node) => node.kind === "block").length,
|
|
1108
|
+
atoms: definition.nodes.filter((node) => node.kind === "atom").length,
|
|
1109
|
+
nodes: definition.nodes.filter((node) => node.kind === "node").length,
|
|
1110
|
+
marks: definition.marks.length
|
|
1111
|
+
});
|
|
1112
|
+
/** Builds the registry an edit consults. A later declaration for a name wins, as a Map does. */
|
|
1113
|
+
const nodeRegistry = (definitions) => {
|
|
1114
|
+
const byName = new Map(definitions.map((definition) => [definition.name, definition]));
|
|
1115
|
+
return Object.freeze({ definitionFor: (kind) => byName.get(kind) });
|
|
1116
|
+
};
|
|
1117
|
+
/**
|
|
1118
|
+
* Checks a document against a Kit's vocabulary without changing it, walking
|
|
1119
|
+
* nested blocks so a container's children are checked too. Reports preserved
|
|
1120
|
+
* unknown blocks, known blocks the Kit does not declare, declarations that
|
|
1121
|
+
* disagree with how the document holds a block, application nodes whose props
|
|
1122
|
+
* their schema refuses, and marks outside the Kit or whose props their definition
|
|
1123
|
+
* refuses. Content diagnostics never strip or repair the document; callers decide
|
|
1124
|
+
* whether to block publishing or surface a placeholder.
|
|
1125
|
+
*/
|
|
1126
|
+
const validate = (document, definition) => {
|
|
1127
|
+
const byName = new Map(definition.nodes.map((node) => [node.name, node]));
|
|
1128
|
+
const declaredMarks = new Map(definition.marks.map((mark) => [mark.name, mark]));
|
|
1129
|
+
const diagnostics = [];
|
|
1130
|
+
eachBlock(document.children, (block, path) => {
|
|
1131
|
+
if (block.type === "Unknown") {
|
|
1132
|
+
diagnostics.push({
|
|
1133
|
+
code: "UnknownNode",
|
|
1134
|
+
node: block.id,
|
|
1135
|
+
detail: block.originalType,
|
|
1136
|
+
message: `Unimplemented node type "${block.originalType}"`
|
|
1137
|
+
});
|
|
1138
|
+
return;
|
|
1139
|
+
}
|
|
1140
|
+
const kind = blockKind(block);
|
|
1141
|
+
const declared = byName.get(kind);
|
|
1142
|
+
if (declared === void 0) diagnostics.push({
|
|
1143
|
+
code: "UnsupportedNode",
|
|
1144
|
+
node: block.id,
|
|
1145
|
+
detail: kind,
|
|
1146
|
+
message: `The Kit does not declare ${block.type === "Node" ? "node " : ""}"${kind}"`
|
|
1147
|
+
});
|
|
1148
|
+
else {
|
|
1149
|
+
const mismatch = definitionMismatch(declared, block);
|
|
1150
|
+
if (mismatch !== void 0) diagnostics.push({
|
|
1151
|
+
code: "MismatchedDefinition",
|
|
1152
|
+
node: block.id,
|
|
1153
|
+
detail: kind,
|
|
1154
|
+
message: mismatch
|
|
1155
|
+
});
|
|
1156
|
+
else {
|
|
1157
|
+
if (block.type === "Node" && declared.kind !== "block" && propsFailure(declared.props, block.props)) diagnostics.push({
|
|
1158
|
+
code: "InvalidProps",
|
|
1159
|
+
node: block.id,
|
|
1160
|
+
detail: kind,
|
|
1161
|
+
message: `"${kind}" props do not match its declared schema`
|
|
1162
|
+
});
|
|
1163
|
+
diagnostics.push(...childKindDiagnostics(declared, block));
|
|
1164
|
+
const parent = path.length > 1 ? blockAtPath(document, path.slice(0, -1)) : void 0;
|
|
1165
|
+
const parentKind = parent === void 0 ? void 0 : blockKind(parent);
|
|
1166
|
+
if (!standsWithin(declared, parentKind)) diagnostics.push({
|
|
1167
|
+
code: "MisplacedNode",
|
|
1168
|
+
node: block.id,
|
|
1169
|
+
detail: kind,
|
|
1170
|
+
message: `"${kind}" cannot stand ${parentKind === void 0 ? "at the top level" : `in "${parentKind}"`}`
|
|
1171
|
+
});
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
const forbidsMarks = declared?.kind === "node" && declared.marks === "none";
|
|
1175
|
+
for (const run of block.children) for (const mark of run.marks) {
|
|
1176
|
+
const name = markName(mark);
|
|
1177
|
+
if (forbidsMarks) diagnostics.push({
|
|
1178
|
+
code: "ForbiddenMark",
|
|
1179
|
+
node: run.id,
|
|
1180
|
+
detail: name,
|
|
1181
|
+
message: `"${kind}" accepts no marks`
|
|
1182
|
+
});
|
|
1183
|
+
const declaredMark = declaredMarks.get(name);
|
|
1184
|
+
if (declaredMark === void 0) diagnostics.push({
|
|
1185
|
+
code: "UnknownMark",
|
|
1186
|
+
node: run.id,
|
|
1187
|
+
detail: name,
|
|
1188
|
+
message: `The Kit does not declare mark "${name}"`
|
|
1189
|
+
});
|
|
1190
|
+
else if (propsFailure(declaredMark.Props, markProps(mark))) diagnostics.push({
|
|
1191
|
+
code: "InvalidProps",
|
|
1192
|
+
node: run.id,
|
|
1193
|
+
detail: name,
|
|
1194
|
+
message: `"${name}" props do not match its declared schema`
|
|
1195
|
+
});
|
|
1196
|
+
}
|
|
1197
|
+
});
|
|
1198
|
+
return diagnostics;
|
|
1199
|
+
};
|
|
1200
|
+
//#endregion
|
|
756
1201
|
//#region src/transform.ts
|
|
757
1202
|
/** A transform that found nothing to do. */
|
|
758
1203
|
const unchanged = (document) => ({
|
|
@@ -770,9 +1215,9 @@ const mergeRunInto = (accumulator, run) => ({
|
|
|
770
1215
|
});
|
|
771
1216
|
/**
|
|
772
1217
|
* Merges adjacent runs whose mark sets match, within the blocks the transaction
|
|
773
|
-
* touched. Merging strictly reduces the run count, so one pass reaches
|
|
774
|
-
* state and a second pass finds nothing: the rule is idempotent, and only
|
|
775
|
-
* mark sets merge, so an unknown mark never drops.
|
|
1218
|
+
* touched, at any depth. Merging strictly reduces the run count, so one pass reaches
|
|
1219
|
+
* a stable state and a second pass finds nothing: the rule is idempotent, and only
|
|
1220
|
+
* equal mark sets merge, so an unknown mark never drops.
|
|
776
1221
|
*/
|
|
777
1222
|
const mergeAdjacentRuns = {
|
|
778
1223
|
name: "mergeAdjacentRuns",
|
|
@@ -781,14 +1226,9 @@ const mergeAdjacentRuns = {
|
|
|
781
1226
|
const removedNodes = /* @__PURE__ */ new Set();
|
|
782
1227
|
const dirtyNodes = /* @__PURE__ */ new Set();
|
|
783
1228
|
const textChanged = /* @__PURE__ */ new Set();
|
|
784
|
-
|
|
785
|
-
const blockIndexes = new Map(document.children.map((block, index) => [block.id, index]));
|
|
786
|
-
for (const blockId of context.dirtyNodes) {
|
|
787
|
-
const blockIndex = blockIndexes.get(blockId);
|
|
788
|
-
if (blockIndex === void 0) continue;
|
|
789
|
-
const block = next.children[blockIndex];
|
|
1229
|
+
const mergeRuns = (block) => {
|
|
790
1230
|
const first = block.children[0];
|
|
791
|
-
if (first === void 0)
|
|
1231
|
+
if (!context.dirtyNodes.has(block.id) || first === void 0) return block;
|
|
792
1232
|
let accumulator = first;
|
|
793
1233
|
let changed = false;
|
|
794
1234
|
const kept = [accumulator];
|
|
@@ -809,19 +1249,33 @@ const mergeAdjacentRuns = {
|
|
|
809
1249
|
accumulator = run;
|
|
810
1250
|
kept.push(run);
|
|
811
1251
|
}
|
|
812
|
-
|
|
813
|
-
const blocks = [...next.children];
|
|
814
|
-
blocks[blockIndex] = {
|
|
1252
|
+
return changed ? {
|
|
815
1253
|
...block,
|
|
816
1254
|
children: kept
|
|
817
|
-
};
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
1255
|
+
} : block;
|
|
1256
|
+
};
|
|
1257
|
+
const mergeWithin = (blocks) => {
|
|
1258
|
+
let changed = false;
|
|
1259
|
+
const next = blocks.map((block) => {
|
|
1260
|
+
let merged = mergeRuns(block);
|
|
1261
|
+
if (merged.type === "Node" && merged.blocks !== void 0) {
|
|
1262
|
+
const nested = mergeWithin(merged.blocks);
|
|
1263
|
+
if (nested !== merged.blocks) merged = {
|
|
1264
|
+
...merged,
|
|
1265
|
+
blocks: nested
|
|
1266
|
+
};
|
|
1267
|
+
}
|
|
1268
|
+
if (merged !== block) changed = true;
|
|
1269
|
+
return merged;
|
|
1270
|
+
});
|
|
1271
|
+
return changed ? next : blocks;
|
|
1272
|
+
};
|
|
1273
|
+
const children = mergeWithin(document.children);
|
|
823
1274
|
return {
|
|
824
|
-
document:
|
|
1275
|
+
document: children === document.children ? document : {
|
|
1276
|
+
...document,
|
|
1277
|
+
children
|
|
1278
|
+
},
|
|
825
1279
|
steps,
|
|
826
1280
|
insertedNodes: /* @__PURE__ */ new Set(),
|
|
827
1281
|
removedNodes,
|
|
@@ -883,9 +1337,12 @@ const MoveNodeOperation = Schema.Struct({
|
|
|
883
1337
|
/** The block list to move into: a node block's, or the document's when absent. */
|
|
884
1338
|
parent: Schema.optionalKey(NodeId)
|
|
885
1339
|
});
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
1340
|
+
/**
|
|
1341
|
+
* What a text block retypes to: a paragraph, or a heading at a level. Its runs are
|
|
1342
|
+
* its own and survive the change; only the block's type does not.
|
|
1343
|
+
*/
|
|
1344
|
+
const TextBlock = Schema.Union([Schema.Struct({ type: Schema.Literal("Paragraph") }), Schema.Struct({
|
|
1345
|
+
type: Schema.Literal("Heading"),
|
|
889
1346
|
level: Schema.Literals([
|
|
890
1347
|
1,
|
|
891
1348
|
2,
|
|
@@ -894,6 +1351,41 @@ const SetNodePropsOperation = Schema.Struct({
|
|
|
894
1351
|
5,
|
|
895
1352
|
6
|
|
896
1353
|
])
|
|
1354
|
+
})]);
|
|
1355
|
+
/**
|
|
1356
|
+
* What a block becomes, under its own identity and with its own content: a block that holds
|
|
1357
|
+
* text becomes a paragraph, a heading, or an application node kind that holds text, such as a
|
|
1358
|
+
* code block, keeping its runs; a node that holds blocks becomes another node kind, keeping
|
|
1359
|
+
* its nested blocks, as a list item becomes a task.
|
|
1360
|
+
*/
|
|
1361
|
+
const RetypeTarget = Schema.Union([
|
|
1362
|
+
Schema.Struct({ type: Schema.Literal("Paragraph") }),
|
|
1363
|
+
Schema.Struct({
|
|
1364
|
+
type: Schema.Literal("Heading"),
|
|
1365
|
+
level: Schema.Literals([
|
|
1366
|
+
1,
|
|
1367
|
+
2,
|
|
1368
|
+
3,
|
|
1369
|
+
4,
|
|
1370
|
+
5,
|
|
1371
|
+
6
|
|
1372
|
+
])
|
|
1373
|
+
}),
|
|
1374
|
+
Schema.Struct({
|
|
1375
|
+
type: Schema.Literal("Node"),
|
|
1376
|
+
kind: Schema.NonEmptyString,
|
|
1377
|
+
props: Schema.JsonObject
|
|
1378
|
+
})
|
|
1379
|
+
]);
|
|
1380
|
+
const RetypeBlockOperation = Schema.Struct({
|
|
1381
|
+
type: Schema.Literal("RetypeBlock"),
|
|
1382
|
+
node: NodeId,
|
|
1383
|
+
to: RetypeTarget
|
|
1384
|
+
});
|
|
1385
|
+
const SetPropsOperation = Schema.Struct({
|
|
1386
|
+
type: Schema.Literal("SetProps"),
|
|
1387
|
+
node: NodeId,
|
|
1388
|
+
props: Schema.JsonObject
|
|
897
1389
|
});
|
|
898
1390
|
const InsertNodeOperation = Schema.Struct({
|
|
899
1391
|
type: Schema.Literal("InsertNode"),
|
|
@@ -921,7 +1413,8 @@ const Operation = Schema.Union([
|
|
|
921
1413
|
SplitNodeOperation,
|
|
922
1414
|
JoinNodeOperation,
|
|
923
1415
|
MoveNodeOperation,
|
|
924
|
-
|
|
1416
|
+
RetypeBlockOperation,
|
|
1417
|
+
SetPropsOperation,
|
|
925
1418
|
InsertNodeOperation,
|
|
926
1419
|
DeleteNodeOperation,
|
|
927
1420
|
SplitRunOperation
|
|
@@ -985,10 +1478,16 @@ const Edit = {
|
|
|
985
1478
|
to,
|
|
986
1479
|
...parent === void 0 ? {} : { parent: targetId(parent) }
|
|
987
1480
|
}),
|
|
988
|
-
|
|
989
|
-
type: "
|
|
1481
|
+
retypeBlock: (node, to) => RetypeBlockOperation.make({
|
|
1482
|
+
type: "RetypeBlock",
|
|
990
1483
|
node: targetId(node),
|
|
991
|
-
|
|
1484
|
+
to
|
|
1485
|
+
}),
|
|
1486
|
+
/** Sets the named props of a node block; props it does not name keep their values. */
|
|
1487
|
+
setProps: (node, props) => SetPropsOperation.make({
|
|
1488
|
+
type: "SetProps",
|
|
1489
|
+
node: targetId(node),
|
|
1490
|
+
props
|
|
992
1491
|
}),
|
|
993
1492
|
insertBlock: (block, at, parent) => InsertNodeOperation.make({
|
|
994
1493
|
type: "InsertNode",
|
|
@@ -1059,7 +1558,6 @@ const mapThrough = (selection, steps) => {
|
|
|
1059
1558
|
focus: mapPosition(selection.focus, steps)
|
|
1060
1559
|
};
|
|
1061
1560
|
};
|
|
1062
|
-
const decodeState = Schema.decodeUnknownSync(EditorState, { onExcessProperty: "error" });
|
|
1063
1561
|
const decodeTransaction = Schema.decodeUnknownSync(Transaction, { onExcessProperty: "error" });
|
|
1064
1562
|
const sameSelection = (left, right) => {
|
|
1065
1563
|
if (left === null || right === null) return left === right;
|
|
@@ -1076,6 +1574,27 @@ const nestedOf = (block) => block.type === "Node" && block.blocks !== void 0 ? b
|
|
|
1076
1574
|
*/
|
|
1077
1575
|
const pathKey = (path) => path.join(".");
|
|
1078
1576
|
const keyToPath = (key) => key === "" ? [] : key.split(".").map(Number);
|
|
1577
|
+
const indexes = /* @__PURE__ */ new WeakMap();
|
|
1578
|
+
/** Where each block and run sits, built once per document: documents are immutable. */
|
|
1579
|
+
const indexDocument = (document) => {
|
|
1580
|
+
const cached = indexes.get(document);
|
|
1581
|
+
if (cached !== void 0) return cached;
|
|
1582
|
+
const blockPaths = /* @__PURE__ */ new Map();
|
|
1583
|
+
const runPaths = /* @__PURE__ */ new Map();
|
|
1584
|
+
eachBlock(document.children, (block, path) => {
|
|
1585
|
+
blockPaths.set(block.id, path);
|
|
1586
|
+
for (const [runIndex, run] of block.children.entries()) runPaths.set(run.id, {
|
|
1587
|
+
path,
|
|
1588
|
+
index: runIndex
|
|
1589
|
+
});
|
|
1590
|
+
});
|
|
1591
|
+
const index = {
|
|
1592
|
+
blockPaths,
|
|
1593
|
+
runPaths
|
|
1594
|
+
};
|
|
1595
|
+
indexes.set(document, index);
|
|
1596
|
+
return index;
|
|
1597
|
+
};
|
|
1079
1598
|
/**
|
|
1080
1599
|
* Pure, atomic text transaction. Rejection returns no partially edited state.
|
|
1081
1600
|
* `transforms` defaults to the registry's shipped rules; a Kit's transforms
|
|
@@ -1083,7 +1602,7 @@ const keyToPath = (key) => key === "" ? [] : key.split(".").map(Number);
|
|
|
1083
1602
|
*/
|
|
1084
1603
|
const apply = (state, transaction, transforms = defaultTransforms) => {
|
|
1085
1604
|
try {
|
|
1086
|
-
|
|
1605
|
+
assertEditorState(state);
|
|
1087
1606
|
decodeTransaction(transaction);
|
|
1088
1607
|
} catch {
|
|
1089
1608
|
return {
|
|
@@ -1091,26 +1610,19 @@ const apply = (state, transaction, transforms = defaultTransforms) => {
|
|
|
1091
1610
|
error: "InvalidInput"
|
|
1092
1611
|
};
|
|
1093
1612
|
}
|
|
1094
|
-
const
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
blockPaths.set(block.id, path);
|
|
1099
|
-
for (const [runIndex, run] of block.children.entries()) runPaths.set(run.id, {
|
|
1100
|
-
path,
|
|
1101
|
-
index: runIndex
|
|
1102
|
-
});
|
|
1103
|
-
});
|
|
1104
|
-
return {
|
|
1105
|
-
blockPaths,
|
|
1106
|
-
runPaths
|
|
1107
|
-
};
|
|
1108
|
-
};
|
|
1109
|
-
let { blockPaths, runPaths } = indexDocument(state.document);
|
|
1613
|
+
const initial = indexDocument(state.document);
|
|
1614
|
+
let { blockPaths, runPaths } = initial;
|
|
1615
|
+
/** The index as this transaction's own copy, once `indexInserted` has written to it. */
|
|
1616
|
+
let owned;
|
|
1110
1617
|
const reindex = () => {
|
|
1111
1618
|
({blockPaths, runPaths} = indexDocument(document));
|
|
1619
|
+
owned = void 0;
|
|
1620
|
+
};
|
|
1621
|
+
const added = /* @__PURE__ */ new Set();
|
|
1622
|
+
const usedIds = {
|
|
1623
|
+
has: (id) => initial.runPaths.has(id) || initial.blockPaths.has(id) || added.has(id),
|
|
1624
|
+
add: (id) => void added.add(id)
|
|
1112
1625
|
};
|
|
1113
|
-
const usedIds = /* @__PURE__ */ new Set([...runPaths.keys(), ...blockPaths.keys()]);
|
|
1114
1626
|
let document = state.document;
|
|
1115
1627
|
const workingBlocks = /* @__PURE__ */ new Map();
|
|
1116
1628
|
const workingRuns = /* @__PURE__ */ new Map();
|
|
@@ -1145,6 +1657,29 @@ const apply = (state, transaction, transforms = defaultTransforms) => {
|
|
|
1145
1657
|
workingRuns.set(key, copy);
|
|
1146
1658
|
return copy;
|
|
1147
1659
|
};
|
|
1660
|
+
/**
|
|
1661
|
+
* Indexes a block just inserted at `at` in a container, and moves each later sibling's
|
|
1662
|
+
* subtree one place on, rather than indexing the whole document again: a paste inserts one
|
|
1663
|
+
* block at a time, and reindexing after each made it quadratic in the blocks pasted.
|
|
1664
|
+
*/
|
|
1665
|
+
const indexInserted = (containerPath, at) => {
|
|
1666
|
+
const index = owned ??= {
|
|
1667
|
+
blocks: new Map(blockPaths),
|
|
1668
|
+
runs: new Map(runPaths)
|
|
1669
|
+
};
|
|
1670
|
+
blockPaths = index.blocks;
|
|
1671
|
+
runPaths = index.runs;
|
|
1672
|
+
const record = (block, path) => {
|
|
1673
|
+
index.blocks.set(block.id, path);
|
|
1674
|
+
block.children.forEach((run, place) => index.runs.set(run.id, {
|
|
1675
|
+
path,
|
|
1676
|
+
index: place
|
|
1677
|
+
}));
|
|
1678
|
+
if (block.type === "Node" && block.blocks !== void 0) block.blocks.forEach((child, place) => record(child, [...path, place]));
|
|
1679
|
+
};
|
|
1680
|
+
const blocks = blocksAt(containerPath);
|
|
1681
|
+
for (let place = at; place < blocks.length; place++) record(blocks[place], [...containerPath, place]);
|
|
1682
|
+
};
|
|
1148
1683
|
const writeBlock = (path, block) => {
|
|
1149
1684
|
const container = ensureContainer(path.slice(0, -1));
|
|
1150
1685
|
container[path[path.length - 1]] = block;
|
|
@@ -1199,11 +1734,21 @@ const apply = (state, transaction, transforms = defaultTransforms) => {
|
|
|
1199
1734
|
const textChanged = /* @__PURE__ */ new Set();
|
|
1200
1735
|
let structureChanged = false;
|
|
1201
1736
|
const positionMap = [];
|
|
1737
|
+
/** `selectionIsValid` against the working document, read through the index this transaction keeps. */
|
|
1738
|
+
const selectionFits = (candidate) => {
|
|
1739
|
+
if (candidate === null) return true;
|
|
1740
|
+
if (candidate.type === "Node") return blockPaths.has(candidate.node) || runPaths.has(candidate.node);
|
|
1741
|
+
return [candidate.anchor, candidate.focus].every((position) => {
|
|
1742
|
+
const location = runPaths.get(position.node);
|
|
1743
|
+
const run = location === void 0 ? void 0 : runsAt(location.path)[location.index];
|
|
1744
|
+
return run !== void 0 && position.offset <= run.text.length;
|
|
1745
|
+
});
|
|
1746
|
+
};
|
|
1202
1747
|
for (let operationIndex = 0; operationIndex < transaction.length; operationIndex++) {
|
|
1203
1748
|
const operation = transaction[operationIndex];
|
|
1204
1749
|
if (operation.type === "SetSelection") {
|
|
1205
1750
|
materialize();
|
|
1206
|
-
if (!
|
|
1751
|
+
if (!selectionFits(operation.selection)) return {
|
|
1207
1752
|
ok: false,
|
|
1208
1753
|
error: "InvalidSelection"
|
|
1209
1754
|
};
|
|
@@ -1426,6 +1971,10 @@ const apply = (state, transaction, transforms = defaultTransforms) => {
|
|
|
1426
1971
|
ok: false,
|
|
1427
1972
|
error: target.error
|
|
1428
1973
|
};
|
|
1974
|
+
if (fromPath.every((index, depth) => target.path[depth] === index)) return {
|
|
1975
|
+
ok: false,
|
|
1976
|
+
error: "InvalidParent"
|
|
1977
|
+
};
|
|
1429
1978
|
const sourcePath = fromPath.slice(0, -1);
|
|
1430
1979
|
const fromIndex = fromPath[fromPath.length - 1];
|
|
1431
1980
|
const sameContainer = pathKey(sourcePath) === pathKey(target.path);
|
|
@@ -1437,61 +1986,109 @@ const apply = (state, transaction, transforms = defaultTransforms) => {
|
|
|
1437
1986
|
if (sameContainer && operation.to === fromIndex) continue;
|
|
1438
1987
|
const source = ensureContainer(sourcePath);
|
|
1439
1988
|
const [moved] = source.splice(fromIndex, 1);
|
|
1440
|
-
(sameContainer
|
|
1989
|
+
if (sameContainer) source.splice(operation.to, 0, moved);
|
|
1990
|
+
else {
|
|
1991
|
+
materialize();
|
|
1992
|
+
reindex();
|
|
1993
|
+
const destination = containerPathOf(operation.parent);
|
|
1994
|
+
if ("error" in destination) return {
|
|
1995
|
+
ok: false,
|
|
1996
|
+
error: destination.error
|
|
1997
|
+
};
|
|
1998
|
+
ensureContainer(destination.path).splice(operation.to, 0, moved);
|
|
1999
|
+
}
|
|
1441
2000
|
materialize();
|
|
1442
2001
|
reindex();
|
|
1443
2002
|
dirtyNodes.add(operation.node);
|
|
1444
2003
|
structureChanged = true;
|
|
1445
2004
|
continue;
|
|
1446
2005
|
}
|
|
1447
|
-
if (operation.type === "
|
|
2006
|
+
if (operation.type === "RetypeBlock") {
|
|
1448
2007
|
const path = blockPaths.get(operation.node);
|
|
1449
2008
|
if (path === void 0) return {
|
|
1450
2009
|
ok: false,
|
|
1451
2010
|
error: "MissingNode"
|
|
1452
2011
|
};
|
|
1453
2012
|
const target = blockAt(path);
|
|
1454
|
-
|
|
2013
|
+
const to = operation.to;
|
|
2014
|
+
const nested = target?.type === "Node" && target.blocks !== void 0;
|
|
2015
|
+
if (target === void 0 || target.type === "Unknown" || nested && to.type !== "Node") return {
|
|
1455
2016
|
ok: false,
|
|
1456
2017
|
error: "InvalidRange"
|
|
1457
2018
|
};
|
|
1458
|
-
if (target.level ===
|
|
1459
|
-
writeBlock(path, {
|
|
1460
|
-
|
|
1461
|
-
|
|
2019
|
+
if (to.type === "Paragraph" ? target.type === "Paragraph" : to.type === "Heading" ? target.type === "Heading" && target.level === to.level : target.type === "Node" && target.kind === to.kind && Equal.equals(target.props, to.props)) continue;
|
|
2020
|
+
writeBlock(path, to.type === "Paragraph" ? {
|
|
2021
|
+
type: "Paragraph",
|
|
2022
|
+
id: target.id,
|
|
2023
|
+
children: target.children
|
|
2024
|
+
} : to.type === "Heading" ? {
|
|
2025
|
+
type: "Heading",
|
|
2026
|
+
id: target.id,
|
|
2027
|
+
level: to.level,
|
|
2028
|
+
children: target.children
|
|
2029
|
+
} : {
|
|
2030
|
+
type: "Node",
|
|
2031
|
+
kind: to.kind,
|
|
2032
|
+
id: target.id,
|
|
2033
|
+
props: to.props,
|
|
2034
|
+
children: target.children,
|
|
2035
|
+
...nested ? { blocks: target.blocks } : {}
|
|
1462
2036
|
});
|
|
1463
2037
|
dirtyNodes.add(target.id);
|
|
1464
2038
|
structureChanged = true;
|
|
1465
2039
|
continue;
|
|
1466
2040
|
}
|
|
1467
|
-
if (operation.type === "
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
if ("error" in target) return {
|
|
2041
|
+
if (operation.type === "SetProps") {
|
|
2042
|
+
const path = blockPaths.get(operation.node);
|
|
2043
|
+
if (path === void 0) return {
|
|
1471
2044
|
ok: false,
|
|
1472
|
-
error:
|
|
2045
|
+
error: "MissingNode"
|
|
2046
|
+
};
|
|
2047
|
+
const target = blockAt(path);
|
|
2048
|
+
if (target?.type !== "Node") return {
|
|
2049
|
+
ok: false,
|
|
2050
|
+
error: "InvalidRange"
|
|
2051
|
+
};
|
|
2052
|
+
const props = {
|
|
2053
|
+
...target.props,
|
|
2054
|
+
...operation.props
|
|
2055
|
+
};
|
|
2056
|
+
if (Equal.equals(props, target.props)) continue;
|
|
2057
|
+
writeBlock(path, {
|
|
2058
|
+
...target,
|
|
2059
|
+
props
|
|
2060
|
+
});
|
|
2061
|
+
dirtyNodes.add(target.id);
|
|
2062
|
+
continue;
|
|
2063
|
+
}
|
|
2064
|
+
if (operation.type === "InsertNode") {
|
|
2065
|
+
const target = containerPathOf(operation.parent);
|
|
2066
|
+
if ("error" in target) return {
|
|
2067
|
+
ok: false,
|
|
2068
|
+
error: target.error
|
|
1473
2069
|
};
|
|
2070
|
+
const unshifted = new Set(Array.from({ length: target.path.length + 1 }, (_, depth) => pathKey(target.path.slice(0, depth))));
|
|
2071
|
+
if (workingRuns.size > 0 || [...workingBlocks.keys()].some((key) => !unshifted.has(key))) materialize();
|
|
1474
2072
|
if (operation.at > blocksAt(target.path).length) return {
|
|
1475
2073
|
ok: false,
|
|
1476
2074
|
error: "InvalidRange"
|
|
1477
2075
|
};
|
|
1478
|
-
const carried = [
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
2076
|
+
const carried = [];
|
|
2077
|
+
eachBlock([operation.block], (block) => {
|
|
2078
|
+
carried.push(block.id);
|
|
2079
|
+
for (const run of block.children) carried.push(run.id);
|
|
2080
|
+
});
|
|
1483
2081
|
if (new Set(carried).size !== carried.length || carried.some((id) => usedIds.has(id))) return {
|
|
1484
2082
|
ok: false,
|
|
1485
2083
|
error: "InvalidInput"
|
|
1486
2084
|
};
|
|
1487
2085
|
ensureContainer(target.path).splice(operation.at, 0, operation.block);
|
|
1488
|
-
materialize();
|
|
1489
2086
|
for (const id of carried) {
|
|
1490
2087
|
usedIds.add(id);
|
|
1491
2088
|
dirtyNodes.add(id);
|
|
1492
2089
|
insertedNodes.add(id);
|
|
1493
2090
|
}
|
|
1494
|
-
|
|
2091
|
+
indexInserted(target.path, operation.at);
|
|
1495
2092
|
structureChanged = true;
|
|
1496
2093
|
continue;
|
|
1497
2094
|
}
|
|
@@ -1673,11 +2270,84 @@ const apply = (state, transaction, transforms = defaultTransforms) => {
|
|
|
1673
2270
|
structureChanged,
|
|
1674
2271
|
selectionChanged: !sameSelection(selection, state.selection)
|
|
1675
2272
|
},
|
|
1676
|
-
positionMap
|
|
2273
|
+
positionMap,
|
|
2274
|
+
transactions: [transaction]
|
|
1677
2275
|
};
|
|
1678
2276
|
};
|
|
1679
2277
|
//#endregion
|
|
1680
2278
|
//#region src/command.ts
|
|
2279
|
+
/** Where `MoveBlock` puts a block: before or after a sibling, named by identity. */
|
|
2280
|
+
const Beside = Schema.Union([Schema.Struct({
|
|
2281
|
+
before: NodeId,
|
|
2282
|
+
after: Schema.optionalKey(Schema.Never)
|
|
2283
|
+
}), Schema.Struct({
|
|
2284
|
+
after: NodeId,
|
|
2285
|
+
before: Schema.optionalKey(Schema.Never)
|
|
2286
|
+
})]);
|
|
2287
|
+
/** A container a block is wrapped in: a node kind, and the props it starts with. */
|
|
2288
|
+
const Container = Schema.Struct({
|
|
2289
|
+
kind: Schema.NonEmptyString,
|
|
2290
|
+
props: Schema.optionalKey(Schema.JsonObject)
|
|
2291
|
+
});
|
|
2292
|
+
/**
|
|
2293
|
+
* Whether the block at a path is declared to carry no marks, in which case adding one
|
|
2294
|
+
* is refused at the command layer rather than reported only by `validate` (§125). A
|
|
2295
|
+
* preserved block is left alone: it has no declaration to read, and preserving it
|
|
2296
|
+
* matters more than forbidding a mark on it.
|
|
2297
|
+
*/
|
|
2298
|
+
const forbidsMarks = (document, path, nodes) => {
|
|
2299
|
+
if (nodes === void 0) return false;
|
|
2300
|
+
const block = blockAtPath(document, path);
|
|
2301
|
+
if (block === void 0 || block.type === "Unknown") return false;
|
|
2302
|
+
return kindForbidsMarks(nodes, blockKind(block));
|
|
2303
|
+
};
|
|
2304
|
+
const kindForbidsMarks = (nodes, kind) => {
|
|
2305
|
+
const declared = nodes.definitionFor(kind);
|
|
2306
|
+
return declared?.kind === "node" && declared.marks === "none";
|
|
2307
|
+
};
|
|
2308
|
+
/**
|
|
2309
|
+
* Whether the block at a path accepts a child of this kind. A declaration without a
|
|
2310
|
+
* constraint accepts any block, and a vocabulary that does not declare the parent is
|
|
2311
|
+
* not consulted — `validate` reports an undeclared kind, and an edit should not fail
|
|
2312
|
+
* for a reason the caller never stated.
|
|
2313
|
+
*/
|
|
2314
|
+
const acceptsChild = (document, path, kind, nodes) => {
|
|
2315
|
+
const parent = blockAtPath(document, path);
|
|
2316
|
+
return parent === void 0 || kindAccepts(nodes, blockKind(parent), kind);
|
|
2317
|
+
};
|
|
2318
|
+
/** Whether a kind's declaration lets it hold another as a nested block; undeclared is open. */
|
|
2319
|
+
const kindAccepts = (nodes, parentKind, childKind) => {
|
|
2320
|
+
if (nodes === void 0) return true;
|
|
2321
|
+
const declared = nodes.definitionFor(parentKind);
|
|
2322
|
+
if (declared?.kind !== "node" || typeof declared.children === "string") return true;
|
|
2323
|
+
return declared.children.of.includes(childKind);
|
|
2324
|
+
};
|
|
2325
|
+
/** Whether the vocabulary declares props for a new node that these do not decode as. */
|
|
2326
|
+
const refusesProps = (nodes, container) => {
|
|
2327
|
+
const declared = nodes?.definitionFor(container.kind);
|
|
2328
|
+
return declared !== void 0 && declared.kind !== "block" && propsFailure(declared.props, container.props ?? {});
|
|
2329
|
+
};
|
|
2330
|
+
/** Whether the vocabulary declares `kind` as a node that holds runs, as `CodeBlock` is. */
|
|
2331
|
+
const declaresText = (nodes, kind) => {
|
|
2332
|
+
const declared = nodes?.definitionFor(kind);
|
|
2333
|
+
return declared?.kind === "node" && declared.children === "text";
|
|
2334
|
+
};
|
|
2335
|
+
/** Whether the vocabulary names `itemKind` among the kinds `listKind` holds, as `List` names `ListItem`. */
|
|
2336
|
+
const holdsItem = (nodes, listKind, itemKind) => {
|
|
2337
|
+
const declared = nodes.definitionFor(listKind);
|
|
2338
|
+
return declared?.kind === "node" && typeof declared.children !== "string" && declared.children.of.includes(itemKind);
|
|
2339
|
+
};
|
|
2340
|
+
/**
|
|
2341
|
+
* Whether a kind can be a new container. Unlike an existing parent, a kind a wrap creates
|
|
2342
|
+
* must be declared as holding nested blocks when there is a vocabulary: wrapping in an
|
|
2343
|
+
* undeclared kind, or a text kind such as `CodeBlock`, would make content `validate`
|
|
2344
|
+
* refuses.
|
|
2345
|
+
*/
|
|
2346
|
+
const holdsBlocks$1 = (nodes, kind) => {
|
|
2347
|
+
if (nodes === void 0) return true;
|
|
2348
|
+
const declared = nodes.definitionFor(kind);
|
|
2349
|
+
return declared?.kind === "node" && declared.children !== "text";
|
|
2350
|
+
};
|
|
1681
2351
|
const failure = (error) => ({
|
|
1682
2352
|
ok: false,
|
|
1683
2353
|
error
|
|
@@ -1705,6 +2375,8 @@ const locate = (document, node) => {
|
|
|
1705
2375
|
};
|
|
1706
2376
|
};
|
|
1707
2377
|
const isCollapsed = (selection) => selection.anchor.node === selection.focus.node && selection.anchor.offset === selection.focus.offset;
|
|
2378
|
+
/** Whether a selection covers text: a range that is not a caret. What a mark or a link applies to. */
|
|
2379
|
+
const coversText = (selection) => selection?.type === "Range" && !isCollapsed(selection);
|
|
1708
2380
|
/** A caret is a range whose endpoints coincide; direction is not yet meaningful. */
|
|
1709
2381
|
const caretAt = (position) => ({
|
|
1710
2382
|
type: "Range",
|
|
@@ -1797,6 +2469,123 @@ const marksInRange = (document, selection) => {
|
|
|
1797
2469
|
}
|
|
1798
2470
|
return sharedMarks(covered(document, bounds.start, bounds.end).map((span) => span.run.marks));
|
|
1799
2471
|
};
|
|
2472
|
+
/**
|
|
2473
|
+
* The named mark on the run a position is in, and the adjacent runs of its block carrying
|
|
2474
|
+
* the same mark with the same props: the whole link a caret sits in, which is what a link
|
|
2475
|
+
* editor shows and what `SetMark` and `ClearMark` act on at a caret. Undefined when that
|
|
2476
|
+
* run does not carry the mark. A read, like `marksInRange`.
|
|
2477
|
+
*/
|
|
2478
|
+
const markExtent = (document, position, name) => {
|
|
2479
|
+
const found = locateRun(document, position.node);
|
|
2480
|
+
const mark = found?.run.marks.find((held) => markName(held) === name);
|
|
2481
|
+
if (found === void 0 || mark === void 0) return void 0;
|
|
2482
|
+
const runs = blockAtPath(document, found.path).children;
|
|
2483
|
+
const carries = (index) => runs[index]?.marks.some((held) => sameMark(held, mark)) === true;
|
|
2484
|
+
let first = found.index;
|
|
2485
|
+
while (carries(first - 1)) first--;
|
|
2486
|
+
let last = found.index;
|
|
2487
|
+
while (carries(last + 1)) last++;
|
|
2488
|
+
const end = runs[last];
|
|
2489
|
+
return {
|
|
2490
|
+
mark,
|
|
2491
|
+
selection: {
|
|
2492
|
+
type: "Range",
|
|
2493
|
+
anchor: {
|
|
2494
|
+
node: runs[first].id,
|
|
2495
|
+
offset: 0,
|
|
2496
|
+
affinity: "after"
|
|
2497
|
+
},
|
|
2498
|
+
focus: {
|
|
2499
|
+
node: end.id,
|
|
2500
|
+
offset: end.text.length,
|
|
2501
|
+
affinity: "before"
|
|
2502
|
+
}
|
|
2503
|
+
}
|
|
2504
|
+
};
|
|
2505
|
+
};
|
|
2506
|
+
/**
|
|
2507
|
+
* The text style of the block a selection starts in, in the shape `RetypeBlock` takes, so a
|
|
2508
|
+
* style picker compares what it would send with what is there. Undefined for a node
|
|
2509
|
+
* selection, one that resolves to nothing, or a block a retype does not reach, such as a code
|
|
2510
|
+
* block.
|
|
2511
|
+
*/
|
|
2512
|
+
const textBlockAt = (document, selection) => {
|
|
2513
|
+
if (selection?.type !== "Range") return void 0;
|
|
2514
|
+
const path = startPath(document, selection);
|
|
2515
|
+
const block = path === void 0 ? void 0 : blockAtPath(document, path);
|
|
2516
|
+
if (block?.type === "Paragraph") return { type: "Paragraph" };
|
|
2517
|
+
if (block?.type === "Heading") return {
|
|
2518
|
+
type: "Heading",
|
|
2519
|
+
level: block.level
|
|
2520
|
+
};
|
|
2521
|
+
};
|
|
2522
|
+
/**
|
|
2523
|
+
* Why block `moving` may not move into the container at `container` (§149), or undefined when
|
|
2524
|
+
* it may. Within its own container it always may. Elsewhere, the container must hold its kind,
|
|
2525
|
+
* the kind must stand in the container's kind (a `ListItem` only in a `List`), it may not leave
|
|
2526
|
+
* a container declared isolating, and it may not go inside itself.
|
|
2527
|
+
*/
|
|
2528
|
+
const moveFailure = (document, moving, container, nodes) => {
|
|
2529
|
+
if (moving.path.every((index, depth) => container[depth] === index)) return "InvalidParent";
|
|
2530
|
+
const source = moving.path.slice(0, -1);
|
|
2531
|
+
if (pathKey$1(source) === pathKey$1(container)) return void 0;
|
|
2532
|
+
const kind = blockKind(moving.block);
|
|
2533
|
+
const parent = container.length === 0 ? void 0 : blockAtPath(document, container);
|
|
2534
|
+
if (!acceptsChild(document, container, kind, nodes) || !standsWithin(nodes?.definitionFor(kind), parent === void 0 ? void 0 : blockKind(parent))) return "UnexpectedChild";
|
|
2535
|
+
for (let depth = source.length; depth > 0; depth--) {
|
|
2536
|
+
const holder = source.slice(0, depth);
|
|
2537
|
+
if (!holder.every((index, at) => container[at] === index) && isIsolating(document, holder, nodes)) return "InvalidParent";
|
|
2538
|
+
}
|
|
2539
|
+
};
|
|
2540
|
+
const isIsolating = (document, path, nodes) => {
|
|
2541
|
+
const block = blockAtPath(document, path);
|
|
2542
|
+
const declared = block === void 0 ? void 0 : nodes?.definitionFor(blockKind(block));
|
|
2543
|
+
return declared?.kind === "node" && declared.isolating === true;
|
|
2544
|
+
};
|
|
2545
|
+
/**
|
|
2546
|
+
* The outermost container a block leaving `source` empties, walking up while each held nothing
|
|
2547
|
+
* else: a list whose only item's only block moved out goes with it. Never the container it lands
|
|
2548
|
+
* in, or one holding that. An isolating one is never reached, since a move may not leave it.
|
|
2549
|
+
*/
|
|
2550
|
+
const emptiedBy = (document, source, container) => {
|
|
2551
|
+
let emptied;
|
|
2552
|
+
for (let path = source; path.length > 0; path = path.slice(0, -1)) {
|
|
2553
|
+
const block = blockAtPath(document, path);
|
|
2554
|
+
const holdsTarget = path.every((index, depth) => container[depth] === index);
|
|
2555
|
+
if (block?.type !== "Node" || (block.blocks?.length ?? 0) > 1 || holdsTarget) break;
|
|
2556
|
+
emptied = block.id;
|
|
2557
|
+
}
|
|
2558
|
+
return emptied;
|
|
2559
|
+
};
|
|
2560
|
+
/**
|
|
2561
|
+
* The blocks `node` may move beside, in document order (§149): the blocks of every container it
|
|
2562
|
+
* may move into, which is what a drag offers. Empty when the document does not hold it.
|
|
2563
|
+
*/
|
|
2564
|
+
const moveTargets = (document, node, nodes) => {
|
|
2565
|
+
const moving = locateBlock(document, node);
|
|
2566
|
+
if (moving === void 0) return [];
|
|
2567
|
+
const targets = [];
|
|
2568
|
+
eachBlock(document.children, (block, path) => {
|
|
2569
|
+
if (moveFailure(document, moving, path.slice(0, -1), nodes) === void 0) targets.push(block.id);
|
|
2570
|
+
});
|
|
2571
|
+
return targets;
|
|
2572
|
+
};
|
|
2573
|
+
/** Where a selection starts: its first run's block, or the block a node selection names. */
|
|
2574
|
+
const startPath = (document, selection) => {
|
|
2575
|
+
if (selection === null) return void 0;
|
|
2576
|
+
if (selection.type === "Node") return locateBlock(document, selection.node)?.path;
|
|
2577
|
+
const start = ordered(document, selection)?.start;
|
|
2578
|
+
return start === void 0 ? void 0 : locateRun(document, start.node)?.path;
|
|
2579
|
+
};
|
|
2580
|
+
/**
|
|
2581
|
+
* The blocks a selection starts in, outermost first: a caret in a list item's paragraph gives
|
|
2582
|
+
* the list, the item, and the paragraph. What a block handle picks from, and a breadcrumb draws.
|
|
2583
|
+
* Empty when the selection is null or resolves to nothing.
|
|
2584
|
+
*/
|
|
2585
|
+
const blocksAt = (document, selection) => {
|
|
2586
|
+
const path = startPath(document, selection) ?? [];
|
|
2587
|
+
return path.map((_, depth) => blockAtPath(document, path.slice(0, depth + 1)));
|
|
2588
|
+
};
|
|
1800
2589
|
/** The last run in a block's subtree, or undefined when it holds none. */
|
|
1801
2590
|
const lastRunOf = (block) => {
|
|
1802
2591
|
if (block.type === "Node" && block.blocks !== void 0) for (let index = block.blocks.length - 1; index >= 0; index--) {
|
|
@@ -1880,6 +2669,214 @@ const graphemeDeletion = (block, caret, runIndex, backward) => {
|
|
|
1880
2669
|
};
|
|
1881
2670
|
};
|
|
1882
2671
|
/**
|
|
2672
|
+
* The operations that lift a block out of its container, or `undefined` when it is at the
|
|
2673
|
+
* top level with nothing to leave. One step moves it into the container's parent: before
|
|
2674
|
+
* the container when it was first, after it when it was last, and between the two halves
|
|
2675
|
+
* of a split container when it was in the middle. A container it leaves empty is deleted.
|
|
2676
|
+
* Steps repeat while the vocabulary says the new parent does not hold the block's kind;
|
|
2677
|
+
* without a vocabulary, one step is taken. A container the vocabulary declares isolating is
|
|
2678
|
+
* never left, so a lift that would start by leaving one lifts nothing.
|
|
2679
|
+
*
|
|
2680
|
+
* Each step is computed against the document the steps before it produced, applied with no
|
|
2681
|
+
* normalization, because a split or a deletion moves the indices the next step reads.
|
|
2682
|
+
*/
|
|
2683
|
+
const liftOperations = (document, node, ids, nodes) => {
|
|
2684
|
+
const operations = [];
|
|
2685
|
+
let current = document;
|
|
2686
|
+
for (;;) {
|
|
2687
|
+
const found = locateBlock(current, node);
|
|
2688
|
+
if (found === void 0 || found.path.length === 1) break;
|
|
2689
|
+
const containerPath = found.path.slice(0, -1);
|
|
2690
|
+
const container = blockAtPath(current, containerPath);
|
|
2691
|
+
if (container?.type !== "Node" || container.blocks === void 0) break;
|
|
2692
|
+
const declared = nodes?.definitionFor(container.kind);
|
|
2693
|
+
if (declared?.kind === "node" && declared.isolating === true) break;
|
|
2694
|
+
const parentPath = containerPath.slice(0, -1);
|
|
2695
|
+
const parent = parentPath.length === 0 ? void 0 : blockAtPath(current, parentPath);
|
|
2696
|
+
const at = containerPath[containerPath.length - 1];
|
|
2697
|
+
const index = found.path[found.path.length - 1];
|
|
2698
|
+
const siblings = container.blocks;
|
|
2699
|
+
const step = [];
|
|
2700
|
+
if (index === 0) {
|
|
2701
|
+
step.push(Edit.moveBlock(node, at, parent?.id));
|
|
2702
|
+
if (siblings.length === 1) step.push(Edit.deleteBlock(container.id));
|
|
2703
|
+
} else if (index === siblings.length - 1) step.push(Edit.moveBlock(node, at + 1, parent?.id));
|
|
2704
|
+
else {
|
|
2705
|
+
const rest = NodeId.make(ids.mint());
|
|
2706
|
+
step.push(Edit.insertBlock({
|
|
2707
|
+
...container,
|
|
2708
|
+
id: rest,
|
|
2709
|
+
children: [],
|
|
2710
|
+
blocks: []
|
|
2711
|
+
}, at + 1, parent?.id), ...siblings.slice(index + 1).map((sibling, offset) => Edit.moveBlock(sibling.id, offset, rest)), Edit.moveBlock(node, at + 1, parent?.id));
|
|
2712
|
+
}
|
|
2713
|
+
const stepped = apply({
|
|
2714
|
+
document: current,
|
|
2715
|
+
selection: null
|
|
2716
|
+
}, step, []);
|
|
2717
|
+
if (!stepped.ok) throw new Error(`liftOperations: a lift step was refused (${stepped.error})`);
|
|
2718
|
+
operations.push(...step);
|
|
2719
|
+
current = stepped.state.document;
|
|
2720
|
+
if (parent === void 0 || kindAccepts(nodes, blockKind(parent), blockKind(found.block))) break;
|
|
2721
|
+
}
|
|
2722
|
+
return operations.length === 0 ? void 0 : operations;
|
|
2723
|
+
};
|
|
2724
|
+
/**
|
|
2725
|
+
* The item a block sits in, when the vocabulary says its container is one: a kind its own
|
|
2726
|
+
* parent declares it holds, as a `List` declares `ListItem`, and not isolating, as a table
|
|
2727
|
+
* cell is. Enter treats such a container as the unit it splits.
|
|
2728
|
+
*/
|
|
2729
|
+
const itemAround = (document, path, nodes) => {
|
|
2730
|
+
if (nodes === void 0) return void 0;
|
|
2731
|
+
const containerPath = path.slice(0, -1);
|
|
2732
|
+
const container = blockAtPath(document, containerPath);
|
|
2733
|
+
const list = blockAtPath(document, containerPath.slice(0, -1));
|
|
2734
|
+
if (container?.type !== "Node" || list?.type !== "Node") return void 0;
|
|
2735
|
+
const declaredItem = nodes.definitionFor(container.kind);
|
|
2736
|
+
const isolating = declaredItem?.kind === "node" && declaredItem.isolating === true;
|
|
2737
|
+
return holdsItem(nodes, list.kind, container.kind) && !isolating ? {
|
|
2738
|
+
container,
|
|
2739
|
+
containerPath,
|
|
2740
|
+
list
|
|
2741
|
+
} : void 0;
|
|
2742
|
+
};
|
|
2743
|
+
/**
|
|
2744
|
+
* Whether Enter in the block at `path`, over to `end`, leaves no heading text after the caret,
|
|
2745
|
+
* so the new block is a paragraph: what follows a title is text. Mid-heading, both halves stay
|
|
2746
|
+
* the heading they were. Over a range, what follows is what the removal leaves: the heading's
|
|
2747
|
+
* own rest when the range ends inside it, or the next block's text, which was never the
|
|
2748
|
+
* heading's, when it ends there.
|
|
2749
|
+
*/
|
|
2750
|
+
const endsHeading = (document, path, end) => {
|
|
2751
|
+
const block = blockAtPath(document, path);
|
|
2752
|
+
const endAt = locate(document, end.node);
|
|
2753
|
+
return block?.type === "Heading" && endAt !== void 0 && (pathKey$1(endAt.path) !== pathKey$1(path) || end.offset >= endAt.text.length && block.children.slice(endAt.runIndex + 1).every((run) => run.text.length === 0));
|
|
2754
|
+
};
|
|
2755
|
+
/**
|
|
2756
|
+
* Enter inside a list item. An empty block that is the item's whole content leaves the list,
|
|
2757
|
+
* as Backspace does. Otherwise the block splits and the second half, with every block after
|
|
2758
|
+
* it in the item, becomes a new item of the same kind and props right after this one.
|
|
2759
|
+
*/
|
|
2760
|
+
const splitItem = (state, at, offset, { container, containerPath, list }, ids, nodes) => {
|
|
2761
|
+
const blocks = container.blocks ?? [];
|
|
2762
|
+
const index = at.path[at.path.length - 1];
|
|
2763
|
+
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) ?? []);
|
|
2764
|
+
const textId = ids.mint();
|
|
2765
|
+
const blockId = ids.mint();
|
|
2766
|
+
const itemId = NodeId.make(ids.mint());
|
|
2767
|
+
const declared = nodes?.definitionFor(container.kind);
|
|
2768
|
+
const props = {
|
|
2769
|
+
...container.props,
|
|
2770
|
+
...declared?.kind === "node" ? declared.splitProps : {}
|
|
2771
|
+
};
|
|
2772
|
+
if (declared?.kind === "node" && propsFailure(declared.props, props)) return failure("InvalidInput");
|
|
2773
|
+
return apply(state, [
|
|
2774
|
+
Edit.splitBlock(at.blockId, at.id, offset, blockId, textId),
|
|
2775
|
+
...endsHeading(state.document, at.path, {
|
|
2776
|
+
node: at.id,
|
|
2777
|
+
offset,
|
|
2778
|
+
affinity: "after"
|
|
2779
|
+
}) ? [Edit.retypeBlock(NodeId.make(blockId), { type: "Paragraph" })] : [],
|
|
2780
|
+
Edit.insertBlock({
|
|
2781
|
+
...container,
|
|
2782
|
+
id: itemId,
|
|
2783
|
+
props,
|
|
2784
|
+
children: [],
|
|
2785
|
+
blocks: []
|
|
2786
|
+
}, containerPath[containerPath.length - 1] + 1, list.id),
|
|
2787
|
+
Edit.moveBlock(NodeId.make(blockId), 0, itemId),
|
|
2788
|
+
...blocks.slice(index + 1).map((later, position) => Edit.moveBlock(later.id, position + 1, itemId)),
|
|
2789
|
+
Edit.setSelection(caretAt({
|
|
2790
|
+
node: NodeId.make(textId),
|
|
2791
|
+
offset: 0,
|
|
2792
|
+
affinity: "after"
|
|
2793
|
+
}))
|
|
2794
|
+
]);
|
|
2795
|
+
};
|
|
2796
|
+
/**
|
|
2797
|
+
* A block-level intent acts on the block the selection starts in: the caret's own block,
|
|
2798
|
+
* or the first block of a range. Acting on every block a range covers would be a surprise,
|
|
2799
|
+
* and a menu or a marker is typed at a caret anyway.
|
|
2800
|
+
*/
|
|
2801
|
+
const startingBlock = (document, selection) => {
|
|
2802
|
+
const start = isCollapsed(selection) ? selection.anchor : ordered(document, selection)?.start;
|
|
2803
|
+
if (start === void 0) return { error: "InvalidSelection" };
|
|
2804
|
+
const at = locate(document, start.node);
|
|
2805
|
+
const block = at === void 0 ? void 0 : blockAtPath(document, at.path);
|
|
2806
|
+
if (at === void 0 || block === void 0) return { error: "MissingText" };
|
|
2807
|
+
const parentPath = at.path.slice(0, -1);
|
|
2808
|
+
return {
|
|
2809
|
+
block,
|
|
2810
|
+
path: at.path,
|
|
2811
|
+
parentPath,
|
|
2812
|
+
parent: parentPath.length === 0 ? void 0 : blockAtPath(document, parentPath),
|
|
2813
|
+
selection
|
|
2814
|
+
};
|
|
2815
|
+
};
|
|
2816
|
+
/**
|
|
2817
|
+
* Retype, wrap, convert, retype a container, and lift: each reshapes the starting block, or
|
|
2818
|
+
* the container holding it, where it stands.
|
|
2819
|
+
*/
|
|
2820
|
+
const runBlockCommand = (state, command, starting, ids, options) => {
|
|
2821
|
+
const { block, path, parentPath, parent } = starting;
|
|
2822
|
+
const index = path[path.length - 1];
|
|
2823
|
+
if (command.type === "LiftBlock") {
|
|
2824
|
+
const lifted = liftOperations(state.document, block.id, ids, options.nodes);
|
|
2825
|
+
return lifted === void 0 ? failure("InvalidInput") : apply(state, lifted);
|
|
2826
|
+
}
|
|
2827
|
+
if (command.type === "RetypeContainer") {
|
|
2828
|
+
if (parent?.type !== "Node" || parent.blocks === void 0 || index !== 0) return failure("InvalidInput");
|
|
2829
|
+
const { kind } = command.to;
|
|
2830
|
+
if (refusesProps(options.nodes, command.to)) return failure("InvalidInput");
|
|
2831
|
+
const outerPath = parentPath.slice(0, -1);
|
|
2832
|
+
const outer = outerPath.length === 0 ? void 0 : blockAtPath(state.document, outerPath);
|
|
2833
|
+
const declared = options.nodes?.definitionFor(kind);
|
|
2834
|
+
if (!(holdsBlocks$1(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");
|
|
2835
|
+
return apply(state, [Edit.retypeBlock(parent.id, {
|
|
2836
|
+
type: "Node",
|
|
2837
|
+
kind,
|
|
2838
|
+
props: command.to.props ?? {}
|
|
2839
|
+
})]);
|
|
2840
|
+
}
|
|
2841
|
+
if (command.type === "RetypeBlock") {
|
|
2842
|
+
if (!acceptsChild(state.document, parentPath, command.to.type, options.nodes)) return failure("UnexpectedChild");
|
|
2843
|
+
if (block.type !== "Paragraph" && block.type !== "Heading" && (block.type !== "Node" || !declaresText(options.nodes, block.kind))) return failure("InvalidInput");
|
|
2844
|
+
return apply(state, [Edit.retypeBlock(block.id, command.to)]);
|
|
2845
|
+
}
|
|
2846
|
+
if (command.type === "WrapBlock") {
|
|
2847
|
+
const [outer] = command.containers;
|
|
2848
|
+
if (outer === void 0) return failure("InvalidInput");
|
|
2849
|
+
if (command.containers.some((container) => refusesProps(options.nodes, container))) return failure("InvalidInput");
|
|
2850
|
+
const kinds = [...command.containers.map((container) => container.kind), blockKind(block)];
|
|
2851
|
+
const parentKind = parent === void 0 ? void 0 : blockKind(parent);
|
|
2852
|
+
if (!(acceptsChild(state.document, parentPath, outer.kind, options.nodes) && command.containers.every((container, at) => holdsBlocks$1(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");
|
|
2853
|
+
const before = (parent === void 0 ? state.document.children : parent.type === "Node" ? parent.blocks ?? [] : [])[index - 1];
|
|
2854
|
+
const item = command.containers[1];
|
|
2855
|
+
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 ?? {});
|
|
2856
|
+
const created = joins ? command.containers.slice(1) : command.containers;
|
|
2857
|
+
const containerIds = created.map(() => NodeId.make(ids.mint()));
|
|
2858
|
+
const chain = created.reduceRight((inner, container, at) => ({
|
|
2859
|
+
type: "Node",
|
|
2860
|
+
kind: container.kind,
|
|
2861
|
+
id: containerIds[at],
|
|
2862
|
+
props: container.props ?? {},
|
|
2863
|
+
children: [],
|
|
2864
|
+
blocks: inner === void 0 ? [] : [inner]
|
|
2865
|
+
}), void 0);
|
|
2866
|
+
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])]);
|
|
2867
|
+
}
|
|
2868
|
+
if (block.type !== "Paragraph" && block.type !== "Heading") return failure("InvalidInput");
|
|
2869
|
+
const kind = command.to.kind;
|
|
2870
|
+
if (refusesProps(options.nodes, command.to)) return failure("InvalidInput");
|
|
2871
|
+
if (!(options.nodes === void 0 || declaresText(options.nodes, kind)) || !acceptsChild(state.document, parentPath, kind, options.nodes)) return failure("UnexpectedChild");
|
|
2872
|
+
if (options.nodes !== void 0 && kindForbidsMarks(options.nodes, kind) && block.children.some((run) => run.marks.length > 0)) return failure("ForbiddenMark");
|
|
2873
|
+
return apply(state, [Edit.retypeBlock(block.id, {
|
|
2874
|
+
type: "Node",
|
|
2875
|
+
kind,
|
|
2876
|
+
props: command.to.props ?? {}
|
|
2877
|
+
})]);
|
|
2878
|
+
};
|
|
2879
|
+
/**
|
|
1883
2880
|
* Resolves one intent into a transaction and applies it atomically. Commands
|
|
1884
2881
|
* describe intent; the returned `positionMap` and `ChangeSet` describe the
|
|
1885
2882
|
* document effect, and rejection returns no partially edited state.
|
|
@@ -1887,6 +2884,46 @@ const graphemeDeletion = (block, caret, runIndex, backward) => {
|
|
|
1887
2884
|
const run = (state, command, ids, options = {}) => {
|
|
1888
2885
|
const declared = options.marks ?? shippedRegistry;
|
|
1889
2886
|
if (command.type === "SetSelection") return apply(state, [Edit.setSelection(command.selection)]);
|
|
2887
|
+
if (command.type === "SetProps") {
|
|
2888
|
+
const target = locateBlock(state.document, command.node)?.block;
|
|
2889
|
+
if (target?.type !== "Node") return failure("InvalidInput");
|
|
2890
|
+
const refuses = (props) => refusesProps(options.nodes, {
|
|
2891
|
+
kind: target.kind,
|
|
2892
|
+
props
|
|
2893
|
+
});
|
|
2894
|
+
if (refuses({
|
|
2895
|
+
...target.props,
|
|
2896
|
+
...command.props
|
|
2897
|
+
}) && !refuses(target.props)) return failure("InvalidInput");
|
|
2898
|
+
return apply(state, [Edit.setProps(command.node, command.props)]);
|
|
2899
|
+
}
|
|
2900
|
+
if (command.type === "MoveBlock") {
|
|
2901
|
+
const moving = locateBlock(state.document, command.node);
|
|
2902
|
+
const beside = locateBlock(state.document, "before" in command.to ? command.to.before : command.to.after);
|
|
2903
|
+
if (moving === void 0 || beside === void 0) return failure("InvalidInput");
|
|
2904
|
+
const container = beside.path.slice(0, -1);
|
|
2905
|
+
const refused = moveFailure(state.document, moving, container, options.nodes);
|
|
2906
|
+
if (refused !== void 0) return failure(refused);
|
|
2907
|
+
const source = moving.path.slice(0, -1);
|
|
2908
|
+
const within = pathKey$1(source) === pathKey$1(container);
|
|
2909
|
+
const from = moving.path[moving.path.length - 1];
|
|
2910
|
+
const place = beside.path[beside.path.length - 1] + ("after" in command.to ? 1 : 0);
|
|
2911
|
+
const to = within && from < place ? place - 1 : place;
|
|
2912
|
+
const parent = container.length === 0 ? void 0 : blockAtPath(state.document, container)?.id;
|
|
2913
|
+
const emptied = emptiedBy(state.document, source, container);
|
|
2914
|
+
const gone = emptied === void 0 ? void 0 : locateBlock(state.document, emptied);
|
|
2915
|
+
const selected = state.selection?.type === "Node" ? locateBlock(state.document, state.selection.node) : void 0;
|
|
2916
|
+
const inside = (path, holder) => holder.every((index, depth) => path[depth] === index);
|
|
2917
|
+
const lost = gone !== void 0 && selected !== void 0 && inside(selected.path, gone.path) && !inside(selected.path, moving.path);
|
|
2918
|
+
return apply(state, [
|
|
2919
|
+
Edit.moveBlock(command.node, to, parent),
|
|
2920
|
+
...emptied === void 0 ? [] : [Edit.deleteBlock(emptied)],
|
|
2921
|
+
...lost ? [Edit.setSelection({
|
|
2922
|
+
type: "Node",
|
|
2923
|
+
node: command.node
|
|
2924
|
+
})] : []
|
|
2925
|
+
]);
|
|
2926
|
+
}
|
|
1890
2927
|
const selection = state.selection;
|
|
1891
2928
|
if (selection === null || selection.type === "Node") return failure("InvalidSelection");
|
|
1892
2929
|
if (command.type === "InsertText") {
|
|
@@ -1896,9 +2933,12 @@ const run = (state, command, ids, options = {}) => {
|
|
|
1896
2933
|
const at = locate(state.document, target.node);
|
|
1897
2934
|
if (at === void 0) return failure("MissingText");
|
|
1898
2935
|
const marks = [];
|
|
1899
|
-
if (stored !== void 0)
|
|
1900
|
-
|
|
1901
|
-
|
|
2936
|
+
if (stored !== void 0) {
|
|
2937
|
+
for (const mark of stored) {
|
|
2938
|
+
if (!declared.accepts(mark)) return failure("InvalidInput");
|
|
2939
|
+
marks.push(mark);
|
|
2940
|
+
}
|
|
2941
|
+
if (marks.length > 0 && forbidsMarks(state.document, at.path, options.nodes)) return failure("ForbiddenMark");
|
|
1902
2942
|
}
|
|
1903
2943
|
const deletions = isCollapsed(selection) ? [] : deleteRange(state.document, target, ordered(state.document, selection).end);
|
|
1904
2944
|
if (deletions === void 0) return failure("InvalidParent");
|
|
@@ -1923,6 +2963,10 @@ const run = (state, command, ids, options = {}) => {
|
|
|
1923
2963
|
for (const mark of at.marks) if (!marks.some((kept) => markName(kept) === markName(mark))) operations.push(Edit.removeMark(piece, markName(mark)));
|
|
1924
2964
|
return apply(state, operations);
|
|
1925
2965
|
}
|
|
2966
|
+
if (command.type === "RetypeBlock" || command.type === "WrapBlock" || command.type === "ConvertBlock" || command.type === "RetypeContainer" || command.type === "LiftBlock") {
|
|
2967
|
+
const target = startingBlock(state.document, selection);
|
|
2968
|
+
return "error" in target ? failure(target.error) : runBlockCommand(state, command, target, ids, options);
|
|
2969
|
+
}
|
|
1926
2970
|
if (command.type === "DeleteBackward" || command.type === "DeleteForward") {
|
|
1927
2971
|
if (!isCollapsed(selection)) {
|
|
1928
2972
|
const span = ordered(state.document, selection);
|
|
@@ -1939,11 +2983,18 @@ const run = (state, command, ids, options = {}) => {
|
|
|
1939
2983
|
if (block === void 0) return failure("MissingText");
|
|
1940
2984
|
const deletion = graphemeDeletion(block, caret, at.runIndex, backward);
|
|
1941
2985
|
if (deletion !== void 0) return apply(state, [...deletion.operations, Edit.setSelection(caretAt(deletion.caret))]);
|
|
2986
|
+
if (backward && block.type === "Node" && declaresText(options.nodes, block.kind)) return run(state, {
|
|
2987
|
+
type: "RetypeBlock",
|
|
2988
|
+
to: { type: "Paragraph" }
|
|
2989
|
+
}, ids, options);
|
|
1942
2990
|
const containerPath = at.path.slice(0, -1);
|
|
1943
2991
|
const siblings = containerBlocks(state.document, containerPath);
|
|
1944
2992
|
const index = at.path[at.path.length - 1];
|
|
1945
2993
|
const neighborBlock = siblings[backward ? index - 1 : index + 1];
|
|
1946
|
-
if (neighborBlock === void 0)
|
|
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;
|
|
2996
|
+
return apply(state, lifted ?? []);
|
|
2997
|
+
}
|
|
1947
2998
|
const survivor = backward ? neighborBlock : siblings[index];
|
|
1948
2999
|
const removed = backward ? siblings[index] : neighborBlock;
|
|
1949
3000
|
const lastRun = lastRunOf(survivor) ?? lastRunOf(removed);
|
|
@@ -1965,10 +3016,14 @@ const run = (state, command, ids, options = {}) => {
|
|
|
1965
3016
|
if (at === void 0) return failure("MissingText");
|
|
1966
3017
|
const deletions = span === void 0 ? [] : deleteRange(state.document, span.start, span.end);
|
|
1967
3018
|
if (deletions === void 0) return failure("InvalidParent");
|
|
3019
|
+
const item = itemAround(state.document, at.path, options.nodes);
|
|
3020
|
+
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);
|
|
1968
3021
|
const textId = ids.mint();
|
|
3022
|
+
const blockId = ids.mint();
|
|
1969
3023
|
return apply(state, [
|
|
1970
3024
|
...deletions,
|
|
1971
|
-
Edit.splitBlock(at.blockId, at.id, caret.offset,
|
|
3025
|
+
Edit.splitBlock(at.blockId, at.id, caret.offset, blockId, textId),
|
|
3026
|
+
...endsHeading(state.document, at.path, span?.end ?? caret) ? [Edit.retypeBlock(NodeId.make(blockId), { type: "Paragraph" })] : [],
|
|
1972
3027
|
Edit.setSelection(caretAt({
|
|
1973
3028
|
node: NodeId.make(textId),
|
|
1974
3029
|
offset: 0,
|
|
@@ -1976,15 +3031,19 @@ const run = (state, command, ids, options = {}) => {
|
|
|
1976
3031
|
}))
|
|
1977
3032
|
]);
|
|
1978
3033
|
}
|
|
1979
|
-
if (command.type === "ToggleMark") {
|
|
1980
|
-
|
|
1981
|
-
const
|
|
3034
|
+
if (command.type === "ToggleMark" || command.type === "SetMark" || command.type === "ClearMark") {
|
|
3035
|
+
const mark = command.mark;
|
|
3036
|
+
const name = markName(mark);
|
|
3037
|
+
let span = ordered(state.document, selection);
|
|
3038
|
+
if (isCollapsed(selection)) {
|
|
3039
|
+
const extent = command.type === "ToggleMark" ? void 0 : markExtent(state.document, selection.anchor, name);
|
|
3040
|
+
if (extent === void 0) return apply(state, []);
|
|
3041
|
+
span = ordered(state.document, extent.selection);
|
|
3042
|
+
}
|
|
1982
3043
|
if (span === void 0) return failure("InvalidSelection");
|
|
1983
3044
|
const spans = covered(state.document, span.start, span.end);
|
|
1984
3045
|
if (spans.length === 0) return apply(state, []);
|
|
1985
|
-
const
|
|
1986
|
-
const name = markName(mark);
|
|
1987
|
-
const adding = !spans.every((entry) => entry.run.marks.some((held) => markName(held) === name));
|
|
3046
|
+
const adding = command.type === "SetMark" || command.type === "ToggleMark" && !spans.every((entry) => entry.run.marks.some((held) => markName(held) === name));
|
|
1988
3047
|
const operations = [];
|
|
1989
3048
|
const targets = [];
|
|
1990
3049
|
for (const [index, entry] of spans.entries()) {
|
|
@@ -2000,7 +3059,8 @@ const run = (state, command, ids, options = {}) => {
|
|
|
2000
3059
|
targets.push(target);
|
|
2001
3060
|
}
|
|
2002
3061
|
if (adding) {
|
|
2003
|
-
if (!declared.
|
|
3062
|
+
if (!declared.accepts(mark)) return failure("InvalidInput");
|
|
3063
|
+
if (spans.some((entry) => forbidsMarks(state.document, entry.run.path, options.nodes))) return failure("ForbiddenMark");
|
|
2004
3064
|
for (const target of targets) operations.push(Edit.addMark(target, mark));
|
|
2005
3065
|
} else for (const target of targets) operations.push(Edit.removeMark(target, name));
|
|
2006
3066
|
return apply(state, operations);
|
|
@@ -2019,6 +3079,8 @@ const run = (state, command, ids, options = {}) => {
|
|
|
2019
3079
|
if (replacements === void 0) return failure("InvalidParent");
|
|
2020
3080
|
const operations = [...replacements];
|
|
2021
3081
|
const inserted = withFreshIds(command.slice, ids.mint).blocks;
|
|
3082
|
+
const holder = containerPath.length === 0 ? void 0 : blockAtPath(state.document, containerPath);
|
|
3083
|
+
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");
|
|
2022
3084
|
const block = blockAtPath(state.document, at.path);
|
|
2023
3085
|
if (block === void 0) return failure("MissingText");
|
|
2024
3086
|
const atBlockStart = at.runIndex === 0 && caret.offset === 0;
|
|
@@ -2063,6 +3125,77 @@ const landingAfter = (inserted, trailingRun, siblings, index, atBlockEnd) => {
|
|
|
2063
3125
|
affinity: "after"
|
|
2064
3126
|
};
|
|
2065
3127
|
};
|
|
3128
|
+
/**
|
|
3129
|
+
* A composed action's invalidation summary is the union of its commands': an identity
|
|
3130
|
+
* one command retired and a later one restored appears in both sets, and a patch reads
|
|
3131
|
+
* that as "remove it, then render it", so it never under-invalidates.
|
|
3132
|
+
*/
|
|
3133
|
+
const unionChangeSet = (left, right) => ({
|
|
3134
|
+
dirtyNodes: /* @__PURE__ */ new Set([...left.dirtyNodes, ...right.dirtyNodes]),
|
|
3135
|
+
insertedNodes: /* @__PURE__ */ new Set([...left.insertedNodes, ...right.insertedNodes]),
|
|
3136
|
+
removedNodes: /* @__PURE__ */ new Set([...left.removedNodes, ...right.removedNodes]),
|
|
3137
|
+
textChanged: /* @__PURE__ */ new Set([...left.textChanged, ...right.textChanged]),
|
|
3138
|
+
structureChanged: left.structureChanged || right.structureChanged,
|
|
3139
|
+
selectionChanged: left.selectionChanged || right.selectionChanged
|
|
3140
|
+
});
|
|
3141
|
+
/**
|
|
3142
|
+
* Resolves commands in order and commits them as one action: one resulting state, one
|
|
3143
|
+
* composed ChangeSet, and one identity stream, so a caller can treat "remove the query,
|
|
3144
|
+
* then apply the choice" as a single transition. It stops at the first refusal and
|
|
3145
|
+
* returns that command's error; state is a value, so nothing partial escapes.
|
|
3146
|
+
*/
|
|
3147
|
+
const runAction = (state, commands, ids, options = {}) => {
|
|
3148
|
+
const [first, ...rest] = commands;
|
|
3149
|
+
if (first === void 0) return apply(state, []);
|
|
3150
|
+
const started = run(state, first, ids, options);
|
|
3151
|
+
if (!started.ok) return started;
|
|
3152
|
+
let current = started.state;
|
|
3153
|
+
let changeSet = started.changeSet;
|
|
3154
|
+
let positionMap = started.positionMap;
|
|
3155
|
+
let transactions = started.transactions;
|
|
3156
|
+
for (const command of rest) {
|
|
3157
|
+
const result = run(current, command, ids, options);
|
|
3158
|
+
if (!result.ok) return result;
|
|
3159
|
+
current = result.state;
|
|
3160
|
+
changeSet = unionChangeSet(changeSet, result.changeSet);
|
|
3161
|
+
positionMap = [...positionMap, ...result.positionMap];
|
|
3162
|
+
transactions = [...transactions, ...result.transactions];
|
|
3163
|
+
}
|
|
3164
|
+
return {
|
|
3165
|
+
ok: true,
|
|
3166
|
+
state: current,
|
|
3167
|
+
changeSet,
|
|
3168
|
+
positionMap,
|
|
3169
|
+
transactions
|
|
3170
|
+
};
|
|
3171
|
+
};
|
|
3172
|
+
//#endregion
|
|
3173
|
+
//#region src/input.ts
|
|
3174
|
+
/**
|
|
3175
|
+
* The commands that insert the text and then let the first matching rule act on it: the
|
|
3176
|
+
* insertion, one backward delete per character the rule consumed, and the rule's commands.
|
|
3177
|
+
* Consumption is by deleting backwards rather than by a range, because a range would have
|
|
3178
|
+
* to be computed against a state the insertion has not produced yet — the deletes resolve
|
|
3179
|
+
* as each one runs. A rule that does not match yields the insertion alone.
|
|
3180
|
+
*
|
|
3181
|
+
* A rule that claims to consume more than it was shown throws: those deletes would run past
|
|
3182
|
+
* the block's start and join it to the one before, which no rule means.
|
|
3183
|
+
*/
|
|
3184
|
+
const applyInputRules = (rules, input) => {
|
|
3185
|
+
const typed = `${input.textBefore}${input.text}`;
|
|
3186
|
+
for (const rule of rules) {
|
|
3187
|
+
const matched = rule.match(typed, input.within ?? []);
|
|
3188
|
+
if (matched === void 0) continue;
|
|
3189
|
+
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
|
+
const consumed = Array.from({ length: matched.remove }, () => ({ type: "DeleteBackward" }));
|
|
3191
|
+
return [
|
|
3192
|
+
input.insertion,
|
|
3193
|
+
...consumed,
|
|
3194
|
+
...matched.commands
|
|
3195
|
+
];
|
|
3196
|
+
}
|
|
3197
|
+
return [input.insertion];
|
|
3198
|
+
};
|
|
2066
3199
|
//#endregion
|
|
2067
3200
|
//#region src/history.ts
|
|
2068
3201
|
/**
|
|
@@ -2141,176 +3274,400 @@ const inspectHistory = (history) => ({
|
|
|
2141
3274
|
group: history.group ?? null
|
|
2142
3275
|
});
|
|
2143
3276
|
//#endregion
|
|
2144
|
-
//#region src/
|
|
2145
|
-
/** Declares a block node kind: a top-level node containing text runs. */
|
|
2146
|
-
const block = (name) => ({
|
|
2147
|
-
name,
|
|
2148
|
-
kind: "block",
|
|
2149
|
-
children: "text"
|
|
2150
|
-
});
|
|
2151
|
-
/** Declares an atom: an addressable node with no text content. */
|
|
2152
|
-
const atom = (name) => ({
|
|
2153
|
-
name,
|
|
2154
|
-
kind: "atom",
|
|
2155
|
-
children: "none"
|
|
2156
|
-
});
|
|
3277
|
+
//#region src/decoration.ts
|
|
2157
3278
|
/**
|
|
2158
|
-
*
|
|
2159
|
-
*
|
|
2160
|
-
*
|
|
3279
|
+
* Decorations (§64): the ephemeral third kind beside Marks and Annotations. A
|
|
3280
|
+
* decoration is presentation derived from current state — a search match, a lint
|
|
3281
|
+
* warning, a remote cursor, a syntax token — rendered by an interpreter and then
|
|
3282
|
+
* discarded. It is never serialized, never part of undo, and never authored content,
|
|
3283
|
+
* which is why this module holds contracts rather than document data.
|
|
3284
|
+
*
|
|
3285
|
+
* The projection here is shared on purpose: a read-only renderer, the editable adapter,
|
|
3286
|
+
* and any other interpreter all need the same answer to "which decorations cover this
|
|
3287
|
+
* run, and where", so they compute it once, in the core, rather than each cutting ranges
|
|
3288
|
+
* their own way.
|
|
2161
3289
|
*/
|
|
2162
|
-
const node = (name, options = {}) => ({
|
|
2163
|
-
name,
|
|
2164
|
-
kind: "node",
|
|
2165
|
-
children: options.children ?? "text",
|
|
2166
|
-
props: options.Props
|
|
2167
|
-
});
|
|
2168
|
-
const kit = (definition) => Object.freeze({
|
|
2169
|
-
nodes: [...definition.nodes],
|
|
2170
|
-
marks: [...definition.marks]
|
|
2171
|
-
});
|
|
2172
|
-
/** Whether a block is held as a built-in block or as an application node. */
|
|
2173
|
-
const heldShape = (block) => block.type === "Node" ? "node" : "block";
|
|
2174
3290
|
/**
|
|
2175
|
-
* The
|
|
2176
|
-
*
|
|
2177
|
-
*
|
|
3291
|
+
* The decorations covering each run, as offsets into it, in document order. A decoration
|
|
3292
|
+
* that crosses runs is cut at each run's edge, so a renderer never has to reason about
|
|
3293
|
+
* document order; a decoration whose endpoints do not resolve is skipped rather than
|
|
3294
|
+
* guessed at, the way every other read treats a position it cannot resolve, and a
|
|
3295
|
+
* direction is honoured rather than required to run forwards.
|
|
3296
|
+
*
|
|
3297
|
+
* The runs are indexed once, so a decoration costs the runs it covers: a hundred search
|
|
3298
|
+
* matches over a long document is one walk, not a hundred.
|
|
2178
3299
|
*/
|
|
2179
|
-
const
|
|
2180
|
-
|
|
2181
|
-
if (
|
|
2182
|
-
|
|
3300
|
+
const decorationsIn = (document, set) => {
|
|
3301
|
+
const spans = /* @__PURE__ */ new Map();
|
|
3302
|
+
if (set.length === 0) return spans;
|
|
3303
|
+
const runs = [];
|
|
3304
|
+
const indexByRun = /* @__PURE__ */ new Map();
|
|
3305
|
+
eachBlock(document.children, (block) => {
|
|
3306
|
+
for (const run of block.children) {
|
|
3307
|
+
indexByRun.set(run.id, runs.length);
|
|
3308
|
+
runs.push({
|
|
3309
|
+
id: run.id,
|
|
3310
|
+
length: run.text.length
|
|
3311
|
+
});
|
|
3312
|
+
}
|
|
3313
|
+
});
|
|
3314
|
+
for (const decoration of set) {
|
|
3315
|
+
const anchor = indexByRun.get(decoration.from.node);
|
|
3316
|
+
const focus = indexByRun.get(decoration.to.node);
|
|
3317
|
+
if (anchor === void 0 || focus === void 0) continue;
|
|
3318
|
+
const forward = anchor <= focus;
|
|
3319
|
+
const first = forward ? anchor : focus;
|
|
3320
|
+
const last = forward ? focus : anchor;
|
|
3321
|
+
const firstOffset = forward ? decoration.from.offset : decoration.to.offset;
|
|
3322
|
+
const lastOffset = forward ? decoration.to.offset : decoration.from.offset;
|
|
3323
|
+
for (let index = first; index <= last; index += 1) {
|
|
3324
|
+
const run = runs[index];
|
|
3325
|
+
const from = Math.max(0, index === first ? firstOffset : 0);
|
|
3326
|
+
const to = Math.min(run.length, index === last ? lastOffset : run.length);
|
|
3327
|
+
if (from >= to) continue;
|
|
3328
|
+
const covered = spans.get(run.id);
|
|
3329
|
+
const span = {
|
|
3330
|
+
from,
|
|
3331
|
+
to,
|
|
3332
|
+
decoration
|
|
3333
|
+
};
|
|
3334
|
+
if (covered === void 0) spans.set(run.id, [span]);
|
|
3335
|
+
else covered.push(span);
|
|
3336
|
+
}
|
|
3337
|
+
}
|
|
3338
|
+
for (const covered of spans.values()) covered.sort((left, right) => left.from - right.from);
|
|
3339
|
+
return spans;
|
|
2183
3340
|
};
|
|
2184
3341
|
/**
|
|
2185
|
-
*
|
|
2186
|
-
*
|
|
2187
|
-
* one
|
|
2188
|
-
*
|
|
3342
|
+
* A run's text cut at every edge of the spans over it, each piece with the decorations
|
|
3343
|
+
* that cover it — what every interpreter draws, so each draws the same pieces. An empty run,
|
|
3344
|
+
* or one no span touches, is one undecorated piece: an interpreter still has to render
|
|
3345
|
+
* somewhere for a caret to sit, and nothing can be drawn over no text.
|
|
2189
3346
|
*/
|
|
2190
|
-
const
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
const
|
|
2196
|
-
|
|
3347
|
+
const runPieces = (text, spans) => {
|
|
3348
|
+
if (spans.length === 0 || text.length === 0) return [{
|
|
3349
|
+
text,
|
|
3350
|
+
decorations: []
|
|
3351
|
+
}];
|
|
3352
|
+
const edges = /* @__PURE__ */ new Set([0, text.length]);
|
|
3353
|
+
for (const span of spans) {
|
|
3354
|
+
edges.add(Math.max(0, Math.min(text.length, span.from)));
|
|
3355
|
+
edges.add(Math.max(0, Math.min(text.length, span.to)));
|
|
3356
|
+
}
|
|
3357
|
+
const cuts = [...edges].sort((left, right) => left - right);
|
|
3358
|
+
const pieces = [];
|
|
3359
|
+
for (let index = 0; index < cuts.length - 1; index += 1) {
|
|
3360
|
+
const from = cuts[index];
|
|
3361
|
+
const to = cuts[index + 1];
|
|
3362
|
+
pieces.push({
|
|
3363
|
+
text: text.slice(from, to),
|
|
3364
|
+
decorations: spans.filter((span) => span.from <= from && to <= span.to).map((span) => span.decoration)
|
|
3365
|
+
});
|
|
3366
|
+
}
|
|
3367
|
+
return pieces;
|
|
2197
3368
|
};
|
|
3369
|
+
//#endregion
|
|
3370
|
+
//#region src/search.ts
|
|
2198
3371
|
/**
|
|
2199
|
-
*
|
|
2200
|
-
*
|
|
2201
|
-
*
|
|
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.
|
|
2202
3382
|
*/
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
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;
|
|
2211
3405
|
};
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
blocks: definition.nodes.filter((node) => node.kind === "block").length,
|
|
2215
|
-
atoms: definition.nodes.filter((node) => node.kind === "atom").length,
|
|
2216
|
-
nodes: definition.nodes.filter((node) => node.kind === "node").length,
|
|
2217
|
-
marks: definition.marks.length
|
|
2218
|
-
});
|
|
3406
|
+
//#endregion
|
|
3407
|
+
//#region src/code.ts
|
|
2219
3408
|
/**
|
|
2220
|
-
*
|
|
2221
|
-
*
|
|
2222
|
-
*
|
|
3409
|
+
* Code highlighting, as decorations (§124 §7, §130): the document holds a `CodeBlock`'s
|
|
3410
|
+
* language and its plain text, and what a highlighter finds in that text is presentation,
|
|
3411
|
+
* derived and discarded like a search match. The contract lives here because it is
|
|
3412
|
+
* format-agnostic — a tokenizer is a function from text to ranges — while grammars, which
|
|
3413
|
+
* are not, live in `foldkit-richtext-code` and its Shiki adapter.
|
|
2223
3414
|
*/
|
|
2224
|
-
const markPropsFailure = (definition, mark) => {
|
|
2225
|
-
if (definition.Props === void 0) return false;
|
|
2226
|
-
try {
|
|
2227
|
-
Schema.decodeUnknownSync(definition.Props, { onExcessProperty: "error" })(markProps(mark));
|
|
2228
|
-
return false;
|
|
2229
|
-
} catch {
|
|
2230
|
-
return true;
|
|
2231
|
-
}
|
|
2232
|
-
};
|
|
2233
3415
|
/**
|
|
2234
|
-
*
|
|
2235
|
-
*
|
|
2236
|
-
*
|
|
2237
|
-
*
|
|
2238
|
-
*
|
|
2239
|
-
*
|
|
2240
|
-
*
|
|
3416
|
+
* Every token the given tokenizers find in the document's `CodeBlock`s, as decorations. A
|
|
3417
|
+
* block is tokenized by the tokenizer registered for its `language` prop; one with no
|
|
3418
|
+
* language, or one nothing is registered for, yields nothing. The registry is a `Map`
|
|
3419
|
+
* because the language is read from the document, and a plain object would answer a
|
|
3420
|
+
* language named `constructor` from its prototype.
|
|
3421
|
+
*
|
|
3422
|
+
* A token outside its block's text, one that covers nothing, or one at a fractional offset
|
|
3423
|
+
* throws with the language that produced it: it is a tokenizer's bug, and a decoration guessed from it would
|
|
3424
|
+
* highlight the wrong text.
|
|
2241
3425
|
*/
|
|
2242
|
-
const
|
|
2243
|
-
const
|
|
2244
|
-
const declaredMarks = new Map(definition.marks.map((mark) => [mark.name, mark]));
|
|
2245
|
-
const diagnostics = [];
|
|
3426
|
+
const codeDecorations = (document, tokenizers) => {
|
|
3427
|
+
const found = [];
|
|
2246
3428
|
eachBlock(document.children, (block) => {
|
|
2247
|
-
if (block.type
|
|
2248
|
-
|
|
2249
|
-
|
|
2250
|
-
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
|
|
2254
|
-
const
|
|
2255
|
-
|
|
2256
|
-
|
|
2257
|
-
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
else {
|
|
2262
|
-
const mismatch = definitionMismatch(declared, block);
|
|
2263
|
-
if (mismatch !== void 0) diagnostics.push({
|
|
2264
|
-
code: "MismatchedDefinition",
|
|
2265
|
-
node: block.id,
|
|
2266
|
-
detail: block.kind,
|
|
2267
|
-
message: mismatch
|
|
2268
|
-
});
|
|
2269
|
-
else if (propsFailure(declared.kind === "node" ? declared.props : void 0, block)) diagnostics.push({
|
|
2270
|
-
code: "InvalidProps",
|
|
2271
|
-
node: block.id,
|
|
2272
|
-
detail: block.kind,
|
|
2273
|
-
message: `"${block.kind}" props do not match its declared schema`
|
|
2274
|
-
});
|
|
2275
|
-
}
|
|
2276
|
-
} else {
|
|
2277
|
-
const declared = byName.get(block.type);
|
|
2278
|
-
if (declared === void 0) diagnostics.push({
|
|
2279
|
-
code: "UnsupportedNode",
|
|
2280
|
-
node: block.id,
|
|
2281
|
-
detail: block.type,
|
|
2282
|
-
message: `The Kit does not declare "${block.type}"`
|
|
2283
|
-
});
|
|
2284
|
-
else {
|
|
2285
|
-
const mismatch = definitionMismatch(declared, block);
|
|
2286
|
-
if (mismatch !== void 0) diagnostics.push({
|
|
2287
|
-
code: "MismatchedDefinition",
|
|
2288
|
-
node: block.id,
|
|
2289
|
-
detail: block.type,
|
|
2290
|
-
message: mismatch
|
|
2291
|
-
});
|
|
2292
|
-
}
|
|
2293
|
-
}
|
|
2294
|
-
for (const run of block.children) for (const mark of run.marks) {
|
|
2295
|
-
const name = markName(mark);
|
|
2296
|
-
const declaredMark = declaredMarks.get(name);
|
|
2297
|
-
if (declaredMark === void 0) diagnostics.push({
|
|
2298
|
-
code: "UnknownMark",
|
|
2299
|
-
node: run.id,
|
|
2300
|
-
detail: name,
|
|
2301
|
-
message: `The Kit does not declare mark "${name}"`
|
|
2302
|
-
});
|
|
2303
|
-
else if (markPropsFailure(declaredMark, mark)) diagnostics.push({
|
|
2304
|
-
code: "InvalidProps",
|
|
2305
|
-
node: run.id,
|
|
2306
|
-
detail: name,
|
|
2307
|
-
message: `"${name}" props do not match its declared schema`
|
|
3429
|
+
if (block.type !== "Node" || block.kind !== "CodeBlock") return;
|
|
3430
|
+
const language = block.props.language;
|
|
3431
|
+
if (typeof language !== "string") return;
|
|
3432
|
+
const tokenizer = tokenizers.get(language);
|
|
3433
|
+
if (tokenizer === void 0) return;
|
|
3434
|
+
const text = block.children.map((run) => run.text).join("");
|
|
3435
|
+
for (const token of tokenizer(text)) {
|
|
3436
|
+
const from = Number.isInteger(token.from) && Number.isInteger(token.to) && token.from < token.to ? positionInBlock(block, token.from) : void 0;
|
|
3437
|
+
const to = from === void 0 ? void 0 : positionInBlock(block, token.to);
|
|
3438
|
+
if (from === void 0 || to === void 0) throw new RangeError(`The ${language} tokenizer produced ${token.kind} at [${token.from}, ${token.to}) in a block of ${text.length} characters`);
|
|
3439
|
+
found.push({
|
|
3440
|
+
from,
|
|
3441
|
+
to,
|
|
3442
|
+
kind: token.kind
|
|
2308
3443
|
});
|
|
2309
3444
|
}
|
|
2310
3445
|
});
|
|
2311
|
-
return
|
|
3446
|
+
return found;
|
|
3447
|
+
};
|
|
3448
|
+
//#endregion
|
|
3449
|
+
//#region src/url.ts
|
|
3450
|
+
/**
|
|
3451
|
+
* The URL policy every importer shares (§70, §124 §10). A link's `href` and an image's `src`
|
|
3452
|
+
* arrive from pasted HTML or Markdown, which is untrusted, and the standard rendering writes
|
|
3453
|
+
* them into attributes, so each passes here before it can become a prop, and again before
|
|
3454
|
+
* the standard rendering writes it.
|
|
3455
|
+
*/
|
|
3456
|
+
/** Schemes a link or a source may carry; anything else — `javascript:`, `data:` — is refused. */
|
|
3457
|
+
const SAFE_SCHEMES = /* @__PURE__ */ new Set([
|
|
3458
|
+
"http",
|
|
3459
|
+
"https",
|
|
3460
|
+
"mailto",
|
|
3461
|
+
"tel"
|
|
3462
|
+
]);
|
|
3463
|
+
/**
|
|
3464
|
+
* A URL safe to carry into props, or `undefined` when it is not. Control characters are
|
|
3465
|
+
* removed first, because `java\tscript:` and a leading NUL are how a scheme check is
|
|
3466
|
+
* usually walked past; then a URL that names a scheme outside the allowlist is refused,
|
|
3467
|
+
* and one with no scheme — a relative path, a fragment, a protocol-relative URL — is
|
|
3468
|
+
* kept. The value is never interpreted, only copied, so what a policy leaves through is
|
|
3469
|
+
* still the application's to trust.
|
|
3470
|
+
*/
|
|
3471
|
+
const safeUrl = (value) => {
|
|
3472
|
+
if (value === null) return void 0;
|
|
3473
|
+
const cleaned = value.replace(/[\u0000-\u001F\u007F]/g, "").trim();
|
|
3474
|
+
if (cleaned.length === 0) return void 0;
|
|
3475
|
+
const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(cleaned)?.[1]?.toLowerCase();
|
|
3476
|
+
return scheme === void 0 || SAFE_SCHEMES.has(scheme) ? cleaned : void 0;
|
|
2312
3477
|
};
|
|
2313
3478
|
//#endregion
|
|
3479
|
+
//#region src/standard.ts
|
|
3480
|
+
/**
|
|
3481
|
+
* The standard semantic vocabulary (§124 §2, §125): the node kinds and marks a
|
|
3482
|
+
* document uses to mean what Markdown and HTML also mean, so an interpreter is a
|
|
3483
|
+
* mapping from this vocabulary rather than a private one. Declarations only — no
|
|
3484
|
+
* renderers, no executable code (§34) — and an application spreads them into its Kit
|
|
3485
|
+
* and adds its own:
|
|
3486
|
+
*
|
|
3487
|
+
* ```ts
|
|
3488
|
+
* RichText.kit({
|
|
3489
|
+
* nodes: [...RichText.standardNodes, Callout],
|
|
3490
|
+
* marks: [...RichText.standardMarks, Highlight],
|
|
3491
|
+
* })
|
|
3492
|
+
* ```
|
|
3493
|
+
*
|
|
3494
|
+
* `Paragraph` and `Heading` are built-in text blocks, `Code` is the inline-code mark,
|
|
3495
|
+
* and the rest are ordinary declarations. `HardBreak` is deliberately absent: it is
|
|
3496
|
+
* inline content, and the model has no inline atoms yet (§116, deferred).
|
|
3497
|
+
*/
|
|
3498
|
+
/**
|
|
3499
|
+
* A struck-through span. It expands `after`, so typing at its edge continues it, as
|
|
3500
|
+
* bold and italic do.
|
|
3501
|
+
*/
|
|
3502
|
+
const Strikethrough = mark("Strikethrough", { expand: "after" });
|
|
3503
|
+
/**
|
|
3504
|
+
* A hyperlink. Its `href` is a prop rather than a mark name, which is what lets the
|
|
3505
|
+
* serializer render a real `<a href>` (§121); it expands `none`, because text typed
|
|
3506
|
+
* after a link is new text, not a continuation of the link.
|
|
3507
|
+
*/
|
|
3508
|
+
const Link = mark("Link", {
|
|
3509
|
+
Props: Schema.Struct({ href: Schema.String }),
|
|
3510
|
+
expand: "none"
|
|
3511
|
+
});
|
|
3512
|
+
/**
|
|
3513
|
+
* The link a selection starts in, which is what a link editor opens on: at a caret, the
|
|
3514
|
+
* link around it; over a range, the link its start is in. Undefined outside a link, and for
|
|
3515
|
+
* a node selection, which covers blocks rather than text.
|
|
3516
|
+
*/
|
|
3517
|
+
const linkAt = (document, selection) => {
|
|
3518
|
+
if (selection?.type !== "Range") return void 0;
|
|
3519
|
+
const start = rangeStart(document, selection);
|
|
3520
|
+
const extent = start === void 0 ? void 0 : markExtent(document, start, Link.name);
|
|
3521
|
+
if (extent === void 0) return void 0;
|
|
3522
|
+
const href = markProps(extent.mark)?.href;
|
|
3523
|
+
return {
|
|
3524
|
+
href: typeof href === "string" ? href : "",
|
|
3525
|
+
selection: extent.selection
|
|
3526
|
+
};
|
|
3527
|
+
};
|
|
3528
|
+
/** Every mark the standard vocabulary names, in menu order. */
|
|
3529
|
+
const standardMarks = [
|
|
3530
|
+
Bold,
|
|
3531
|
+
Italic,
|
|
3532
|
+
Code,
|
|
3533
|
+
Strikethrough,
|
|
3534
|
+
Link
|
|
3535
|
+
];
|
|
3536
|
+
/**
|
|
3537
|
+
* The standard node kinds. Constraints are what make a kind more than a name: a
|
|
3538
|
+
* `List` accepts only `ListItem`s and a `Table` only `TableRow`s, so `validate`
|
|
3539
|
+
* reports a document that says otherwise (§125); a `CodeBlock` carries text with no
|
|
3540
|
+
* formatting, and its `language` is a prop, not a mark.
|
|
3541
|
+
*/
|
|
3542
|
+
const standardNodes = [
|
|
3543
|
+
block("Paragraph"),
|
|
3544
|
+
block("Heading"),
|
|
3545
|
+
node("Quote", { children: blockContent }),
|
|
3546
|
+
node("List", {
|
|
3547
|
+
Props: Schema.Struct({
|
|
3548
|
+
ordered: Schema.optional(Schema.Boolean),
|
|
3549
|
+
start: Schema.optional(Schema.Number)
|
|
3550
|
+
}),
|
|
3551
|
+
children: blocksOf("ListItem", "TaskItem")
|
|
3552
|
+
}),
|
|
3553
|
+
node("ListItem", {
|
|
3554
|
+
children: blockContent,
|
|
3555
|
+
within: ["List"]
|
|
3556
|
+
}),
|
|
3557
|
+
node("TaskItem", {
|
|
3558
|
+
Props: Schema.Struct({ checked: Schema.Boolean }),
|
|
3559
|
+
children: blockContent,
|
|
3560
|
+
splitProps: { checked: false },
|
|
3561
|
+
within: ["List"]
|
|
3562
|
+
}),
|
|
3563
|
+
node("CodeBlock", {
|
|
3564
|
+
Props: Schema.Struct({ language: Schema.optional(Schema.String) }),
|
|
3565
|
+
children: textContent,
|
|
3566
|
+
marks: "none"
|
|
3567
|
+
}),
|
|
3568
|
+
atom("ThematicBreak"),
|
|
3569
|
+
atom("Image", { Props: Schema.Struct({
|
|
3570
|
+
src: Schema.String,
|
|
3571
|
+
alt: Schema.optional(Schema.String)
|
|
3572
|
+
}) }),
|
|
3573
|
+
node("Table", { children: blocksOf("TableRow") }),
|
|
3574
|
+
node("TableRow", {
|
|
3575
|
+
Props: Schema.Struct({ header: Schema.optional(Schema.Boolean) }),
|
|
3576
|
+
children: blocksOf("TableCell"),
|
|
3577
|
+
within: ["Table"]
|
|
3578
|
+
}),
|
|
3579
|
+
node("TableCell", {
|
|
3580
|
+
children: blockContent,
|
|
3581
|
+
isolating: true,
|
|
3582
|
+
within: ["TableRow"]
|
|
3583
|
+
})
|
|
3584
|
+
];
|
|
3585
|
+
/**
|
|
3586
|
+
* A URL attribute, or none when the value fails the URL policy. Import already applies the
|
|
3587
|
+
* policy, but a document also arrives decoded, synchronized, or edited through `SetMark`,
|
|
3588
|
+
* and this is where a `javascript:` href would become live.
|
|
3589
|
+
*/
|
|
3590
|
+
const urlAttribute = (name, value) => {
|
|
3591
|
+
const safe = typeof value === "string" ? safeUrl(value) : void 0;
|
|
3592
|
+
return safe === void 0 ? {} : { [name]: safe };
|
|
3593
|
+
};
|
|
3594
|
+
/**
|
|
3595
|
+
* How the standard vocabulary renders (§121): the element each kind is, with the props
|
|
3596
|
+
* that belong in attributes read from the block, so a `Link` is an `<a href>`, an `Image`
|
|
3597
|
+
* carries its source, and a `List` is an `<ol>` or a `<ul>`. The shipped marks already
|
|
3598
|
+
* nest in `strong`/`em`/`code`; this adds the two that do not. An application composes it
|
|
3599
|
+
* with `renderingOver` and names its own kinds beside it:
|
|
3600
|
+
*
|
|
3601
|
+
* ```ts
|
|
3602
|
+
* renderingOver(RichText.standardRendering, { nodes: { Callout: { tag: 'aside' } } })
|
|
3603
|
+
* ```
|
|
3604
|
+
*/
|
|
3605
|
+
const standardRendering = rendering({
|
|
3606
|
+
marks: {
|
|
3607
|
+
Strikethrough: {
|
|
3608
|
+
tag: "s",
|
|
3609
|
+
attributes: {}
|
|
3610
|
+
},
|
|
3611
|
+
Link: (mark) => ({
|
|
3612
|
+
tag: "a",
|
|
3613
|
+
attributes: urlAttribute("href", markProps(mark)?.href)
|
|
3614
|
+
})
|
|
3615
|
+
},
|
|
3616
|
+
nodes: {
|
|
3617
|
+
Quote: {
|
|
3618
|
+
tag: "blockquote",
|
|
3619
|
+
attributes: {}
|
|
3620
|
+
},
|
|
3621
|
+
List: (block) => {
|
|
3622
|
+
const ordered = block.props.ordered === true;
|
|
3623
|
+
const start = block.props.start;
|
|
3624
|
+
return {
|
|
3625
|
+
tag: ordered ? "ol" : "ul",
|
|
3626
|
+
attributes: ordered && typeof start === "number" ? { start: String(start) } : {}
|
|
3627
|
+
};
|
|
3628
|
+
},
|
|
3629
|
+
ListItem: {
|
|
3630
|
+
tag: "li",
|
|
3631
|
+
attributes: {}
|
|
3632
|
+
},
|
|
3633
|
+
TaskItem: (block) => ({
|
|
3634
|
+
tag: "li",
|
|
3635
|
+
attributes: { "data-task": block.props.checked === true ? "checked" : "unchecked" }
|
|
3636
|
+
}),
|
|
3637
|
+
CodeBlock: (block) => ({
|
|
3638
|
+
tag: "pre",
|
|
3639
|
+
attributes: { "data-language": String(block.props.language ?? "") }
|
|
3640
|
+
}),
|
|
3641
|
+
ThematicBreak: {
|
|
3642
|
+
tag: "hr",
|
|
3643
|
+
attributes: {}
|
|
3644
|
+
},
|
|
3645
|
+
Image: (block) => ({
|
|
3646
|
+
tag: "img",
|
|
3647
|
+
attributes: {
|
|
3648
|
+
...urlAttribute("src", block.props.src),
|
|
3649
|
+
alt: String(block.props.alt ?? "")
|
|
3650
|
+
}
|
|
3651
|
+
}),
|
|
3652
|
+
Table: {
|
|
3653
|
+
tag: "table",
|
|
3654
|
+
attributes: {},
|
|
3655
|
+
inner: "tbody"
|
|
3656
|
+
},
|
|
3657
|
+
TableRow: (block) => block.props.header === true ? {
|
|
3658
|
+
tag: "tr",
|
|
3659
|
+
attributes: { "data-header": "" }
|
|
3660
|
+
} : {
|
|
3661
|
+
tag: "tr",
|
|
3662
|
+
attributes: {}
|
|
3663
|
+
},
|
|
3664
|
+
TableCell: {
|
|
3665
|
+
tag: "td",
|
|
3666
|
+
attributes: {}
|
|
3667
|
+
}
|
|
3668
|
+
}
|
|
3669
|
+
});
|
|
3670
|
+
//#endregion
|
|
2314
3671
|
//#region src/migration.ts
|
|
2315
3672
|
const matches = (block, from) => block.type === "Unknown" ? block.originalType === from : block.type === "Node" ? block.kind === from : block.type === from;
|
|
2316
3673
|
const decodeMigratedDocument = Schema.decodeUnknownSync(Document, { onExcessProperty: "error" });
|
|
@@ -2431,6 +3788,1746 @@ const decodeProps = (Props, props) => {
|
|
|
2431
3788
|
/** A node block's props as the codec stores them: plain JSON, nothing more. */
|
|
2432
3789
|
const nodeProps = (block) => block.props;
|
|
2433
3790
|
//#endregion
|
|
2434
|
-
|
|
3791
|
+
//#region src/replicated.ts
|
|
3792
|
+
var replicated_exports = /* @__PURE__ */ __exportAll({
|
|
3793
|
+
AnchoredPosition: () => AnchoredPosition,
|
|
3794
|
+
AnchoredSelection: () => AnchoredSelection,
|
|
3795
|
+
BlockShape: () => BlockShape,
|
|
3796
|
+
CharRange: () => CharRange,
|
|
3797
|
+
CharRef: () => CharRef,
|
|
3798
|
+
ReplicatedId: () => ReplicatedId,
|
|
3799
|
+
ReplicatedOp: () => ReplicatedOp,
|
|
3800
|
+
ReplicatedState: () => ReplicatedState,
|
|
3801
|
+
anchor: () => anchor,
|
|
3802
|
+
applyOps: () => applyOps,
|
|
3803
|
+
coalesce: () => coalesce,
|
|
3804
|
+
empty: () => empty,
|
|
3805
|
+
fromDocument: () => fromDocument,
|
|
3806
|
+
invert: () => invert,
|
|
3807
|
+
project: () => project,
|
|
3808
|
+
resolve: () => resolve,
|
|
3809
|
+
translate: () => translate
|
|
3810
|
+
});
|
|
3811
|
+
/**
|
|
3812
|
+
* A document shared by several replicas, where every character has an identity that
|
|
3813
|
+
* outlives the edits around it.
|
|
3814
|
+
*
|
|
3815
|
+
* The editor keeps working on a plain `Document`: `project` derives one from this state.
|
|
3816
|
+
* An edit runs as an ordinary command against that projection, `translate` restates the
|
|
3817
|
+
* transactions it applied as `ReplicatedOp`s that name characters and blocks rather than
|
|
3818
|
+
* offsets and indices, and `applyOps` folds those ops into the state. Replicas converge
|
|
3819
|
+
* because a server gives every op one order and `applyOps` is a deterministic, total
|
|
3820
|
+
* function of the state and the ops: it never throws.
|
|
3821
|
+
*/
|
|
3822
|
+
/**
|
|
3823
|
+
* An identity this state minted: segments joined by `:`, at least two of them. The colon
|
|
3824
|
+
* keeps an id from ever naming an `Object.prototype` key, which is why the block record is
|
|
3825
|
+
* indexed directly, and the absent `.` is what separates an id from a character reference
|
|
3826
|
+
* built on it.
|
|
3827
|
+
*/
|
|
3828
|
+
const ReplicatedId = Schema.String.check(Schema.isPattern(/^[A-Za-z0-9_-]+(?::[A-Za-z0-9_-]+)+$/)).pipe(Schema.brand("foldkit-richtext/ReplicatedId"));
|
|
3829
|
+
/** A character: the insert that created it, and its index within that insert's text. */
|
|
3830
|
+
const CharRef = Schema.String.check(Schema.isPattern(/^[A-Za-z0-9_-]+(?::[A-Za-z0-9_-]+)+\.(?:0|[1-9][0-9]*)$/)).pipe(Schema.brand("foldkit-richtext/CharRef"));
|
|
3831
|
+
const Index = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0));
|
|
3832
|
+
/** Characters `from` up to, not including, `to` of one insert. */
|
|
3833
|
+
const CharRange = Schema.Struct({
|
|
3834
|
+
id: ReplicatedId,
|
|
3835
|
+
from: Index,
|
|
3836
|
+
to: Index
|
|
3837
|
+
});
|
|
3838
|
+
/** What a block is, apart from its content and place. */
|
|
3839
|
+
const BlockShape = Schema.Union([
|
|
3840
|
+
Schema.Struct({ type: Schema.Literal("Paragraph") }),
|
|
3841
|
+
Schema.Struct({
|
|
3842
|
+
type: Schema.Literal("Heading"),
|
|
3843
|
+
level: Schema.Literals([
|
|
3844
|
+
1,
|
|
3845
|
+
2,
|
|
3846
|
+
3,
|
|
3847
|
+
4,
|
|
3848
|
+
5,
|
|
3849
|
+
6
|
|
3850
|
+
])
|
|
3851
|
+
}),
|
|
3852
|
+
Schema.Struct({
|
|
3853
|
+
type: Schema.Literal("Node"),
|
|
3854
|
+
kind: Schema.NonEmptyString,
|
|
3855
|
+
props: Schema.JsonObject,
|
|
3856
|
+
/** What the node holds: runs, nested blocks, or nothing (an atom such as an image). */
|
|
3857
|
+
holds: Schema.Literals([
|
|
3858
|
+
"text",
|
|
3859
|
+
"blocks",
|
|
3860
|
+
"none"
|
|
3861
|
+
])
|
|
3862
|
+
}),
|
|
3863
|
+
Schema.Struct({
|
|
3864
|
+
type: Schema.Literal("Unknown"),
|
|
3865
|
+
originalType: Schema.NonEmptyString,
|
|
3866
|
+
props: Schema.JsonObject
|
|
3867
|
+
})
|
|
3868
|
+
]);
|
|
3869
|
+
/** A stretch of one insert's characters with one mark set, visible or deleted. */
|
|
3870
|
+
const Span = Schema.Struct({
|
|
3871
|
+
id: ReplicatedId,
|
|
3872
|
+
offset: Index,
|
|
3873
|
+
text: Schema.NonEmptyString,
|
|
3874
|
+
marks: Schema.Array(RunMark),
|
|
3875
|
+
deleted: Schema.Boolean,
|
|
3876
|
+
/** Deleted when a `Collect` ran, so the next one removes it. */
|
|
3877
|
+
swept: Schema.optionalKey(Schema.Boolean),
|
|
3878
|
+
/**
|
|
3879
|
+
* The last character of a collected stretch, kept only so its insert's indexes are never
|
|
3880
|
+
* reused. It is never shown again, not even by an undo.
|
|
3881
|
+
*/
|
|
3882
|
+
kept: Schema.optionalKey(Schema.Literal(true))
|
|
3883
|
+
});
|
|
3884
|
+
const Entry = Schema.Struct({
|
|
3885
|
+
shape: BlockShape,
|
|
3886
|
+
parent: Schema.NullOr(ReplicatedId),
|
|
3887
|
+
spans: Schema.Array(Span),
|
|
3888
|
+
/** Nested blocks in order, deleted ones included, so a sibling anchor still resolves. */
|
|
3889
|
+
children: Schema.Array(ReplicatedId),
|
|
3890
|
+
deleted: Schema.Boolean,
|
|
3891
|
+
/** Deleted when a `Collect` ran, so the next one removes the text it holds. */
|
|
3892
|
+
swept: Schema.optionalKey(Schema.Boolean),
|
|
3893
|
+
/** Where a joined block's start now is: after this character of `into`, or its start. */
|
|
3894
|
+
joined: Schema.optionalKey(Schema.Struct({
|
|
3895
|
+
into: ReplicatedId,
|
|
3896
|
+
after: Schema.NullOr(CharRef)
|
|
3897
|
+
}))
|
|
3898
|
+
});
|
|
3899
|
+
const ReplicatedState = Schema.Struct({
|
|
3900
|
+
version: Schema.Literal(1),
|
|
3901
|
+
root: Schema.Array(ReplicatedId),
|
|
3902
|
+
blocks: Schema.Record(ReplicatedId, Entry)
|
|
3903
|
+
});
|
|
3904
|
+
/**
|
|
3905
|
+
* One change, naming what it touches by identity. Inserts and splits anchor after a
|
|
3906
|
+
* character, or at a block's start when `after` is null; block ops anchor after a sibling,
|
|
3907
|
+
* or at the start of the container when `after` is null.
|
|
3908
|
+
*/
|
|
3909
|
+
const ReplicatedOp = Schema.Union([
|
|
3910
|
+
Schema.Struct({
|
|
3911
|
+
type: Schema.Literal("Insert"),
|
|
3912
|
+
id: ReplicatedId,
|
|
3913
|
+
/** The block the anchor was in when the op was made: where a lost anchor falls back to. */
|
|
3914
|
+
block: ReplicatedId,
|
|
3915
|
+
after: Schema.NullOr(CharRef),
|
|
3916
|
+
text: Schema.NonEmptyString,
|
|
3917
|
+
marks: Schema.Array(RunMark),
|
|
3918
|
+
/**
|
|
3919
|
+
* The index of its first character, when it continues an insert of the same id rather
|
|
3920
|
+
* than starting one: `id.from` onwards. Absent means 0.
|
|
3921
|
+
*/
|
|
3922
|
+
from: Schema.optionalKey(Index)
|
|
3923
|
+
}),
|
|
3924
|
+
Schema.Struct({
|
|
3925
|
+
type: Schema.Literal("Delete"),
|
|
3926
|
+
ranges: Schema.Array(CharRange)
|
|
3927
|
+
}),
|
|
3928
|
+
Schema.Struct({
|
|
3929
|
+
type: Schema.Literal("Mark"),
|
|
3930
|
+
ranges: Schema.Array(CharRange),
|
|
3931
|
+
mark: RunMark
|
|
3932
|
+
}),
|
|
3933
|
+
Schema.Struct({
|
|
3934
|
+
type: Schema.Literal("Unmark"),
|
|
3935
|
+
ranges: Schema.Array(CharRange),
|
|
3936
|
+
name: Schema.NonEmptyString
|
|
3937
|
+
}),
|
|
3938
|
+
Schema.Struct({
|
|
3939
|
+
type: Schema.Literal("InsertBlock"),
|
|
3940
|
+
id: ReplicatedId,
|
|
3941
|
+
shape: BlockShape,
|
|
3942
|
+
parent: Schema.NullOr(ReplicatedId),
|
|
3943
|
+
after: Schema.NullOr(ReplicatedId)
|
|
3944
|
+
}),
|
|
3945
|
+
Schema.Struct({
|
|
3946
|
+
type: Schema.Literal("DeleteBlock"),
|
|
3947
|
+
id: ReplicatedId
|
|
3948
|
+
}),
|
|
3949
|
+
Schema.Struct({
|
|
3950
|
+
type: Schema.Literal("MoveBlock"),
|
|
3951
|
+
id: ReplicatedId,
|
|
3952
|
+
parent: Schema.NullOr(ReplicatedId),
|
|
3953
|
+
after: Schema.NullOr(ReplicatedId)
|
|
3954
|
+
}),
|
|
3955
|
+
Schema.Struct({
|
|
3956
|
+
type: Schema.Literal("Split"),
|
|
3957
|
+
block: ReplicatedId,
|
|
3958
|
+
after: Schema.NullOr(CharRef),
|
|
3959
|
+
into: ReplicatedId
|
|
3960
|
+
}),
|
|
3961
|
+
Schema.Struct({
|
|
3962
|
+
type: Schema.Literal("Join"),
|
|
3963
|
+
into: ReplicatedId,
|
|
3964
|
+
removed: ReplicatedId,
|
|
3965
|
+
/**
|
|
3966
|
+
* The last character of `into` when the op was made, or null when it had none: the
|
|
3967
|
+
* removed block's text goes right after it, wherever it has gone since, so a join still
|
|
3968
|
+
* lands where it was made after `into` is split or joined itself.
|
|
3969
|
+
*/
|
|
3970
|
+
after: Schema.NullOr(CharRef),
|
|
3971
|
+
/**
|
|
3972
|
+
* `'end'` puts the text at the end of the block holding `after` (of `into` when null) as
|
|
3973
|
+
* that block is when the join applies, so text typed at its end since stays before it.
|
|
3974
|
+
* Only undo makes it: rejoining halves someone has typed into since.
|
|
3975
|
+
*/
|
|
3976
|
+
at: Schema.optionalKey(Schema.Literal("end"))
|
|
3977
|
+
}),
|
|
3978
|
+
Schema.Struct({
|
|
3979
|
+
type: Schema.Literal("Retype"),
|
|
3980
|
+
id: ReplicatedId,
|
|
3981
|
+
to: RetypeTarget
|
|
3982
|
+
}),
|
|
3983
|
+
Schema.Struct({
|
|
3984
|
+
type: Schema.Literal("SetProps"),
|
|
3985
|
+
id: ReplicatedId,
|
|
3986
|
+
props: Schema.JsonObject
|
|
3987
|
+
}),
|
|
3988
|
+
Schema.Struct({
|
|
3989
|
+
type: Schema.Literal("Undelete"),
|
|
3990
|
+
ranges: Schema.Array(CharRange)
|
|
3991
|
+
}),
|
|
3992
|
+
Schema.Struct({
|
|
3993
|
+
type: Schema.Literal("UndeleteBlock"),
|
|
3994
|
+
id: ReplicatedId
|
|
3995
|
+
}),
|
|
3996
|
+
Schema.Struct({
|
|
3997
|
+
type: Schema.Literal("Unjoin"),
|
|
3998
|
+
/** The block a join removed, restored where it stood. */
|
|
3999
|
+
id: ReplicatedId,
|
|
4000
|
+
/** The characters it held, taken back from wherever they are now. */
|
|
4001
|
+
ranges: Schema.Array(CharRange),
|
|
4002
|
+
/** The nested blocks it held, taken back from the container they were joined into. */
|
|
4003
|
+
children: Schema.Array(ReplicatedId)
|
|
4004
|
+
}),
|
|
4005
|
+
Schema.Struct({ type: Schema.Literal("Collect") })
|
|
4006
|
+
]);
|
|
4007
|
+
const charRef = (id, index) => `${id}.${index}`;
|
|
4008
|
+
const parseChar = (ref) => {
|
|
4009
|
+
const dot = ref.lastIndexOf(".");
|
|
4010
|
+
return {
|
|
4011
|
+
id: ref.slice(0, dot),
|
|
4012
|
+
index: Number(ref.slice(dot + 1))
|
|
4013
|
+
};
|
|
4014
|
+
};
|
|
4015
|
+
/** The run a text block with no visible characters shows, so a caret has somewhere to be. */
|
|
4016
|
+
const emptyRunId = (block) => NodeId.make(`${block}.0`);
|
|
4017
|
+
const empty = {
|
|
4018
|
+
version: 1,
|
|
4019
|
+
root: [],
|
|
4020
|
+
blocks: {}
|
|
4021
|
+
};
|
|
4022
|
+
const lookup = (state, id) => state.blocks[id];
|
|
4023
|
+
const MAX_HOLDER_LAYERS = 16;
|
|
4024
|
+
const holdersIn = (holders, id) => {
|
|
4025
|
+
for (let at = holders; at !== void 0; at = at.parent) {
|
|
4026
|
+
const found = at.own.get(id);
|
|
4027
|
+
if (found !== void 0) return found;
|
|
4028
|
+
}
|
|
4029
|
+
};
|
|
4030
|
+
const insertIdsOf = (entry) => new Set(entry?.spans.map((span) => span.id) ?? []);
|
|
4031
|
+
const holderIndexes = /* @__PURE__ */ new WeakMap();
|
|
4032
|
+
const holdersOf = (state) => {
|
|
4033
|
+
const cached = holderIndexes.get(state);
|
|
4034
|
+
if (cached !== void 0) return cached;
|
|
4035
|
+
const own = /* @__PURE__ */ new Map();
|
|
4036
|
+
for (const [block, entry] of Object.entries(state.blocks)) for (const id of insertIdsOf(entry)) {
|
|
4037
|
+
const list = own.get(id);
|
|
4038
|
+
if (list === void 0) own.set(id, [block]);
|
|
4039
|
+
else list.push(block);
|
|
4040
|
+
}
|
|
4041
|
+
const holders = {
|
|
4042
|
+
parent: void 0,
|
|
4043
|
+
own,
|
|
4044
|
+
depth: 0
|
|
4045
|
+
};
|
|
4046
|
+
holderIndexes.set(state, holders);
|
|
4047
|
+
return holders;
|
|
4048
|
+
};
|
|
4049
|
+
/** The holders after `changed` blocks were rewritten from `before` to `after`. */
|
|
4050
|
+
const nextHolders = (holders, before, after, changed) => {
|
|
4051
|
+
const own = /* @__PURE__ */ new Map();
|
|
4052
|
+
const listFor = (id) => {
|
|
4053
|
+
let list = own.get(id);
|
|
4054
|
+
if (list === void 0) {
|
|
4055
|
+
list = [...holdersIn(holders, id) ?? []];
|
|
4056
|
+
own.set(id, list);
|
|
4057
|
+
}
|
|
4058
|
+
return list;
|
|
4059
|
+
};
|
|
4060
|
+
for (const block of changed) {
|
|
4061
|
+
const was = insertIdsOf(lookup(before, block));
|
|
4062
|
+
const is = insertIdsOf(lookup(after, block));
|
|
4063
|
+
for (const id of was) {
|
|
4064
|
+
if (is.has(id)) continue;
|
|
4065
|
+
const list = listFor(id);
|
|
4066
|
+
list.splice(list.indexOf(block), 1);
|
|
4067
|
+
}
|
|
4068
|
+
for (const id of is) if (!was.has(id)) listFor(id).push(block);
|
|
4069
|
+
}
|
|
4070
|
+
if (own.size === 0) return holders;
|
|
4071
|
+
if (holders.depth < MAX_HOLDER_LAYERS) return {
|
|
4072
|
+
parent: holders,
|
|
4073
|
+
own,
|
|
4074
|
+
depth: holders.depth + 1
|
|
4075
|
+
};
|
|
4076
|
+
const merged = /* @__PURE__ */ new Map();
|
|
4077
|
+
const layers = [];
|
|
4078
|
+
for (let at = holders; at !== void 0; at = at.parent) layers.push(at);
|
|
4079
|
+
for (const layer of layers.reverse()) for (const [id, list] of layer.own) merged.set(id, list);
|
|
4080
|
+
for (const [id, list] of own) merged.set(id, list);
|
|
4081
|
+
return {
|
|
4082
|
+
parent: void 0,
|
|
4083
|
+
own: merged,
|
|
4084
|
+
depth: 0
|
|
4085
|
+
};
|
|
4086
|
+
};
|
|
4087
|
+
/**
|
|
4088
|
+
* A working copy of the state for one `applyOps`: the block record is copied on the first
|
|
4089
|
+
* write, and each entry the ops touch once, so a batch of ops costs one copy of what it
|
|
4090
|
+
* touches, and a read-only walk (`resolve`'s) copies nothing.
|
|
4091
|
+
*/
|
|
4092
|
+
const draft = (state) => {
|
|
4093
|
+
let blocks = state.blocks;
|
|
4094
|
+
let blocksCopied = false;
|
|
4095
|
+
let root = state.root;
|
|
4096
|
+
let rootCopied = false;
|
|
4097
|
+
const copied = /* @__PURE__ */ new Set();
|
|
4098
|
+
/** Blocks each insert's spans have been put into by this draft, beyond the index's. */
|
|
4099
|
+
const moved = /* @__PURE__ */ new Map();
|
|
4100
|
+
const own = (id, entry) => {
|
|
4101
|
+
if (!blocksCopied) {
|
|
4102
|
+
blocks = { ...blocks };
|
|
4103
|
+
blocksCopied = true;
|
|
4104
|
+
}
|
|
4105
|
+
blocks[id] = entry;
|
|
4106
|
+
copied.add(id);
|
|
4107
|
+
};
|
|
4108
|
+
const read = (id) => blocks[id];
|
|
4109
|
+
const write = (id) => {
|
|
4110
|
+
const entry = read(id);
|
|
4111
|
+
if (entry === void 0) return void 0;
|
|
4112
|
+
if (copied.has(id)) return entry;
|
|
4113
|
+
const copy = {
|
|
4114
|
+
...entry,
|
|
4115
|
+
spans: [...entry.spans],
|
|
4116
|
+
children: [...entry.children]
|
|
4117
|
+
};
|
|
4118
|
+
own(id, copy);
|
|
4119
|
+
return copy;
|
|
4120
|
+
};
|
|
4121
|
+
/** Records that `spans` were put into `block`, so `holding` finds them there. */
|
|
4122
|
+
const hold = (block, spans) => {
|
|
4123
|
+
for (const span of spans) {
|
|
4124
|
+
const set = moved.get(span.id);
|
|
4125
|
+
if (set === void 0) moved.set(span.id, /* @__PURE__ */ new Set([block]));
|
|
4126
|
+
else set.add(block);
|
|
4127
|
+
}
|
|
4128
|
+
};
|
|
4129
|
+
const siblings = (parent) => {
|
|
4130
|
+
if (parent === null) {
|
|
4131
|
+
if (!rootCopied) {
|
|
4132
|
+
root = [...root];
|
|
4133
|
+
rootCopied = true;
|
|
4134
|
+
}
|
|
4135
|
+
return root;
|
|
4136
|
+
}
|
|
4137
|
+
const entry = write(parent);
|
|
4138
|
+
return entry !== void 0 && holdsBlocks(entry.shape) ? entry.children : void 0;
|
|
4139
|
+
};
|
|
4140
|
+
const create = (id, entry) => {
|
|
4141
|
+
own(id, {
|
|
4142
|
+
...entry,
|
|
4143
|
+
spans: [...entry.spans],
|
|
4144
|
+
children: [...entry.children]
|
|
4145
|
+
});
|
|
4146
|
+
hold(id, entry.spans);
|
|
4147
|
+
};
|
|
4148
|
+
/**
|
|
4149
|
+
* The blocks that may hold spans of an insert: those that did before this `applyOps`, and
|
|
4150
|
+
* those it has put spans of it into since.
|
|
4151
|
+
*/
|
|
4152
|
+
const holding = (id) => {
|
|
4153
|
+
const since = moved.get(id);
|
|
4154
|
+
const before = holdersIn(holdersOf(state), id) ?? [];
|
|
4155
|
+
return since === void 0 ? new Set(before) : /* @__PURE__ */ new Set([...before, ...since]);
|
|
4156
|
+
};
|
|
4157
|
+
const finish = () => {
|
|
4158
|
+
const next = {
|
|
4159
|
+
version: 1,
|
|
4160
|
+
root,
|
|
4161
|
+
blocks
|
|
4162
|
+
};
|
|
4163
|
+
const holders = holderIndexes.get(state);
|
|
4164
|
+
if (holders !== void 0) holderIndexes.set(next, nextHolders(holders, state, next, copied));
|
|
4165
|
+
return next;
|
|
4166
|
+
};
|
|
4167
|
+
const ids = () => Object.keys(blocks);
|
|
4168
|
+
return {
|
|
4169
|
+
read,
|
|
4170
|
+
write,
|
|
4171
|
+
hold,
|
|
4172
|
+
siblings,
|
|
4173
|
+
create,
|
|
4174
|
+
finish,
|
|
4175
|
+
holding,
|
|
4176
|
+
ids
|
|
4177
|
+
};
|
|
4178
|
+
};
|
|
4179
|
+
/** Marks with `mark` set: a same-named one replaced where it stands, or `mark` added last. */
|
|
4180
|
+
const withMark = (marks, mark) => marks.some((held) => markName(held) === markName(mark)) ? marks.map((held) => markName(held) === markName(mark) ? mark : held) : [...marks, mark];
|
|
4181
|
+
const holdsText = (shape) => shape.type === "Paragraph" || shape.type === "Heading" || shape.type === "Node" && shape.holds === "text";
|
|
4182
|
+
const holdsBlocks = (shape) => shape.type === "Node" && shape.holds === "blocks";
|
|
4183
|
+
/** Whether an id already names a block or an insert anywhere in the state. */
|
|
4184
|
+
const taken = (work, id) => work.read(id) !== void 0 || [...work.holding(id)].some((block) => work.read(block).spans.some((span) => span.id === id));
|
|
4185
|
+
/** Whether any of characters `from` up to `to` of an insert are already in the state. */
|
|
4186
|
+
const charsTaken = (read, holders, id, from, to) => read(id) !== void 0 || [...holders].some((block) => read(block).spans.some((span) => span.id === id && span.offset < to && from < span.offset + span.text.length));
|
|
4187
|
+
const findChar = (work, ref, hint) => {
|
|
4188
|
+
const { id, index } = parseChar(ref);
|
|
4189
|
+
const search = (block) => {
|
|
4190
|
+
const spans = work.read(block)?.spans ?? [];
|
|
4191
|
+
for (const [span, candidate] of spans.entries()) if (candidate.id === id && index >= candidate.offset && index < candidate.offset + candidate.text.length) return {
|
|
4192
|
+
block,
|
|
4193
|
+
span,
|
|
4194
|
+
within: index - candidate.offset
|
|
4195
|
+
};
|
|
4196
|
+
};
|
|
4197
|
+
const hinted = hint === void 0 ? void 0 : search(hint);
|
|
4198
|
+
if (hinted !== void 0) return hinted;
|
|
4199
|
+
for (const block of work.holding(id)) {
|
|
4200
|
+
const found = search(block);
|
|
4201
|
+
if (found !== void 0) return found;
|
|
4202
|
+
}
|
|
4203
|
+
};
|
|
4204
|
+
/** Splits a block's span so a boundary falls `within` characters into it. */
|
|
4205
|
+
const cut = (spans, span, within) => {
|
|
4206
|
+
const target = spans[span];
|
|
4207
|
+
if (within <= 0 || within >= target.text.length) return;
|
|
4208
|
+
spans.splice(span, 1, {
|
|
4209
|
+
...target,
|
|
4210
|
+
text: target.text.slice(0, within)
|
|
4211
|
+
}, {
|
|
4212
|
+
...target,
|
|
4213
|
+
offset: target.offset + within,
|
|
4214
|
+
text: target.text.slice(within)
|
|
4215
|
+
});
|
|
4216
|
+
};
|
|
4217
|
+
/** The start of a block; a joined block's start is where its characters went. */
|
|
4218
|
+
const startOf = (work, block, seen = /* @__PURE__ */ new Set()) => {
|
|
4219
|
+
const entry = work.read(block);
|
|
4220
|
+
if (entry === void 0 || seen.has(block)) return void 0;
|
|
4221
|
+
if (entry.joined === void 0) return {
|
|
4222
|
+
block,
|
|
4223
|
+
index: 0
|
|
4224
|
+
};
|
|
4225
|
+
seen.add(block);
|
|
4226
|
+
return entry.joined.after === null ? startOf(work, entry.joined.into, seen) : afterChar(work, entry.joined.after, entry.joined.into) ?? endOf(work, entry.joined.into);
|
|
4227
|
+
};
|
|
4228
|
+
/**
|
|
4229
|
+
* The end of a block, or of the block a joined one went into: where text whose anchor is
|
|
4230
|
+
* gone (rejected, or collected) is kept, near where it was typed and shown.
|
|
4231
|
+
*/
|
|
4232
|
+
const endOf = (work, block) => {
|
|
4233
|
+
const live = liveContainer(work, block);
|
|
4234
|
+
if (live === void 0) return void 0;
|
|
4235
|
+
return {
|
|
4236
|
+
block: live,
|
|
4237
|
+
index: work.read(live).spans.length
|
|
4238
|
+
};
|
|
4239
|
+
};
|
|
4240
|
+
/** The place right after a character, cutting its span so a boundary falls there. */
|
|
4241
|
+
const afterChar = (work, ref, hint) => {
|
|
4242
|
+
const found = findChar(work, ref, hint);
|
|
4243
|
+
if (found === void 0) return void 0;
|
|
4244
|
+
const spans = work.write(found.block).spans;
|
|
4245
|
+
cut(spans, found.span, found.within + 1);
|
|
4246
|
+
return {
|
|
4247
|
+
block: found.block,
|
|
4248
|
+
index: found.span + 1
|
|
4249
|
+
};
|
|
4250
|
+
};
|
|
4251
|
+
/** Every stretch of spans a set of ranges covers, cut so each lies wholly inside or out. */
|
|
4252
|
+
const eachCovered = (work, ranges, visit) => {
|
|
4253
|
+
const ids = new Set(ranges.map((range) => range.id));
|
|
4254
|
+
const candidates = new Set([...ids].flatMap((id) => [...work.holding(id)]));
|
|
4255
|
+
for (const block of candidates) {
|
|
4256
|
+
if (!work.read(block).spans.some((span) => ids.has(span.id))) continue;
|
|
4257
|
+
const spans = work.write(block).spans;
|
|
4258
|
+
for (const range of ranges) for (let index = 0; index < spans.length; index++) {
|
|
4259
|
+
const span = spans[index];
|
|
4260
|
+
if (span.id !== range.id) continue;
|
|
4261
|
+
const end = span.offset + span.text.length;
|
|
4262
|
+
if (range.to <= span.offset || range.from >= end) continue;
|
|
4263
|
+
cut(spans, index, range.from - span.offset);
|
|
4264
|
+
const inside = spans[index];
|
|
4265
|
+
if (inside.offset < range.from) continue;
|
|
4266
|
+
cut(spans, index, range.to - inside.offset);
|
|
4267
|
+
spans[index] = visit(spans[index]);
|
|
4268
|
+
}
|
|
4269
|
+
}
|
|
4270
|
+
};
|
|
4271
|
+
/**
|
|
4272
|
+
* Takes the spans a set of ranges covers out of whatever blocks hold them, cut so each lies
|
|
4273
|
+
* wholly inside, and gives them back in range order, and each range's in character order:
|
|
4274
|
+
* the order of the blocks holding them depends on how the state was reached, not on what
|
|
4275
|
+
* it holds, so it would give two replicas different text.
|
|
4276
|
+
*/
|
|
4277
|
+
const takeCovered = (work, ranges) => {
|
|
4278
|
+
const taken = [];
|
|
4279
|
+
for (const range of ranges) {
|
|
4280
|
+
const ofRange = [];
|
|
4281
|
+
for (const block of work.holding(range.id)) {
|
|
4282
|
+
if (!work.read(block).spans.some((span) => span.id === range.id)) continue;
|
|
4283
|
+
const spans = work.write(block).spans;
|
|
4284
|
+
for (let index = 0; index < spans.length; index++) {
|
|
4285
|
+
const span = spans[index];
|
|
4286
|
+
if (span.id !== range.id) continue;
|
|
4287
|
+
const end = span.offset + span.text.length;
|
|
4288
|
+
if (range.to <= span.offset || range.from >= end) continue;
|
|
4289
|
+
cut(spans, index, range.from - span.offset);
|
|
4290
|
+
const inside = spans[index];
|
|
4291
|
+
if (inside.offset < range.from) continue;
|
|
4292
|
+
cut(spans, index, range.to - inside.offset);
|
|
4293
|
+
ofRange.push(...spans.splice(index, 1));
|
|
4294
|
+
index--;
|
|
4295
|
+
}
|
|
4296
|
+
}
|
|
4297
|
+
taken.push(...ofRange.sort((left, right) => left.offset - right.offset));
|
|
4298
|
+
}
|
|
4299
|
+
return taken;
|
|
4300
|
+
};
|
|
4301
|
+
/**
|
|
4302
|
+
* Where a block was last inserted into each sibling list. A paste inserts each block after the
|
|
4303
|
+
* one before it, so the next anchor is usually found there rather than by a scan of the list,
|
|
4304
|
+
* which made applying a paste quadratic in its blocks. A hint that no longer names the anchor
|
|
4305
|
+
* falls back to the scan.
|
|
4306
|
+
*/
|
|
4307
|
+
const lastInserted = /* @__PURE__ */ new WeakMap();
|
|
4308
|
+
const insertAfterSibling = (list, id, after) => {
|
|
4309
|
+
const hint = lastInserted.get(list);
|
|
4310
|
+
const at = after === null ? 0 : (hint !== void 0 && list[hint] === after ? hint : list.indexOf(after)) + 1;
|
|
4311
|
+
const place = after !== null && at === 0 ? list.length : at;
|
|
4312
|
+
list.splice(place, 0, id);
|
|
4313
|
+
lastInserted.set(list, place);
|
|
4314
|
+
};
|
|
4315
|
+
/**
|
|
4316
|
+
* The container a block's children are in now: a container joined into another passed its
|
|
4317
|
+
* children on, so an op naming it means the one it was joined into. Undefined when gone.
|
|
4318
|
+
*/
|
|
4319
|
+
const liveContainer = (work, id) => {
|
|
4320
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4321
|
+
for (let at = id; !seen.has(at);) {
|
|
4322
|
+
seen.add(at);
|
|
4323
|
+
const entry = work.read(at);
|
|
4324
|
+
if (entry === void 0) return void 0;
|
|
4325
|
+
if (entry.joined === void 0) return at;
|
|
4326
|
+
at = entry.joined.into;
|
|
4327
|
+
}
|
|
4328
|
+
};
|
|
4329
|
+
const isWithin = (work, block, ancestor) => {
|
|
4330
|
+
for (let at = block; at !== null; at = work.read(at)?.parent ?? null) if (at === ancestor) return true;
|
|
4331
|
+
return false;
|
|
4332
|
+
};
|
|
4333
|
+
const applyOp = (work, op) => {
|
|
4334
|
+
switch (op.type) {
|
|
4335
|
+
case "Insert": {
|
|
4336
|
+
const from = op.from ?? 0;
|
|
4337
|
+
if (charsTaken(work.read, work.holding(op.id), op.id, from, from + op.text.length)) return;
|
|
4338
|
+
const place = (op.after === null ? startOf(work, op.block) : afterChar(work, op.after, op.block)) ?? endOf(work, op.block);
|
|
4339
|
+
if (place === void 0) return;
|
|
4340
|
+
const span = {
|
|
4341
|
+
id: op.id,
|
|
4342
|
+
offset: from,
|
|
4343
|
+
text: op.text,
|
|
4344
|
+
marks: op.marks,
|
|
4345
|
+
deleted: false
|
|
4346
|
+
};
|
|
4347
|
+
work.write(place.block).spans.splice(place.index, 0, span);
|
|
4348
|
+
work.hold(place.block, [span]);
|
|
4349
|
+
return;
|
|
4350
|
+
}
|
|
4351
|
+
case "Delete":
|
|
4352
|
+
eachCovered(work, op.ranges, (span) => ({
|
|
4353
|
+
...span,
|
|
4354
|
+
deleted: true
|
|
4355
|
+
}));
|
|
4356
|
+
return;
|
|
4357
|
+
case "Mark":
|
|
4358
|
+
eachCovered(work, op.ranges, (span) => ({
|
|
4359
|
+
...span,
|
|
4360
|
+
marks: withMark(span.marks, op.mark)
|
|
4361
|
+
}));
|
|
4362
|
+
return;
|
|
4363
|
+
case "Unmark":
|
|
4364
|
+
eachCovered(work, op.ranges, (span) => ({
|
|
4365
|
+
...span,
|
|
4366
|
+
marks: span.marks.filter((mark) => markName(mark) !== op.name)
|
|
4367
|
+
}));
|
|
4368
|
+
return;
|
|
4369
|
+
case "InsertBlock": {
|
|
4370
|
+
if (taken(work, op.id)) return;
|
|
4371
|
+
const parent = op.parent === null ? null : liveContainer(work, op.parent);
|
|
4372
|
+
if (parent === void 0) return;
|
|
4373
|
+
const list = work.siblings(parent);
|
|
4374
|
+
if (list === void 0) return;
|
|
4375
|
+
insertAfterSibling(list, op.id, op.after);
|
|
4376
|
+
work.create(op.id, {
|
|
4377
|
+
shape: op.shape,
|
|
4378
|
+
parent,
|
|
4379
|
+
spans: [],
|
|
4380
|
+
children: [],
|
|
4381
|
+
deleted: false
|
|
4382
|
+
});
|
|
4383
|
+
return;
|
|
4384
|
+
}
|
|
4385
|
+
case "DeleteBlock":
|
|
4386
|
+
if (work.read(op.id) === void 0) return;
|
|
4387
|
+
work.write(op.id).deleted = true;
|
|
4388
|
+
return;
|
|
4389
|
+
case "MoveBlock": {
|
|
4390
|
+
const entry = work.read(op.id);
|
|
4391
|
+
if (entry === void 0) return;
|
|
4392
|
+
const parent = op.parent === null ? null : liveContainer(work, op.parent);
|
|
4393
|
+
if (parent === void 0 || parent !== null && isWithin(work, parent, op.id)) return;
|
|
4394
|
+
const destination = work.siblings(parent);
|
|
4395
|
+
if (destination === void 0) return;
|
|
4396
|
+
const source = work.siblings(entry.parent);
|
|
4397
|
+
source.splice(source.indexOf(op.id), 1);
|
|
4398
|
+
insertAfterSibling(destination, op.id, op.after);
|
|
4399
|
+
work.write(op.id).parent = parent;
|
|
4400
|
+
return;
|
|
4401
|
+
}
|
|
4402
|
+
case "Split": {
|
|
4403
|
+
if (taken(work, op.into)) return;
|
|
4404
|
+
const place = (op.after === null ? startOf(work, op.block) : afterChar(work, op.after, op.block)) ?? endOf(work, op.block);
|
|
4405
|
+
if (place === void 0) return;
|
|
4406
|
+
const source = work.read(place.block);
|
|
4407
|
+
if (!holdsText(source.shape)) return;
|
|
4408
|
+
const list = work.siblings(source.parent);
|
|
4409
|
+
const moved = work.write(place.block).spans.splice(place.index);
|
|
4410
|
+
insertAfterSibling(list, op.into, place.block);
|
|
4411
|
+
work.create(op.into, {
|
|
4412
|
+
shape: source.shape,
|
|
4413
|
+
parent: source.parent,
|
|
4414
|
+
spans: moved,
|
|
4415
|
+
children: [],
|
|
4416
|
+
deleted: source.deleted
|
|
4417
|
+
});
|
|
4418
|
+
return;
|
|
4419
|
+
}
|
|
4420
|
+
case "Join": {
|
|
4421
|
+
const removed = work.read(op.removed);
|
|
4422
|
+
if (removed === void 0 || removed.deleted) return;
|
|
4423
|
+
if (holdsText(removed.shape)) {
|
|
4424
|
+
const place = op.at === "end" ? endOf(work, (op.after === null ? void 0 : findChar(work, op.after, op.into)?.block) ?? op.into) : op.after === null ? startOf(work, op.into) : afterChar(work, op.after, op.into);
|
|
4425
|
+
if (place === void 0 || place.block === op.removed) return;
|
|
4426
|
+
const target = work.read(place.block);
|
|
4427
|
+
if (target.deleted || !holdsText(target.shape)) return;
|
|
4428
|
+
const before = target.spans[place.index - 1];
|
|
4429
|
+
const gone = work.write(op.removed);
|
|
4430
|
+
work.write(place.block).spans.splice(place.index, 0, ...gone.spans);
|
|
4431
|
+
work.hold(place.block, gone.spans);
|
|
4432
|
+
gone.spans = [];
|
|
4433
|
+
gone.deleted = true;
|
|
4434
|
+
gone.joined = {
|
|
4435
|
+
into: place.block,
|
|
4436
|
+
after: before === void 0 ? null : charRef(before.id, before.offset + before.text.length - 1)
|
|
4437
|
+
};
|
|
4438
|
+
return;
|
|
4439
|
+
}
|
|
4440
|
+
const into = liveContainer(work, op.into);
|
|
4441
|
+
if (into === void 0) return;
|
|
4442
|
+
const target = work.read(into);
|
|
4443
|
+
if (target.deleted) return;
|
|
4444
|
+
if (isWithin(work, into, op.removed) || isWithin(work, op.removed, into)) return;
|
|
4445
|
+
if (!holdsBlocks(target.shape) || !holdsBlocks(removed.shape)) return;
|
|
4446
|
+
const gone = work.write(op.removed);
|
|
4447
|
+
for (const child of gone.children) work.write(child).parent = into;
|
|
4448
|
+
work.write(into).children.push(...gone.children);
|
|
4449
|
+
gone.children = [];
|
|
4450
|
+
gone.deleted = true;
|
|
4451
|
+
gone.joined = {
|
|
4452
|
+
into,
|
|
4453
|
+
after: null
|
|
4454
|
+
};
|
|
4455
|
+
return;
|
|
4456
|
+
}
|
|
4457
|
+
case "Retype": {
|
|
4458
|
+
const entry = work.read(op.id);
|
|
4459
|
+
if (entry === void 0) return;
|
|
4460
|
+
if (holdsText(entry.shape)) work.write(op.id).shape = op.to.type === "Node" ? {
|
|
4461
|
+
...op.to,
|
|
4462
|
+
holds: "text"
|
|
4463
|
+
} : op.to;
|
|
4464
|
+
else if (holdsBlocks(entry.shape) && op.to.type === "Node") work.write(op.id).shape = {
|
|
4465
|
+
...op.to,
|
|
4466
|
+
holds: "blocks"
|
|
4467
|
+
};
|
|
4468
|
+
return;
|
|
4469
|
+
}
|
|
4470
|
+
case "Undelete":
|
|
4471
|
+
eachCovered(work, op.ranges, (span) => {
|
|
4472
|
+
if (span.kept === true) return span;
|
|
4473
|
+
const { swept: _, ...shown } = span;
|
|
4474
|
+
return {
|
|
4475
|
+
...shown,
|
|
4476
|
+
deleted: false
|
|
4477
|
+
};
|
|
4478
|
+
});
|
|
4479
|
+
return;
|
|
4480
|
+
case "UndeleteBlock": {
|
|
4481
|
+
const entry = work.read(op.id);
|
|
4482
|
+
if (entry === void 0 || !entry.deleted || entry.joined !== void 0) return;
|
|
4483
|
+
const restored = work.write(op.id);
|
|
4484
|
+
restored.deleted = false;
|
|
4485
|
+
delete restored.swept;
|
|
4486
|
+
return;
|
|
4487
|
+
}
|
|
4488
|
+
case "Collect":
|
|
4489
|
+
collect(work);
|
|
4490
|
+
return;
|
|
4491
|
+
case "Unjoin": {
|
|
4492
|
+
const entry = work.read(op.id);
|
|
4493
|
+
if (entry?.joined === void 0) return;
|
|
4494
|
+
const home = liveContainer(work, entry.joined.into);
|
|
4495
|
+
const restored = work.write(op.id);
|
|
4496
|
+
restored.deleted = false;
|
|
4497
|
+
delete restored.swept;
|
|
4498
|
+
delete restored.joined;
|
|
4499
|
+
restored.spans = takeCovered(work, op.ranges);
|
|
4500
|
+
work.hold(op.id, restored.spans);
|
|
4501
|
+
for (const child of op.children) {
|
|
4502
|
+
const moved = work.read(child);
|
|
4503
|
+
if (moved === void 0 || moved.parent !== home || isWithin(work, op.id, child)) continue;
|
|
4504
|
+
const list = work.write(home).children;
|
|
4505
|
+
list.splice(list.indexOf(child), 1);
|
|
4506
|
+
work.write(child).parent = op.id;
|
|
4507
|
+
restored.children.push(child);
|
|
4508
|
+
}
|
|
4509
|
+
return;
|
|
4510
|
+
}
|
|
4511
|
+
case "SetProps": {
|
|
4512
|
+
const entry = work.read(op.id);
|
|
4513
|
+
if (entry?.shape.type !== "Node") return;
|
|
4514
|
+
work.write(op.id).shape = {
|
|
4515
|
+
...entry.shape,
|
|
4516
|
+
props: {
|
|
4517
|
+
...entry.shape.props,
|
|
4518
|
+
...op.props
|
|
4519
|
+
}
|
|
4520
|
+
};
|
|
4521
|
+
return;
|
|
4522
|
+
}
|
|
4523
|
+
}
|
|
4524
|
+
};
|
|
4525
|
+
/**
|
|
4526
|
+
* Removes the text the last `Collect` found deleted, deleted characters and those of a
|
|
4527
|
+
* deleted block alike, then marks what is deleted now for the next one. A late op that
|
|
4528
|
+
* names a removed character takes the fallback a lost anchor does.
|
|
4529
|
+
*
|
|
4530
|
+
* An insert keeps its highest index: where a removed stretch ended it, its last character
|
|
4531
|
+
* stays, deleted. Otherwise `translate` could continue the insert from a lower index, and a
|
|
4532
|
+
* late op naming the removed character would find the new one.
|
|
4533
|
+
*/
|
|
4534
|
+
const collect = (work) => {
|
|
4535
|
+
const ends = /* @__PURE__ */ new Map();
|
|
4536
|
+
for (const block of work.ids()) for (const span of work.read(block)?.spans ?? []) {
|
|
4537
|
+
const end = span.offset + span.text.length;
|
|
4538
|
+
if (end > (ends.get(span.id) ?? 0)) ends.set(span.id, end);
|
|
4539
|
+
}
|
|
4540
|
+
for (const block of work.ids()) {
|
|
4541
|
+
const entry = work.read(block);
|
|
4542
|
+
if (entry === void 0) continue;
|
|
4543
|
+
const blockGone = entry.deleted && entry.swept === true;
|
|
4544
|
+
const collected = (span) => span.kept !== true && (blockGone || span.deleted && span.swept === true);
|
|
4545
|
+
const unmarked = (span) => span.deleted && span.swept !== true;
|
|
4546
|
+
if (!entry.spans.some((span) => collected(span) || unmarked(span))) {
|
|
4547
|
+
if (entry.deleted && entry.swept !== true) work.write(block).swept = true;
|
|
4548
|
+
continue;
|
|
4549
|
+
}
|
|
4550
|
+
const spans = [];
|
|
4551
|
+
for (const span of entry.spans) {
|
|
4552
|
+
const end = span.offset + span.text.length;
|
|
4553
|
+
if (!collected(span)) spans.push(unmarked(span) ? {
|
|
4554
|
+
...span,
|
|
4555
|
+
swept: true
|
|
4556
|
+
} : span);
|
|
4557
|
+
else if (end === ends.get(span.id)) {
|
|
4558
|
+
const last = span.text.slice(-1);
|
|
4559
|
+
spans.push({
|
|
4560
|
+
...span,
|
|
4561
|
+
offset: end - 1,
|
|
4562
|
+
text: last,
|
|
4563
|
+
deleted: true,
|
|
4564
|
+
swept: true,
|
|
4565
|
+
kept: true
|
|
4566
|
+
});
|
|
4567
|
+
}
|
|
4568
|
+
}
|
|
4569
|
+
const written = work.write(block);
|
|
4570
|
+
written.spans = spans;
|
|
4571
|
+
if (entry.deleted) written.swept = true;
|
|
4572
|
+
}
|
|
4573
|
+
};
|
|
4574
|
+
const applied = /* @__PURE__ */ new WeakMap();
|
|
4575
|
+
/**
|
|
4576
|
+
* Folds ops into the state in order. Total: an op whose target is gone, whose ids are
|
|
4577
|
+
* already taken, or that would make the tree cyclic changes nothing, and an insert or split
|
|
4578
|
+
* anchored on a character that is gone (never arrived, or collected) lands at the end of the
|
|
4579
|
+
* block it names, or of the block that one was joined into. It trusts the
|
|
4580
|
+
* state to be one these functions made (the ops are the untrusted input): a state decoded
|
|
4581
|
+
* from elsewhere is not checked for a block listed twice or a cycle of parents.
|
|
4582
|
+
*
|
|
4583
|
+
* The same ops on the same state give back the same state object, so the edit that made
|
|
4584
|
+
* the ops and the durable Message that replays them agree on identity, and whatever is
|
|
4585
|
+
* derived from it (`project`, an editor host's key) is derived once. The ops array is
|
|
4586
|
+
* remembered by identity, so do not change one after applying it.
|
|
4587
|
+
*/
|
|
4588
|
+
const applyOps = (state, ops) => {
|
|
4589
|
+
if (ops.length === 0) return state;
|
|
4590
|
+
const known = applied.get(state)?.get(ops);
|
|
4591
|
+
if (known !== void 0) return known;
|
|
4592
|
+
const work = draft(state);
|
|
4593
|
+
for (const op of ops) applyOp(work, op);
|
|
4594
|
+
const next = work.finish();
|
|
4595
|
+
const byOps = applied.get(state) ?? /* @__PURE__ */ new WeakMap();
|
|
4596
|
+
byOps.set(ops, next);
|
|
4597
|
+
applied.set(state, byOps);
|
|
4598
|
+
return next;
|
|
4599
|
+
};
|
|
4600
|
+
/**
|
|
4601
|
+
* The same ops with each insert that continues the one right before it folded into that one:
|
|
4602
|
+
* a run of typing `translate` carried on as one insert becomes one op again. For ops
|
|
4603
|
+
* `translate` made, which never reuse a character, applying the result shows what applying
|
|
4604
|
+
* `ops` does.
|
|
4605
|
+
*/
|
|
4606
|
+
const coalesce = (ops) => {
|
|
4607
|
+
const out = [];
|
|
4608
|
+
for (const op of ops) {
|
|
4609
|
+
const last = out[out.length - 1];
|
|
4610
|
+
if (op.type === "Insert" && last?.type === "Insert") {
|
|
4611
|
+
const end = (last.from ?? 0) + last.text.length;
|
|
4612
|
+
if (op.id === last.id && op.block === last.block && (op.from ?? 0) === end && op.after === charRef(last.id, end - 1) && sameMarkSet(op.marks, last.marks)) {
|
|
4613
|
+
out[out.length - 1] = {
|
|
4614
|
+
...last,
|
|
4615
|
+
text: last.text + op.text
|
|
4616
|
+
};
|
|
4617
|
+
continue;
|
|
4618
|
+
}
|
|
4619
|
+
}
|
|
4620
|
+
out.push(op);
|
|
4621
|
+
}
|
|
4622
|
+
return out;
|
|
4623
|
+
};
|
|
4624
|
+
/**
|
|
4625
|
+
* The stretches of `state`'s spans each range covers, with where each span is: in range
|
|
4626
|
+
* order, and each range's in character order, whatever order the blocks are indexed in.
|
|
4627
|
+
*/
|
|
4628
|
+
const coveredParts = (state, ranges) => ranges.flatMap((range) => (holdersIn(holdersOf(state), range.id) ?? []).flatMap((block) => lookup(state, block).spans.flatMap((span, index) => {
|
|
4629
|
+
if (span.id !== range.id) return [];
|
|
4630
|
+
const from = Math.max(range.from, span.offset);
|
|
4631
|
+
const to = Math.min(range.to, span.offset + span.text.length);
|
|
4632
|
+
return from < to ? [{
|
|
4633
|
+
block,
|
|
4634
|
+
index,
|
|
4635
|
+
span,
|
|
4636
|
+
range: {
|
|
4637
|
+
id: range.id,
|
|
4638
|
+
from,
|
|
4639
|
+
to
|
|
4640
|
+
}
|
|
4641
|
+
}] : [];
|
|
4642
|
+
})).sort((left, right) => left.span.offset - right.span.offset));
|
|
4643
|
+
/** What a block that holds text or blocks is, as a retype names it. */
|
|
4644
|
+
const retypeTargetOf = (shape) => shape.type === "Paragraph" || shape.type === "Heading" ? shape : shape.type === "Node" && shape.holds !== "none" ? {
|
|
4645
|
+
type: "Node",
|
|
4646
|
+
kind: shape.kind,
|
|
4647
|
+
props: shape.props
|
|
4648
|
+
} : void 0;
|
|
4649
|
+
/** The ops that take back one op, made against the state it was applied to. */
|
|
4650
|
+
const invertOne = (state, op) => {
|
|
4651
|
+
switch (op.type) {
|
|
4652
|
+
case "Insert": {
|
|
4653
|
+
const from = op.from ?? 0;
|
|
4654
|
+
const to = from + op.text.length;
|
|
4655
|
+
const holders = holdersIn(holdersOf(state), op.id) ?? [];
|
|
4656
|
+
return charsTaken((id) => lookup(state, id), holders, op.id, from, to) ? [] : [{
|
|
4657
|
+
type: "Delete",
|
|
4658
|
+
ranges: [{
|
|
4659
|
+
id: op.id,
|
|
4660
|
+
from,
|
|
4661
|
+
to
|
|
4662
|
+
}]
|
|
4663
|
+
}];
|
|
4664
|
+
}
|
|
4665
|
+
case "Delete": {
|
|
4666
|
+
const ranges = coveredParts(state, op.ranges).filter((part) => !part.span.deleted).map((part) => part.range);
|
|
4667
|
+
return ranges.length === 0 ? [] : [{
|
|
4668
|
+
type: "Undelete",
|
|
4669
|
+
ranges
|
|
4670
|
+
}];
|
|
4671
|
+
}
|
|
4672
|
+
case "Undelete": {
|
|
4673
|
+
const ranges = coveredParts(state, op.ranges).filter((part) => part.span.deleted).map((part) => part.range);
|
|
4674
|
+
return ranges.length === 0 ? [] : [{
|
|
4675
|
+
type: "Delete",
|
|
4676
|
+
ranges
|
|
4677
|
+
}];
|
|
4678
|
+
}
|
|
4679
|
+
case "Mark":
|
|
4680
|
+
case "Unmark": {
|
|
4681
|
+
const name = op.type === "Mark" ? markName(op.mark) : op.name;
|
|
4682
|
+
const inverse = [];
|
|
4683
|
+
const unmarked = [];
|
|
4684
|
+
for (const { span, range } of coveredParts(state, op.ranges)) {
|
|
4685
|
+
const prior = span.marks.find((mark) => markName(mark) === name);
|
|
4686
|
+
if (prior === void 0) {
|
|
4687
|
+
if (op.type === "Mark") unmarked.push(range);
|
|
4688
|
+
} else inverse.push({
|
|
4689
|
+
type: "Mark",
|
|
4690
|
+
ranges: [range],
|
|
4691
|
+
mark: prior
|
|
4692
|
+
});
|
|
4693
|
+
}
|
|
4694
|
+
return unmarked.length === 0 ? inverse : [{
|
|
4695
|
+
type: "Unmark",
|
|
4696
|
+
ranges: unmarked,
|
|
4697
|
+
name
|
|
4698
|
+
}, ...inverse];
|
|
4699
|
+
}
|
|
4700
|
+
case "InsertBlock": return lookup(state, op.id) !== void 0 ? [] : [{
|
|
4701
|
+
type: "DeleteBlock",
|
|
4702
|
+
id: op.id
|
|
4703
|
+
}];
|
|
4704
|
+
case "DeleteBlock": {
|
|
4705
|
+
const entry = lookup(state, op.id);
|
|
4706
|
+
return entry === void 0 || entry.deleted ? [] : [{
|
|
4707
|
+
type: "UndeleteBlock",
|
|
4708
|
+
id: op.id
|
|
4709
|
+
}];
|
|
4710
|
+
}
|
|
4711
|
+
case "UndeleteBlock": {
|
|
4712
|
+
const entry = lookup(state, op.id);
|
|
4713
|
+
return entry?.deleted === true && entry.joined === void 0 ? [{
|
|
4714
|
+
type: "DeleteBlock",
|
|
4715
|
+
id: op.id
|
|
4716
|
+
}] : [];
|
|
4717
|
+
}
|
|
4718
|
+
case "MoveBlock": {
|
|
4719
|
+
const entry = lookup(state, op.id);
|
|
4720
|
+
if (entry === void 0) return [];
|
|
4721
|
+
const siblings = entry.parent === null ? state.root : lookup(state, entry.parent)?.children ?? [];
|
|
4722
|
+
const at = siblings.indexOf(op.id);
|
|
4723
|
+
return [{
|
|
4724
|
+
type: "MoveBlock",
|
|
4725
|
+
id: op.id,
|
|
4726
|
+
parent: entry.parent,
|
|
4727
|
+
after: at > 0 ? siblings[at - 1] : null
|
|
4728
|
+
}];
|
|
4729
|
+
}
|
|
4730
|
+
case "Split": return lookup(state, op.into) !== void 0 ? [] : [{
|
|
4731
|
+
type: "Join",
|
|
4732
|
+
into: op.block,
|
|
4733
|
+
removed: op.into,
|
|
4734
|
+
after: op.after,
|
|
4735
|
+
at: "end"
|
|
4736
|
+
}];
|
|
4737
|
+
case "Join": {
|
|
4738
|
+
const removed = lookup(state, op.removed);
|
|
4739
|
+
if (removed === void 0 || removed.deleted) return [];
|
|
4740
|
+
return [{
|
|
4741
|
+
type: "Unjoin",
|
|
4742
|
+
id: op.removed,
|
|
4743
|
+
ranges: removed.spans.map((span) => ({
|
|
4744
|
+
id: span.id,
|
|
4745
|
+
from: span.offset,
|
|
4746
|
+
to: span.offset + span.text.length
|
|
4747
|
+
})),
|
|
4748
|
+
children: [...removed.children]
|
|
4749
|
+
}];
|
|
4750
|
+
}
|
|
4751
|
+
case "Unjoin": {
|
|
4752
|
+
const joined = lookup(state, op.id)?.joined;
|
|
4753
|
+
if (joined === void 0) return [];
|
|
4754
|
+
const parts = coveredParts(state, op.ranges);
|
|
4755
|
+
const first = parts[0];
|
|
4756
|
+
if (first === void 0) return [{
|
|
4757
|
+
type: "Join",
|
|
4758
|
+
into: joined.into,
|
|
4759
|
+
removed: op.id,
|
|
4760
|
+
after: joined.after
|
|
4761
|
+
}];
|
|
4762
|
+
const spans = lookup(state, first.block).spans;
|
|
4763
|
+
const before = spans[first.index - 1];
|
|
4764
|
+
const after = before === void 0 ? null : charRef(before.id, before.offset + before.text.length - 1);
|
|
4765
|
+
const last = Math.max(...parts.filter((part) => part.block === first.block).map((part) => part.index));
|
|
4766
|
+
return [{
|
|
4767
|
+
type: "Join",
|
|
4768
|
+
into: first.block,
|
|
4769
|
+
removed: op.id,
|
|
4770
|
+
after,
|
|
4771
|
+
...last === spans.length - 1 ? { at: "end" } : {}
|
|
4772
|
+
}];
|
|
4773
|
+
}
|
|
4774
|
+
case "Collect": return [];
|
|
4775
|
+
case "Retype": {
|
|
4776
|
+
const entry = lookup(state, op.id);
|
|
4777
|
+
const prior = entry === void 0 ? void 0 : retypeTargetOf(entry.shape);
|
|
4778
|
+
return prior === void 0 ? [] : [{
|
|
4779
|
+
type: "Retype",
|
|
4780
|
+
id: op.id,
|
|
4781
|
+
to: prior
|
|
4782
|
+
}];
|
|
4783
|
+
}
|
|
4784
|
+
case "SetProps": {
|
|
4785
|
+
const shape = lookup(state, op.id)?.shape;
|
|
4786
|
+
if (shape?.type !== "Node") return [];
|
|
4787
|
+
const prior = Object.fromEntries(Object.keys(op.props).filter((key) => Object.hasOwn(shape.props, key)).map((key) => [key, shape.props[key]]));
|
|
4788
|
+
return Object.keys(prior).length === 0 ? [] : [{
|
|
4789
|
+
type: "SetProps",
|
|
4790
|
+
id: op.id,
|
|
4791
|
+
props: prior
|
|
4792
|
+
}];
|
|
4793
|
+
}
|
|
4794
|
+
}
|
|
4795
|
+
};
|
|
4796
|
+
/**
|
|
4797
|
+
* The ops that undo `ops`, made against `state`, the state `ops` were applied to. Applied
|
|
4798
|
+
* after `ops` and after whatever else has happened since, they take back what `ops` did
|
|
4799
|
+
* and leave the rest alone. Characters it inserted are deleted, and characters it deleted
|
|
4800
|
+
* come back. Marks, block types and props return to what they were, a split is joined and
|
|
4801
|
+
* a join split out, and a moved block goes back beside the sibling it followed. A prop it
|
|
4802
|
+
* added where there was none stays, since `SetProps` cannot delete one. Inverting the
|
|
4803
|
+
* result gives the ops that redo it.
|
|
4804
|
+
*/
|
|
4805
|
+
const invert = (state, ops) => {
|
|
4806
|
+
const inverses = [];
|
|
4807
|
+
let current = state;
|
|
4808
|
+
for (const op of ops) {
|
|
4809
|
+
inverses.push(invertOne(current, op));
|
|
4810
|
+
current = applyOps(current, [op]);
|
|
4811
|
+
}
|
|
4812
|
+
return inverses.reverse().flat();
|
|
4813
|
+
};
|
|
4814
|
+
const appendChars = (chars, id, from, to) => {
|
|
4815
|
+
const last = chars[chars.length - 1];
|
|
4816
|
+
if (last !== void 0 && last.id === id && last.to === from) chars[chars.length - 1] = {
|
|
4817
|
+
id,
|
|
4818
|
+
from: last.from,
|
|
4819
|
+
to
|
|
4820
|
+
};
|
|
4821
|
+
else chars.push({
|
|
4822
|
+
id,
|
|
4823
|
+
from,
|
|
4824
|
+
to
|
|
4825
|
+
});
|
|
4826
|
+
};
|
|
4827
|
+
const projectRuns = (block, entry) => {
|
|
4828
|
+
const runs = [];
|
|
4829
|
+
const shown = [];
|
|
4830
|
+
for (const span of entry.spans) {
|
|
4831
|
+
if (span.deleted) continue;
|
|
4832
|
+
const previous = runs[runs.length - 1];
|
|
4833
|
+
if (previous !== void 0 && sameMarkSet(previous.marks, span.marks)) {
|
|
4834
|
+
runs[runs.length - 1] = {
|
|
4835
|
+
...previous,
|
|
4836
|
+
text: previous.text + span.text
|
|
4837
|
+
};
|
|
4838
|
+
appendChars(shown[shown.length - 1].chars, span.id, span.offset, span.offset + span.text.length);
|
|
4839
|
+
continue;
|
|
4840
|
+
}
|
|
4841
|
+
const id = NodeId.make(charRef(span.id, span.offset));
|
|
4842
|
+
runs.push({
|
|
4843
|
+
type: "Text",
|
|
4844
|
+
id,
|
|
4845
|
+
text: span.text,
|
|
4846
|
+
marks: span.marks
|
|
4847
|
+
});
|
|
4848
|
+
shown.push({
|
|
4849
|
+
id,
|
|
4850
|
+
chars: [{
|
|
4851
|
+
id: span.id,
|
|
4852
|
+
from: span.offset,
|
|
4853
|
+
to: span.offset + span.text.length
|
|
4854
|
+
}]
|
|
4855
|
+
});
|
|
4856
|
+
}
|
|
4857
|
+
if (runs.length === 0) {
|
|
4858
|
+
const id = emptyRunId(block);
|
|
4859
|
+
runs.push({
|
|
4860
|
+
type: "Text",
|
|
4861
|
+
id,
|
|
4862
|
+
text: "",
|
|
4863
|
+
marks: []
|
|
4864
|
+
});
|
|
4865
|
+
shown.push({
|
|
4866
|
+
id,
|
|
4867
|
+
chars: []
|
|
4868
|
+
});
|
|
4869
|
+
}
|
|
4870
|
+
return {
|
|
4871
|
+
runs,
|
|
4872
|
+
shown
|
|
4873
|
+
};
|
|
4874
|
+
};
|
|
4875
|
+
const projections = /* @__PURE__ */ new WeakMap();
|
|
4876
|
+
const projectedBlocks = /* @__PURE__ */ new WeakMap();
|
|
4877
|
+
const projection = (state) => {
|
|
4878
|
+
const cached = projections.get(state);
|
|
4879
|
+
if (cached !== void 0) return cached;
|
|
4880
|
+
const runs = /* @__PURE__ */ new Map();
|
|
4881
|
+
const blocks = (ids) => ids.flatMap((id) => {
|
|
4882
|
+
const entry = lookup(state, id);
|
|
4883
|
+
if (entry === void 0 || entry.deleted) return [];
|
|
4884
|
+
const nested = holdsBlocks(entry.shape) ? blocks(entry.children) : [];
|
|
4885
|
+
const known = projectedBlocks.get(entry);
|
|
4886
|
+
if (known !== void 0 && known.nested.length === nested.length && known.nested.every((child, at) => child === nested[at])) {
|
|
4887
|
+
if (known.shown !== void 0) runs.set(id, known.shown);
|
|
4888
|
+
return [known.block];
|
|
4889
|
+
}
|
|
4890
|
+
const made = projectBlock(id, entry, nested);
|
|
4891
|
+
projectedBlocks.set(entry, {
|
|
4892
|
+
...made,
|
|
4893
|
+
nested
|
|
4894
|
+
});
|
|
4895
|
+
if (made.shown !== void 0) runs.set(id, made.shown);
|
|
4896
|
+
return [made.block];
|
|
4897
|
+
});
|
|
4898
|
+
const result = {
|
|
4899
|
+
document: {
|
|
4900
|
+
version: 1,
|
|
4901
|
+
children: blocks(state.root)
|
|
4902
|
+
},
|
|
4903
|
+
runs
|
|
4904
|
+
};
|
|
4905
|
+
projections.set(state, result);
|
|
4906
|
+
return result;
|
|
4907
|
+
};
|
|
4908
|
+
const projectBlock = (id, entry, nested) => {
|
|
4909
|
+
const nodeId = NodeId.make(id);
|
|
4910
|
+
const shape = entry.shape;
|
|
4911
|
+
if (shape.type === "Unknown") return {
|
|
4912
|
+
block: {
|
|
4913
|
+
type: "Unknown",
|
|
4914
|
+
id: nodeId,
|
|
4915
|
+
originalType: shape.originalType,
|
|
4916
|
+
props: shape.props,
|
|
4917
|
+
children: []
|
|
4918
|
+
},
|
|
4919
|
+
shown: void 0
|
|
4920
|
+
};
|
|
4921
|
+
if (shape.type === "Node" && shape.holds !== "text") return {
|
|
4922
|
+
block: {
|
|
4923
|
+
type: "Node",
|
|
4924
|
+
kind: shape.kind,
|
|
4925
|
+
id: nodeId,
|
|
4926
|
+
props: shape.props,
|
|
4927
|
+
children: [],
|
|
4928
|
+
...shape.holds === "blocks" ? { blocks: nested } : {}
|
|
4929
|
+
},
|
|
4930
|
+
shown: void 0
|
|
4931
|
+
};
|
|
4932
|
+
const { runs: children, shown } = projectRuns(id, entry);
|
|
4933
|
+
if (shape.type === "Paragraph") return {
|
|
4934
|
+
block: {
|
|
4935
|
+
type: "Paragraph",
|
|
4936
|
+
id: nodeId,
|
|
4937
|
+
children
|
|
4938
|
+
},
|
|
4939
|
+
shown
|
|
4940
|
+
};
|
|
4941
|
+
if (shape.type === "Heading") return {
|
|
4942
|
+
block: {
|
|
4943
|
+
type: "Heading",
|
|
4944
|
+
id: nodeId,
|
|
4945
|
+
level: shape.level,
|
|
4946
|
+
children
|
|
4947
|
+
},
|
|
4948
|
+
shown
|
|
4949
|
+
};
|
|
4950
|
+
return {
|
|
4951
|
+
block: {
|
|
4952
|
+
type: "Node",
|
|
4953
|
+
kind: shape.kind,
|
|
4954
|
+
id: nodeId,
|
|
4955
|
+
props: shape.props,
|
|
4956
|
+
children
|
|
4957
|
+
},
|
|
4958
|
+
shown
|
|
4959
|
+
};
|
|
4960
|
+
};
|
|
4961
|
+
/** The document a state shows: visible blocks and characters, with runs merged by marks. */
|
|
4962
|
+
const project = (state) => projection(state).document;
|
|
4963
|
+
const shapeOf = (block) => {
|
|
4964
|
+
switch (block.type) {
|
|
4965
|
+
case "Paragraph": return { type: "Paragraph" };
|
|
4966
|
+
case "Heading": return {
|
|
4967
|
+
type: "Heading",
|
|
4968
|
+
level: block.level
|
|
4969
|
+
};
|
|
4970
|
+
case "Unknown": return {
|
|
4971
|
+
type: "Unknown",
|
|
4972
|
+
originalType: block.originalType,
|
|
4973
|
+
props: block.props
|
|
4974
|
+
};
|
|
4975
|
+
case "Node": return {
|
|
4976
|
+
type: "Node",
|
|
4977
|
+
kind: block.kind,
|
|
4978
|
+
props: block.props,
|
|
4979
|
+
holds: block.blocks !== void 0 ? "blocks" : block.children.length > 0 ? "text" : "none"
|
|
4980
|
+
};
|
|
4981
|
+
}
|
|
4982
|
+
};
|
|
4983
|
+
/** The ops that build these blocks, and their text, inside `parent` after `after`. */
|
|
4984
|
+
const buildOps = (blocks, parent, after, mint, named = () => {}) => {
|
|
4985
|
+
const ops = [];
|
|
4986
|
+
let previous = after;
|
|
4987
|
+
for (const block of blocks) {
|
|
4988
|
+
const id = mint();
|
|
4989
|
+
named(block, id);
|
|
4990
|
+
ops.push({
|
|
4991
|
+
type: "InsertBlock",
|
|
4992
|
+
id,
|
|
4993
|
+
shape: shapeOf(block),
|
|
4994
|
+
parent,
|
|
4995
|
+
after: previous
|
|
4996
|
+
});
|
|
4997
|
+
let last = null;
|
|
4998
|
+
for (const run of block.children) {
|
|
4999
|
+
if (run.text.length === 0) continue;
|
|
5000
|
+
const key = mint();
|
|
5001
|
+
ops.push({
|
|
5002
|
+
type: "Insert",
|
|
5003
|
+
id: key,
|
|
5004
|
+
block: id,
|
|
5005
|
+
after: last,
|
|
5006
|
+
text: run.text,
|
|
5007
|
+
marks: run.marks
|
|
5008
|
+
});
|
|
5009
|
+
last = charRef(key, run.text.length - 1);
|
|
5010
|
+
}
|
|
5011
|
+
if (block.type === "Node" && block.blocks !== void 0) ops.push(...buildOps(block.blocks, id, null, mint, named));
|
|
5012
|
+
previous = id;
|
|
5013
|
+
}
|
|
5014
|
+
return ops;
|
|
5015
|
+
};
|
|
5016
|
+
/** A minter of fresh ids under one key: `key:0`, `key:1`, and so on. */
|
|
5017
|
+
const minter = (key) => {
|
|
5018
|
+
const prefix = ReplicatedId.make(`${key}:x`).slice(0, -2);
|
|
5019
|
+
let next = 0;
|
|
5020
|
+
return () => `${prefix}:${next++}`;
|
|
5021
|
+
};
|
|
5022
|
+
/**
|
|
5023
|
+
* A state that shows `document`, with every block and character given a new identity
|
|
5024
|
+
* under `key`, which must be unique among the keys this state's ops are minted under.
|
|
5025
|
+
*/
|
|
5026
|
+
const fromDocument = (document, key) => applyOps(empty, buildOps(document.children, null, null, minter(key)));
|
|
5027
|
+
/** A caret or selection end held by what it sits after, so it survives others' edits. */
|
|
5028
|
+
const AnchoredPosition = Schema.Struct({
|
|
5029
|
+
block: ReplicatedId,
|
|
5030
|
+
/** The character just before the position, or null at the block's start. */
|
|
5031
|
+
after: Schema.NullOr(CharRef),
|
|
5032
|
+
affinity: Schema.Literals(["before", "after"])
|
|
5033
|
+
});
|
|
5034
|
+
const AnchoredSelection = Schema.Union([Schema.Struct({
|
|
5035
|
+
type: Schema.Literal("Range"),
|
|
5036
|
+
anchor: AnchoredPosition,
|
|
5037
|
+
focus: AnchoredPosition
|
|
5038
|
+
}), Schema.Struct({
|
|
5039
|
+
type: Schema.Literal("Node"),
|
|
5040
|
+
node: ReplicatedId
|
|
5041
|
+
})]);
|
|
5042
|
+
const charsLength = (chars) => chars.reduce((total, range) => total + range.to - range.from, 0);
|
|
5043
|
+
const sliceChars = (chars, from, to) => {
|
|
5044
|
+
const out = [];
|
|
5045
|
+
let at = 0;
|
|
5046
|
+
for (const range of chars) {
|
|
5047
|
+
const length = range.to - range.from;
|
|
5048
|
+
const start = Math.max(from, at);
|
|
5049
|
+
const end = Math.min(to, at + length);
|
|
5050
|
+
if (start < end) appendChars(out, range.id, range.from + start - at, range.from + end - at);
|
|
5051
|
+
at += length;
|
|
5052
|
+
}
|
|
5053
|
+
return out;
|
|
5054
|
+
};
|
|
5055
|
+
const concatChars = (...lists) => {
|
|
5056
|
+
const out = [];
|
|
5057
|
+
for (const list of lists) for (const range of list) appendChars(out, range.id, range.from, range.to);
|
|
5058
|
+
return out;
|
|
5059
|
+
};
|
|
5060
|
+
const charAt = (chars, index) => {
|
|
5061
|
+
const [range] = sliceChars(chars, index, index + 1);
|
|
5062
|
+
return charRef(range.id, range.from);
|
|
5063
|
+
};
|
|
5064
|
+
/**
|
|
5065
|
+
* A map that derives each key on first read and keeps what it derived, so a translation
|
|
5066
|
+
* builds only the part of the shadow it touches.
|
|
5067
|
+
*/
|
|
5068
|
+
var Lazy = class {
|
|
5069
|
+
derive;
|
|
5070
|
+
own = /* @__PURE__ */ new Map();
|
|
5071
|
+
constructor(derive) {
|
|
5072
|
+
this.derive = derive;
|
|
5073
|
+
}
|
|
5074
|
+
get(key) {
|
|
5075
|
+
if (this.own.has(key)) return this.own.get(key);
|
|
5076
|
+
const value = this.derive(key);
|
|
5077
|
+
if (value !== void 0) this.own.set(key, value);
|
|
5078
|
+
return value;
|
|
5079
|
+
}
|
|
5080
|
+
has(key) {
|
|
5081
|
+
return this.get(key) !== void 0;
|
|
5082
|
+
}
|
|
5083
|
+
set(key, value) {
|
|
5084
|
+
this.own.set(key, value);
|
|
5085
|
+
}
|
|
5086
|
+
/** Forgets a block the edit joined away, whose runs another block now holds. */
|
|
5087
|
+
delete(key) {
|
|
5088
|
+
this.own.delete(key);
|
|
5089
|
+
}
|
|
5090
|
+
};
|
|
5091
|
+
const ROOT = null;
|
|
5092
|
+
/** The shadow for `document`, each block keeping the characters `chars` says it held. */
|
|
5093
|
+
const shadowOf = (document, chars, names) => {
|
|
5094
|
+
const index = nodeIndex(document);
|
|
5095
|
+
const blockNamed = (id) => {
|
|
5096
|
+
const node = index.nodes.get(id);
|
|
5097
|
+
return node === void 0 || node.type === "Text" ? void 0 : node;
|
|
5098
|
+
};
|
|
5099
|
+
return {
|
|
5100
|
+
document,
|
|
5101
|
+
names,
|
|
5102
|
+
runs: new Lazy((id) => {
|
|
5103
|
+
const block = blockNamed(id);
|
|
5104
|
+
if (block === void 0) return void 0;
|
|
5105
|
+
const held = chars(id);
|
|
5106
|
+
let at = 0;
|
|
5107
|
+
return block.children.map((run) => {
|
|
5108
|
+
const slice = sliceChars(held, at, at + run.text.length);
|
|
5109
|
+
at += run.text.length;
|
|
5110
|
+
return {
|
|
5111
|
+
id: run.id,
|
|
5112
|
+
chars: slice,
|
|
5113
|
+
marks: run.marks
|
|
5114
|
+
};
|
|
5115
|
+
});
|
|
5116
|
+
}),
|
|
5117
|
+
children: new Lazy((parent) => {
|
|
5118
|
+
if (parent === ROOT) return document.children.map((block) => block.id);
|
|
5119
|
+
const block = blockNamed(parent);
|
|
5120
|
+
return block?.type === "Node" && block.blocks !== void 0 ? block.blocks.map((child) => child.id) : void 0;
|
|
5121
|
+
}),
|
|
5122
|
+
parents: new Lazy((block) => index.parentOf.get(block))
|
|
5123
|
+
};
|
|
5124
|
+
};
|
|
5125
|
+
/** The characters each block holds once a shadow's edits are done. */
|
|
5126
|
+
const charsAfter = (shadow, before) => (block) => {
|
|
5127
|
+
const runs = shadow.runs.own.get(block);
|
|
5128
|
+
return runs === void 0 ? before(block) : concatChars(...runs.map((run) => run.chars));
|
|
5129
|
+
};
|
|
5130
|
+
/**
|
|
5131
|
+
* Restates an edit's transactions as ops against `state`, which the edit ran on the
|
|
5132
|
+
* projection of. `key` must be unique to this edit among everything the state has seen: it
|
|
5133
|
+
* names the edit's new characters and blocks. Also anchors the edit's resulting selection.
|
|
5134
|
+
* Throws if the transactions do not apply to the projection, which is a caller's bug. The
|
|
5135
|
+
* transactions are replayed with `apply`'s default transforms, as `RichText.run` applies
|
|
5136
|
+
* them; an edit normalized by other transforms does not translate.
|
|
5137
|
+
*
|
|
5138
|
+
* Text typed right after the last character of an insert `continues` accepts carries on that
|
|
5139
|
+
* insert (`from` its next index) instead of starting one, so `coalesce` can fold a run of
|
|
5140
|
+
* typing into one op. Accept only inserts this replica minted: two replicas continuing one
|
|
5141
|
+
* insert at once would both claim its next characters, and the later would be dropped.
|
|
5142
|
+
*/
|
|
5143
|
+
const translate = (state, result, key, options = {}) => {
|
|
5144
|
+
const mint = minter(key);
|
|
5145
|
+
const continues = options.continues ?? (() => false);
|
|
5146
|
+
const lengths = /* @__PURE__ */ new Map();
|
|
5147
|
+
const lengthOf = (id) => {
|
|
5148
|
+
const known = lengths.get(id);
|
|
5149
|
+
if (known !== void 0) return known;
|
|
5150
|
+
let length = 0;
|
|
5151
|
+
for (const block of holdersIn(holdersOf(state), id) ?? []) for (const span of lookup(state, block).spans) if (span.id === id) length = Math.max(length, span.offset + span.text.length);
|
|
5152
|
+
lengths.set(id, length);
|
|
5153
|
+
return length;
|
|
5154
|
+
};
|
|
5155
|
+
const next = (after, length) => {
|
|
5156
|
+
if (after !== null) {
|
|
5157
|
+
const { id, index } = parseChar(after);
|
|
5158
|
+
if (continues(id) && lengthOf(id) === index + 1) {
|
|
5159
|
+
lengths.set(id, index + 1 + length);
|
|
5160
|
+
return {
|
|
5161
|
+
id,
|
|
5162
|
+
from: index + 1
|
|
5163
|
+
};
|
|
5164
|
+
}
|
|
5165
|
+
}
|
|
5166
|
+
const id = mint();
|
|
5167
|
+
lengths.set(id, length);
|
|
5168
|
+
return {
|
|
5169
|
+
id,
|
|
5170
|
+
from: 0
|
|
5171
|
+
};
|
|
5172
|
+
};
|
|
5173
|
+
const ops = [];
|
|
5174
|
+
const names = /* @__PURE__ */ new Map();
|
|
5175
|
+
const start = projection(state);
|
|
5176
|
+
let chars = projectedChars(start);
|
|
5177
|
+
let current = {
|
|
5178
|
+
document: start.document,
|
|
5179
|
+
selection: null
|
|
5180
|
+
};
|
|
5181
|
+
for (const transaction of result.transactions) {
|
|
5182
|
+
const applied = apply(current, transaction);
|
|
5183
|
+
if (!applied.ok) throw new Error(`translate: a transaction was refused (${applied.error})`);
|
|
5184
|
+
const shadow = shadowOf(current.document, chars, names);
|
|
5185
|
+
for (const operation of transaction) translateOne(shadow, operation, ops, mint, next);
|
|
5186
|
+
current = applied.state;
|
|
5187
|
+
chars = charsAfter(shadow, chars);
|
|
5188
|
+
}
|
|
5189
|
+
return {
|
|
5190
|
+
ops,
|
|
5191
|
+
selection: anchorIn(shadowOf(current.document, chars, names), result.state.selection)
|
|
5192
|
+
};
|
|
5193
|
+
};
|
|
5194
|
+
const replicated = (shadow, block) => shadow.names.get(block) ?? block;
|
|
5195
|
+
/**
|
|
5196
|
+
* A run and where it is. The blocks this translation has already touched come first, since
|
|
5197
|
+
* a run may have moved between them; any other run is where the document has it.
|
|
5198
|
+
*/
|
|
5199
|
+
const locateRun$1 = (shadow, run) => {
|
|
5200
|
+
const inBlock = (block, runs) => {
|
|
5201
|
+
const index = runs.findIndex((candidate) => candidate.id === run);
|
|
5202
|
+
return index === -1 ? void 0 : {
|
|
5203
|
+
block,
|
|
5204
|
+
runs,
|
|
5205
|
+
index,
|
|
5206
|
+
run: runs[index]
|
|
5207
|
+
};
|
|
5208
|
+
};
|
|
5209
|
+
for (const [block, runs] of shadow.runs.own) {
|
|
5210
|
+
const found = inBlock(block, runs);
|
|
5211
|
+
if (found !== void 0) return found;
|
|
5212
|
+
}
|
|
5213
|
+
const block = nodeIndex(shadow.document).blockOf.get(run)?.id;
|
|
5214
|
+
const runs = block === void 0 ? void 0 : shadow.runs.get(block);
|
|
5215
|
+
const found = runs === void 0 ? void 0 : inBlock(block, runs);
|
|
5216
|
+
if (found === void 0) throw new Error(`translate: no run ${run}`);
|
|
5217
|
+
return found;
|
|
5218
|
+
};
|
|
5219
|
+
/** Each block's characters as a projection shows them. */
|
|
5220
|
+
const projectedChars = (start) => (block) => concatChars(...(start.runs.get(block) ?? []).map((run) => run.chars));
|
|
5221
|
+
/** The character before `offset` in a run, looking back through earlier runs of its block. */
|
|
5222
|
+
const charBefore = (runs, index, offset) => {
|
|
5223
|
+
if (offset > 0) return charAt(runs[index].chars, offset - 1);
|
|
5224
|
+
for (let earlier = index - 1; earlier >= 0; earlier--) {
|
|
5225
|
+
const chars = runs[earlier].chars;
|
|
5226
|
+
const length = charsLength(chars);
|
|
5227
|
+
if (length > 0) return charAt(chars, length - 1);
|
|
5228
|
+
}
|
|
5229
|
+
return null;
|
|
5230
|
+
};
|
|
5231
|
+
const siblingBefore = (shadow, parent, index) => index === 0 ? null : replicated(shadow, shadow.children.get(parent)[index - 1]);
|
|
5232
|
+
const removeFromParent = (shadow, block) => {
|
|
5233
|
+
const list = shadow.children.get(shadow.parents.get(block) ?? ROOT);
|
|
5234
|
+
list.splice(list.indexOf(block), 1);
|
|
5235
|
+
};
|
|
5236
|
+
/** Records a block subtree the edit inserted, with minted names for its blocks. */
|
|
5237
|
+
const addSubtree = (shadow, block, parent) => {
|
|
5238
|
+
shadow.parents.set(block.id, parent);
|
|
5239
|
+
shadow.runs.set(block.id, block.children.map((run) => ({
|
|
5240
|
+
id: run.id,
|
|
5241
|
+
chars: [],
|
|
5242
|
+
marks: run.marks
|
|
5243
|
+
})));
|
|
5244
|
+
if (block.type === "Node" && block.blocks !== void 0) {
|
|
5245
|
+
shadow.children.set(block.id, block.blocks.map((child) => child.id));
|
|
5246
|
+
for (const child of block.blocks) addSubtree(shadow, child, block.id);
|
|
5247
|
+
}
|
|
5248
|
+
};
|
|
5249
|
+
const translateOne = (shadow, operation, ops, mint, next) => {
|
|
5250
|
+
switch (operation.type) {
|
|
5251
|
+
case "SetSelection": return;
|
|
5252
|
+
case "InsertText": {
|
|
5253
|
+
if (operation.text.length === 0) return;
|
|
5254
|
+
const { block, runs, index, run } = locateRun$1(shadow, operation.at.node);
|
|
5255
|
+
const after = charBefore(runs, index, operation.at.offset);
|
|
5256
|
+
const { id, from } = next(after, operation.text.length);
|
|
5257
|
+
ops.push({
|
|
5258
|
+
type: "Insert",
|
|
5259
|
+
id,
|
|
5260
|
+
block: replicated(shadow, block),
|
|
5261
|
+
after,
|
|
5262
|
+
text: operation.text,
|
|
5263
|
+
marks: run.marks,
|
|
5264
|
+
...from === 0 ? {} : { from }
|
|
5265
|
+
});
|
|
5266
|
+
run.chars = concatChars(sliceChars(run.chars, 0, operation.at.offset), [{
|
|
5267
|
+
id,
|
|
5268
|
+
from,
|
|
5269
|
+
to: from + operation.text.length
|
|
5270
|
+
}], sliceChars(run.chars, operation.at.offset, charsLength(run.chars)));
|
|
5271
|
+
return;
|
|
5272
|
+
}
|
|
5273
|
+
case "DeleteText": {
|
|
5274
|
+
const { run } = locateRun$1(shadow, operation.node);
|
|
5275
|
+
const removed = sliceChars(run.chars, operation.from, operation.to);
|
|
5276
|
+
if (removed.length > 0) ops.push({
|
|
5277
|
+
type: "Delete",
|
|
5278
|
+
ranges: removed
|
|
5279
|
+
});
|
|
5280
|
+
run.chars = concatChars(sliceChars(run.chars, 0, operation.from), sliceChars(run.chars, operation.to, charsLength(run.chars)));
|
|
5281
|
+
return;
|
|
5282
|
+
}
|
|
5283
|
+
case "AddMark": {
|
|
5284
|
+
const { run } = locateRun$1(shadow, operation.node);
|
|
5285
|
+
if (run.marks.some((mark) => sameMark(mark, operation.mark))) return;
|
|
5286
|
+
if (run.chars.length > 0) ops.push({
|
|
5287
|
+
type: "Mark",
|
|
5288
|
+
ranges: run.chars,
|
|
5289
|
+
mark: operation.mark
|
|
5290
|
+
});
|
|
5291
|
+
run.marks = withMark(run.marks, operation.mark);
|
|
5292
|
+
return;
|
|
5293
|
+
}
|
|
5294
|
+
case "RemoveMark": {
|
|
5295
|
+
const { run } = locateRun$1(shadow, operation.node);
|
|
5296
|
+
if (!run.marks.some((mark) => markName(mark) === operation.mark)) return;
|
|
5297
|
+
if (run.chars.length > 0) ops.push({
|
|
5298
|
+
type: "Unmark",
|
|
5299
|
+
ranges: run.chars,
|
|
5300
|
+
name: operation.mark
|
|
5301
|
+
});
|
|
5302
|
+
run.marks = run.marks.filter((mark) => markName(mark) !== operation.mark);
|
|
5303
|
+
return;
|
|
5304
|
+
}
|
|
5305
|
+
case "SplitRun": {
|
|
5306
|
+
if (operation.offset === 0) return;
|
|
5307
|
+
const { runs, index, run } = locateRun$1(shadow, operation.node);
|
|
5308
|
+
const rest = sliceChars(run.chars, operation.offset, charsLength(run.chars));
|
|
5309
|
+
run.chars = sliceChars(run.chars, 0, operation.offset);
|
|
5310
|
+
runs.splice(index + 1, 0, {
|
|
5311
|
+
id: operation.textId,
|
|
5312
|
+
chars: rest,
|
|
5313
|
+
marks: run.marks
|
|
5314
|
+
});
|
|
5315
|
+
return;
|
|
5316
|
+
}
|
|
5317
|
+
case "SplitNode": {
|
|
5318
|
+
const { block, runs, index, run } = locateRun$1(shadow, operation.node);
|
|
5319
|
+
const into = mint();
|
|
5320
|
+
shadow.names.set(operation.blockId, into);
|
|
5321
|
+
ops.push({
|
|
5322
|
+
type: "Split",
|
|
5323
|
+
block: replicated(shadow, block),
|
|
5324
|
+
after: charBefore(runs, index, operation.offset),
|
|
5325
|
+
into
|
|
5326
|
+
});
|
|
5327
|
+
const moved = [{
|
|
5328
|
+
id: operation.textId,
|
|
5329
|
+
chars: sliceChars(run.chars, operation.offset, charsLength(run.chars)),
|
|
5330
|
+
marks: run.marks
|
|
5331
|
+
}, ...runs.slice(index + 1)];
|
|
5332
|
+
run.chars = sliceChars(run.chars, 0, operation.offset);
|
|
5333
|
+
runs.splice(index + 1);
|
|
5334
|
+
shadow.runs.set(operation.blockId, moved);
|
|
5335
|
+
const parent = shadow.parents.get(block) ?? ROOT;
|
|
5336
|
+
const list = shadow.children.get(parent);
|
|
5337
|
+
list.splice(list.indexOf(block) + 1, 0, operation.blockId);
|
|
5338
|
+
shadow.parents.set(operation.blockId, parent);
|
|
5339
|
+
return;
|
|
5340
|
+
}
|
|
5341
|
+
case "JoinNode": {
|
|
5342
|
+
const intoRuns = shadow.runs.get(operation.into);
|
|
5343
|
+
const lastRun = intoRuns.length - 1;
|
|
5344
|
+
ops.push({
|
|
5345
|
+
type: "Join",
|
|
5346
|
+
into: replicated(shadow, operation.into),
|
|
5347
|
+
removed: replicated(shadow, operation.removed),
|
|
5348
|
+
after: lastRun < 0 ? null : charBefore(intoRuns, lastRun, charsLength(intoRuns[lastRun].chars))
|
|
5349
|
+
});
|
|
5350
|
+
shadow.runs.get(operation.into).push(...shadow.runs.get(operation.removed));
|
|
5351
|
+
shadow.runs.delete(operation.removed);
|
|
5352
|
+
const nested = shadow.children.get(operation.removed);
|
|
5353
|
+
if (nested !== void 0) {
|
|
5354
|
+
for (const child of nested) shadow.parents.set(child, operation.into);
|
|
5355
|
+
shadow.children.get(operation.into).push(...nested);
|
|
5356
|
+
shadow.children.delete(operation.removed);
|
|
5357
|
+
}
|
|
5358
|
+
removeFromParent(shadow, operation.removed);
|
|
5359
|
+
return;
|
|
5360
|
+
}
|
|
5361
|
+
case "MoveNode": {
|
|
5362
|
+
const parent = operation.parent ?? ROOT;
|
|
5363
|
+
if ((shadow.parents.get(operation.node) ?? ROOT) === parent && shadow.children.get(parent).indexOf(operation.node) === operation.to) return;
|
|
5364
|
+
removeFromParent(shadow, operation.node);
|
|
5365
|
+
ops.push({
|
|
5366
|
+
type: "MoveBlock",
|
|
5367
|
+
id: replicated(shadow, operation.node),
|
|
5368
|
+
parent: parent === ROOT ? null : replicated(shadow, parent),
|
|
5369
|
+
after: siblingBefore(shadow, parent, operation.to)
|
|
5370
|
+
});
|
|
5371
|
+
shadow.children.get(parent).splice(operation.to, 0, operation.node);
|
|
5372
|
+
shadow.parents.set(operation.node, parent);
|
|
5373
|
+
return;
|
|
5374
|
+
}
|
|
5375
|
+
case "RetypeBlock":
|
|
5376
|
+
ops.push({
|
|
5377
|
+
type: "Retype",
|
|
5378
|
+
id: replicated(shadow, operation.node),
|
|
5379
|
+
to: operation.to
|
|
5380
|
+
});
|
|
5381
|
+
return;
|
|
5382
|
+
case "SetProps":
|
|
5383
|
+
ops.push({
|
|
5384
|
+
type: "SetProps",
|
|
5385
|
+
id: replicated(shadow, operation.node),
|
|
5386
|
+
props: operation.props
|
|
5387
|
+
});
|
|
5388
|
+
return;
|
|
5389
|
+
case "InsertNode": {
|
|
5390
|
+
const parent = operation.parent ?? ROOT;
|
|
5391
|
+
const after = siblingBefore(shadow, parent, operation.at);
|
|
5392
|
+
const built = buildOps([operation.block], parent === ROOT ? null : replicated(shadow, parent), after, mint, (block, id) => shadow.names.set(block.id, id));
|
|
5393
|
+
ops.push(...built);
|
|
5394
|
+
shadow.children.get(parent).splice(operation.at, 0, operation.block.id);
|
|
5395
|
+
addSubtree(shadow, operation.block, parent);
|
|
5396
|
+
const inserts = built.filter((op) => op.type === "Insert");
|
|
5397
|
+
let next = 0;
|
|
5398
|
+
const fill = (block) => {
|
|
5399
|
+
const runs = shadow.runs.get(block.id);
|
|
5400
|
+
for (const [index, run] of block.children.entries()) {
|
|
5401
|
+
if (run.text.length === 0) continue;
|
|
5402
|
+
runs[index].chars = [{
|
|
5403
|
+
id: inserts[next++].id,
|
|
5404
|
+
from: 0,
|
|
5405
|
+
to: run.text.length
|
|
5406
|
+
}];
|
|
5407
|
+
}
|
|
5408
|
+
if (block.type === "Node" && block.blocks !== void 0) block.blocks.forEach(fill);
|
|
5409
|
+
};
|
|
5410
|
+
fill(operation.block);
|
|
5411
|
+
return;
|
|
5412
|
+
}
|
|
5413
|
+
case "DeleteNode":
|
|
5414
|
+
ops.push({
|
|
5415
|
+
type: "DeleteBlock",
|
|
5416
|
+
id: replicated(shadow, operation.node)
|
|
5417
|
+
});
|
|
5418
|
+
removeFromParent(shadow, operation.node);
|
|
5419
|
+
return;
|
|
5420
|
+
}
|
|
5421
|
+
};
|
|
5422
|
+
const anchorPosition = (shadow, position) => {
|
|
5423
|
+
const { block, runs, index } = locateRun$1(shadow, position.node);
|
|
5424
|
+
return {
|
|
5425
|
+
block: replicated(shadow, block),
|
|
5426
|
+
after: charBefore(runs, index, position.offset),
|
|
5427
|
+
affinity: position.affinity
|
|
5428
|
+
};
|
|
5429
|
+
};
|
|
5430
|
+
const anchorIn = (shadow, selection) => {
|
|
5431
|
+
if (selection === null) return null;
|
|
5432
|
+
if (selection.type === "Node") return shadow.parents.has(selection.node) ? {
|
|
5433
|
+
type: "Node",
|
|
5434
|
+
node: replicated(shadow, selection.node)
|
|
5435
|
+
} : null;
|
|
5436
|
+
return {
|
|
5437
|
+
type: "Range",
|
|
5438
|
+
anchor: anchorPosition(shadow, selection.anchor),
|
|
5439
|
+
focus: anchorPosition(shadow, selection.focus)
|
|
5440
|
+
};
|
|
5441
|
+
};
|
|
5442
|
+
/**
|
|
5443
|
+
* Anchors a selection on the projection of `state`, so it can be resolved again after
|
|
5444
|
+
* other replicas' ops change the text around it.
|
|
5445
|
+
*/
|
|
5446
|
+
const anchor = (state, selection) => {
|
|
5447
|
+
const start = projection(state);
|
|
5448
|
+
return anchorIn(shadowOf(start.document, projectedChars(start), /* @__PURE__ */ new Map()), selection);
|
|
5449
|
+
};
|
|
5450
|
+
const visible = (state, block) => {
|
|
5451
|
+
for (let at = block; at !== null;) {
|
|
5452
|
+
const entry = lookup(state, at);
|
|
5453
|
+
if (entry === void 0 || entry.deleted) return false;
|
|
5454
|
+
at = entry.parent;
|
|
5455
|
+
}
|
|
5456
|
+
return true;
|
|
5457
|
+
};
|
|
5458
|
+
/** Where a position resolves in the projection: after the nearest visible character. */
|
|
5459
|
+
const resolvePosition = (state, position) => {
|
|
5460
|
+
const runs = projection(state).runs;
|
|
5461
|
+
const atStart = (block) => {
|
|
5462
|
+
const first = runs.get(block)?.[0];
|
|
5463
|
+
return first === void 0 ? void 0 : {
|
|
5464
|
+
node: first.id,
|
|
5465
|
+
offset: 0,
|
|
5466
|
+
affinity: position.affinity
|
|
5467
|
+
};
|
|
5468
|
+
};
|
|
5469
|
+
if (position.after === null) {
|
|
5470
|
+
const place = startOf(draft(state), position.block);
|
|
5471
|
+
if (place === void 0 || !visible(state, place.block)) return void 0;
|
|
5472
|
+
const before = lookup(state, place.block)?.spans[place.index - 1];
|
|
5473
|
+
return before === void 0 ? atStart(place.block) : resolvePosition(state, {
|
|
5474
|
+
...position,
|
|
5475
|
+
block: place.block,
|
|
5476
|
+
after: charRef(before.id, before.offset + before.text.length - 1)
|
|
5477
|
+
});
|
|
5478
|
+
}
|
|
5479
|
+
const { id, index } = parseChar(position.after);
|
|
5480
|
+
for (const block of holdersIn(holdersOf(state), id) ?? []) {
|
|
5481
|
+
const entry = lookup(state, block);
|
|
5482
|
+
const spanIndex = entry.spans.findIndex((span) => span.id === id && index >= span.offset && index < span.offset + span.text.length);
|
|
5483
|
+
if (spanIndex === -1) continue;
|
|
5484
|
+
let target = entry.spans[spanIndex].deleted ? void 0 : {
|
|
5485
|
+
id,
|
|
5486
|
+
index
|
|
5487
|
+
};
|
|
5488
|
+
for (let earlier = spanIndex - 1; target === void 0 && earlier >= 0; earlier--) {
|
|
5489
|
+
const candidate = entry.spans[earlier];
|
|
5490
|
+
if (!candidate.deleted) target = {
|
|
5491
|
+
id: candidate.id,
|
|
5492
|
+
index: candidate.offset + candidate.text.length - 1
|
|
5493
|
+
};
|
|
5494
|
+
}
|
|
5495
|
+
if (target === void 0) return atStart(block);
|
|
5496
|
+
let offset = 0;
|
|
5497
|
+
for (const run of runs.get(block) ?? []) {
|
|
5498
|
+
for (const range of run.chars) {
|
|
5499
|
+
if (range.id === target.id && target.index >= range.from && target.index < range.to) return {
|
|
5500
|
+
node: run.id,
|
|
5501
|
+
offset: offset + target.index - range.from + 1,
|
|
5502
|
+
affinity: position.affinity
|
|
5503
|
+
};
|
|
5504
|
+
offset += range.to - range.from;
|
|
5505
|
+
}
|
|
5506
|
+
offset = 0;
|
|
5507
|
+
}
|
|
5508
|
+
}
|
|
5509
|
+
return visible(state, position.block) ? atStart(position.block) : void 0;
|
|
5510
|
+
};
|
|
5511
|
+
/**
|
|
5512
|
+
* The selection an anchored one names in the projection of `state`. A position whose
|
|
5513
|
+
* character was deleted moves back to the nearest character still shown; one whose block
|
|
5514
|
+
* is gone resolves to nothing, and so does the selection.
|
|
5515
|
+
*/
|
|
5516
|
+
const resolve = (state, selection) => {
|
|
5517
|
+
if (selection === null) return null;
|
|
5518
|
+
if (selection.type === "Node") return visible(state, selection.node) ? {
|
|
5519
|
+
type: "Node",
|
|
5520
|
+
node: NodeId.make(selection.node)
|
|
5521
|
+
} : null;
|
|
5522
|
+
const anchorAt = resolvePosition(state, selection.anchor);
|
|
5523
|
+
const focusAt = resolvePosition(state, selection.focus);
|
|
5524
|
+
return anchorAt === void 0 || focusAt === void 0 ? null : {
|
|
5525
|
+
type: "Range",
|
|
5526
|
+
anchor: anchorAt,
|
|
5527
|
+
focus: focusAt
|
|
5528
|
+
};
|
|
5529
|
+
};
|
|
5530
|
+
//#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 };
|
|
2435
5532
|
|
|
2436
5533
|
//# sourceMappingURL=index.mjs.map
|