foldkit-richtext 0.1.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/LICENSE +21 -0
- package/README.md +614 -0
- package/dist/index.d.mts +3968 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +2436 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +52 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,2436 @@
|
|
|
1
|
+
import { Equal, Schema } from "effect";
|
|
2
|
+
//#region src/document.ts
|
|
3
|
+
/** Caller-assigned identity, unique across blocks and text runs in a document. */
|
|
4
|
+
const NodeId = Schema.NonEmptyString.pipe(Schema.brand("foldkit-richtext/NodeId"));
|
|
5
|
+
/** The mark names this vocabulary defines; a document may hold others verbatim. */
|
|
6
|
+
const Mark = Schema.Literals([
|
|
7
|
+
"Bold",
|
|
8
|
+
"Italic",
|
|
9
|
+
"Code"
|
|
10
|
+
]);
|
|
11
|
+
/**
|
|
12
|
+
* A mark with props: which mark, plus the JSON data it carries. Props are JSON
|
|
13
|
+
* here for the same reason a node's are: the document codec cannot know an
|
|
14
|
+
* application's schemas, so a Kit validates them at that boundary (§12).
|
|
15
|
+
*/
|
|
16
|
+
const MarkValue = Schema.Struct({
|
|
17
|
+
name: Schema.NonEmptyString,
|
|
18
|
+
props: Schema.optionalKey(Schema.JsonObject)
|
|
19
|
+
});
|
|
20
|
+
/**
|
|
21
|
+
* A mark as a text run stores it: a bare name for a mark with no props, or a
|
|
22
|
+
* value when it has them. Loading preserves the form it found, so a names-only
|
|
23
|
+
* document round-trips byte-equal, and because a run carries a name at most once
|
|
24
|
+
* it never holds both forms of one mark.
|
|
25
|
+
*/
|
|
26
|
+
const RunMark = Schema.Union([Schema.NonEmptyString, MarkValue]);
|
|
27
|
+
/** A mark's name: a bare string is a mark with no props, an object carries them. */
|
|
28
|
+
const markName = (mark) => typeof mark === "string" ? mark : mark.name;
|
|
29
|
+
/**
|
|
30
|
+
* The content a block holds: runs, or nested blocks (§13). A document does not
|
|
31
|
+
* declare which a block kind accepts — its Kit does — so these are the words a
|
|
32
|
+
* declaration and a migration both use.
|
|
33
|
+
*/
|
|
34
|
+
const textContent = "text";
|
|
35
|
+
const blockContent = "blocks";
|
|
36
|
+
const Text = Schema.Struct({
|
|
37
|
+
type: Schema.Literal("Text"),
|
|
38
|
+
id: NodeId,
|
|
39
|
+
text: Schema.String,
|
|
40
|
+
marks: Schema.Array(RunMark).check(Schema.makeFilter((marks) => new Set(marks.map(markName)).size === marks.length || "Invalid marks"))
|
|
41
|
+
});
|
|
42
|
+
const Paragraph = Schema.Struct({
|
|
43
|
+
type: Schema.Literal("Paragraph"),
|
|
44
|
+
id: NodeId,
|
|
45
|
+
children: Schema.Array(Text)
|
|
46
|
+
});
|
|
47
|
+
const Heading = Schema.Struct({
|
|
48
|
+
type: Schema.Literal("Heading"),
|
|
49
|
+
id: NodeId,
|
|
50
|
+
level: Schema.Literals([
|
|
51
|
+
1,
|
|
52
|
+
2,
|
|
53
|
+
3,
|
|
54
|
+
4,
|
|
55
|
+
5,
|
|
56
|
+
6
|
|
57
|
+
]),
|
|
58
|
+
children: Schema.Array(Text)
|
|
59
|
+
});
|
|
60
|
+
/**
|
|
61
|
+
* A block whose `type` this version does not implement, retained verbatim for
|
|
62
|
+
* recovery and migration: the original type, its remaining JSON fields, and no
|
|
63
|
+
* text runs (its subtree lives in `props`, opaque). Unknown blocks are
|
|
64
|
+
* read-only content: address them structurally, never edit their text.
|
|
65
|
+
*/
|
|
66
|
+
const UnknownBlock = Schema.Struct({
|
|
67
|
+
type: Schema.Literal("Unknown"),
|
|
68
|
+
id: NodeId,
|
|
69
|
+
originalType: Schema.NonEmptyString,
|
|
70
|
+
props: Schema.JsonObject,
|
|
71
|
+
children: Schema.Array(Text).check(Schema.makeFilter((runs) => runs.length === 0 || "Unknown blocks keep no text runs"))
|
|
72
|
+
});
|
|
73
|
+
const NodeBlock = Schema.Struct({
|
|
74
|
+
type: Schema.Literal("Node"),
|
|
75
|
+
kind: Schema.NonEmptyString,
|
|
76
|
+
id: NodeId,
|
|
77
|
+
props: Schema.JsonObject,
|
|
78
|
+
children: Schema.Array(Text),
|
|
79
|
+
blocks: Schema.optionalKey(Schema.suspend(() => Schema.Array(Block)))
|
|
80
|
+
}).check(Schema.makeFilter((block) => block.blocks === void 0 || block.children.length === 0 || "A block with nested blocks keeps no direct runs"));
|
|
81
|
+
const Block = Schema.Union([
|
|
82
|
+
Paragraph,
|
|
83
|
+
Heading,
|
|
84
|
+
NodeBlock,
|
|
85
|
+
UnknownBlock
|
|
86
|
+
]);
|
|
87
|
+
/** Every identity a block subtree owns, block and run alike, in document order. */
|
|
88
|
+
const subtreeIds = (block) => [
|
|
89
|
+
block.id,
|
|
90
|
+
...block.children.map((run) => run.id),
|
|
91
|
+
...block.type === "Node" && block.blocks !== void 0 ? block.blocks.flatMap(subtreeIds) : []
|
|
92
|
+
];
|
|
93
|
+
/** Version 1's initial block vocabulary, with document-wide identity validation. */
|
|
94
|
+
const Document = Schema.Struct({
|
|
95
|
+
version: Schema.Literal(1),
|
|
96
|
+
children: Schema.Array(Block)
|
|
97
|
+
}).check(Schema.makeFilter((document) => {
|
|
98
|
+
const ids = /* @__PURE__ */ new Set();
|
|
99
|
+
for (const block of document.children) for (const id of subtreeIds(block)) {
|
|
100
|
+
if (ids.has(id)) return "Duplicate node identity";
|
|
101
|
+
ids.add(id);
|
|
102
|
+
}
|
|
103
|
+
return true;
|
|
104
|
+
}));
|
|
105
|
+
const isKnownBlockType = (type) => type === "Paragraph" || type === "Heading" || type === "Node";
|
|
106
|
+
/**
|
|
107
|
+
* Converts a block whose type this version does not implement into an `Unknown`
|
|
108
|
+
* node, and does the same inside a known node block's nested blocks. Everything
|
|
109
|
+
* except `type` and `id` becomes opaque JSON props; the raw subtree is preserved
|
|
110
|
+
* there verbatim.
|
|
111
|
+
*/
|
|
112
|
+
const preserveBlock = (input) => {
|
|
113
|
+
if (typeof input !== "object" || input === null) return input;
|
|
114
|
+
const block = input;
|
|
115
|
+
if (!isKnownBlockType(block.type) && block.type !== "Unknown") {
|
|
116
|
+
const { type, id, ...props } = block;
|
|
117
|
+
return {
|
|
118
|
+
type: "Unknown",
|
|
119
|
+
id,
|
|
120
|
+
originalType: type,
|
|
121
|
+
props,
|
|
122
|
+
children: []
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
return Array.isArray(block.blocks) ? {
|
|
126
|
+
...block,
|
|
127
|
+
blocks: block.blocks.map(preserveBlock)
|
|
128
|
+
} : block;
|
|
129
|
+
};
|
|
130
|
+
/**
|
|
131
|
+
* Converts blocks whose type this version does not implement into `Unknown`
|
|
132
|
+
* nodes before structural decoding, so persisted content survives a deploy
|
|
133
|
+
* that lost a node implementation. Nested blocks are walked for the same reason.
|
|
134
|
+
*/
|
|
135
|
+
const preserveUnknownBlocks = (input) => {
|
|
136
|
+
if (typeof input !== "object" || input === null) return input;
|
|
137
|
+
const document = input;
|
|
138
|
+
if (!Array.isArray(document.children)) return input;
|
|
139
|
+
return {
|
|
140
|
+
...document,
|
|
141
|
+
children: document.children.map(preserveBlock)
|
|
142
|
+
};
|
|
143
|
+
};
|
|
144
|
+
/** Strict boundary for persisted content. Throws a Schema error on invalid input. */
|
|
145
|
+
const decodeStructure = Schema.decodeUnknownSync(Document, { onExcessProperty: "error" });
|
|
146
|
+
const PositiveCount = Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0));
|
|
147
|
+
/** Bounds for decoded documents: blocks, text runs, and total UTF-16 text units. */
|
|
148
|
+
const DocumentLimits = Schema.Struct({
|
|
149
|
+
maxBlocks: PositiveCount,
|
|
150
|
+
maxTextRuns: PositiveCount,
|
|
151
|
+
maxTextLength: PositiveCount
|
|
152
|
+
});
|
|
153
|
+
/** Generous DoS guardrails, not application quotas; tighten per document with a spread. */
|
|
154
|
+
const DefaultDocumentLimits = DocumentLimits.make({
|
|
155
|
+
maxBlocks: 1e4,
|
|
156
|
+
maxTextRuns: 5e4,
|
|
157
|
+
maxTextLength: 5e6
|
|
158
|
+
});
|
|
159
|
+
/** Every block a subtree holds, nested ones included. */
|
|
160
|
+
const countBlocks = (blocks) => {
|
|
161
|
+
let count = 0;
|
|
162
|
+
eachBlock(blocks, () => {
|
|
163
|
+
count += 1;
|
|
164
|
+
});
|
|
165
|
+
return count;
|
|
166
|
+
};
|
|
167
|
+
/**
|
|
168
|
+
* Strict boundary for persisted content. Decodes structure first, then enforces
|
|
169
|
+
* `limits`. Throws a Schema error on invalid input, or an Error naming the
|
|
170
|
+
* first exceeded bound.
|
|
171
|
+
*/
|
|
172
|
+
const decodeDocument = (input, limits = DefaultDocumentLimits) => {
|
|
173
|
+
const document = decodeStructure(preserveUnknownBlocks(input));
|
|
174
|
+
const summary = inspect(document);
|
|
175
|
+
const blocks = countBlocks(document.children);
|
|
176
|
+
const runs = summary.nodeCount - blocks;
|
|
177
|
+
if (blocks > limits.maxBlocks) throw new Error(`Document exceeds maxBlocks: ${blocks} > ${limits.maxBlocks}`);
|
|
178
|
+
if (runs > limits.maxTextRuns) throw new Error(`Document exceeds maxTextRuns: ${runs} > ${limits.maxTextRuns}`);
|
|
179
|
+
if (summary.textLength > limits.maxTextLength) throw new Error(`Document exceeds maxTextLength: ${summary.textLength} > ${limits.maxTextLength}`);
|
|
180
|
+
return document;
|
|
181
|
+
};
|
|
182
|
+
/** A stable key for a block path, so paths can key maps and compare cheaply. */
|
|
183
|
+
const pathKey$1 = (path) => path.join(".");
|
|
184
|
+
/** Walks every block subtree in document order, visiting each with its path. */
|
|
185
|
+
const eachBlock = (blocks, visit, prefix = []) => {
|
|
186
|
+
for (const [index, block] of blocks.entries()) {
|
|
187
|
+
const path = [...prefix, index];
|
|
188
|
+
visit(block, path);
|
|
189
|
+
if (block.type === "Node" && block.blocks !== void 0) eachBlock(block.blocks, visit, path);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
/** Document order over run places: path first, then the run's index. */
|
|
193
|
+
const compareRunPlaces = (left, right) => {
|
|
194
|
+
const shared = Math.min(left.path.length, right.path.length);
|
|
195
|
+
for (let index = 0; index < shared; index++) if (left.path[index] !== right.path[index]) return left.path[index] - right.path[index];
|
|
196
|
+
if (left.path.length !== right.path.length) return left.path.length - right.path.length;
|
|
197
|
+
return left.index - right.index;
|
|
198
|
+
};
|
|
199
|
+
/** The block a path addresses, or undefined when the path does not resolve. */
|
|
200
|
+
const blockAtPath = (document, path) => {
|
|
201
|
+
let blocks = document.children;
|
|
202
|
+
let found;
|
|
203
|
+
for (const index of path) {
|
|
204
|
+
found = blocks[index];
|
|
205
|
+
if (found === void 0) return void 0;
|
|
206
|
+
blocks = found.type === "Node" && found.blocks !== void 0 ? found.blocks : [];
|
|
207
|
+
}
|
|
208
|
+
return found;
|
|
209
|
+
};
|
|
210
|
+
/** The block with this identity, wherever it sits. */
|
|
211
|
+
const locateBlock = (document, node) => {
|
|
212
|
+
let found;
|
|
213
|
+
eachBlock(document.children, (block, path) => {
|
|
214
|
+
if (found === void 0 && block.id === node) found = {
|
|
215
|
+
path,
|
|
216
|
+
block
|
|
217
|
+
};
|
|
218
|
+
});
|
|
219
|
+
return found;
|
|
220
|
+
};
|
|
221
|
+
/** The run with this identity, wherever it sits. */
|
|
222
|
+
const locateRun = (document, node) => {
|
|
223
|
+
let found;
|
|
224
|
+
eachBlock(document.children, (block, path) => {
|
|
225
|
+
if (found !== void 0) return;
|
|
226
|
+
const index = block.children.findIndex((run) => run.id === node);
|
|
227
|
+
if (index >= 0) found = {
|
|
228
|
+
path,
|
|
229
|
+
index,
|
|
230
|
+
run: block.children[index]
|
|
231
|
+
};
|
|
232
|
+
});
|
|
233
|
+
return found;
|
|
234
|
+
};
|
|
235
|
+
/** Every node a block subtree owns, block and run alike, keyed by identity. */
|
|
236
|
+
const indexNodes = (blocks, nodes) => {
|
|
237
|
+
eachBlock(blocks, (block) => {
|
|
238
|
+
nodes.set(block.id, block);
|
|
239
|
+
for (const run of block.children) nodes.set(run.id, run);
|
|
240
|
+
});
|
|
241
|
+
};
|
|
242
|
+
const isKnownMarkName = Schema.is(Mark);
|
|
243
|
+
/** Lists unknown marks per text run; empty means the document publishes cleanly. */
|
|
244
|
+
const findUnknownMarks = (document) => {
|
|
245
|
+
const unknown = [];
|
|
246
|
+
eachBlock(document.children, (block) => {
|
|
247
|
+
for (const text of block.children) for (const mark of text.marks) {
|
|
248
|
+
const name = markName(mark);
|
|
249
|
+
if (!isKnownMarkName(name)) unknown.push({
|
|
250
|
+
node: text.id,
|
|
251
|
+
mark: name
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
return unknown;
|
|
256
|
+
};
|
|
257
|
+
/** Lists preserved unknown blocks; empty means the document publishes cleanly. */
|
|
258
|
+
const findUnknownNodes = (document) => {
|
|
259
|
+
const unknown = [];
|
|
260
|
+
eachBlock(document.children, (block) => {
|
|
261
|
+
if (block.type === "Unknown") unknown.push({
|
|
262
|
+
node: block.id,
|
|
263
|
+
originalType: block.originalType
|
|
264
|
+
});
|
|
265
|
+
});
|
|
266
|
+
return unknown;
|
|
267
|
+
};
|
|
268
|
+
/** UTF-16 offset in one text run, with insertion affinity at that offset. */
|
|
269
|
+
const Position = Schema.Struct({
|
|
270
|
+
node: NodeId,
|
|
271
|
+
offset: Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0)),
|
|
272
|
+
affinity: Schema.Literals(["before", "after"])
|
|
273
|
+
});
|
|
274
|
+
const Node = {
|
|
275
|
+
/** Declares an immutable reference. Does not insert a node or reserve its ID. */
|
|
276
|
+
make: (id) => {
|
|
277
|
+
const nodeId = NodeId.make(id);
|
|
278
|
+
return Object.freeze({
|
|
279
|
+
id: nodeId,
|
|
280
|
+
read: (document) => {
|
|
281
|
+
const nodes = /* @__PURE__ */ new Map();
|
|
282
|
+
indexNodes(document.children, nodes);
|
|
283
|
+
return nodes.get(nodeId);
|
|
284
|
+
},
|
|
285
|
+
at: (offset, affinity) => Position.make({
|
|
286
|
+
node: nodeId,
|
|
287
|
+
offset,
|
|
288
|
+
affinity
|
|
289
|
+
})
|
|
290
|
+
});
|
|
291
|
+
} };
|
|
292
|
+
const Selection = Schema.Union([Schema.Struct({
|
|
293
|
+
type: Schema.Literal("Range"),
|
|
294
|
+
anchor: Position,
|
|
295
|
+
focus: Position
|
|
296
|
+
}), Schema.Struct({
|
|
297
|
+
type: Schema.Literal("Node"),
|
|
298
|
+
node: NodeId
|
|
299
|
+
})]);
|
|
300
|
+
/** Validates references without sorting range endpoints or changing direction. */
|
|
301
|
+
const selectionIsValid = (document, selection) => {
|
|
302
|
+
if (selection === null) return true;
|
|
303
|
+
const nodes = /* @__PURE__ */ new Map();
|
|
304
|
+
indexNodes(document.children, nodes);
|
|
305
|
+
if (selection.type === "Node") return nodes.has(selection.node);
|
|
306
|
+
return [selection.anchor, selection.focus].every((position) => {
|
|
307
|
+
const node = nodes.get(position.node);
|
|
308
|
+
return node?.type === "Text" && Number.isInteger(position.offset) && position.offset >= 0 && position.offset <= node.text.length;
|
|
309
|
+
});
|
|
310
|
+
};
|
|
311
|
+
const EditorState = Schema.Struct({
|
|
312
|
+
document: Document,
|
|
313
|
+
selection: Schema.NullOr(Selection)
|
|
314
|
+
}).check(Schema.makeFilter((state) => selectionIsValid(state.document, state.selection) || "Unresolved selection"));
|
|
315
|
+
/**
|
|
316
|
+
* Counts semantic nodes and UTF-16 text units, and reports nesting depth. Depth
|
|
317
|
+
* counts levels of content: an empty document is 0, blocks are 1, runs inside a
|
|
318
|
+
* block are 2, and a block nested inside a block adds a level (§116).
|
|
319
|
+
*/
|
|
320
|
+
const inspect = (document) => {
|
|
321
|
+
let nodeCount = 0;
|
|
322
|
+
let textLength = 0;
|
|
323
|
+
let depth = 0;
|
|
324
|
+
eachBlock(document.children, (block, path) => {
|
|
325
|
+
nodeCount += 1 + block.children.length;
|
|
326
|
+
for (const text of block.children) textLength += text.text.length;
|
|
327
|
+
depth = Math.max(depth, path.length + (block.children.length > 0 ? 1 : 0));
|
|
328
|
+
});
|
|
329
|
+
return {
|
|
330
|
+
nodeCount,
|
|
331
|
+
textLength,
|
|
332
|
+
depth
|
|
333
|
+
};
|
|
334
|
+
};
|
|
335
|
+
//#endregion
|
|
336
|
+
//#region src/marks.ts
|
|
337
|
+
const decodeJsonProps = Schema.decodeUnknownSync(Schema.JsonObject);
|
|
338
|
+
/**
|
|
339
|
+
* Declares a mark. Expansion defaults to `both`: the conservative choice for a
|
|
340
|
+
* name no policy knows. A definition with `Props` gets an `of` that builds the
|
|
341
|
+
* value; a definition without props builds a value that carries only its name.
|
|
342
|
+
*/
|
|
343
|
+
const mark = (name, options = {}) => {
|
|
344
|
+
if (name.length === 0) throw new Error("RichText.mark: a mark needs a name");
|
|
345
|
+
const encodeProps = options.Props === void 0 ? void 0 : Schema.encodeUnknownSync(options.Props, { onExcessProperty: "error" });
|
|
346
|
+
return {
|
|
347
|
+
name,
|
|
348
|
+
expand: options.expand ?? "both",
|
|
349
|
+
Props: options.Props,
|
|
350
|
+
of: ((props) => {
|
|
351
|
+
if (encodeProps === void 0) return { name };
|
|
352
|
+
return {
|
|
353
|
+
name,
|
|
354
|
+
props: decodeJsonProps(encodeProps(props))
|
|
355
|
+
};
|
|
356
|
+
})
|
|
357
|
+
};
|
|
358
|
+
};
|
|
359
|
+
const Bold = mark("Bold", { expand: "after" });
|
|
360
|
+
const Italic = mark("Italic", { expand: "after" });
|
|
361
|
+
const Code = mark("Code", { expand: "none" });
|
|
362
|
+
/** The marks this vocabulary defines, and the policy a document without a Kit gets. */
|
|
363
|
+
const shippedMarks = [
|
|
364
|
+
Bold,
|
|
365
|
+
Italic,
|
|
366
|
+
Code
|
|
367
|
+
];
|
|
368
|
+
const markRegistry = (definitions) => {
|
|
369
|
+
const byName = new Map(definitions.map((definition) => [definition.name, definition.expand]));
|
|
370
|
+
return {
|
|
371
|
+
expansionOf: (name) => byName.get(name) ?? "both",
|
|
372
|
+
declares: (name) => byName.has(name)
|
|
373
|
+
};
|
|
374
|
+
};
|
|
375
|
+
/** The policy of the shipped vocabulary. */
|
|
376
|
+
const shippedRegistry = markRegistry(shippedMarks);
|
|
377
|
+
/** A mark's props, or undefined when it carries none. */
|
|
378
|
+
const markProps = (mark) => typeof mark === "string" ? void 0 : mark.props;
|
|
379
|
+
/**
|
|
380
|
+
* Whether two marks are the same mark with the same props. This is the
|
|
381
|
+
* equivalence normalization merges on, so props compare structurally and key
|
|
382
|
+
* order does not matter.
|
|
383
|
+
*/
|
|
384
|
+
const sameMark = (left, right) => markName(left) === markName(right) && Equal.equals(markProps(left), markProps(right));
|
|
385
|
+
/** Order-insensitive mark-set equality; a run carries a name at most once. */
|
|
386
|
+
const sameMarkSet = (left, right) => left.length === right.length && left.every((mark) => right.some((other) => sameMark(mark, other)));
|
|
387
|
+
/**
|
|
388
|
+
* Retargets a boundary insertion to the neighboring run when the current run
|
|
389
|
+
* carries marks that forbid the edge and the neighbor carries exactly the
|
|
390
|
+
* marks that remain. Interior positions, missing neighbors, and mismatched
|
|
391
|
+
* neighbors return the input reference unchanged; unknown node ids are left
|
|
392
|
+
* for `apply` to diagnose. Never invents runs: mixed-mark edges stay put.
|
|
393
|
+
*/
|
|
394
|
+
const resolveInsertion = (document, position, registry = shippedRegistry) => {
|
|
395
|
+
for (const block of document.children) {
|
|
396
|
+
const index = block.children.findIndex((run) => run.id === position.node);
|
|
397
|
+
const run = block.children[index];
|
|
398
|
+
if (run === void 0) continue;
|
|
399
|
+
const leavingLeft = position.affinity === "before" && position.offset === 0;
|
|
400
|
+
const leavingRight = position.affinity === "after" && position.offset === run.text.length;
|
|
401
|
+
if (!leavingLeft && !leavingRight) return position;
|
|
402
|
+
const neighbor = leavingLeft ? block.children[index - 1] : block.children[index + 1];
|
|
403
|
+
if (neighbor === void 0) return position;
|
|
404
|
+
const direction = leavingLeft ? "before" : "after";
|
|
405
|
+
const desired = run.marks.filter((mark) => {
|
|
406
|
+
const expand = registry.expansionOf(markName(mark));
|
|
407
|
+
return expand === "both" || expand === direction;
|
|
408
|
+
});
|
|
409
|
+
if (!sameMarkSet(desired, neighbor.marks)) return position;
|
|
410
|
+
return {
|
|
411
|
+
node: neighbor.id,
|
|
412
|
+
offset: leavingLeft ? neighbor.text.length : 0,
|
|
413
|
+
affinity: position.affinity
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
return position;
|
|
417
|
+
};
|
|
418
|
+
//#endregion
|
|
419
|
+
//#region src/rendering.ts
|
|
420
|
+
/** The nesting the shipped marks get, innermost first. */
|
|
421
|
+
const BUILT_IN_MARK_TAGS = [
|
|
422
|
+
["Bold", "strong"],
|
|
423
|
+
["Italic", "em"],
|
|
424
|
+
["Code", "code"]
|
|
425
|
+
];
|
|
426
|
+
/**
|
|
427
|
+
* Own-property lookup: a mark or node name is document content, so a plain or
|
|
428
|
+
* hand-built `Rendering` must not let `__proto__` resolve to a prototype.
|
|
429
|
+
*/
|
|
430
|
+
const entryFor = (entries, name) => Object.hasOwn(entries, name) ? entries[name] : void 0;
|
|
431
|
+
const resolve = (entry, value) => typeof entry === "function" ? entry(value) : entry;
|
|
432
|
+
/** A name's own entry map, with no prototype for a content-chosen name to reach. */
|
|
433
|
+
const entryMap = (entries) => {
|
|
434
|
+
const map = Object.create(null);
|
|
435
|
+
for (const [name, entry] of Object.entries(entries ?? {})) map[name] = entry;
|
|
436
|
+
return Object.freeze(map);
|
|
437
|
+
};
|
|
438
|
+
const rendering = (definition = {}) => Object.freeze({
|
|
439
|
+
marks: entryMap(definition.marks),
|
|
440
|
+
nodes: entryMap(definition.nodes)
|
|
441
|
+
});
|
|
442
|
+
/** The behaviour without a renderer: shipped tags for shipped marks, names otherwise. */
|
|
443
|
+
const noRendering = rendering();
|
|
444
|
+
const byName = (left, right) => left < right ? -1 : left > right ? 1 : 0;
|
|
445
|
+
/**
|
|
446
|
+
* Resolves a run's marks to elements. Order is the vocabulary's, then names
|
|
447
|
+
* alphabetically, never the order marks happen to be stored in — the same set of
|
|
448
|
+
* marks must serialize the same way however it was assembled. An entry for a
|
|
449
|
+
* shipped name replaces that name's tag but keeps its place in the nesting.
|
|
450
|
+
*/
|
|
451
|
+
const runRendering = (definition, run) => {
|
|
452
|
+
const nest = [];
|
|
453
|
+
const unrendered = [];
|
|
454
|
+
for (const [name, tag] of BUILT_IN_MARK_TAGS) {
|
|
455
|
+
const mark = run.marks.find((candidate) => markName(candidate) === name);
|
|
456
|
+
if (mark === void 0) continue;
|
|
457
|
+
const entry = entryFor(definition.marks, name);
|
|
458
|
+
nest.push(entry === void 0 ? {
|
|
459
|
+
tag,
|
|
460
|
+
attributes: {}
|
|
461
|
+
} : resolve(entry, mark) ?? {
|
|
462
|
+
tag,
|
|
463
|
+
attributes: {}
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
const others = run.marks.filter((mark) => !BUILT_IN_MARK_TAGS.some(([name]) => name === markName(mark))).sort((left, right) => byName(markName(left), markName(right)));
|
|
467
|
+
for (const mark of others) {
|
|
468
|
+
const name = markName(mark);
|
|
469
|
+
const entry = entryFor(definition.marks, name);
|
|
470
|
+
const element = entry === void 0 ? void 0 : resolve(entry, mark);
|
|
471
|
+
if (element === void 0) unrendered.push(name);
|
|
472
|
+
else nest.push(element);
|
|
473
|
+
}
|
|
474
|
+
return {
|
|
475
|
+
nest,
|
|
476
|
+
unrendered
|
|
477
|
+
};
|
|
478
|
+
};
|
|
479
|
+
/** The element a node kind renders as, or undefined when no entry applies. */
|
|
480
|
+
const nodeRendering = (definition, block) => {
|
|
481
|
+
const entry = entryFor(definition.nodes, block.kind);
|
|
482
|
+
return entry === void 0 ? void 0 : resolve(entry, block);
|
|
483
|
+
};
|
|
484
|
+
//#endregion
|
|
485
|
+
//#region src/html.ts
|
|
486
|
+
const escapeText = (text) => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
487
|
+
const escapeAttribute = (value) => escapeText(value).replace(/"/g, """).replace(/'/g, "'");
|
|
488
|
+
const TAG = /^[A-Za-z][-A-Za-z0-9]*$/;
|
|
489
|
+
const ATTRIBUTE = /^[A-Za-z_:][-A-Za-z0-9_:.]*$/;
|
|
490
|
+
/**
|
|
491
|
+
* Writes an element. An attribute *value* is content and is escaped; a tag or
|
|
492
|
+
* attribute *name* is refused rather than written when malformed, because a name
|
|
493
|
+
* cannot be escaped — one holding a quote, a space, or `>` would end the attribute
|
|
494
|
+
* and inject markup. A well-formed but unwise name (an event handler built from a
|
|
495
|
+
* mark's props, say) is the application's own decision to make.
|
|
496
|
+
*/
|
|
497
|
+
const renderElement = (element, inner) => {
|
|
498
|
+
if (!TAG.test(element.tag)) throw new Error(`RichText.toHtml: invalid tag "${element.tag}"`);
|
|
499
|
+
const attributes = Object.entries(element.attributes).map(([name, value]) => {
|
|
500
|
+
if (!ATTRIBUTE.test(name)) throw new Error(`RichText.toHtml: invalid attribute name "${name}"`);
|
|
501
|
+
return ` ${name}="${escapeAttribute(value)}"`;
|
|
502
|
+
}).join("");
|
|
503
|
+
return `<${element.tag}${attributes}>${inner}</${element.tag}>`;
|
|
504
|
+
};
|
|
505
|
+
const renderRun = (run, renderer) => {
|
|
506
|
+
const { nest, unrendered } = runRendering(renderer, run);
|
|
507
|
+
let html = escapeText(run.text);
|
|
508
|
+
for (const element of nest) html = renderElement(element, html);
|
|
509
|
+
return unrendered.length === 0 ? html : `<span data-marks="${escapeAttribute(unrendered.join(" "))}">${html}</span>`;
|
|
510
|
+
};
|
|
511
|
+
const blockTag = (block) => {
|
|
512
|
+
if (block.type === "Heading") return `h${block.level}`;
|
|
513
|
+
return block.type === "Node" ? "div" : "p";
|
|
514
|
+
};
|
|
515
|
+
const renderBlock = (block, renderer) => {
|
|
516
|
+
if (block.type === "Unknown") return `<div data-unknown="${escapeAttribute(block.originalType)}"></div>`;
|
|
517
|
+
const runs = block.children.map((run) => renderRun(run, renderer)).join("");
|
|
518
|
+
const nested = block.type === "Node" && block.blocks !== void 0 ? toHtml(block.blocks, renderer) : "";
|
|
519
|
+
const element = (block.type === "Node" ? nodeRendering(renderer, block) : void 0) ?? {
|
|
520
|
+
tag: blockTag(block),
|
|
521
|
+
attributes: block.type === "Node" ? { "data-node": block.kind } : {}
|
|
522
|
+
};
|
|
523
|
+
return renderElement(element, `${runs}${nested}`);
|
|
524
|
+
};
|
|
525
|
+
/** Serializes blocks as HTML, with text and attributes escaped. */
|
|
526
|
+
const toHtml = (blocks, renderer = noRendering) => blocks.map((block) => renderBlock(block, renderer)).join("");
|
|
527
|
+
/**
|
|
528
|
+
* Plain text of blocks, one line per text block; unknown blocks keep a
|
|
529
|
+
* placeholder and a container contributes its children's lines.
|
|
530
|
+
*/
|
|
531
|
+
const toText = (blocks) => {
|
|
532
|
+
const lines = [];
|
|
533
|
+
const walk = (current) => {
|
|
534
|
+
for (const block of current) {
|
|
535
|
+
if (block.type === "Unknown") {
|
|
536
|
+
lines.push(`[${block.originalType}]`);
|
|
537
|
+
continue;
|
|
538
|
+
}
|
|
539
|
+
if (block.type === "Node" && block.blocks !== void 0) {
|
|
540
|
+
walk(block.blocks);
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
lines.push(block.children.map((run) => run.text).join(""));
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
walk(blocks);
|
|
547
|
+
return lines.join("\n");
|
|
548
|
+
};
|
|
549
|
+
/** Convenience for a whole document, whose blocks are its children. */
|
|
550
|
+
const documentToHtml = (document, renderer) => toHtml(document.children, renderer);
|
|
551
|
+
const documentToText = (document) => toText(document.children);
|
|
552
|
+
//#endregion
|
|
553
|
+
//#region src/clipboard.ts
|
|
554
|
+
/**
|
|
555
|
+
* Clipboard content is semantic, not HTML (§69). A slice is a versioned,
|
|
556
|
+
* identity-carrying fragment of a document: it round-trips through an
|
|
557
|
+
* application's own format, and a paste mints fresh identities so nothing
|
|
558
|
+
* collides with the document it lands in. HTML and plain text are interchange
|
|
559
|
+
* fallbacks the adapter adds; they are not the slice.
|
|
560
|
+
*/
|
|
561
|
+
const Slice = Schema.Struct({
|
|
562
|
+
version: Schema.Literal(1),
|
|
563
|
+
blocks: Schema.Array(Block)
|
|
564
|
+
}).check(Schema.makeFilter((slice) => {
|
|
565
|
+
const ids = /* @__PURE__ */ new Set();
|
|
566
|
+
let duplicate = false;
|
|
567
|
+
eachBlock(slice.blocks, (block) => {
|
|
568
|
+
for (const id of [block.id, ...block.children.map((run) => run.id)]) {
|
|
569
|
+
if (ids.has(id)) duplicate = true;
|
|
570
|
+
ids.add(id);
|
|
571
|
+
}
|
|
572
|
+
});
|
|
573
|
+
return !duplicate || "Duplicate slice identity";
|
|
574
|
+
}));
|
|
575
|
+
const emptySlice = Object.freeze({
|
|
576
|
+
version: 1,
|
|
577
|
+
blocks: []
|
|
578
|
+
});
|
|
579
|
+
const decodeSlice = Schema.decodeUnknownSync(Slice, { onExcessProperty: "error" });
|
|
580
|
+
const encodeSlice = Schema.encodeSync(Slice);
|
|
581
|
+
const trim = (run, from, to) => ({
|
|
582
|
+
...run,
|
|
583
|
+
text: run.text.slice(from, to)
|
|
584
|
+
});
|
|
585
|
+
/** Whether a block's subtree contains an endpoint, or sits between the two. */
|
|
586
|
+
const inRange = (blockPath, span) => {
|
|
587
|
+
const contains = (place) => blockPath.length <= place.path.length && blockPath.every((index, depth) => place.path[depth] === index);
|
|
588
|
+
if (contains(span.start) || contains(span.end)) return true;
|
|
589
|
+
const first = {
|
|
590
|
+
path: blockPath,
|
|
591
|
+
index: 0
|
|
592
|
+
};
|
|
593
|
+
return compareRunPlaces(first, span.start) > 0 && compareRunPlaces(first, span.end) < 0;
|
|
594
|
+
};
|
|
595
|
+
/** The runs of one block that the span covers, trimmed to it. */
|
|
596
|
+
const coveredRuns = (block, blockPath, span) => {
|
|
597
|
+
const atStart = pathKey$1(blockPath) === pathKey$1(span.start.path);
|
|
598
|
+
const atEnd = pathKey$1(blockPath) === pathKey$1(span.end.path);
|
|
599
|
+
if (!atStart && !atEnd) return block.children;
|
|
600
|
+
const from = atStart ? span.start.index : 0;
|
|
601
|
+
const to = atEnd ? span.end.index : block.children.length - 1;
|
|
602
|
+
const children = [];
|
|
603
|
+
for (const [index, run] of block.children.entries()) {
|
|
604
|
+
if (index < from || index > to) continue;
|
|
605
|
+
const trimFrom = index === from && atStart ? span.start.offset : 0;
|
|
606
|
+
const trimTo = index === to && atEnd ? span.end.offset : run.text.length;
|
|
607
|
+
if (trimFrom >= trimTo) continue;
|
|
608
|
+
children.push(trim(run, trimFrom, trimTo));
|
|
609
|
+
}
|
|
610
|
+
return children;
|
|
611
|
+
};
|
|
612
|
+
/**
|
|
613
|
+
* The covered part of a block list: the blocks the span reaches, each trimmed to
|
|
614
|
+
* it. A container is kept with the children the span reaches, so copying across
|
|
615
|
+
* two list items carries the list rather than two loose paragraphs.
|
|
616
|
+
*/
|
|
617
|
+
const coveredBlocks = (blocks, prefix, span) => {
|
|
618
|
+
const covered = [];
|
|
619
|
+
for (const [index, block] of blocks.entries()) {
|
|
620
|
+
const path = [...prefix, index];
|
|
621
|
+
if (!inRange(path, span)) continue;
|
|
622
|
+
if (block.type === "Unknown") {
|
|
623
|
+
covered.push(block);
|
|
624
|
+
continue;
|
|
625
|
+
}
|
|
626
|
+
const children = coveredRuns(block, path, span);
|
|
627
|
+
if (block.type === "Node" && block.blocks !== void 0) {
|
|
628
|
+
const nested = coveredBlocks(block.blocks, path, span);
|
|
629
|
+
if (children.length === 0 && nested.length === 0) continue;
|
|
630
|
+
covered.push({
|
|
631
|
+
...block,
|
|
632
|
+
children,
|
|
633
|
+
blocks: nested
|
|
634
|
+
});
|
|
635
|
+
continue;
|
|
636
|
+
}
|
|
637
|
+
if (children.length === 0) continue;
|
|
638
|
+
covered.push({
|
|
639
|
+
...block,
|
|
640
|
+
children
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
return covered;
|
|
644
|
+
};
|
|
645
|
+
/**
|
|
646
|
+
* The semantic content a copy would take: a whole block for a node selection,
|
|
647
|
+
* and for a range only the covered part of what it reaches, with runs trimmed to
|
|
648
|
+
* the selection. Blocks the range never enters are left out, so a partial copy
|
|
649
|
+
* never drags a paragraph along.
|
|
650
|
+
*/
|
|
651
|
+
const sliceOf = (document, selection) => {
|
|
652
|
+
if (selection === null) return void 0;
|
|
653
|
+
if (selection.type === "Node") {
|
|
654
|
+
const located = locateBlock(document, selection.node);
|
|
655
|
+
return located === void 0 ? void 0 : {
|
|
656
|
+
version: 1,
|
|
657
|
+
blocks: [located.block]
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
const anchor = locateRun(document, selection.anchor.node);
|
|
661
|
+
const focus = locateRun(document, selection.focus.node);
|
|
662
|
+
if (anchor === void 0 || focus === void 0) return void 0;
|
|
663
|
+
const anchorPlace = {
|
|
664
|
+
...anchor,
|
|
665
|
+
offset: selection.anchor.offset
|
|
666
|
+
};
|
|
667
|
+
const focusPlace = {
|
|
668
|
+
...focus,
|
|
669
|
+
offset: selection.focus.offset
|
|
670
|
+
};
|
|
671
|
+
const span = compareRunPlaces(anchor, focus) <= 0 ? {
|
|
672
|
+
start: anchorPlace,
|
|
673
|
+
end: focusPlace
|
|
674
|
+
} : {
|
|
675
|
+
start: focusPlace,
|
|
676
|
+
end: anchorPlace
|
|
677
|
+
};
|
|
678
|
+
if (pathKey$1(span.start.path) === pathKey$1(span.end.path)) {
|
|
679
|
+
const block = blockAtPath(document, span.start.path);
|
|
680
|
+
if (block === void 0 || block.type === "Unknown") return {
|
|
681
|
+
version: 1,
|
|
682
|
+
blocks: []
|
|
683
|
+
};
|
|
684
|
+
const children = coveredRuns(block, span.start.path, span);
|
|
685
|
+
return {
|
|
686
|
+
version: 1,
|
|
687
|
+
blocks: children.length === 0 ? [] : [{
|
|
688
|
+
...block,
|
|
689
|
+
children
|
|
690
|
+
}]
|
|
691
|
+
};
|
|
692
|
+
}
|
|
693
|
+
return {
|
|
694
|
+
version: 1,
|
|
695
|
+
blocks: coveredBlocks(document.children, [], span)
|
|
696
|
+
};
|
|
697
|
+
};
|
|
698
|
+
/**
|
|
699
|
+
* Plain text of a slice, one line per text block. A slice and a block list have
|
|
700
|
+
* the same shape, so the serializer's walk serves both.
|
|
701
|
+
*/
|
|
702
|
+
const plainTextOf = (slice) => toText(slice.blocks);
|
|
703
|
+
/**
|
|
704
|
+
* A slice from pasted plain text: one paragraph per line. Identities come from
|
|
705
|
+
* the caller, like every other identity a live edit mints.
|
|
706
|
+
*/
|
|
707
|
+
const sliceFromText = (text, mint) => ({
|
|
708
|
+
version: 1,
|
|
709
|
+
blocks: text.split(/\r\n|\r|\n/).map((line) => ({
|
|
710
|
+
type: "Paragraph",
|
|
711
|
+
id: NodeId.make(mint()),
|
|
712
|
+
children: [{
|
|
713
|
+
type: "Text",
|
|
714
|
+
id: NodeId.make(mint()),
|
|
715
|
+
text: line,
|
|
716
|
+
marks: []
|
|
717
|
+
}]
|
|
718
|
+
}))
|
|
719
|
+
});
|
|
720
|
+
/** The same content under fresh identities, so a paste can never collide. */
|
|
721
|
+
const withFreshIds = (slice, mint) => {
|
|
722
|
+
const freshBlock = (block) => {
|
|
723
|
+
const id = NodeId.make(mint());
|
|
724
|
+
const children = block.children.map((run) => ({
|
|
725
|
+
...run,
|
|
726
|
+
id: NodeId.make(mint())
|
|
727
|
+
}));
|
|
728
|
+
if (block.type === "Node" && block.blocks !== void 0) return {
|
|
729
|
+
...block,
|
|
730
|
+
id,
|
|
731
|
+
children,
|
|
732
|
+
blocks: block.blocks.map(freshBlock)
|
|
733
|
+
};
|
|
734
|
+
return {
|
|
735
|
+
...block,
|
|
736
|
+
id,
|
|
737
|
+
children
|
|
738
|
+
};
|
|
739
|
+
};
|
|
740
|
+
return {
|
|
741
|
+
version: 1,
|
|
742
|
+
blocks: slice.blocks.map(freshBlock)
|
|
743
|
+
};
|
|
744
|
+
};
|
|
745
|
+
/** Encodes a slice for the clipboard. */
|
|
746
|
+
const serializeSlice = (slice) => JSON.stringify(encodeSlice(slice));
|
|
747
|
+
/** Decodes a slice, or undefined when the payload is not one this version wrote. */
|
|
748
|
+
const deserializeSlice = (input) => {
|
|
749
|
+
try {
|
|
750
|
+
return decodeSlice(typeof input === "string" ? JSON.parse(input) : input);
|
|
751
|
+
} catch {
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
};
|
|
755
|
+
//#endregion
|
|
756
|
+
//#region src/transform.ts
|
|
757
|
+
/** A transform that found nothing to do. */
|
|
758
|
+
const unchanged = (document) => ({
|
|
759
|
+
document,
|
|
760
|
+
steps: [],
|
|
761
|
+
insertedNodes: /* @__PURE__ */ new Set(),
|
|
762
|
+
removedNodes: /* @__PURE__ */ new Set(),
|
|
763
|
+
dirtyNodes: /* @__PURE__ */ new Set(),
|
|
764
|
+
textChanged: /* @__PURE__ */ new Set(),
|
|
765
|
+
structureChanged: false
|
|
766
|
+
});
|
|
767
|
+
const mergeRunInto = (accumulator, run) => ({
|
|
768
|
+
...accumulator,
|
|
769
|
+
text: accumulator.text + run.text
|
|
770
|
+
});
|
|
771
|
+
/**
|
|
772
|
+
* Merges adjacent runs whose mark sets match, within the blocks the transaction
|
|
773
|
+
* touched. Merging strictly reduces the run count, so one pass reaches a stable
|
|
774
|
+
* state and a second pass finds nothing: the rule is idempotent, and only equal
|
|
775
|
+
* mark sets merge, so an unknown mark never drops.
|
|
776
|
+
*/
|
|
777
|
+
const mergeAdjacentRuns = {
|
|
778
|
+
name: "mergeAdjacentRuns",
|
|
779
|
+
apply: (document, context) => {
|
|
780
|
+
const steps = [];
|
|
781
|
+
const removedNodes = /* @__PURE__ */ new Set();
|
|
782
|
+
const dirtyNodes = /* @__PURE__ */ new Set();
|
|
783
|
+
const textChanged = /* @__PURE__ */ new Set();
|
|
784
|
+
let next = document;
|
|
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];
|
|
790
|
+
const first = block.children[0];
|
|
791
|
+
if (first === void 0) continue;
|
|
792
|
+
let accumulator = first;
|
|
793
|
+
let changed = false;
|
|
794
|
+
const kept = [accumulator];
|
|
795
|
+
for (const run of block.children.slice(1)) if (sameMarkSet(accumulator.marks, run.marks)) {
|
|
796
|
+
steps.push({
|
|
797
|
+
node: run.id,
|
|
798
|
+
into: accumulator.id,
|
|
799
|
+
at: 0,
|
|
800
|
+
base: accumulator.text.length
|
|
801
|
+
});
|
|
802
|
+
accumulator = mergeRunInto(accumulator, run);
|
|
803
|
+
kept[kept.length - 1] = accumulator;
|
|
804
|
+
removedNodes.add(run.id);
|
|
805
|
+
dirtyNodes.add(accumulator.id);
|
|
806
|
+
textChanged.add(accumulator.id);
|
|
807
|
+
changed = true;
|
|
808
|
+
} else {
|
|
809
|
+
accumulator = run;
|
|
810
|
+
kept.push(run);
|
|
811
|
+
}
|
|
812
|
+
if (!changed) continue;
|
|
813
|
+
const blocks = [...next.children];
|
|
814
|
+
blocks[blockIndex] = {
|
|
815
|
+
...block,
|
|
816
|
+
children: kept
|
|
817
|
+
};
|
|
818
|
+
next = {
|
|
819
|
+
...next,
|
|
820
|
+
children: blocks
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
return {
|
|
824
|
+
document: next,
|
|
825
|
+
steps,
|
|
826
|
+
insertedNodes: /* @__PURE__ */ new Set(),
|
|
827
|
+
removedNodes,
|
|
828
|
+
dirtyNodes,
|
|
829
|
+
textChanged,
|
|
830
|
+
structureChanged: false
|
|
831
|
+
};
|
|
832
|
+
}
|
|
833
|
+
};
|
|
834
|
+
/** The transforms every transaction runs, in order, unless a caller says otherwise. */
|
|
835
|
+
const defaultTransforms = [mergeAdjacentRuns];
|
|
836
|
+
//#endregion
|
|
837
|
+
//#region src/transaction.ts
|
|
838
|
+
/** How many normalization passes a transaction may spend before it gives up. */
|
|
839
|
+
const MAX_NORMALIZATION_PASSES = 10;
|
|
840
|
+
const Offset = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0));
|
|
841
|
+
const InsertTextOperation = Schema.Struct({
|
|
842
|
+
type: Schema.Literal("InsertText"),
|
|
843
|
+
at: Position,
|
|
844
|
+
text: Schema.String
|
|
845
|
+
});
|
|
846
|
+
const DeleteTextOperation = Schema.Struct({
|
|
847
|
+
type: Schema.Literal("DeleteText"),
|
|
848
|
+
node: NodeId,
|
|
849
|
+
from: Offset,
|
|
850
|
+
to: Offset
|
|
851
|
+
});
|
|
852
|
+
const AddMarkOperation = Schema.Struct({
|
|
853
|
+
type: Schema.Literal("AddMark"),
|
|
854
|
+
node: NodeId,
|
|
855
|
+
mark: RunMark
|
|
856
|
+
});
|
|
857
|
+
const RemoveMarkOperation = Schema.Struct({
|
|
858
|
+
type: Schema.Literal("RemoveMark"),
|
|
859
|
+
node: NodeId,
|
|
860
|
+
mark: Schema.String
|
|
861
|
+
});
|
|
862
|
+
const SetSelectionOperation = Schema.Struct({
|
|
863
|
+
type: Schema.Literal("SetSelection"),
|
|
864
|
+
selection: Schema.NullOr(Selection)
|
|
865
|
+
});
|
|
866
|
+
const SplitNodeOperation = Schema.Struct({
|
|
867
|
+
type: Schema.Literal("SplitNode"),
|
|
868
|
+
block: NodeId,
|
|
869
|
+
node: NodeId,
|
|
870
|
+
offset: Offset,
|
|
871
|
+
blockId: NodeId,
|
|
872
|
+
textId: NodeId
|
|
873
|
+
});
|
|
874
|
+
const JoinNodeOperation = Schema.Struct({
|
|
875
|
+
type: Schema.Literal("JoinNode"),
|
|
876
|
+
into: NodeId,
|
|
877
|
+
removed: NodeId
|
|
878
|
+
});
|
|
879
|
+
const MoveNodeOperation = Schema.Struct({
|
|
880
|
+
type: Schema.Literal("MoveNode"),
|
|
881
|
+
node: NodeId,
|
|
882
|
+
to: Offset,
|
|
883
|
+
/** The block list to move into: a node block's, or the document's when absent. */
|
|
884
|
+
parent: Schema.optionalKey(NodeId)
|
|
885
|
+
});
|
|
886
|
+
const SetNodePropsOperation = Schema.Struct({
|
|
887
|
+
type: Schema.Literal("SetNodeProps"),
|
|
888
|
+
node: NodeId,
|
|
889
|
+
level: Schema.Literals([
|
|
890
|
+
1,
|
|
891
|
+
2,
|
|
892
|
+
3,
|
|
893
|
+
4,
|
|
894
|
+
5,
|
|
895
|
+
6
|
|
896
|
+
])
|
|
897
|
+
});
|
|
898
|
+
const InsertNodeOperation = Schema.Struct({
|
|
899
|
+
type: Schema.Literal("InsertNode"),
|
|
900
|
+
block: Block,
|
|
901
|
+
at: Offset,
|
|
902
|
+
/** The block list to insert into: a node block's, or the document's when absent. */
|
|
903
|
+
parent: Schema.optionalKey(NodeId)
|
|
904
|
+
});
|
|
905
|
+
const DeleteNodeOperation = Schema.Struct({
|
|
906
|
+
type: Schema.Literal("DeleteNode"),
|
|
907
|
+
node: NodeId
|
|
908
|
+
});
|
|
909
|
+
const SplitRunOperation = Schema.Struct({
|
|
910
|
+
type: Schema.Literal("SplitRun"),
|
|
911
|
+
node: NodeId,
|
|
912
|
+
offset: Offset,
|
|
913
|
+
textId: NodeId
|
|
914
|
+
});
|
|
915
|
+
const Operation = Schema.Union([
|
|
916
|
+
InsertTextOperation,
|
|
917
|
+
DeleteTextOperation,
|
|
918
|
+
AddMarkOperation,
|
|
919
|
+
RemoveMarkOperation,
|
|
920
|
+
SetSelectionOperation,
|
|
921
|
+
SplitNodeOperation,
|
|
922
|
+
JoinNodeOperation,
|
|
923
|
+
MoveNodeOperation,
|
|
924
|
+
SetNodePropsOperation,
|
|
925
|
+
InsertNodeOperation,
|
|
926
|
+
DeleteNodeOperation,
|
|
927
|
+
SplitRunOperation
|
|
928
|
+
]);
|
|
929
|
+
const Transaction = Schema.Array(Operation);
|
|
930
|
+
const targetId = (target) => typeof target === "string" ? target : target.id;
|
|
931
|
+
/** Accepts a raw string or validated id; empty strings throw via `NodeId`. */
|
|
932
|
+
const freshId = (id) => typeof id === "string" ? NodeId.make(id) : id;
|
|
933
|
+
/**
|
|
934
|
+
* Typesafe constructors for transaction operations. Each builder accepts a
|
|
935
|
+
* `NodeId` or a `Node.make` reference and validates shape immediately
|
|
936
|
+
* (misuse throws), while document-dependent checks — node kind, existence,
|
|
937
|
+
* bounds, selection resolution — remain `apply` diagnostics. Compose with
|
|
938
|
+
* `Node.at` for positions: `Edit.insertText(Text.at(5, 'after'), '!')`.
|
|
939
|
+
*/
|
|
940
|
+
const Edit = {
|
|
941
|
+
insertText: (at, text) => InsertTextOperation.make({
|
|
942
|
+
type: "InsertText",
|
|
943
|
+
at,
|
|
944
|
+
text
|
|
945
|
+
}),
|
|
946
|
+
deleteText: (node, from, to) => {
|
|
947
|
+
if (from > to) throw new Error(`Edit.deleteText: from (${from}) must not exceed to (${to})`);
|
|
948
|
+
return DeleteTextOperation.make({
|
|
949
|
+
type: "DeleteText",
|
|
950
|
+
node: targetId(node),
|
|
951
|
+
from,
|
|
952
|
+
to
|
|
953
|
+
});
|
|
954
|
+
},
|
|
955
|
+
addMark: (node, mark) => AddMarkOperation.make({
|
|
956
|
+
type: "AddMark",
|
|
957
|
+
node: targetId(node),
|
|
958
|
+
mark
|
|
959
|
+
}),
|
|
960
|
+
removeMark: (node, mark) => RemoveMarkOperation.make({
|
|
961
|
+
type: "RemoveMark",
|
|
962
|
+
node: targetId(node),
|
|
963
|
+
mark
|
|
964
|
+
}),
|
|
965
|
+
setSelection: (selection) => SetSelectionOperation.make({
|
|
966
|
+
type: "SetSelection",
|
|
967
|
+
selection
|
|
968
|
+
}),
|
|
969
|
+
splitBlock: (block, node, offset, newBlock, newRun) => SplitNodeOperation.make({
|
|
970
|
+
type: "SplitNode",
|
|
971
|
+
block: targetId(block),
|
|
972
|
+
node: targetId(node),
|
|
973
|
+
offset,
|
|
974
|
+
blockId: freshId(newBlock),
|
|
975
|
+
textId: freshId(newRun)
|
|
976
|
+
}),
|
|
977
|
+
joinBlocks: (survivor, removed) => JoinNodeOperation.make({
|
|
978
|
+
type: "JoinNode",
|
|
979
|
+
into: targetId(survivor),
|
|
980
|
+
removed: targetId(removed)
|
|
981
|
+
}),
|
|
982
|
+
moveBlock: (node, to, parent) => MoveNodeOperation.make({
|
|
983
|
+
type: "MoveNode",
|
|
984
|
+
node: targetId(node),
|
|
985
|
+
to,
|
|
986
|
+
...parent === void 0 ? {} : { parent: targetId(parent) }
|
|
987
|
+
}),
|
|
988
|
+
setNodeProps: (node, level) => SetNodePropsOperation.make({
|
|
989
|
+
type: "SetNodeProps",
|
|
990
|
+
node: targetId(node),
|
|
991
|
+
level
|
|
992
|
+
}),
|
|
993
|
+
insertBlock: (block, at, parent) => InsertNodeOperation.make({
|
|
994
|
+
type: "InsertNode",
|
|
995
|
+
block,
|
|
996
|
+
at,
|
|
997
|
+
...parent === void 0 ? {} : { parent: targetId(parent) }
|
|
998
|
+
}),
|
|
999
|
+
deleteBlock: (node) => DeleteNodeOperation.make({
|
|
1000
|
+
type: "DeleteNode",
|
|
1001
|
+
node: targetId(node)
|
|
1002
|
+
}),
|
|
1003
|
+
splitRun: (node, offset, newRun) => SplitRunOperation.make({
|
|
1004
|
+
type: "SplitRun",
|
|
1005
|
+
node: targetId(node),
|
|
1006
|
+
offset,
|
|
1007
|
+
textId: freshId(newRun)
|
|
1008
|
+
})
|
|
1009
|
+
};
|
|
1010
|
+
/** Maps a position through each edit, preserving insertion affinity. */
|
|
1011
|
+
const mapPosition = (position, steps) => steps.reduce((current, step) => {
|
|
1012
|
+
if (current.node !== step.node) return current;
|
|
1013
|
+
if ("base" in step) {
|
|
1014
|
+
if (current.offset < step.at) return current;
|
|
1015
|
+
return {
|
|
1016
|
+
...current,
|
|
1017
|
+
node: step.into,
|
|
1018
|
+
offset: step.base + current.offset - step.at
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
if ("at" in step) {
|
|
1022
|
+
if (current.offset < step.at) return current;
|
|
1023
|
+
if (current.offset === step.at && current.affinity === "before") return current;
|
|
1024
|
+
return {
|
|
1025
|
+
...current,
|
|
1026
|
+
node: step.into,
|
|
1027
|
+
offset: current.offset - step.at
|
|
1028
|
+
};
|
|
1029
|
+
}
|
|
1030
|
+
if ("into" in step) return {
|
|
1031
|
+
...current,
|
|
1032
|
+
node: step.into,
|
|
1033
|
+
offset: 0
|
|
1034
|
+
};
|
|
1035
|
+
if (current.offset < step.from) return current;
|
|
1036
|
+
const offset = current.offset > step.to ? current.offset + step.inserted - (step.to - step.from) : step.from + (current.affinity === "after" ? step.inserted : 0);
|
|
1037
|
+
return offset === current.offset ? current : {
|
|
1038
|
+
...current,
|
|
1039
|
+
offset
|
|
1040
|
+
};
|
|
1041
|
+
}, position);
|
|
1042
|
+
/**
|
|
1043
|
+
* Maps a whole selection through steps: both range endpoints, or a node target
|
|
1044
|
+
* whose identity a step relocated. Steps that only replace text have no `into`,
|
|
1045
|
+
* so a node selection is unaffected by them.
|
|
1046
|
+
*/
|
|
1047
|
+
const mapThrough = (selection, steps) => {
|
|
1048
|
+
if (selection === null) return null;
|
|
1049
|
+
if (selection.type === "Node") {
|
|
1050
|
+
const step = steps.find((candidate) => "into" in candidate && candidate.node === selection.node);
|
|
1051
|
+
return step === void 0 || !("into" in step) ? selection : {
|
|
1052
|
+
...selection,
|
|
1053
|
+
node: step.into
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
1056
|
+
return {
|
|
1057
|
+
...selection,
|
|
1058
|
+
anchor: mapPosition(selection.anchor, steps),
|
|
1059
|
+
focus: mapPosition(selection.focus, steps)
|
|
1060
|
+
};
|
|
1061
|
+
};
|
|
1062
|
+
const decodeState = Schema.decodeUnknownSync(EditorState, { onExcessProperty: "error" });
|
|
1063
|
+
const decodeTransaction = Schema.decodeUnknownSync(Transaction, { onExcessProperty: "error" });
|
|
1064
|
+
const sameSelection = (left, right) => {
|
|
1065
|
+
if (left === null || right === null) return left === right;
|
|
1066
|
+
if (left.type === "Node") return right.type === "Node" && left.node === right.node;
|
|
1067
|
+
if (right.type !== "Range") return false;
|
|
1068
|
+
return ["anchor", "focus"].every((key) => left[key].node === right[key].node && left[key].offset === right[key].offset && left[key].affinity === right[key].affinity);
|
|
1069
|
+
};
|
|
1070
|
+
/** The nested block list of a container, or undefined for any other block. */
|
|
1071
|
+
const nestedOf = (block) => block.type === "Node" && block.blocks !== void 0 ? block.blocks : void 0;
|
|
1072
|
+
/**
|
|
1073
|
+
* A block's address: root-first container indices. `[2]` is the third top-level
|
|
1074
|
+
* block; `[2, 0]` is the first block nested inside it (§116). The document's own
|
|
1075
|
+
* block list is the container at `[]`.
|
|
1076
|
+
*/
|
|
1077
|
+
const pathKey = (path) => path.join(".");
|
|
1078
|
+
const keyToPath = (key) => key === "" ? [] : key.split(".").map(Number);
|
|
1079
|
+
/**
|
|
1080
|
+
* Pure, atomic text transaction. Rejection returns no partially edited state.
|
|
1081
|
+
* `transforms` defaults to the registry's shipped rules; a Kit's transforms
|
|
1082
|
+
* arrive here when Kit support lands.
|
|
1083
|
+
*/
|
|
1084
|
+
const apply = (state, transaction, transforms = defaultTransforms) => {
|
|
1085
|
+
try {
|
|
1086
|
+
decodeState(state);
|
|
1087
|
+
decodeTransaction(transaction);
|
|
1088
|
+
} catch {
|
|
1089
|
+
return {
|
|
1090
|
+
ok: false,
|
|
1091
|
+
error: "InvalidInput"
|
|
1092
|
+
};
|
|
1093
|
+
}
|
|
1094
|
+
const indexDocument = (current) => {
|
|
1095
|
+
const blockPaths = /* @__PURE__ */ new Map();
|
|
1096
|
+
const runPaths = /* @__PURE__ */ new Map();
|
|
1097
|
+
eachBlock(current.children, (block, path) => {
|
|
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);
|
|
1110
|
+
const reindex = () => {
|
|
1111
|
+
({blockPaths, runPaths} = indexDocument(document));
|
|
1112
|
+
};
|
|
1113
|
+
const usedIds = /* @__PURE__ */ new Set([...runPaths.keys(), ...blockPaths.keys()]);
|
|
1114
|
+
let document = state.document;
|
|
1115
|
+
const workingBlocks = /* @__PURE__ */ new Map();
|
|
1116
|
+
const workingRuns = /* @__PURE__ */ new Map();
|
|
1117
|
+
const blockAt = (path) => blocksAt(path.slice(0, -1))[path[path.length - 1]];
|
|
1118
|
+
/** The block list at a container path, reading through any pending copy. */
|
|
1119
|
+
function blocksAt(containerPath) {
|
|
1120
|
+
const pending = workingBlocks.get(pathKey(containerPath));
|
|
1121
|
+
if (pending !== void 0) return pending;
|
|
1122
|
+
if (containerPath.length === 0) return document.children;
|
|
1123
|
+
const parent = blockAt(containerPath);
|
|
1124
|
+
return parent?.type === "Node" && parent.blocks !== void 0 ? parent.blocks : [];
|
|
1125
|
+
}
|
|
1126
|
+
/** Copies a container, and its ancestors, once: writes never touch the input. */
|
|
1127
|
+
const ensureContainer = (containerPath) => {
|
|
1128
|
+
const key = pathKey(containerPath);
|
|
1129
|
+
const existing = workingBlocks.get(key);
|
|
1130
|
+
if (existing !== void 0) return existing;
|
|
1131
|
+
if (containerPath.length > 0) ensureContainer(containerPath.slice(0, -1));
|
|
1132
|
+
const copy = [...blocksAt(containerPath)];
|
|
1133
|
+
workingBlocks.set(key, copy);
|
|
1134
|
+
return copy;
|
|
1135
|
+
};
|
|
1136
|
+
/** The block's runs as they stand: a pending copy if one exists, else the document's. */
|
|
1137
|
+
const runsAt = (path) => workingRuns.get(pathKey(path)) ?? blockAt(path)?.children ?? [];
|
|
1138
|
+
/** The block's run array, copied on first write and mutated in place after. */
|
|
1139
|
+
const runArray = (path) => {
|
|
1140
|
+
const key = pathKey(path);
|
|
1141
|
+
const existing = workingRuns.get(key);
|
|
1142
|
+
if (existing !== void 0) return existing;
|
|
1143
|
+
ensureContainer(path.slice(0, -1));
|
|
1144
|
+
const copy = [...blockAt(path)?.children ?? []];
|
|
1145
|
+
workingRuns.set(key, copy);
|
|
1146
|
+
return copy;
|
|
1147
|
+
};
|
|
1148
|
+
const writeBlock = (path, block) => {
|
|
1149
|
+
const container = ensureContainer(path.slice(0, -1));
|
|
1150
|
+
container[path[path.length - 1]] = block;
|
|
1151
|
+
};
|
|
1152
|
+
/**
|
|
1153
|
+
* The block list a structural operation targets: the document's, or a node
|
|
1154
|
+
* block's nested blocks. A parent that cannot hold blocks is `InvalidParent`,
|
|
1155
|
+
* one that does not exist is `MissingNode`.
|
|
1156
|
+
*/
|
|
1157
|
+
const containerPathOf = (parent) => {
|
|
1158
|
+
if (parent === void 0) return { path: [] };
|
|
1159
|
+
const path = blockPaths.get(parent);
|
|
1160
|
+
if (path === void 0) return { error: "MissingNode" };
|
|
1161
|
+
const block = blockAt(path);
|
|
1162
|
+
return block?.type === "Node" && block.blocks !== void 0 ? { path } : { error: "InvalidParent" };
|
|
1163
|
+
};
|
|
1164
|
+
const materialize = () => {
|
|
1165
|
+
if (workingBlocks.size === 0 && workingRuns.size === 0) return;
|
|
1166
|
+
for (const [key, runs] of workingRuns) {
|
|
1167
|
+
const path = keyToPath(key);
|
|
1168
|
+
const container = workingBlocks.get(pathKey(path.slice(0, -1)));
|
|
1169
|
+
const index = path[path.length - 1];
|
|
1170
|
+
container[index] = {
|
|
1171
|
+
...container[index],
|
|
1172
|
+
children: runs
|
|
1173
|
+
};
|
|
1174
|
+
}
|
|
1175
|
+
workingRuns.clear();
|
|
1176
|
+
for (const [key, blocks] of workingBlocks) {
|
|
1177
|
+
const path = keyToPath(key);
|
|
1178
|
+
if (path.length === 0) {
|
|
1179
|
+
document = {
|
|
1180
|
+
...document,
|
|
1181
|
+
children: blocks
|
|
1182
|
+
};
|
|
1183
|
+
continue;
|
|
1184
|
+
}
|
|
1185
|
+
const parent = workingBlocks.get(pathKey(path.slice(0, -1)));
|
|
1186
|
+
const index = path[path.length - 1];
|
|
1187
|
+
const parentBlock = parent[index];
|
|
1188
|
+
if (parentBlock.type === "Node") parent[index] = {
|
|
1189
|
+
...parentBlock,
|
|
1190
|
+
blocks
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
workingBlocks.clear();
|
|
1194
|
+
};
|
|
1195
|
+
let selection = state.selection;
|
|
1196
|
+
const dirtyNodes = /* @__PURE__ */ new Set();
|
|
1197
|
+
const insertedNodes = /* @__PURE__ */ new Set();
|
|
1198
|
+
const removedNodes = /* @__PURE__ */ new Set();
|
|
1199
|
+
const textChanged = /* @__PURE__ */ new Set();
|
|
1200
|
+
let structureChanged = false;
|
|
1201
|
+
const positionMap = [];
|
|
1202
|
+
for (let operationIndex = 0; operationIndex < transaction.length; operationIndex++) {
|
|
1203
|
+
const operation = transaction[operationIndex];
|
|
1204
|
+
if (operation.type === "SetSelection") {
|
|
1205
|
+
materialize();
|
|
1206
|
+
if (!selectionIsValid(document, operation.selection)) return {
|
|
1207
|
+
ok: false,
|
|
1208
|
+
error: "InvalidSelection"
|
|
1209
|
+
};
|
|
1210
|
+
selection = operation.selection;
|
|
1211
|
+
continue;
|
|
1212
|
+
}
|
|
1213
|
+
if (operation.type === "SplitRun") {
|
|
1214
|
+
const location = runPaths.get(operation.node);
|
|
1215
|
+
if (location === void 0) return {
|
|
1216
|
+
ok: false,
|
|
1217
|
+
error: "MissingText"
|
|
1218
|
+
};
|
|
1219
|
+
const { path, index: textIndex } = location;
|
|
1220
|
+
const target = blockAt(path);
|
|
1221
|
+
if (target === void 0) return {
|
|
1222
|
+
ok: false,
|
|
1223
|
+
error: "MissingText"
|
|
1224
|
+
};
|
|
1225
|
+
const run = runsAt(path)[textIndex];
|
|
1226
|
+
if (operation.offset > run.text.length) return {
|
|
1227
|
+
ok: false,
|
|
1228
|
+
error: "InvalidRange"
|
|
1229
|
+
};
|
|
1230
|
+
if (usedIds.has(operation.textId)) return {
|
|
1231
|
+
ok: false,
|
|
1232
|
+
error: "InvalidInput"
|
|
1233
|
+
};
|
|
1234
|
+
if (operation.offset === 0) continue;
|
|
1235
|
+
const children = runArray(path);
|
|
1236
|
+
children[textIndex] = {
|
|
1237
|
+
...run,
|
|
1238
|
+
text: run.text.slice(0, operation.offset)
|
|
1239
|
+
};
|
|
1240
|
+
children.splice(textIndex + 1, 0, {
|
|
1241
|
+
...run,
|
|
1242
|
+
id: operation.textId,
|
|
1243
|
+
text: run.text.slice(operation.offset)
|
|
1244
|
+
});
|
|
1245
|
+
usedIds.add(operation.textId);
|
|
1246
|
+
materialize();
|
|
1247
|
+
reindex();
|
|
1248
|
+
const relocate = {
|
|
1249
|
+
node: run.id,
|
|
1250
|
+
into: operation.textId,
|
|
1251
|
+
at: operation.offset
|
|
1252
|
+
};
|
|
1253
|
+
positionMap.push(relocate);
|
|
1254
|
+
if (selection?.type === "Range") selection = {
|
|
1255
|
+
...selection,
|
|
1256
|
+
anchor: mapPosition(selection.anchor, [relocate]),
|
|
1257
|
+
focus: mapPosition(selection.focus, [relocate])
|
|
1258
|
+
};
|
|
1259
|
+
dirtyNodes.add(target.id);
|
|
1260
|
+
dirtyNodes.add(run.id);
|
|
1261
|
+
dirtyNodes.add(operation.textId);
|
|
1262
|
+
textChanged.add(run.id);
|
|
1263
|
+
textChanged.add(operation.textId);
|
|
1264
|
+
insertedNodes.add(operation.textId);
|
|
1265
|
+
continue;
|
|
1266
|
+
}
|
|
1267
|
+
if (operation.type === "SplitNode") {
|
|
1268
|
+
materialize();
|
|
1269
|
+
const blockPath = blockPaths.get(operation.block);
|
|
1270
|
+
if (blockPath === void 0) return {
|
|
1271
|
+
ok: false,
|
|
1272
|
+
error: "MissingNode"
|
|
1273
|
+
};
|
|
1274
|
+
const runLocation = runPaths.get(operation.node);
|
|
1275
|
+
if (runLocation === void 0) return {
|
|
1276
|
+
ok: false,
|
|
1277
|
+
error: "MissingText"
|
|
1278
|
+
};
|
|
1279
|
+
const { path: runBlockPath, index: textIndex } = runLocation;
|
|
1280
|
+
if (pathKey(runBlockPath) !== pathKey(blockPath)) return {
|
|
1281
|
+
ok: false,
|
|
1282
|
+
error: "InvalidRange"
|
|
1283
|
+
};
|
|
1284
|
+
const target = blockAt(blockPath);
|
|
1285
|
+
const run = target.children[textIndex];
|
|
1286
|
+
if (operation.offset > run.text.length) return {
|
|
1287
|
+
ok: false,
|
|
1288
|
+
error: "InvalidRange"
|
|
1289
|
+
};
|
|
1290
|
+
if (usedIds.has(operation.blockId) || usedIds.has(operation.textId) || operation.blockId === operation.textId) return {
|
|
1291
|
+
ok: false,
|
|
1292
|
+
error: "InvalidInput"
|
|
1293
|
+
};
|
|
1294
|
+
const leftBlock = {
|
|
1295
|
+
...target,
|
|
1296
|
+
children: [...target.children.slice(0, textIndex), {
|
|
1297
|
+
...run,
|
|
1298
|
+
text: run.text.slice(0, operation.offset)
|
|
1299
|
+
}]
|
|
1300
|
+
};
|
|
1301
|
+
const rightBlock = {
|
|
1302
|
+
...target,
|
|
1303
|
+
id: operation.blockId,
|
|
1304
|
+
children: [{
|
|
1305
|
+
...run,
|
|
1306
|
+
id: operation.textId,
|
|
1307
|
+
text: run.text.slice(operation.offset)
|
|
1308
|
+
}, ...target.children.slice(textIndex + 1)]
|
|
1309
|
+
};
|
|
1310
|
+
const containerPath = blockPath.slice(0, -1);
|
|
1311
|
+
const index = blockPath[blockPath.length - 1];
|
|
1312
|
+
const container = ensureContainer(containerPath);
|
|
1313
|
+
container[index] = leftBlock;
|
|
1314
|
+
container.splice(index + 1, 0, rightBlock);
|
|
1315
|
+
materialize();
|
|
1316
|
+
usedIds.add(operation.blockId);
|
|
1317
|
+
usedIds.add(operation.textId);
|
|
1318
|
+
reindex();
|
|
1319
|
+
const relocate = {
|
|
1320
|
+
node: run.id,
|
|
1321
|
+
into: operation.textId,
|
|
1322
|
+
at: operation.offset
|
|
1323
|
+
};
|
|
1324
|
+
positionMap.push(relocate);
|
|
1325
|
+
if (selection?.type === "Range") selection = {
|
|
1326
|
+
...selection,
|
|
1327
|
+
anchor: mapPosition(selection.anchor, [relocate]),
|
|
1328
|
+
focus: mapPosition(selection.focus, [relocate])
|
|
1329
|
+
};
|
|
1330
|
+
dirtyNodes.add(target.id);
|
|
1331
|
+
dirtyNodes.add(operation.blockId);
|
|
1332
|
+
dirtyNodes.add(run.id);
|
|
1333
|
+
dirtyNodes.add(operation.textId);
|
|
1334
|
+
for (const moved of target.children.slice(textIndex + 1)) dirtyNodes.add(moved.id);
|
|
1335
|
+
textChanged.add(run.id);
|
|
1336
|
+
textChanged.add(operation.textId);
|
|
1337
|
+
insertedNodes.add(operation.blockId);
|
|
1338
|
+
insertedNodes.add(operation.textId);
|
|
1339
|
+
structureChanged = true;
|
|
1340
|
+
continue;
|
|
1341
|
+
}
|
|
1342
|
+
if (operation.type === "JoinNode") {
|
|
1343
|
+
materialize();
|
|
1344
|
+
const intoPath = blockPaths.get(operation.into);
|
|
1345
|
+
if (intoPath === void 0) return {
|
|
1346
|
+
ok: false,
|
|
1347
|
+
error: "MissingNode"
|
|
1348
|
+
};
|
|
1349
|
+
const removedPath = blockPaths.get(operation.removed);
|
|
1350
|
+
if (removedPath === void 0) return {
|
|
1351
|
+
ok: false,
|
|
1352
|
+
error: "MissingNode"
|
|
1353
|
+
};
|
|
1354
|
+
if (pathKey(intoPath.slice(0, -1)) !== pathKey(removedPath.slice(0, -1))) return {
|
|
1355
|
+
ok: false,
|
|
1356
|
+
error: "InvalidParent"
|
|
1357
|
+
};
|
|
1358
|
+
const containerPath = intoPath.slice(0, -1);
|
|
1359
|
+
const intoIndex = intoPath[intoPath.length - 1];
|
|
1360
|
+
const removedIndex = removedPath[removedPath.length - 1];
|
|
1361
|
+
if (removedIndex !== intoIndex + 1) return {
|
|
1362
|
+
ok: false,
|
|
1363
|
+
error: "InvalidRange"
|
|
1364
|
+
};
|
|
1365
|
+
const container = ensureContainer(containerPath);
|
|
1366
|
+
const survivor = container[intoIndex];
|
|
1367
|
+
const removedBlocks = [];
|
|
1368
|
+
while (operationIndex < transaction.length) {
|
|
1369
|
+
const next = transaction[operationIndex];
|
|
1370
|
+
if (next?.type !== "JoinNode" || next.into !== operation.into) break;
|
|
1371
|
+
const removed = container[intoIndex + removedBlocks.length + 1];
|
|
1372
|
+
if (removed?.id !== next.removed) break;
|
|
1373
|
+
if (survivor.type === "Unknown" || removed.type === "Unknown") return {
|
|
1374
|
+
ok: false,
|
|
1375
|
+
error: "InvalidRange"
|
|
1376
|
+
};
|
|
1377
|
+
if (survivor.type === "Node" || removed.type === "Node") {
|
|
1378
|
+
if (survivor.type !== "Node" || removed.type !== "Node" || survivor.kind !== removed.kind || !Equal.equals(survivor.props, removed.props)) return {
|
|
1379
|
+
ok: false,
|
|
1380
|
+
error: "InvalidRange"
|
|
1381
|
+
};
|
|
1382
|
+
}
|
|
1383
|
+
if (nestedOf(survivor) === void 0 !== (nestedOf(removed) === void 0)) return {
|
|
1384
|
+
ok: false,
|
|
1385
|
+
error: "InvalidRange"
|
|
1386
|
+
};
|
|
1387
|
+
removedBlocks.push(removed);
|
|
1388
|
+
operationIndex++;
|
|
1389
|
+
}
|
|
1390
|
+
operationIndex--;
|
|
1391
|
+
const mergedRuns = [...survivor.children, ...removedBlocks.flatMap((block) => block.children)];
|
|
1392
|
+
if (survivor.type === "Node" && survivor.blocks !== void 0) container[intoIndex] = {
|
|
1393
|
+
...survivor,
|
|
1394
|
+
children: mergedRuns,
|
|
1395
|
+
blocks: [...survivor.blocks, ...removedBlocks.flatMap((block) => nestedOf(block) ?? [])]
|
|
1396
|
+
};
|
|
1397
|
+
else container[intoIndex] = {
|
|
1398
|
+
...survivor,
|
|
1399
|
+
children: mergedRuns
|
|
1400
|
+
};
|
|
1401
|
+
container.splice(removedIndex, removedBlocks.length);
|
|
1402
|
+
materialize();
|
|
1403
|
+
reindex();
|
|
1404
|
+
for (const removed of removedBlocks) if (selection?.type === "Node" && selection.node === removed.id) selection = {
|
|
1405
|
+
...selection,
|
|
1406
|
+
node: operation.into
|
|
1407
|
+
};
|
|
1408
|
+
dirtyNodes.add(operation.into);
|
|
1409
|
+
for (const removed of removedBlocks) {
|
|
1410
|
+
dirtyNodes.add(removed.id);
|
|
1411
|
+
removedNodes.add(removed.id);
|
|
1412
|
+
for (const moved of removed.children) dirtyNodes.add(moved.id);
|
|
1413
|
+
}
|
|
1414
|
+
structureChanged = true;
|
|
1415
|
+
continue;
|
|
1416
|
+
}
|
|
1417
|
+
if (operation.type === "MoveNode") {
|
|
1418
|
+
materialize();
|
|
1419
|
+
const fromPath = blockPaths.get(operation.node);
|
|
1420
|
+
if (fromPath === void 0) return {
|
|
1421
|
+
ok: false,
|
|
1422
|
+
error: "MissingNode"
|
|
1423
|
+
};
|
|
1424
|
+
const target = containerPathOf(operation.parent);
|
|
1425
|
+
if ("error" in target) return {
|
|
1426
|
+
ok: false,
|
|
1427
|
+
error: target.error
|
|
1428
|
+
};
|
|
1429
|
+
const sourcePath = fromPath.slice(0, -1);
|
|
1430
|
+
const fromIndex = fromPath[fromPath.length - 1];
|
|
1431
|
+
const sameContainer = pathKey(sourcePath) === pathKey(target.path);
|
|
1432
|
+
const limit = sameContainer ? blocksAt(target.path).length - 1 : blocksAt(target.path).length;
|
|
1433
|
+
if (operation.to > limit) return {
|
|
1434
|
+
ok: false,
|
|
1435
|
+
error: "InvalidRange"
|
|
1436
|
+
};
|
|
1437
|
+
if (sameContainer && operation.to === fromIndex) continue;
|
|
1438
|
+
const source = ensureContainer(sourcePath);
|
|
1439
|
+
const [moved] = source.splice(fromIndex, 1);
|
|
1440
|
+
(sameContainer ? source : ensureContainer(target.path)).splice(operation.to, 0, moved);
|
|
1441
|
+
materialize();
|
|
1442
|
+
reindex();
|
|
1443
|
+
dirtyNodes.add(operation.node);
|
|
1444
|
+
structureChanged = true;
|
|
1445
|
+
continue;
|
|
1446
|
+
}
|
|
1447
|
+
if (operation.type === "SetNodeProps") {
|
|
1448
|
+
const path = blockPaths.get(operation.node);
|
|
1449
|
+
if (path === void 0) return {
|
|
1450
|
+
ok: false,
|
|
1451
|
+
error: "MissingNode"
|
|
1452
|
+
};
|
|
1453
|
+
const target = blockAt(path);
|
|
1454
|
+
if (target === void 0 || target.type !== "Heading") return {
|
|
1455
|
+
ok: false,
|
|
1456
|
+
error: "InvalidRange"
|
|
1457
|
+
};
|
|
1458
|
+
if (target.level === operation.level) continue;
|
|
1459
|
+
writeBlock(path, {
|
|
1460
|
+
...target,
|
|
1461
|
+
level: operation.level
|
|
1462
|
+
});
|
|
1463
|
+
dirtyNodes.add(target.id);
|
|
1464
|
+
structureChanged = true;
|
|
1465
|
+
continue;
|
|
1466
|
+
}
|
|
1467
|
+
if (operation.type === "InsertNode") {
|
|
1468
|
+
materialize();
|
|
1469
|
+
const target = containerPathOf(operation.parent);
|
|
1470
|
+
if ("error" in target) return {
|
|
1471
|
+
ok: false,
|
|
1472
|
+
error: target.error
|
|
1473
|
+
};
|
|
1474
|
+
if (operation.at > blocksAt(target.path).length) return {
|
|
1475
|
+
ok: false,
|
|
1476
|
+
error: "InvalidRange"
|
|
1477
|
+
};
|
|
1478
|
+
const carried = [
|
|
1479
|
+
operation.block.id,
|
|
1480
|
+
...operation.block.children.map((run) => run.id),
|
|
1481
|
+
...operation.block.type === "Node" && operation.block.blocks !== void 0 ? operation.block.blocks.flatMap((block) => [block.id, ...block.children.map((run) => run.id)]) : []
|
|
1482
|
+
];
|
|
1483
|
+
if (new Set(carried).size !== carried.length || carried.some((id) => usedIds.has(id))) return {
|
|
1484
|
+
ok: false,
|
|
1485
|
+
error: "InvalidInput"
|
|
1486
|
+
};
|
|
1487
|
+
ensureContainer(target.path).splice(operation.at, 0, operation.block);
|
|
1488
|
+
materialize();
|
|
1489
|
+
for (const id of carried) {
|
|
1490
|
+
usedIds.add(id);
|
|
1491
|
+
dirtyNodes.add(id);
|
|
1492
|
+
insertedNodes.add(id);
|
|
1493
|
+
}
|
|
1494
|
+
reindex();
|
|
1495
|
+
structureChanged = true;
|
|
1496
|
+
continue;
|
|
1497
|
+
}
|
|
1498
|
+
if (operation.type === "DeleteNode") {
|
|
1499
|
+
materialize();
|
|
1500
|
+
const path = blockPaths.get(operation.node);
|
|
1501
|
+
if (path === void 0) return {
|
|
1502
|
+
ok: false,
|
|
1503
|
+
error: "MissingNode"
|
|
1504
|
+
};
|
|
1505
|
+
const containerPath = path.slice(0, -1);
|
|
1506
|
+
const index = path[path.length - 1];
|
|
1507
|
+
const target = blockAt(path);
|
|
1508
|
+
ensureContainer(containerPath).splice(index, 1);
|
|
1509
|
+
materialize();
|
|
1510
|
+
reindex();
|
|
1511
|
+
const removedPlace = {
|
|
1512
|
+
path,
|
|
1513
|
+
index: 0
|
|
1514
|
+
};
|
|
1515
|
+
let fallback;
|
|
1516
|
+
let after;
|
|
1517
|
+
eachBlock(document.children, (block, blockPath) => {
|
|
1518
|
+
for (const [runIndex, run] of block.children.entries()) if (compareRunPlaces({
|
|
1519
|
+
path: blockPath,
|
|
1520
|
+
index: runIndex
|
|
1521
|
+
}, removedPlace) >= 0) after ??= {
|
|
1522
|
+
block,
|
|
1523
|
+
run
|
|
1524
|
+
};
|
|
1525
|
+
else fallback = {
|
|
1526
|
+
block,
|
|
1527
|
+
run
|
|
1528
|
+
};
|
|
1529
|
+
});
|
|
1530
|
+
const landing = after ?? fallback;
|
|
1531
|
+
const collapses = [];
|
|
1532
|
+
const removedRuns = [];
|
|
1533
|
+
const collect = (block) => {
|
|
1534
|
+
for (const run of block.children) removedRuns.push(run.id);
|
|
1535
|
+
if (block.type === "Node" && block.blocks !== void 0) block.blocks.forEach(collect);
|
|
1536
|
+
};
|
|
1537
|
+
collect(target);
|
|
1538
|
+
if (landing !== void 0) for (const run of removedRuns) collapses.push({
|
|
1539
|
+
node: run,
|
|
1540
|
+
into: landing.run.id
|
|
1541
|
+
});
|
|
1542
|
+
if (selection?.type === "Range") selection = landing === void 0 ? null : {
|
|
1543
|
+
...selection,
|
|
1544
|
+
anchor: mapPosition(selection.anchor, collapses),
|
|
1545
|
+
focus: mapPosition(selection.focus, collapses)
|
|
1546
|
+
};
|
|
1547
|
+
else if (selection?.type === "Node") {
|
|
1548
|
+
const selectedNode = selection.node;
|
|
1549
|
+
if (selectedNode === operation.node || removedRuns.includes(selectedNode)) selection = landing === void 0 ? null : {
|
|
1550
|
+
...selection,
|
|
1551
|
+
node: landing.block.id
|
|
1552
|
+
};
|
|
1553
|
+
}
|
|
1554
|
+
for (const step of collapses) positionMap.push(step);
|
|
1555
|
+
const removedIds = [];
|
|
1556
|
+
const collectIds = (block) => {
|
|
1557
|
+
removedIds.push(block.id, ...block.children.map((run) => run.id));
|
|
1558
|
+
if (block.type === "Node" && block.blocks !== void 0) block.blocks.forEach(collectIds);
|
|
1559
|
+
};
|
|
1560
|
+
collectIds(target);
|
|
1561
|
+
for (const id of removedIds) {
|
|
1562
|
+
dirtyNodes.add(id);
|
|
1563
|
+
removedNodes.add(id);
|
|
1564
|
+
}
|
|
1565
|
+
structureChanged = true;
|
|
1566
|
+
continue;
|
|
1567
|
+
}
|
|
1568
|
+
const id = operation.type === "InsertText" ? operation.at.node : operation.node;
|
|
1569
|
+
const location = runPaths.get(id);
|
|
1570
|
+
if (location === void 0) return {
|
|
1571
|
+
ok: false,
|
|
1572
|
+
error: "MissingText"
|
|
1573
|
+
};
|
|
1574
|
+
const { path, index: textIndex } = location;
|
|
1575
|
+
const block = blockAt(path);
|
|
1576
|
+
if (block === void 0) return {
|
|
1577
|
+
ok: false,
|
|
1578
|
+
error: "MissingText"
|
|
1579
|
+
};
|
|
1580
|
+
const text = runsAt(path)[textIndex];
|
|
1581
|
+
if (operation.type === "AddMark") {
|
|
1582
|
+
const existing = text.marks.find((mark) => markName(mark) === markName(operation.mark));
|
|
1583
|
+
if (existing !== void 0 && sameMark(existing, operation.mark)) continue;
|
|
1584
|
+
const children = runArray(path);
|
|
1585
|
+
children[textIndex] = {
|
|
1586
|
+
...text,
|
|
1587
|
+
marks: existing === void 0 ? [...text.marks, operation.mark] : text.marks.map((mark) => markName(mark) === markName(operation.mark) ? operation.mark : mark)
|
|
1588
|
+
};
|
|
1589
|
+
dirtyNodes.add(block.id);
|
|
1590
|
+
dirtyNodes.add(id);
|
|
1591
|
+
textChanged.add(id);
|
|
1592
|
+
continue;
|
|
1593
|
+
}
|
|
1594
|
+
if (operation.type === "RemoveMark") {
|
|
1595
|
+
if (!text.marks.some((mark) => markName(mark) === operation.mark)) continue;
|
|
1596
|
+
const children = runArray(path);
|
|
1597
|
+
children[textIndex] = {
|
|
1598
|
+
...text,
|
|
1599
|
+
marks: text.marks.filter((mark) => markName(mark) !== operation.mark)
|
|
1600
|
+
};
|
|
1601
|
+
dirtyNodes.add(block.id);
|
|
1602
|
+
dirtyNodes.add(id);
|
|
1603
|
+
textChanged.add(id);
|
|
1604
|
+
continue;
|
|
1605
|
+
}
|
|
1606
|
+
const from = operation.type === "InsertText" ? operation.at.offset : operation.from;
|
|
1607
|
+
const to = operation.type === "InsertText" ? from : operation.to;
|
|
1608
|
+
const inserted = operation.type === "InsertText" ? operation.text : "";
|
|
1609
|
+
if (from > to || to > text.text.length) return {
|
|
1610
|
+
ok: false,
|
|
1611
|
+
error: "InvalidRange"
|
|
1612
|
+
};
|
|
1613
|
+
if (from === to && inserted.length === 0) continue;
|
|
1614
|
+
const children = runArray(path);
|
|
1615
|
+
children[textIndex] = {
|
|
1616
|
+
...text,
|
|
1617
|
+
text: text.text.slice(0, from) + inserted + text.text.slice(to)
|
|
1618
|
+
};
|
|
1619
|
+
const step = {
|
|
1620
|
+
node: id,
|
|
1621
|
+
from,
|
|
1622
|
+
to,
|
|
1623
|
+
inserted: inserted.length
|
|
1624
|
+
};
|
|
1625
|
+
positionMap.push(step);
|
|
1626
|
+
if (selection?.type === "Range") selection = {
|
|
1627
|
+
...selection,
|
|
1628
|
+
anchor: mapPosition(selection.anchor, [step]),
|
|
1629
|
+
focus: mapPosition(selection.focus, [step])
|
|
1630
|
+
};
|
|
1631
|
+
dirtyNodes.add(block.id);
|
|
1632
|
+
dirtyNodes.add(id);
|
|
1633
|
+
textChanged.add(id);
|
|
1634
|
+
}
|
|
1635
|
+
materialize();
|
|
1636
|
+
let pass = 0;
|
|
1637
|
+
for (; pass < 10; pass++) {
|
|
1638
|
+
let changed = false;
|
|
1639
|
+
for (const transform of transforms) {
|
|
1640
|
+
const report = transform.apply(document, {
|
|
1641
|
+
dirtyNodes,
|
|
1642
|
+
pass
|
|
1643
|
+
});
|
|
1644
|
+
if (report.document === document) continue;
|
|
1645
|
+
changed = true;
|
|
1646
|
+
document = report.document;
|
|
1647
|
+
for (const id of report.insertedNodes) insertedNodes.add(id);
|
|
1648
|
+
for (const id of report.removedNodes) removedNodes.add(id);
|
|
1649
|
+
for (const id of report.dirtyNodes) dirtyNodes.add(id);
|
|
1650
|
+
for (const id of report.textChanged) textChanged.add(id);
|
|
1651
|
+
for (const step of report.steps) positionMap.push(step);
|
|
1652
|
+
if (report.structureChanged) structureChanged = true;
|
|
1653
|
+
if (report.steps.length > 0) selection = mapThrough(selection, report.steps);
|
|
1654
|
+
reindex();
|
|
1655
|
+
}
|
|
1656
|
+
if (!changed) break;
|
|
1657
|
+
}
|
|
1658
|
+
if (pass === 10) return {
|
|
1659
|
+
ok: false,
|
|
1660
|
+
error: "UnstableNormalization"
|
|
1661
|
+
};
|
|
1662
|
+
return {
|
|
1663
|
+
ok: true,
|
|
1664
|
+
state: document === state.document && sameSelection(selection, state.selection) ? state : {
|
|
1665
|
+
document,
|
|
1666
|
+
selection
|
|
1667
|
+
},
|
|
1668
|
+
changeSet: {
|
|
1669
|
+
dirtyNodes,
|
|
1670
|
+
insertedNodes,
|
|
1671
|
+
removedNodes,
|
|
1672
|
+
textChanged,
|
|
1673
|
+
structureChanged,
|
|
1674
|
+
selectionChanged: !sameSelection(selection, state.selection)
|
|
1675
|
+
},
|
|
1676
|
+
positionMap
|
|
1677
|
+
};
|
|
1678
|
+
};
|
|
1679
|
+
//#endregion
|
|
1680
|
+
//#region src/command.ts
|
|
1681
|
+
const failure = (error) => ({
|
|
1682
|
+
ok: false,
|
|
1683
|
+
error
|
|
1684
|
+
});
|
|
1685
|
+
/** Document order over a located run, by the shared place rule. */
|
|
1686
|
+
const locatedOrder = (left, right) => compareRunPlaces({
|
|
1687
|
+
path: left.path,
|
|
1688
|
+
index: left.runIndex
|
|
1689
|
+
}, {
|
|
1690
|
+
path: right.path,
|
|
1691
|
+
index: right.runIndex
|
|
1692
|
+
});
|
|
1693
|
+
const locate = (document, node) => {
|
|
1694
|
+
const found = locateRun(document, node);
|
|
1695
|
+
if (found === void 0) return void 0;
|
|
1696
|
+
const block = blockAtPath(document, found.path);
|
|
1697
|
+
if (block === void 0) return void 0;
|
|
1698
|
+
return {
|
|
1699
|
+
path: found.path,
|
|
1700
|
+
runIndex: found.index,
|
|
1701
|
+
blockId: block.id,
|
|
1702
|
+
id: found.run.id,
|
|
1703
|
+
text: found.run.text,
|
|
1704
|
+
marks: found.run.marks
|
|
1705
|
+
};
|
|
1706
|
+
};
|
|
1707
|
+
const isCollapsed = (selection) => selection.anchor.node === selection.focus.node && selection.anchor.offset === selection.focus.offset;
|
|
1708
|
+
/** A caret is a range whose endpoints coincide; direction is not yet meaningful. */
|
|
1709
|
+
const caretAt = (position) => ({
|
|
1710
|
+
type: "Range",
|
|
1711
|
+
anchor: position,
|
|
1712
|
+
focus: position
|
|
1713
|
+
});
|
|
1714
|
+
/** Orders a range's endpoints by document order without losing direction. */
|
|
1715
|
+
const ordered = (document, selection) => {
|
|
1716
|
+
const anchor = locate(document, selection.anchor.node);
|
|
1717
|
+
const focus = locate(document, selection.focus.node);
|
|
1718
|
+
if (anchor === void 0 || focus === void 0) return void 0;
|
|
1719
|
+
const byPlace = locatedOrder(anchor, focus);
|
|
1720
|
+
return (byPlace !== 0 ? byPlace > 0 : selection.anchor.offset > selection.focus.offset) ? {
|
|
1721
|
+
start: selection.focus,
|
|
1722
|
+
end: selection.anchor
|
|
1723
|
+
} : {
|
|
1724
|
+
start: selection.anchor,
|
|
1725
|
+
end: selection.focus
|
|
1726
|
+
};
|
|
1727
|
+
};
|
|
1728
|
+
/** Runs intersecting an ordered [start, end), with the covered sub-range. */
|
|
1729
|
+
const covered = (document, start, end) => {
|
|
1730
|
+
const startAt = locate(document, start.node);
|
|
1731
|
+
const endAt = locate(document, end.node);
|
|
1732
|
+
if (startAt === void 0 || endAt === void 0) return [];
|
|
1733
|
+
const spans = [];
|
|
1734
|
+
eachBlock(document.children, (block, path) => {
|
|
1735
|
+
for (const [runIndex, run] of block.children.entries()) {
|
|
1736
|
+
const place = {
|
|
1737
|
+
path,
|
|
1738
|
+
runIndex
|
|
1739
|
+
};
|
|
1740
|
+
if (locatedOrder(place, startAt) < 0 || locatedOrder(place, endAt) > 0) continue;
|
|
1741
|
+
const from = locatedOrder(place, startAt) === 0 ? start.offset : 0;
|
|
1742
|
+
const to = locatedOrder(place, endAt) === 0 ? end.offset : run.text.length;
|
|
1743
|
+
if (from >= to) continue;
|
|
1744
|
+
spans.push({
|
|
1745
|
+
run: {
|
|
1746
|
+
path,
|
|
1747
|
+
runIndex,
|
|
1748
|
+
blockId: block.id,
|
|
1749
|
+
id: run.id,
|
|
1750
|
+
text: run.text,
|
|
1751
|
+
marks: run.marks
|
|
1752
|
+
},
|
|
1753
|
+
from,
|
|
1754
|
+
to
|
|
1755
|
+
});
|
|
1756
|
+
}
|
|
1757
|
+
});
|
|
1758
|
+
return spans;
|
|
1759
|
+
};
|
|
1760
|
+
/** Marks every run in the list carries; empty when there are no runs. */
|
|
1761
|
+
const sharedMarks = (runs) => {
|
|
1762
|
+
let common;
|
|
1763
|
+
for (const marks of runs) {
|
|
1764
|
+
const names = new Set(marks.map(markName));
|
|
1765
|
+
if (common === void 0) {
|
|
1766
|
+
common = names;
|
|
1767
|
+
continue;
|
|
1768
|
+
}
|
|
1769
|
+
for (const name of common) if (!names.has(name)) common.delete(name);
|
|
1770
|
+
}
|
|
1771
|
+
return common ?? /* @__PURE__ */ new Set();
|
|
1772
|
+
};
|
|
1773
|
+
/**
|
|
1774
|
+
* The marks every run the selection covers carries: the ones a toggle would
|
|
1775
|
+
* remove, which is what an "active" toolbar button means. A caret reports its
|
|
1776
|
+
* run's marks — an empty run can carry them, which is how a caret holds a format
|
|
1777
|
+
* — and a range is not bold when it straddles a bold run and a plain one. A node
|
|
1778
|
+
* selection reports what its whole subtree agrees on. A read, not a command:
|
|
1779
|
+
* nothing here changes anything.
|
|
1780
|
+
*/
|
|
1781
|
+
const marksInRange = (document, selection) => {
|
|
1782
|
+
if (selection === null) return /* @__PURE__ */ new Set();
|
|
1783
|
+
if (selection.type === "Node") {
|
|
1784
|
+
const found = locateBlock(document, selection.node);
|
|
1785
|
+
if (found === void 0) return /* @__PURE__ */ new Set();
|
|
1786
|
+
const runs = [];
|
|
1787
|
+
eachBlock([found.block], (each) => {
|
|
1788
|
+
for (const run of each.children) runs.push(run.marks);
|
|
1789
|
+
});
|
|
1790
|
+
return sharedMarks(runs);
|
|
1791
|
+
}
|
|
1792
|
+
const bounds = ordered(document, selection);
|
|
1793
|
+
if (bounds === void 0) return /* @__PURE__ */ new Set();
|
|
1794
|
+
if (isCollapsed(selection)) {
|
|
1795
|
+
const caret = locate(document, selection.anchor.node);
|
|
1796
|
+
return caret === void 0 ? /* @__PURE__ */ new Set() : sharedMarks([caret.marks]);
|
|
1797
|
+
}
|
|
1798
|
+
return sharedMarks(covered(document, bounds.start, bounds.end).map((span) => span.run.marks));
|
|
1799
|
+
};
|
|
1800
|
+
/** The last run in a block's subtree, or undefined when it holds none. */
|
|
1801
|
+
const lastRunOf = (block) => {
|
|
1802
|
+
if (block.type === "Node" && block.blocks !== void 0) for (let index = block.blocks.length - 1; index >= 0; index--) {
|
|
1803
|
+
const found = lastRunOf(block.blocks[index]);
|
|
1804
|
+
if (found !== void 0) return found;
|
|
1805
|
+
}
|
|
1806
|
+
return block.children[block.children.length - 1];
|
|
1807
|
+
};
|
|
1808
|
+
/** The block list a path lives in: the document's, or a container's nested blocks. */
|
|
1809
|
+
const containerBlocks = (document, containerPath) => {
|
|
1810
|
+
if (containerPath.length === 0) return document.children;
|
|
1811
|
+
const container = blockAtPath(document, containerPath);
|
|
1812
|
+
return container?.type === "Node" && container.blocks !== void 0 ? container.blocks : [];
|
|
1813
|
+
};
|
|
1814
|
+
/**
|
|
1815
|
+
* Deletes an ordered [start, end): one operation per covered run, then the
|
|
1816
|
+
* blocks the range spanned are joined, so selecting across a paragraph boundary
|
|
1817
|
+
* and deleting removes the boundary too. The first block survives, which is
|
|
1818
|
+
* where the caret already is. Returns undefined when the range needs a join this
|
|
1819
|
+
* version cannot express — one across containers, which has no boundary to
|
|
1820
|
+
* remove — so the caller refuses rather than deleting half of what was selected.
|
|
1821
|
+
*/
|
|
1822
|
+
const deleteRange = (document, start, end) => {
|
|
1823
|
+
const startAt = locate(document, start.node);
|
|
1824
|
+
const endAt = locate(document, end.node);
|
|
1825
|
+
const deletions = covered(document, start, end).map((span) => Edit.deleteText(span.run.id, span.from, span.to));
|
|
1826
|
+
if (startAt === void 0 || endAt === void 0) return deletions;
|
|
1827
|
+
if (pathKey$1(startAt.path) === pathKey$1(endAt.path)) return deletions;
|
|
1828
|
+
const containerPath = startAt.path.slice(0, -1);
|
|
1829
|
+
if (pathKey$1(containerPath) !== pathKey$1(endAt.path.slice(0, -1))) return void 0;
|
|
1830
|
+
const blocks = containerBlocks(document, containerPath);
|
|
1831
|
+
const from = startAt.path[startAt.path.length - 1];
|
|
1832
|
+
const to = endAt.path[endAt.path.length - 1];
|
|
1833
|
+
const survivor = blocks[from].id;
|
|
1834
|
+
for (let index = from + 1; index <= to; index++) {
|
|
1835
|
+
const block = blocks[index];
|
|
1836
|
+
if (block !== void 0) deletions.push(Edit.joinBlocks(survivor, block.id));
|
|
1837
|
+
}
|
|
1838
|
+
return deletions;
|
|
1839
|
+
};
|
|
1840
|
+
const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
|
|
1841
|
+
/** A caret uses UTF-16 offsets, while a deletion removes a whole grapheme. */
|
|
1842
|
+
const graphemeDeletion = (block, caret, runIndex, backward) => {
|
|
1843
|
+
const starts = [];
|
|
1844
|
+
let length = 0;
|
|
1845
|
+
for (const run of block.children) {
|
|
1846
|
+
starts.push(length);
|
|
1847
|
+
length += run.text.length;
|
|
1848
|
+
}
|
|
1849
|
+
const at = starts[runIndex] + caret.offset;
|
|
1850
|
+
if (backward ? at === 0 : at === length) return void 0;
|
|
1851
|
+
const text = block.children.map((run) => run.text).join("");
|
|
1852
|
+
let from = 0;
|
|
1853
|
+
let to = 0;
|
|
1854
|
+
for (const segment of segmenter.segment(text)) {
|
|
1855
|
+
const end = segment.index + segment.segment.length;
|
|
1856
|
+
if (backward ? end >= at : end > at) {
|
|
1857
|
+
from = segment.index;
|
|
1858
|
+
to = end;
|
|
1859
|
+
break;
|
|
1860
|
+
}
|
|
1861
|
+
}
|
|
1862
|
+
const operations = [];
|
|
1863
|
+
let graphemeStart;
|
|
1864
|
+
for (const [index, run] of block.children.entries()) {
|
|
1865
|
+
const start = starts[index];
|
|
1866
|
+
const localFrom = Math.max(0, from - start);
|
|
1867
|
+
const localTo = Math.min(run.text.length, to - start);
|
|
1868
|
+
if (localFrom >= localTo) continue;
|
|
1869
|
+
graphemeStart ??= {
|
|
1870
|
+
node: run.id,
|
|
1871
|
+
offset: localFrom,
|
|
1872
|
+
affinity: "after"
|
|
1873
|
+
};
|
|
1874
|
+
operations.push(Edit.deleteText(run.id, localFrom, localTo));
|
|
1875
|
+
}
|
|
1876
|
+
if (graphemeStart === void 0) return void 0;
|
|
1877
|
+
return {
|
|
1878
|
+
operations,
|
|
1879
|
+
caret: backward ? graphemeStart : caret
|
|
1880
|
+
};
|
|
1881
|
+
};
|
|
1882
|
+
/**
|
|
1883
|
+
* Resolves one intent into a transaction and applies it atomically. Commands
|
|
1884
|
+
* describe intent; the returned `positionMap` and `ChangeSet` describe the
|
|
1885
|
+
* document effect, and rejection returns no partially edited state.
|
|
1886
|
+
*/
|
|
1887
|
+
const run = (state, command, ids, options = {}) => {
|
|
1888
|
+
const declared = options.marks ?? shippedRegistry;
|
|
1889
|
+
if (command.type === "SetSelection") return apply(state, [Edit.setSelection(command.selection)]);
|
|
1890
|
+
const selection = state.selection;
|
|
1891
|
+
if (selection === null || selection.type === "Node") return failure("InvalidSelection");
|
|
1892
|
+
if (command.type === "InsertText") {
|
|
1893
|
+
const stored = command.marks;
|
|
1894
|
+
const target = isCollapsed(selection) ? stored === void 0 ? resolveInsertion(state.document, selection.anchor, options.marks) : selection.anchor : ordered(state.document, selection)?.start;
|
|
1895
|
+
if (target === void 0) return failure("InvalidSelection");
|
|
1896
|
+
const at = locate(state.document, target.node);
|
|
1897
|
+
if (at === void 0) return failure("MissingText");
|
|
1898
|
+
const marks = [];
|
|
1899
|
+
if (stored !== void 0) for (const mark of stored) {
|
|
1900
|
+
if (!declared.declares(markName(mark))) return failure("InvalidInput");
|
|
1901
|
+
marks.push(mark);
|
|
1902
|
+
}
|
|
1903
|
+
const deletions = isCollapsed(selection) ? [] : deleteRange(state.document, target, ordered(state.document, selection).end);
|
|
1904
|
+
if (deletions === void 0) return failure("InvalidParent");
|
|
1905
|
+
if (command.text.length === 0) return apply(state, deletions.length === 0 ? [] : [...deletions, Edit.setSelection(caretAt(target))]);
|
|
1906
|
+
if (stored === void 0) return apply(state, [
|
|
1907
|
+
...deletions,
|
|
1908
|
+
Edit.insertText(target, command.text),
|
|
1909
|
+
Edit.setSelection(caretAt({
|
|
1910
|
+
...target,
|
|
1911
|
+
offset: target.offset + command.text.length,
|
|
1912
|
+
affinity: "after"
|
|
1913
|
+
}))
|
|
1914
|
+
]);
|
|
1915
|
+
const span = isCollapsed(selection) ? void 0 : ordered(state.document, selection);
|
|
1916
|
+
const tailFrom = span === void 0 ? target.offset : span.end.node === target.node ? span.end.offset : at.text.length;
|
|
1917
|
+
const operations = [...deletions, Edit.insertText(target, command.text)];
|
|
1918
|
+
const end = target.offset + command.text.length;
|
|
1919
|
+
if (tailFrom < at.text.length) operations.push(Edit.splitRun(target.node, end, ids.mint()));
|
|
1920
|
+
const piece = target.offset > 0 ? NodeId.make(ids.mint()) : target.node;
|
|
1921
|
+
if (target.offset > 0) operations.push(Edit.splitRun(target.node, target.offset, piece));
|
|
1922
|
+
for (const mark of marks) if (!at.marks.some((existing) => sameMark(existing, mark))) operations.push(Edit.addMark(piece, mark));
|
|
1923
|
+
for (const mark of at.marks) if (!marks.some((kept) => markName(kept) === markName(mark))) operations.push(Edit.removeMark(piece, markName(mark)));
|
|
1924
|
+
return apply(state, operations);
|
|
1925
|
+
}
|
|
1926
|
+
if (command.type === "DeleteBackward" || command.type === "DeleteForward") {
|
|
1927
|
+
if (!isCollapsed(selection)) {
|
|
1928
|
+
const span = ordered(state.document, selection);
|
|
1929
|
+
if (span === void 0) return failure("InvalidSelection");
|
|
1930
|
+
const deletions = deleteRange(state.document, span.start, span.end);
|
|
1931
|
+
if (deletions === void 0) return failure("InvalidParent");
|
|
1932
|
+
return apply(state, [...deletions, Edit.setSelection(caretAt(span.start))]);
|
|
1933
|
+
}
|
|
1934
|
+
const caret = selection.anchor;
|
|
1935
|
+
const at = locate(state.document, caret.node);
|
|
1936
|
+
if (at === void 0) return failure("MissingText");
|
|
1937
|
+
const backward = command.type === "DeleteBackward";
|
|
1938
|
+
const block = blockAtPath(state.document, at.path);
|
|
1939
|
+
if (block === void 0) return failure("MissingText");
|
|
1940
|
+
const deletion = graphemeDeletion(block, caret, at.runIndex, backward);
|
|
1941
|
+
if (deletion !== void 0) return apply(state, [...deletion.operations, Edit.setSelection(caretAt(deletion.caret))]);
|
|
1942
|
+
const containerPath = at.path.slice(0, -1);
|
|
1943
|
+
const siblings = containerBlocks(state.document, containerPath);
|
|
1944
|
+
const index = at.path[at.path.length - 1];
|
|
1945
|
+
const neighborBlock = siblings[backward ? index - 1 : index + 1];
|
|
1946
|
+
if (neighborBlock === void 0) return apply(state, []);
|
|
1947
|
+
const survivor = backward ? neighborBlock : siblings[index];
|
|
1948
|
+
const removed = backward ? siblings[index] : neighborBlock;
|
|
1949
|
+
const lastRun = lastRunOf(survivor) ?? lastRunOf(removed);
|
|
1950
|
+
return apply(state, [Edit.joinBlocks(survivor.id, removed.id), Edit.setSelection(caretAt(lastRun === void 0 ? {
|
|
1951
|
+
node: survivor.id,
|
|
1952
|
+
offset: 0,
|
|
1953
|
+
affinity: "after"
|
|
1954
|
+
} : {
|
|
1955
|
+
node: lastRun.id,
|
|
1956
|
+
offset: lastRun.text.length,
|
|
1957
|
+
affinity: "after"
|
|
1958
|
+
}))]);
|
|
1959
|
+
}
|
|
1960
|
+
if (command.type === "SplitBlock") {
|
|
1961
|
+
const span = isCollapsed(selection) ? void 0 : ordered(state.document, selection);
|
|
1962
|
+
if (!isCollapsed(selection) && span === void 0) return failure("InvalidSelection");
|
|
1963
|
+
const caret = span?.start ?? selection.anchor;
|
|
1964
|
+
const at = locate(state.document, caret.node);
|
|
1965
|
+
if (at === void 0) return failure("MissingText");
|
|
1966
|
+
const deletions = span === void 0 ? [] : deleteRange(state.document, span.start, span.end);
|
|
1967
|
+
if (deletions === void 0) return failure("InvalidParent");
|
|
1968
|
+
const textId = ids.mint();
|
|
1969
|
+
return apply(state, [
|
|
1970
|
+
...deletions,
|
|
1971
|
+
Edit.splitBlock(at.blockId, at.id, caret.offset, ids.mint(), textId),
|
|
1972
|
+
Edit.setSelection(caretAt({
|
|
1973
|
+
node: NodeId.make(textId),
|
|
1974
|
+
offset: 0,
|
|
1975
|
+
affinity: "after"
|
|
1976
|
+
}))
|
|
1977
|
+
]);
|
|
1978
|
+
}
|
|
1979
|
+
if (command.type === "ToggleMark") {
|
|
1980
|
+
if (isCollapsed(selection)) return apply(state, []);
|
|
1981
|
+
const span = ordered(state.document, selection);
|
|
1982
|
+
if (span === void 0) return failure("InvalidSelection");
|
|
1983
|
+
const spans = covered(state.document, span.start, span.end);
|
|
1984
|
+
if (spans.length === 0) return apply(state, []);
|
|
1985
|
+
const mark = command.mark;
|
|
1986
|
+
const name = markName(mark);
|
|
1987
|
+
const adding = !spans.every((entry) => entry.run.marks.some((held) => markName(held) === name));
|
|
1988
|
+
const operations = [];
|
|
1989
|
+
const targets = [];
|
|
1990
|
+
for (const [index, entry] of spans.entries()) {
|
|
1991
|
+
let target = entry.run.id;
|
|
1992
|
+
let base = 0;
|
|
1993
|
+
if (index === 0 && entry.from > 0) {
|
|
1994
|
+
const textId = ids.mint();
|
|
1995
|
+
operations.push(Edit.splitRun(target, entry.from, textId));
|
|
1996
|
+
target = NodeId.make(textId);
|
|
1997
|
+
base = entry.from;
|
|
1998
|
+
}
|
|
1999
|
+
if (index === spans.length - 1 && entry.to < entry.run.text.length) operations.push(Edit.splitRun(target, entry.to - base, ids.mint()));
|
|
2000
|
+
targets.push(target);
|
|
2001
|
+
}
|
|
2002
|
+
if (adding) {
|
|
2003
|
+
if (!declared.declares(name)) return failure("InvalidInput");
|
|
2004
|
+
for (const target of targets) operations.push(Edit.addMark(target, mark));
|
|
2005
|
+
} else for (const target of targets) operations.push(Edit.removeMark(target, name));
|
|
2006
|
+
return apply(state, operations);
|
|
2007
|
+
}
|
|
2008
|
+
if (command.type === "Paste") {
|
|
2009
|
+
if (command.slice.blocks.length === 0) return apply(state, []);
|
|
2010
|
+
const span = isCollapsed(selection) ? void 0 : ordered(state.document, selection);
|
|
2011
|
+
if (!isCollapsed(selection) && span === void 0) return failure("InvalidSelection");
|
|
2012
|
+
const caret = span?.start ?? selection.anchor;
|
|
2013
|
+
const at = locate(state.document, caret.node);
|
|
2014
|
+
if (at === void 0) return failure("MissingText");
|
|
2015
|
+
const index = at.path[at.path.length - 1];
|
|
2016
|
+
const containerPath = at.path.slice(0, -1);
|
|
2017
|
+
const parent = containerPath.length === 0 ? void 0 : blockAtPath(state.document, containerPath)?.id;
|
|
2018
|
+
const replacements = span === void 0 ? [] : deleteRange(state.document, span.start, span.end);
|
|
2019
|
+
if (replacements === void 0) return failure("InvalidParent");
|
|
2020
|
+
const operations = [...replacements];
|
|
2021
|
+
const inserted = withFreshIds(command.slice, ids.mint).blocks;
|
|
2022
|
+
const block = blockAtPath(state.document, at.path);
|
|
2023
|
+
if (block === void 0) return failure("MissingText");
|
|
2024
|
+
const atBlockStart = at.runIndex === 0 && caret.offset === 0;
|
|
2025
|
+
const atBlockEnd = at.runIndex === block.children.length - 1 && caret.offset === at.text.length;
|
|
2026
|
+
let trailingRun;
|
|
2027
|
+
if (atBlockStart) for (const [offset, piece] of inserted.entries()) operations.push(Edit.insertBlock(piece, index + offset, parent));
|
|
2028
|
+
else if (atBlockEnd) for (const [offset, piece] of inserted.entries()) operations.push(Edit.insertBlock(piece, index + 1 + offset, parent));
|
|
2029
|
+
else {
|
|
2030
|
+
const textId = ids.mint();
|
|
2031
|
+
operations.push(Edit.splitBlock(at.blockId, at.id, caret.offset, ids.mint(), textId));
|
|
2032
|
+
trailingRun = NodeId.make(textId);
|
|
2033
|
+
for (const [offset, piece] of inserted.entries()) operations.push(Edit.insertBlock(piece, index + 1 + offset, parent));
|
|
2034
|
+
}
|
|
2035
|
+
const landing = landingAfter(inserted, trailingRun, containerBlocks(state.document, containerPath), index, atBlockEnd);
|
|
2036
|
+
if (landing !== void 0) operations.push(Edit.setSelection(caretAt(landing)));
|
|
2037
|
+
return apply(state, operations);
|
|
2038
|
+
}
|
|
2039
|
+
return apply(state, []);
|
|
2040
|
+
};
|
|
2041
|
+
/**
|
|
2042
|
+
* Where the caret goes after a paste: the end of the last inserted run, or the
|
|
2043
|
+
* start of what follows when the inserted content ends without text — the
|
|
2044
|
+
* trailing half a split created, then the next sibling.
|
|
2045
|
+
*/
|
|
2046
|
+
const landingAfter = (inserted, trailingRun, siblings, index, atBlockEnd) => {
|
|
2047
|
+
const last = inserted[inserted.length - 1];
|
|
2048
|
+
const lastRun = last.children[last.children.length - 1];
|
|
2049
|
+
if (lastRun !== void 0) return {
|
|
2050
|
+
node: lastRun.id,
|
|
2051
|
+
offset: lastRun.text.length,
|
|
2052
|
+
affinity: "after"
|
|
2053
|
+
};
|
|
2054
|
+
if (trailingRun !== void 0) return {
|
|
2055
|
+
node: trailingRun,
|
|
2056
|
+
offset: 0,
|
|
2057
|
+
affinity: "after"
|
|
2058
|
+
};
|
|
2059
|
+
const followingRun = siblings[index + (atBlockEnd ? 1 : 0)]?.children[0];
|
|
2060
|
+
return followingRun === void 0 ? void 0 : {
|
|
2061
|
+
node: followingRun.id,
|
|
2062
|
+
offset: 0,
|
|
2063
|
+
affinity: "after"
|
|
2064
|
+
};
|
|
2065
|
+
};
|
|
2066
|
+
//#endregion
|
|
2067
|
+
//#region src/history.ts
|
|
2068
|
+
/**
|
|
2069
|
+
* Local undo history over editor snapshots. Snapshots are `EditorState` values
|
|
2070
|
+
* (document plus selection), so undo restores what the user saw, including the
|
|
2071
|
+
* caret. History is interaction state: it belongs in the application Model
|
|
2072
|
+
* beside the selection, never in published content, and collaborative undo is a
|
|
2073
|
+
* different operation (§§65–66).
|
|
2074
|
+
*/
|
|
2075
|
+
const History = Schema.Struct({
|
|
2076
|
+
/** States to return to, oldest first. */
|
|
2077
|
+
past: Schema.Array(EditorState),
|
|
2078
|
+
/** States undone from, nearest first. */
|
|
2079
|
+
future: Schema.Array(EditorState),
|
|
2080
|
+
/** The group the last commit joined, if any. */
|
|
2081
|
+
group: Schema.optional(Schema.String)
|
|
2082
|
+
});
|
|
2083
|
+
const emptyHistory = Object.freeze({
|
|
2084
|
+
past: [],
|
|
2085
|
+
future: []
|
|
2086
|
+
});
|
|
2087
|
+
/**
|
|
2088
|
+
* Typing continues one undo step; every other command is its own step. Callers
|
|
2089
|
+
* pass this to `commit`, so grouping policy lives with the editor vocabulary
|
|
2090
|
+
* rather than being reinvented per adapter.
|
|
2091
|
+
*/
|
|
2092
|
+
const groupFor = (command) => command.type === "InsertText" || command.type === "DeleteBackward" || command.type === "DeleteForward" ? "typing" : void 0;
|
|
2093
|
+
const bounded = (past, capacity) => past.length > capacity ? past.slice(past.length - capacity) : past;
|
|
2094
|
+
/**
|
|
2095
|
+
* Records a committed transition. `previous` is the state before the command
|
|
2096
|
+
* and `next` the state after it; only `previous` is stored, because the caller
|
|
2097
|
+
* already holds `next`.
|
|
2098
|
+
*/
|
|
2099
|
+
const commit = (history, previous, options = {}) => {
|
|
2100
|
+
const past = options.group !== void 0 && history.group === options.group ? history.past : bounded([...history.past, previous], options.capacity ?? 200);
|
|
2101
|
+
return options.group === void 0 ? {
|
|
2102
|
+
past,
|
|
2103
|
+
future: []
|
|
2104
|
+
} : {
|
|
2105
|
+
past,
|
|
2106
|
+
future: [],
|
|
2107
|
+
group: options.group
|
|
2108
|
+
};
|
|
2109
|
+
};
|
|
2110
|
+
/** Steps back one group. Returns undefined when there is nothing to undo. */
|
|
2111
|
+
const undo = (history, current) => {
|
|
2112
|
+
const previous = history.past[history.past.length - 1];
|
|
2113
|
+
if (previous === void 0) return void 0;
|
|
2114
|
+
return {
|
|
2115
|
+
history: {
|
|
2116
|
+
past: history.past.slice(0, -1),
|
|
2117
|
+
future: [current, ...history.future]
|
|
2118
|
+
},
|
|
2119
|
+
state: previous
|
|
2120
|
+
};
|
|
2121
|
+
};
|
|
2122
|
+
/** Steps forward again. Returns undefined when there is nothing to redo. */
|
|
2123
|
+
const redo = (history, current) => {
|
|
2124
|
+
const next = history.future[0];
|
|
2125
|
+
if (next === void 0) return void 0;
|
|
2126
|
+
return {
|
|
2127
|
+
history: {
|
|
2128
|
+
past: [...history.past, current],
|
|
2129
|
+
future: history.future.slice(1),
|
|
2130
|
+
group: history.group
|
|
2131
|
+
},
|
|
2132
|
+
state: next
|
|
2133
|
+
};
|
|
2134
|
+
};
|
|
2135
|
+
const canUndo = (history) => history.past.length > 0;
|
|
2136
|
+
const canRedo = (history) => history.future.length > 0;
|
|
2137
|
+
/** Structural summary for tooling and tests. */
|
|
2138
|
+
const inspectHistory = (history) => ({
|
|
2139
|
+
past: history.past.length,
|
|
2140
|
+
future: history.future.length,
|
|
2141
|
+
group: history.group ?? null
|
|
2142
|
+
});
|
|
2143
|
+
//#endregion
|
|
2144
|
+
//#region src/kit.ts
|
|
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
|
+
});
|
|
2157
|
+
/**
|
|
2158
|
+
* Declares an application node kind: a `Node` block whose props this schema
|
|
2159
|
+
* validates and whose content the `children` mode declares. The document codec
|
|
2160
|
+
* keeps those props as JSON; the Kit is where an application's types meet them.
|
|
2161
|
+
*/
|
|
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
|
+
/**
|
|
2175
|
+
* The content a block actually holds. An empty application node is `either`: the
|
|
2176
|
+
* document cannot say whether it is an atom or a run holder that happens to have
|
|
2177
|
+
* no runs, so a declaration of either kind agrees with it.
|
|
2178
|
+
*/
|
|
2179
|
+
const heldContent = (block) => {
|
|
2180
|
+
if (block.type !== "Node") return "text";
|
|
2181
|
+
if (block.blocks !== void 0) return "blocks";
|
|
2182
|
+
return block.children.length > 0 ? "text" : "either";
|
|
2183
|
+
};
|
|
2184
|
+
/**
|
|
2185
|
+
* Whether a declared definition agrees with the block it is declared for, and
|
|
2186
|
+
* why not. A `block` declaration expects a built-in block and a `node` or `atom`
|
|
2187
|
+
* one expects an application node; then the declared content mode must match what
|
|
2188
|
+
* the block holds, which is what makes an atom's no-children rule real.
|
|
2189
|
+
*/
|
|
2190
|
+
const definitionMismatch = (definition, block) => {
|
|
2191
|
+
const expected = definition.kind === "block" ? "block" : "node";
|
|
2192
|
+
const held = heldShape(block);
|
|
2193
|
+
if (held !== expected) return `"${definition.name}" is declared as ${definition.kind}, but the document holds it as ${held}`;
|
|
2194
|
+
const declared = definition.kind === "atom" ? "none" : definition.children;
|
|
2195
|
+
const content = heldContent(block);
|
|
2196
|
+
return (content === "either" ? declared !== "blocks" : declared === content) ? void 0 : `"${definition.name}" is declared to hold ${declared}, but the document holds ${content}`;
|
|
2197
|
+
};
|
|
2198
|
+
/**
|
|
2199
|
+
* Whether a node's props decode against its declared schema, and why not. The
|
|
2200
|
+
* diagnostic is deliberately stable: a schema's own message can name internals
|
|
2201
|
+
* an API boundary should not leak, so only the verdict travels.
|
|
2202
|
+
*/
|
|
2203
|
+
const propsFailure = (props, node) => {
|
|
2204
|
+
if (props === void 0) return false;
|
|
2205
|
+
try {
|
|
2206
|
+
Schema.decodeUnknownSync(props, { onExcessProperty: "error" })(node.props);
|
|
2207
|
+
return false;
|
|
2208
|
+
} catch {
|
|
2209
|
+
return true;
|
|
2210
|
+
}
|
|
2211
|
+
};
|
|
2212
|
+
/** Structural summary of a Kit, for tooling and tests. */
|
|
2213
|
+
const inspectKit = (definition) => ({
|
|
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
|
+
});
|
|
2219
|
+
/**
|
|
2220
|
+
* Whether a mark's props decode against its declared schema, and why not. The
|
|
2221
|
+
* same stability rule as node props: only the verdict travels, not a schema's
|
|
2222
|
+
* message. A mark that declares props must carry them.
|
|
2223
|
+
*/
|
|
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
|
+
/**
|
|
2234
|
+
* Checks a document against a Kit's vocabulary without changing it, walking
|
|
2235
|
+
* nested blocks so a container's children are checked too. Reports preserved
|
|
2236
|
+
* unknown blocks, known blocks the Kit does not declare, declarations that
|
|
2237
|
+
* disagree with how the document holds a block, application nodes whose props
|
|
2238
|
+
* their schema refuses, and marks outside the Kit or whose props their definition
|
|
2239
|
+
* refuses. Content diagnostics never strip or repair the document; callers decide
|
|
2240
|
+
* whether to block publishing or surface a placeholder.
|
|
2241
|
+
*/
|
|
2242
|
+
const validate = (document, definition) => {
|
|
2243
|
+
const byName = new Map(definition.nodes.map((node) => [node.name, node]));
|
|
2244
|
+
const declaredMarks = new Map(definition.marks.map((mark) => [mark.name, mark]));
|
|
2245
|
+
const diagnostics = [];
|
|
2246
|
+
eachBlock(document.children, (block) => {
|
|
2247
|
+
if (block.type === "Unknown") diagnostics.push({
|
|
2248
|
+
code: "UnknownNode",
|
|
2249
|
+
node: block.id,
|
|
2250
|
+
detail: block.originalType,
|
|
2251
|
+
message: `Unimplemented node type "${block.originalType}"`
|
|
2252
|
+
});
|
|
2253
|
+
else if (block.type === "Node") {
|
|
2254
|
+
const declared = byName.get(block.kind);
|
|
2255
|
+
if (declared === void 0) diagnostics.push({
|
|
2256
|
+
code: "UnsupportedNode",
|
|
2257
|
+
node: block.id,
|
|
2258
|
+
detail: block.kind,
|
|
2259
|
+
message: `The Kit does not declare node "${block.kind}"`
|
|
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`
|
|
2308
|
+
});
|
|
2309
|
+
}
|
|
2310
|
+
});
|
|
2311
|
+
return diagnostics;
|
|
2312
|
+
};
|
|
2313
|
+
//#endregion
|
|
2314
|
+
//#region src/migration.ts
|
|
2315
|
+
const matches = (block, from) => block.type === "Unknown" ? block.originalType === from : block.type === "Node" ? block.kind === from : block.type === from;
|
|
2316
|
+
const decodeMigratedDocument = Schema.decodeUnknownSync(Document, { onExcessProperty: "error" });
|
|
2317
|
+
/** Declares a migration, checking at construction that it is shaped like one. */
|
|
2318
|
+
const migration = (name, from, migrate, to) => {
|
|
2319
|
+
if (name.length === 0) throw new Error("Migration.make: a migration needs a name");
|
|
2320
|
+
if (from.length === 0) throw new Error(`Migration "${name}": from must not be empty`);
|
|
2321
|
+
return {
|
|
2322
|
+
name,
|
|
2323
|
+
from,
|
|
2324
|
+
migrate,
|
|
2325
|
+
to
|
|
2326
|
+
};
|
|
2327
|
+
};
|
|
2328
|
+
/**
|
|
2329
|
+
* Runs one migration over a block list, recursing into containers so a nested
|
|
2330
|
+
* block is migrated where it sits. A later migration sees what an earlier one
|
|
2331
|
+
* produced, because the caller runs them in list order.
|
|
2332
|
+
*/
|
|
2333
|
+
const migrateBlocks = (blocks, migration, applied) => {
|
|
2334
|
+
let changed = false;
|
|
2335
|
+
const next = blocks.map((block) => {
|
|
2336
|
+
let current = block;
|
|
2337
|
+
if (current.type === "Node" && current.blocks !== void 0) {
|
|
2338
|
+
const nested = migrateBlocks(current.blocks, migration, applied);
|
|
2339
|
+
if (nested.changed) {
|
|
2340
|
+
changed = true;
|
|
2341
|
+
current = {
|
|
2342
|
+
...current,
|
|
2343
|
+
blocks: nested.blocks
|
|
2344
|
+
};
|
|
2345
|
+
}
|
|
2346
|
+
}
|
|
2347
|
+
if (!matches(current, migration.from)) return current;
|
|
2348
|
+
const migrated = migration.migrate(current);
|
|
2349
|
+
if (migrated === void 0) return current;
|
|
2350
|
+
if (migrated.id !== current.id) throw new Error(`Migration "${migration.name}" changed a block's identity`);
|
|
2351
|
+
try {
|
|
2352
|
+
Schema.decodeUnknownSync(Block, { onExcessProperty: "error" })(migrated);
|
|
2353
|
+
} catch {
|
|
2354
|
+
throw new Error(`Migration "${migration.name}" produced an invalid block`);
|
|
2355
|
+
}
|
|
2356
|
+
applied.push({
|
|
2357
|
+
name: migration.name,
|
|
2358
|
+
node: current.id
|
|
2359
|
+
});
|
|
2360
|
+
changed = true;
|
|
2361
|
+
return migrated;
|
|
2362
|
+
});
|
|
2363
|
+
return {
|
|
2364
|
+
blocks: changed ? next : blocks,
|
|
2365
|
+
changed
|
|
2366
|
+
};
|
|
2367
|
+
};
|
|
2368
|
+
/**
|
|
2369
|
+
* Runs each migration over every block it reads, in list order, descending into
|
|
2370
|
+
* containers. A migration that changes a block's identity is a bug and throws
|
|
2371
|
+
* rather than silently breaking every reference to that node.
|
|
2372
|
+
*/
|
|
2373
|
+
const migrate = (document, migrations) => {
|
|
2374
|
+
const applied = [];
|
|
2375
|
+
const unused = [];
|
|
2376
|
+
let next = document;
|
|
2377
|
+
for (const migration of migrations) {
|
|
2378
|
+
const result = migrateBlocks(next.children, migration, applied);
|
|
2379
|
+
if (!result.changed) {
|
|
2380
|
+
unused.push(migration.name);
|
|
2381
|
+
continue;
|
|
2382
|
+
}
|
|
2383
|
+
next = {
|
|
2384
|
+
...next,
|
|
2385
|
+
children: result.blocks
|
|
2386
|
+
};
|
|
2387
|
+
try {
|
|
2388
|
+
decodeMigratedDocument(next);
|
|
2389
|
+
} catch {
|
|
2390
|
+
throw new Error(`Migration "${migration.name}" produced an invalid document`);
|
|
2391
|
+
}
|
|
2392
|
+
}
|
|
2393
|
+
return {
|
|
2394
|
+
document: next,
|
|
2395
|
+
applied,
|
|
2396
|
+
unused
|
|
2397
|
+
};
|
|
2398
|
+
};
|
|
2399
|
+
/**
|
|
2400
|
+
* A migration from a preserved unknown block into a declared node kind: the
|
|
2401
|
+
* props are decoded by the target's own schema, and a block whose data does not
|
|
2402
|
+
* decode is left alone rather than half-converted. The target's content mode
|
|
2403
|
+
* decides whether the promoted node holds runs or (empty) nested blocks, so
|
|
2404
|
+
* promoting into a container kind produces a valid block rather than one the
|
|
2405
|
+
* Kit will call a mismatch.
|
|
2406
|
+
*/
|
|
2407
|
+
const promoteUnknown = (name, from, to, Props, children = textContent) => migration(name, from, (block) => {
|
|
2408
|
+
if (block.type !== "Unknown") return void 0;
|
|
2409
|
+
const decoded = decodeProps(Props, block.props);
|
|
2410
|
+
if (decoded === void 0) return void 0;
|
|
2411
|
+
const promoted = {
|
|
2412
|
+
type: "Node",
|
|
2413
|
+
kind: to,
|
|
2414
|
+
id: block.id,
|
|
2415
|
+
props: decoded,
|
|
2416
|
+
children: []
|
|
2417
|
+
};
|
|
2418
|
+
return children === "blocks" ? {
|
|
2419
|
+
...promoted,
|
|
2420
|
+
blocks: []
|
|
2421
|
+
} : promoted;
|
|
2422
|
+
}, to);
|
|
2423
|
+
const decodeProps = (Props, props) => {
|
|
2424
|
+
try {
|
|
2425
|
+
const decoded = Schema.decodeUnknownSync(Props)(props);
|
|
2426
|
+
return Schema.decodeUnknownSync(Schema.JsonObject)(decoded);
|
|
2427
|
+
} catch {
|
|
2428
|
+
return;
|
|
2429
|
+
}
|
|
2430
|
+
};
|
|
2431
|
+
/** A node block's props as the codec stores them: plain JSON, nothing more. */
|
|
2432
|
+
const nodeProps = (block) => block.props;
|
|
2433
|
+
//#endregion
|
|
2434
|
+
export { Block, Bold, Code, DefaultDocumentLimits, Document, DocumentLimits, Edit, EditorState, Heading, History, Italic, MAX_NORMALIZATION_PASSES, Mark, MarkValue, Node, NodeBlock, NodeId, Operation, Paragraph, Position, RunMark, Selection, Slice, Text, Transaction, UnknownBlock, apply, atom, block, blockAtPath, blockContent, canRedo, canUndo, commit, decodeDocument, defaultTransforms, deserializeSlice, documentToHtml, documentToText, emptyHistory, emptySlice, findUnknownMarks, findUnknownNodes, groupFor, inspect, inspectHistory, inspectKit, kit, locateBlock, locateRun, mapPosition, mark, markName, markProps, markRegistry, marksInRange, mergeAdjacentRuns, migrate, migration, noRendering, node, nodeProps, nodeRendering, plainTextOf, promoteUnknown, redo, rendering, resolveInsertion, run, runRendering, sameMark, sameMarkSet, selectionIsValid, serializeSlice, shippedMarks, shippedRegistry, sliceFromText, sliceOf, textContent, toHtml, toText, unchanged, undo, validate, withFreshIds };
|
|
2435
|
+
|
|
2436
|
+
//# sourceMappingURL=index.mjs.map
|