foldkit-richtext 0.5.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/dist/clipboard.d.ts +224 -0
  2. package/dist/clipboard.d.ts.map +1 -0
  3. package/dist/clipboard.js +208 -0
  4. package/dist/clipboard.js.map +1 -0
  5. package/dist/code.d.ts +27 -0
  6. package/dist/code.d.ts.map +1 -0
  7. package/dist/code.js +45 -0
  8. package/dist/code.js.map +1 -0
  9. package/dist/command.d.ts +300 -0
  10. package/dist/command.d.ts.map +1 -0
  11. package/dist/command.js +1438 -0
  12. package/dist/command.js.map +1 -0
  13. package/dist/decoration.d.ts +44 -0
  14. package/dist/decoration.d.ts.map +1 -0
  15. package/dist/decoration.js +96 -0
  16. package/dist/decoration.js.map +1 -0
  17. package/dist/document.d.ts +1045 -0
  18. package/dist/document.d.ts.map +1 -0
  19. package/dist/document.js +544 -0
  20. package/dist/document.js.map +1 -0
  21. package/dist/footnote.d.ts +35 -0
  22. package/dist/footnote.d.ts.map +1 -0
  23. package/dist/footnote.js +100 -0
  24. package/dist/footnote.js.map +1 -0
  25. package/dist/history.d.ts +470 -0
  26. package/dist/history.d.ts.map +1 -0
  27. package/dist/history.js +81 -0
  28. package/dist/history.js.map +1 -0
  29. package/dist/html.d.ts +27 -0
  30. package/dist/html.d.ts.map +1 -0
  31. package/dist/html.js +99 -0
  32. package/dist/html.js.map +1 -0
  33. package/dist/indent.d.ts +16 -0
  34. package/dist/indent.d.ts.map +1 -0
  35. package/dist/indent.js +101 -0
  36. package/dist/indent.js.map +1 -0
  37. package/dist/index.d.ts +24 -0
  38. package/dist/index.js +24 -0
  39. package/dist/input.d.ts +54 -0
  40. package/dist/input.d.ts.map +1 -0
  41. package/dist/input.js +37 -0
  42. package/dist/input.js.map +1 -0
  43. package/dist/kit.d.ts +179 -0
  44. package/dist/kit.d.ts.map +1 -0
  45. package/dist/kit.js +202 -0
  46. package/dist/kit.js.map +1 -0
  47. package/dist/marks.d.ts +79 -0
  48. package/dist/marks.d.ts.map +1 -0
  49. package/dist/marks.js +127 -0
  50. package/dist/marks.js.map +1 -0
  51. package/dist/media.d.ts +30 -0
  52. package/dist/media.d.ts.map +1 -0
  53. package/dist/media.js +148 -0
  54. package/dist/media.js.map +1 -0
  55. package/dist/migration.d.ts +55 -0
  56. package/dist/migration.d.ts.map +1 -0
  57. package/dist/migration.js +124 -0
  58. package/dist/migration.js.map +1 -0
  59. package/dist/outline.d.ts +15 -0
  60. package/dist/outline.d.ts.map +1 -0
  61. package/dist/outline.js +39 -0
  62. package/dist/outline.js.map +1 -0
  63. package/dist/rendering.d.ts +96 -0
  64. package/dist/rendering.d.ts.map +1 -0
  65. package/dist/rendering.js +106 -0
  66. package/dist/rendering.js.map +1 -0
  67. package/dist/replicated.d.ts +340 -0
  68. package/dist/replicated.d.ts.map +1 -0
  69. package/dist/replicated.js +1727 -0
  70. package/dist/replicated.js.map +1 -0
  71. package/dist/search.d.ts +28 -0
  72. package/dist/search.d.ts.map +1 -0
  73. package/dist/search.js +61 -0
  74. package/dist/search.js.map +1 -0
  75. package/dist/standard.d.ts +61 -0
  76. package/dist/standard.d.ts.map +1 -0
  77. package/dist/standard.js +231 -0
  78. package/dist/standard.js.map +1 -0
  79. package/dist/table.d.ts +38 -0
  80. package/dist/table.d.ts.map +1 -0
  81. package/dist/table.js +160 -0
  82. package/dist/table.js.map +1 -0
  83. package/dist/transaction.d.ts +712 -0
  84. package/dist/transaction.d.ts.map +1 -0
  85. package/dist/transaction.js +993 -0
  86. package/dist/transaction.js.map +1 -0
  87. package/dist/transform.d.ts +48 -0
  88. package/dist/transform.d.ts.map +1 -0
  89. package/dist/transform.js +94 -0
  90. package/dist/transform.js.map +1 -0
  91. package/dist/url.d.ts +16 -0
  92. package/dist/url.d.ts.map +1 -0
  93. package/dist/url.js +32 -0
  94. package/dist/url.js.map +1 -0
  95. package/package.json +7 -7
  96. package/dist/index.d.mts +0 -3787
  97. package/dist/index.d.mts.map +0 -1
  98. package/dist/index.mjs +0 -6688
  99. package/dist/index.mjs.map +0 -1
  100. package/dist/rolldown-runtime-D8jQpDG7.mjs +0 -12
@@ -0,0 +1 @@
1
+ {"version":3,"file":"document.d.ts","names":[],"sources":["../src/document.ts"],"mappings":";;qBAGa,QAAM,OAAA,MAAA,OAAA;YACP,gBAAgB,OAAO;;qBAGtB,MAAI,OAAA;YACL,cAAc,KAAK;;YAGnB,cAAc,OAAO;;;;;;qBAOpB,WAAS,OAAA;;;;YAIV,mBAAmB,UAAU;;;;;;;qBAQ5B,SAAO,OAAA,gBAAA,OAAA,gBAAA,OAAA;;;;YACR,iBAAiB,QAAQ;;qBAGxB,WAAQ,MAAU;;;;;;qBAOlB;qBACA;YACD,qBAAqB,qBAAqB;qBAgBzC,MAAI,OAAA;;;;;;;;;YAaL,cAAc,KAAK;qBAElB,WAAS,OAAA;;;;;;;;;;;;;YAKV,mBAAmB,UAAU;qBAE5B,SAAO,OAAA;;;;;;;;;;;;;;YAMR,iBAAiB,QAAQ;;;;;;;qBAQxB,cAAY,OAAA;;;;;;;;;;;;;;;YASb,sBAAsB,aAAa;;;;;;;;;;;;;;;;;iBAkB9B;WACN;WACA;WACA,IAAI;WACJ,OAAO,OAAO;WACd,UAAU,cAAc;WACxB,SAAS,cAAc;;qBAGrB,WAAS,OAAA;;;;;;;;;;;;;;;aARL;aACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YA2BL,QAAQ,YAAY,UAAU,YAAY;qBACzC,OAAK,OAAA,gBAAA,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aA7BD;aACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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gB,UAAc,aAAW,cAAc;;iBAcnD;WACN,MAAM;WACN;;;qBAIE,mBAAgB,UAAc,aAAW,cAAc;;qBAWvD,UAAQ,OAAA;;;;;YAKT,kBAAkB,SAAS;;iBAGtB;WACN,IAAI;;WAEJ,OAAO,UAAU,aAAa,QAAQ;;WAEtC,KAAK,gBAAgB,UAAU,yBAAyB;;qBAGtD;;EAEX,OAAI,eAAgB;;qBAeT,WAAS,OAAA,gBAAA,OAAA;;;;;;;;;;;;;;;;YAIV,mBAAmB,UAAU;;iBAGxB;WACN,OAAO,YAAY,QAAQ,QAAQ;;WAEnC,SAAS,YAAY,QAAQ;;WAE7B,UAAU,YAAY,QAAQ;;;qBAI5B,YAAS,UAAc,aAAW;;qBAwBlC,mBAAgB,UAAc,UAAQ,WAAa;qBAenD,aAAW,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAzeP;iBACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAgfL,qBAAqB,YAAY;;;;;;qBA+ChC,oBAAiB;;;;;;qBAiCjB,UAAO,UAAc;;;;;;;;;;;qBAqBrB,QAAK,UAAc;EAAa;EAAe"}
@@ -0,0 +1,544 @@
1
+ import { Schema } from "effect";
2
+ // 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 = (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
+ /** Document order over position places: the run first, then the offset within it. */
200
+ const comparePositionPlaces = (left, right) => compareRunPlaces(left, right) || left.offset - right.offset;
201
+ /** The block a path addresses, or undefined when the path does not resolve. */
202
+ const blockAtPath = (document, path) => {
203
+ let blocks = document.children;
204
+ let found;
205
+ for (const index of path) {
206
+ found = blocks[index];
207
+ if (found === void 0) return void 0;
208
+ blocks = found.type === "Node" && found.blocks !== void 0 ? found.blocks : [];
209
+ }
210
+ return found;
211
+ };
212
+ /** The block with this identity, wherever it sits. */
213
+ const locateBlock = (document, node) => {
214
+ let found;
215
+ eachBlock(document.children, (block, path) => {
216
+ if (found === void 0 && block.id === node) found = {
217
+ path,
218
+ block
219
+ };
220
+ });
221
+ return found;
222
+ };
223
+ /**
224
+ * The blocks either side of a block in its own container, which a handle's up and down move it
225
+ * past; both absent when the document does not hold it.
226
+ */
227
+ const siblingsOf = (document, node) => {
228
+ const found = locateBlock(document, node);
229
+ if (found === void 0) return {};
230
+ const index = found.path[found.path.length - 1];
231
+ const container = found.path.slice(0, -1);
232
+ const parent = container.length === 0 ? void 0 : blockAtPath(document, container);
233
+ const blocks = parent?.type === "Node" ? parent.blocks ?? [] : document.children;
234
+ return {
235
+ previous: blocks[index - 1],
236
+ next: blocks[index + 1]
237
+ };
238
+ };
239
+ /** The run with this identity, wherever it sits. */
240
+ const locateRun = (document, node) => {
241
+ let found;
242
+ eachBlock(document.children, (block, path) => {
243
+ if (found !== void 0) return;
244
+ const index = block.children.findIndex((run) => run.id === node);
245
+ if (index >= 0) found = {
246
+ path,
247
+ index,
248
+ run: block.children[index]
249
+ };
250
+ });
251
+ return found;
252
+ };
253
+ /**
254
+ * Whether a reader would see nothing: no blocks, or a lone paragraph or heading whose runs
255
+ * hold no text. What an editor shows its placeholder for; a lone empty list or code block is
256
+ * content a writer made, so it is not blank.
257
+ */
258
+ const isBlank = (document) => {
259
+ const first = document.children[0];
260
+ if (first === void 0) return true;
261
+ return document.children.length === 1 && (first.type === "Paragraph" || first.type === "Heading") && first.children.every((run) => run.text.length === 0);
262
+ };
263
+ /**
264
+ * The text of the block a position addresses, up to that position, in run order.
265
+ * A menu reads this: what a query is typed into is the block's text between its
266
+ * start and the caret, and a query never spans blocks. Affinity is not consulted — a
267
+ * prefix ends between characters whatever side the caret leans to — an offset past a
268
+ * run's end clamps to it, a negative one reads as none of it, and a position that
269
+ * resolves to nothing gives an empty string.
270
+ */
271
+ const textBefore = (document, position) => {
272
+ const found = locateRun(document, position.node);
273
+ if (found === void 0) return "";
274
+ const block = blockAtPath(document, found.path);
275
+ if (block === void 0) return "";
276
+ return block.children.slice(0, found.index).map((earlier) => earlier.text).join("") + found.run.text.slice(0, Math.max(0, position.offset));
277
+ };
278
+ /**
279
+ * Whichever end of a range comes first in the document, whatever direction it was made in,
280
+ * or `undefined` when either end does not resolve. What replaces a range starts here, so a
281
+ * read of the text before an edit reads from this end rather than the anchor.
282
+ */
283
+ const rangeStart = (document, range) => {
284
+ const anchor = locateRun(document, range.anchor.node);
285
+ const focus = locateRun(document, range.focus.node);
286
+ if (anchor === void 0 || focus === void 0) return void 0;
287
+ return comparePositionPlaces({
288
+ ...anchor,
289
+ offset: range.anchor.offset
290
+ }, {
291
+ ...focus,
292
+ offset: range.focus.offset
293
+ }) <= 0 ? range.anchor : range.focus;
294
+ };
295
+ /**
296
+ * The position a block's text offset addresses, or `undefined` when it is negative or past
297
+ * the end. The inverse of `textBefore` for one block: a rule, a search match, or any producer
298
+ * working in a block's own text needs it to say where what it found is.
299
+ */
300
+ const positionInBlock = (block, offset) => {
301
+ if (offset < 0) return void 0;
302
+ let consumed = 0;
303
+ for (const run of block.children) {
304
+ const next = consumed + run.text.length;
305
+ if (offset <= next) return {
306
+ node: run.id,
307
+ offset: offset - consumed,
308
+ affinity: offset === next ? "after" : "before"
309
+ };
310
+ consumed = next;
311
+ }
312
+ };
313
+ /**
314
+ * The range covering the `length` characters before `position` in its block, or
315
+ * `undefined` when the position does not resolve, `length` is not positive, or fewer
316
+ * characters precede it. The inverse of `textBefore`: an input rule or a menu deletes
317
+ * what it matched with this range, so removing the match and acting on it commit as one
318
+ * action (§124 §5). Endpoints land at run boundaries with `after` affinity, which is
319
+ * where a caret that typed that character would sit.
320
+ */
321
+ const textRangeBefore = (document, position, length) => {
322
+ if (length <= 0) return void 0;
323
+ const found = locateRun(document, position.node);
324
+ if (found === void 0) return void 0;
325
+ const block = blockAtPath(document, found.path);
326
+ if (block === void 0) return void 0;
327
+ const end = block.children.slice(0, found.index).reduce((total, run) => total + run.text.length, 0) + Math.min(found.run.text.length, Math.max(0, position.offset));
328
+ const start = end - length;
329
+ if (start < 0) return void 0;
330
+ const anchor = positionInBlock(block, start);
331
+ const focus = positionInBlock(block, end);
332
+ return anchor === void 0 || focus === void 0 ? void 0 : {
333
+ type: "Range",
334
+ anchor,
335
+ focus
336
+ };
337
+ };
338
+ /** Every node a block subtree owns, block and run alike, keyed by identity. */
339
+ const indexNodes = (blocks, nodes) => {
340
+ eachBlock(blocks, (block) => {
341
+ nodes.set(block.id, block);
342
+ for (const run of block.children) nodes.set(run.id, run);
343
+ });
344
+ };
345
+ const isKnownMarkName = Schema.is(Mark);
346
+ /** Lists unknown marks per text run; empty means the document publishes cleanly. */
347
+ const findUnknownMarks = (document) => {
348
+ const unknown = [];
349
+ eachBlock(document.children, (block) => {
350
+ for (const text of block.children) for (const mark of text.marks) {
351
+ const name = markName(mark);
352
+ if (!isKnownMarkName(name)) unknown.push({
353
+ node: text.id,
354
+ mark: name
355
+ });
356
+ }
357
+ });
358
+ return unknown;
359
+ };
360
+ /** Lists preserved unknown blocks; empty means the document publishes cleanly. */
361
+ const findUnknownNodes = (document) => {
362
+ const unknown = [];
363
+ eachBlock(document.children, (block) => {
364
+ if (block.type === "Unknown") unknown.push({
365
+ node: block.id,
366
+ originalType: block.originalType
367
+ });
368
+ });
369
+ return unknown;
370
+ };
371
+ /** UTF-16 offset in one text run, with insertion affinity at that offset. */
372
+ const Position = Schema.Struct({
373
+ node: NodeId,
374
+ offset: Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0)),
375
+ affinity: Schema.Literals(["before", "after"])
376
+ });
377
+ const Node = {
378
+ /** Declares an immutable reference. Does not insert a node or reserve its ID. */
379
+ make: (id) => {
380
+ const nodeId = NodeId.make(id);
381
+ return Object.freeze({
382
+ id: nodeId,
383
+ read: (document) => {
384
+ const nodes = /* @__PURE__ */ new Map();
385
+ indexNodes(document.children, nodes);
386
+ return nodes.get(nodeId);
387
+ },
388
+ at: (offset, affinity) => Position.make({
389
+ node: nodeId,
390
+ offset,
391
+ affinity
392
+ })
393
+ });
394
+ } };
395
+ const Selection = Schema.Union([Schema.Struct({
396
+ type: Schema.Literal("Range"),
397
+ anchor: Position,
398
+ focus: Position
399
+ }), Schema.Struct({
400
+ type: Schema.Literal("Node"),
401
+ node: NodeId
402
+ })]);
403
+ const nodeIndexes = /* @__PURE__ */ new WeakMap();
404
+ /** The document's `NodeIndex`, built once per document: documents are immutable. */
405
+ const nodeIndex = (document) => {
406
+ const cached = nodeIndexes.get(document);
407
+ if (cached !== void 0) return cached;
408
+ const nodes = /* @__PURE__ */ new Map();
409
+ const blockOf = /* @__PURE__ */ new Map();
410
+ const parentOf = /* @__PURE__ */ new Map();
411
+ const visit = (blocks, parent) => {
412
+ for (const block of blocks) {
413
+ nodes.set(block.id, block);
414
+ parentOf.set(block.id, parent);
415
+ for (const run of block.children) {
416
+ nodes.set(run.id, run);
417
+ blockOf.set(run.id, block);
418
+ }
419
+ if (block.type === "Node" && block.blocks !== void 0) visit(block.blocks, block.id);
420
+ }
421
+ };
422
+ visit(document.children, null);
423
+ const index = {
424
+ nodes,
425
+ blockOf,
426
+ parentOf
427
+ };
428
+ nodeIndexes.set(document, index);
429
+ return index;
430
+ };
431
+ /** Validates references without sorting range endpoints or changing direction. */
432
+ const selectionIsValid = (document, selection) => {
433
+ if (selection === null) return true;
434
+ const { nodes } = nodeIndex(document);
435
+ if (selection.type === "Node") return nodes.has(selection.node);
436
+ return [selection.anchor, selection.focus].every((position) => {
437
+ const node = nodes.get(position.node);
438
+ return node?.type === "Text" && Number.isInteger(position.offset) && position.offset >= 0 && position.offset <= node.text.length;
439
+ });
440
+ };
441
+ const EditorState = Schema.Struct({
442
+ document: Document,
443
+ selection: Schema.NullOr(Selection)
444
+ }).check(Schema.makeFilter((state) => selectionIsValid(state.document, state.selection) || "Unresolved selection"));
445
+ const decodeBlock = Schema.decodeUnknownSync(Block, { onExcessProperty: "error" });
446
+ const decodeSelection = Schema.decodeUnknownSync(Schema.NullOr(Selection), { onExcessProperty: "error" });
447
+ /**
448
+ * Blocks and documents that have passed validation. They are immutable, and an edit copies
449
+ * only the blocks on the path to what it touches, so a keystroke re-validates that path
450
+ * rather than the document or a whole container.
451
+ */
452
+ const validBlocks = /* @__PURE__ */ new WeakSet();
453
+ const validDocuments = /* @__PURE__ */ new WeakSet();
454
+ /**
455
+ * Throws unless `block` decodes as a `Block`, caching every block that passes, nested ones
456
+ * included. A block's validity does not depend on where it sits (the codec has no placement
457
+ * or depth rules; identity is checked document-wide by the caller), so a node block is valid
458
+ * exactly when its own fields are and each nested block is: those are checked separately, the
459
+ * fields by decoding the block with its nested blocks emptied.
460
+ */
461
+ const assertBlock = (block) => {
462
+ if (typeof block !== "object" || block === null) return void decodeBlock(block);
463
+ if (validBlocks.has(block)) return;
464
+ const nested = Object.getOwnPropertyDescriptor(block, "blocks");
465
+ if (block.type === "Node" && Array.isArray(nested?.value)) {
466
+ decodeBlock(Object.create(Object.getPrototypeOf(block), {
467
+ ...Object.getOwnPropertyDescriptors(block),
468
+ blocks: {
469
+ ...nested,
470
+ value: []
471
+ }
472
+ }));
473
+ for (const child of nested.value) assertBlock(child);
474
+ } else decodeBlock(block);
475
+ validBlocks.add(block);
476
+ };
477
+ const hasOnlyKeys = (value, keys) => Object.keys(value).every((key) => keys.includes(key));
478
+ /**
479
+ * Whether `input` decodes as an `EditorState`, with no excess properties, as
480
+ * `Schema.decodeUnknownSync(EditorState, { onExcessProperty: 'error' })` decides, but
481
+ * remembering each block and document that passed. Throws on invalid input.
482
+ */
483
+ const assertEditorState = (input) => {
484
+ if (typeof input !== "object" || input === null || !hasOnlyKeys(input, ["document", "selection"])) throw new Error("Invalid editor state");
485
+ const { document, selection } = input;
486
+ if (typeof document !== "object" || document === null) throw new Error("Invalid document");
487
+ if (!validDocuments.has(document)) {
488
+ const { version, children } = document;
489
+ if (version !== 1 || !Array.isArray(children) || !hasOnlyKeys(document, ["version", "children"])) throw new Error("Invalid document");
490
+ for (const block of children) assertBlock(block);
491
+ const ids = /* @__PURE__ */ new Set();
492
+ for (const block of children) for (const id of subtreeIds(block)) {
493
+ if (ids.has(id)) throw new Error("Duplicate node identity");
494
+ ids.add(id);
495
+ }
496
+ validDocuments.add(document);
497
+ }
498
+ decodeSelection(selection);
499
+ if (!selectionIsValid(document, selection)) throw new Error("Unresolved selection");
500
+ };
501
+ /**
502
+ * Counts semantic nodes and UTF-16 text units, and reports nesting depth. Depth
503
+ * counts levels of content: an empty document is 0, blocks are 1, runs inside a
504
+ * block are 2, and a block nested inside a block adds a level (§116).
505
+ */
506
+ const inspect = (document) => {
507
+ let nodeCount = 0;
508
+ let textLength = 0;
509
+ let depth = 0;
510
+ eachBlock(document.children, (block, path) => {
511
+ nodeCount += 1 + block.children.length;
512
+ for (const text of block.children) textLength += text.text.length;
513
+ depth = Math.max(depth, path.length + (block.children.length > 0 ? 1 : 0));
514
+ });
515
+ return {
516
+ nodeCount,
517
+ textLength,
518
+ depth
519
+ };
520
+ };
521
+ const words = new Intl.Segmenter(void 0, { granularity: "word" });
522
+ const graphemes = new Intl.Segmenter(void 0, { granularity: "grapheme" });
523
+ /**
524
+ * What a reader would count: words and user-perceived characters, as `Intl.Segmenter` splits
525
+ * them in the default locale, so a word in a script without spaces still counts. Runs are
526
+ * joined within a block, so a word that changes mark midway is one word, and blocks never
527
+ * join, so the last word of one block and the first of the next are two.
528
+ */
529
+ const count = (document) => {
530
+ let wordCount = 0;
531
+ let characterCount = 0;
532
+ eachBlock(document.children, (block) => {
533
+ const text = block.children.map((run) => run.text).join("");
534
+ for (const segment of words.segment(text)) if (segment.isWordLike) wordCount += 1;
535
+ for (const _ of graphemes.segment(text)) characterCount += 1;
536
+ });
537
+ return {
538
+ words: wordCount,
539
+ characters: characterCount
540
+ };
541
+ };
542
+ export { Block, DefaultDocumentLimits, Document, DocumentLimits, EditorState, Heading, Mark, MarkValue, Node, NodeBlock, NodeId, Paragraph, Position, RunMark, Selection, Text, UnknownBlock, assertEditorState, blockAtPath, blockContent, comparePositionPlaces, compareRunPlaces, count, decodeDocument, eachBlock, findUnknownMarks, findUnknownNodes, inspect, isBlank, locateBlock, locateRun, markName, nodeIndex, pathKey, positionInBlock, rangeStart, selectionIsValid, siblingsOf, textBefore, textContent, textRangeBefore };
543
+
544
+ //# sourceMappingURL=document.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"document.js","names":[],"sources":["../src/document.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** Caller-assigned identity, unique across blocks and text runs in a document. */\nexport const NodeId = Schema.NonEmptyString.pipe(Schema.brand('foldkit-richtext/NodeId'))\nexport type NodeId = typeof NodeId.Type\n\n/** The mark names this vocabulary defines; a document may hold others verbatim. */\nexport const Mark = Schema.Literals(['Bold', 'Italic', 'Code'])\nexport type Mark = typeof Mark.Type\n\n/** A schema this version can hand to `decodeUnknownSync` at a Kit boundary. */\nexport type PropsSchema = Schema.Codec<any, any, never>\n\n/**\n * A mark with props: which mark, plus the JSON data it carries. Props are JSON\n * here for the same reason a node's are: the document codec cannot know an\n * application's schemas, so a Kit validates them at that boundary (§12).\n */\nexport const MarkValue = Schema.Struct({\n name: Schema.NonEmptyString,\n props: Schema.optionalKey(Schema.JsonObject),\n})\nexport type MarkValue = typeof MarkValue.Type\n\n/**\n * A mark as a text run stores it: a bare name for a mark with no props, or a\n * value when it has them. Loading preserves the form it found, so a names-only\n * document round-trips byte-equal, and because a run carries a name at most once\n * it never holds both forms of one mark.\n */\nexport const RunMark = Schema.Union([Schema.NonEmptyString, MarkValue])\nexport type RunMark = typeof RunMark.Type\n\n/** A mark's name: a bare string is a mark with no props, an object carries them. */\nexport const markName = (mark: RunMark): string => (typeof mark === 'string' ? mark : mark.name)\n\n/**\n * The content a block holds: runs, or nested blocks (§13). A document does not\n * declare which a block kind accepts — its Kit does — so these are the words a\n * declaration and a migration both use.\n */\nexport const textContent = 'text' as const\nexport const blockContent = 'blocks' as const\nexport type ContentMode = typeof textContent | typeof blockContent\n\n/**\n * The wire shape of a value: the same structure with identities unbranded. A\n * branded `NodeId` encodes as a plain string, so an annotated schema whose type\n * mentions one cannot claim its encoded form is the type itself; this names the\n * wire side, which the recursive block schema needs to break its type cycle.\n */\ntype Wire<T> = T extends NodeId\n ? string\n : T extends ReadonlyArray<infer E>\n ? ReadonlyArray<Wire<E>>\n : T extends object\n ? { readonly [K in keyof T]: Wire<T[K]> }\n : T\n\nexport const Text = Schema.Struct({\n type: Schema.Literal('Text'),\n id: NodeId,\n text: Schema.String,\n // A mark name this version does not define loads verbatim; `Edit.addMark`\n // still accepts only what the caller's vocabulary declares. A run carries a\n // name at most once; see `findUnknownMarks` for the publishing gate.\n marks: Schema.Array(RunMark).check(\n Schema.makeFilter(\n marks => new Set(marks.map(markName)).size === marks.length || 'Invalid marks',\n ),\n ),\n})\nexport type Text = typeof Text.Type\n\nexport const Paragraph = Schema.Struct({\n type: Schema.Literal('Paragraph'),\n id: NodeId,\n children: Schema.Array(Text),\n})\nexport type Paragraph = typeof Paragraph.Type\n\nexport const Heading = Schema.Struct({\n type: Schema.Literal('Heading'),\n id: NodeId,\n level: Schema.Literals([1, 2, 3, 4, 5, 6]),\n children: Schema.Array(Text),\n})\nexport type Heading = typeof Heading.Type\n\n/**\n * A block whose `type` this version does not implement, retained verbatim for\n * recovery and migration: the original type, its remaining JSON fields, and no\n * text runs (its subtree lives in `props`, opaque). Unknown blocks are\n * read-only content: address them structurally, never edit their text.\n */\nexport const UnknownBlock = Schema.Struct({\n type: Schema.Literal('Unknown'),\n id: NodeId,\n originalType: Schema.NonEmptyString,\n props: Schema.JsonObject,\n children: Schema.Array(Text).check(\n Schema.makeFilter(runs => runs.length === 0 || 'Unknown blocks keep no text runs'),\n ),\n})\nexport type UnknownBlock = typeof UnknownBlock.Type\n\n/**\n * A block whose kind the application declares: a Callout, an Image, an embed.\n * `props` is JSON at the codec level because the document codec cannot know an\n * application's schemas; a Kit's node definition validates it at that boundary,\n * and runtime declarations stay outside the codec (§12). `children` are text\n * runs, so positions, operations, and selection work on it unchanged.\n *\n * `blocks` holds nested blocks, and its presence is what says the kind accepts\n * them (§116): a List holds ListItems, a Quote holds paragraphs. A kind with\n * nested blocks has no direct runs, which is why `children` stays `Text[]` on\n * every block kind — a container simply leaves it empty, as `UnknownBlock` does.\n *\n * The shape is written by hand because `Block` and this type are mutually\n * recursive, and TypeScript cannot infer through that cycle: the schema's\n * nested field names the interface, and the interface names the union.\n */\nexport interface NodeBlock {\n readonly type: 'Node'\n readonly kind: string\n readonly id: NodeId\n readonly props: Schema.JsonObject\n readonly children: ReadonlyArray<Text>\n readonly blocks?: ReadonlyArray<Block>\n}\n\nexport const NodeBlock = Schema.Struct({\n type: Schema.Literal('Node'),\n kind: Schema.NonEmptyString,\n id: NodeId,\n props: Schema.JsonObject,\n children: Schema.Array(Text),\n blocks: Schema.optionalKey(\n Schema.suspend((): Schema.Codec<ReadonlyArray<Block>, Wire<ReadonlyArray<Block>>> =>\n Schema.Array(Block),\n ),\n ),\n}).check(\n Schema.makeFilter(\n block =>\n block.blocks === undefined ||\n block.children.length === 0 ||\n 'A block with nested blocks keeps no direct runs',\n ),\n)\n\nexport type Block = Paragraph | Heading | NodeBlock | UnknownBlock\nexport const Block = Schema.Union([Paragraph, Heading, NodeBlock, UnknownBlock])\n\n/** Every identity a block subtree owns, block and run alike, in document order. */\nconst subtreeIds = (block: Block): ReadonlyArray<NodeId> => [\n block.id,\n ...block.children.map(run => run.id),\n ...(block.type === 'Node' && block.blocks !== undefined ? block.blocks.flatMap(subtreeIds) : []),\n]\n\n/** Version 1's initial block vocabulary, with document-wide identity validation. */\nexport const Document = Schema.Struct({\n version: Schema.Literal(1),\n children: Schema.Array(Block),\n}).check(\n Schema.makeFilter(document => {\n const ids = new Set<NodeId>()\n for (const block of document.children) {\n for (const id of subtreeIds(block)) {\n if (ids.has(id)) return 'Duplicate node identity'\n ids.add(id)\n }\n }\n return true\n }),\n)\nexport type Document = typeof Document.Type\n\nconst isKnownBlockType = (type: unknown): boolean =>\n type === 'Paragraph' || type === 'Heading' || type === 'Node'\n\n/**\n * Converts a block whose type this version does not implement into an `Unknown`\n * node, and does the same inside a known node block's nested blocks. Everything\n * except `type` and `id` becomes opaque JSON props; the raw subtree is preserved\n * there verbatim.\n */\nconst preserveBlock = (input: unknown): unknown => {\n if (typeof input !== 'object' || input === null) return input\n const block = input as Record<string, unknown>\n if (!isKnownBlockType(block.type) && block.type !== 'Unknown') {\n const { type, id, ...props } = block\n return { type: 'Unknown', id, originalType: type, props, children: [] }\n }\n return Array.isArray(block.blocks) ? { ...block, blocks: block.blocks.map(preserveBlock) } : block\n}\n\n/**\n * Converts blocks whose type this version does not implement into `Unknown`\n * nodes before structural decoding, so persisted content survives a deploy\n * that lost a node implementation. Nested blocks are walked for the same reason.\n */\nconst preserveUnknownBlocks = (input: unknown): unknown => {\n if (typeof input !== 'object' || input === null) return input\n const document = input as { children?: unknown }\n if (!Array.isArray(document.children)) return input\n return { ...document, children: document.children.map(preserveBlock) }\n}\n\n/** Strict boundary for persisted content. Throws a Schema error on invalid input. */\nconst decodeStructure = Schema.decodeUnknownSync(Document, { onExcessProperty: 'error' })\n\nconst PositiveCount = Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0))\n\n/** Bounds for decoded documents: blocks, text runs, and total UTF-16 text units. */\nexport const DocumentLimits = Schema.Struct({\n maxBlocks: PositiveCount,\n maxTextRuns: PositiveCount,\n maxTextLength: PositiveCount,\n})\nexport type DocumentLimits = typeof DocumentLimits.Type\n\n/** Generous DoS guardrails, not application quotas; tighten per document with a spread. */\nexport const DefaultDocumentLimits: DocumentLimits = DocumentLimits.make({\n maxBlocks: 10_000,\n maxTextRuns: 50_000,\n maxTextLength: 5_000_000,\n})\n\n/** Every block a subtree holds, nested ones included. */\nconst countBlocks = (blocks: ReadonlyArray<Block>): number => {\n let count = 0\n eachBlock(blocks, () => {\n count += 1\n })\n return count\n}\n\n/**\n * Strict boundary for persisted content. Decodes structure first, then enforces\n * `limits`. Throws a Schema error on invalid input, or an Error naming the\n * first exceeded bound.\n */\nexport const decodeDocument = (\n input: unknown,\n limits: DocumentLimits = DefaultDocumentLimits,\n): Document => {\n const document = decodeStructure(preserveUnknownBlocks(input))\n const summary = inspect(document)\n const blocks = countBlocks(document.children)\n const runs = summary.nodeCount - blocks\n if (blocks > limits.maxBlocks)\n throw new Error(`Document exceeds maxBlocks: ${blocks} > ${limits.maxBlocks}`)\n if (runs > limits.maxTextRuns)\n throw new Error(`Document exceeds maxTextRuns: ${runs} > ${limits.maxTextRuns}`)\n if (summary.textLength > limits.maxTextLength)\n throw new Error(\n `Document exceeds maxTextLength: ${summary.textLength} > ${limits.maxTextLength}`,\n )\n return document\n}\n\n/**\n * A block's address: root-first container indices. `[2]` is the third top-level\n * block, `[2, 0]` is the first block nested inside it (§116). A block's depth is\n * its path's length.\n */\nexport type BlockPath = ReadonlyArray<number>\n\n/** A stable key for a block path, so paths can key maps and compare cheaply. */\nexport const pathKey = (path: BlockPath): string => path.join('.')\n\n/** Walks every block subtree in document order, visiting each with its path. */\nexport const eachBlock = (\n blocks: ReadonlyArray<Block>,\n visit: (block: Block, path: BlockPath) => void,\n prefix: BlockPath = [],\n): void => {\n for (const [index, block] of blocks.entries()) {\n const path = [...prefix, index]\n visit(block, path)\n if (block.type === 'Node' && block.blocks !== undefined) eachBlock(block.blocks, visit, path)\n }\n}\n\n/** A run's place in document order: its block's path, then its index in that block. */\nexport interface RunPlace {\n readonly path: BlockPath\n readonly index: number\n}\n\n/** A run with the identity it was found by. */\nexport interface LocatedRun extends RunPlace {\n readonly run: Text\n}\n\n/** Document order over run places: path first, then the run's index. */\nexport const compareRunPlaces = (left: RunPlace, right: RunPlace): number => {\n const shared = Math.min(left.path.length, right.path.length)\n for (let index = 0; index < shared; index++) {\n if (left.path[index] !== right.path[index]) return left.path[index]! - right.path[index]!\n }\n if (left.path.length !== right.path.length) return left.path.length - right.path.length\n return left.index - right.index\n}\n\n/** A position's place in document order: its run's place, then its offset in that run. */\nexport interface PositionPlace extends RunPlace {\n readonly offset: number\n}\n\n/** Document order over position places: the run first, then the offset within it. */\nexport const comparePositionPlaces = (left: PositionPlace, right: PositionPlace): number =>\n compareRunPlaces(left, right) || left.offset - right.offset\n\n/** The block a path addresses, or undefined when the path does not resolve. */\nexport const blockAtPath = (document: Document, path: BlockPath): Block | undefined => {\n let blocks: ReadonlyArray<Block> = document.children\n let found: Block | undefined\n for (const index of path) {\n found = blocks[index]\n if (found === undefined) return undefined\n blocks = found.type === 'Node' && found.blocks !== undefined ? found.blocks : []\n }\n return found\n}\n\n/** The block with this identity, wherever it sits. */\nexport const locateBlock = (\n document: Document,\n node: NodeId,\n): { readonly path: BlockPath; readonly block: Block } | undefined => {\n let found: { readonly path: BlockPath; readonly block: Block } | undefined\n eachBlock(document.children, (block, path) => {\n if (found === undefined && block.id === node) found = { path, block }\n })\n return found\n}\n\n/**\n * The blocks either side of a block in its own container, which a handle's up and down move it\n * past; both absent when the document does not hold it.\n */\nexport const siblingsOf = (\n document: Document,\n node: NodeId,\n): { readonly previous?: Block | undefined; readonly next?: Block | undefined } => {\n const found = locateBlock(document, node)\n if (found === undefined) return {}\n const index = found.path[found.path.length - 1]!\n const container = found.path.slice(0, -1)\n const parent = container.length === 0 ? undefined : blockAtPath(document, container)\n const blocks = parent?.type === 'Node' ? (parent.blocks ?? []) : document.children\n return { previous: blocks[index - 1], next: blocks[index + 1] }\n}\n\n/** The run with this identity, wherever it sits. */\nexport const locateRun = (document: Document, node: NodeId): LocatedRun | undefined => {\n let found: LocatedRun | undefined\n eachBlock(document.children, (block, path) => {\n if (found !== undefined) return\n const index = block.children.findIndex(run => run.id === node)\n if (index >= 0) found = { path, index, run: block.children[index]! }\n })\n return found\n}\n\n/**\n * Whether a reader would see nothing: no blocks, or a lone paragraph or heading whose runs\n * hold no text. What an editor shows its placeholder for; a lone empty list or code block is\n * content a writer made, so it is not blank.\n */\nexport const isBlank = (document: Document): boolean => {\n const first = document.children[0]\n if (first === undefined) return true\n return (\n document.children.length === 1 &&\n (first.type === 'Paragraph' || first.type === 'Heading') &&\n first.children.every(run => run.text.length === 0)\n )\n}\n\n/**\n * The text of the block a position addresses, up to that position, in run order.\n * A menu reads this: what a query is typed into is the block's text between its\n * start and the caret, and a query never spans blocks. Affinity is not consulted — a\n * prefix ends between characters whatever side the caret leans to — an offset past a\n * run's end clamps to it, a negative one reads as none of it, and a position that\n * resolves to nothing gives an empty string.\n */\nexport const textBefore = (document: Document, position: Position): string => {\n const found = locateRun(document, position.node)\n if (found === undefined) return ''\n const block = blockAtPath(document, found.path)\n if (block === undefined) return ''\n const lead = block.children\n .slice(0, found.index)\n .map(earlier => earlier.text)\n .join('')\n return lead + found.run.text.slice(0, Math.max(0, position.offset))\n}\n\n/**\n * Whichever end of a range comes first in the document, whatever direction it was made in,\n * or `undefined` when either end does not resolve. What replaces a range starts here, so a\n * read of the text before an edit reads from this end rather than the anchor.\n */\nexport const rangeStart = (\n document: Document,\n range: Extract<Selection, { readonly type: 'Range' }>,\n): Position | undefined => {\n const anchor = locateRun(document, range.anchor.node)\n const focus = locateRun(document, range.focus.node)\n if (anchor === undefined || focus === undefined) return undefined\n return comparePositionPlaces(\n { ...anchor, offset: range.anchor.offset },\n { ...focus, offset: range.focus.offset },\n ) <= 0\n ? range.anchor\n : range.focus\n}\n\n/**\n * The position a block's text offset addresses, or `undefined` when it is negative or past\n * the end. The inverse of `textBefore` for one block: a rule, a search match, or any producer\n * working in a block's own text needs it to say where what it found is.\n */\nexport const positionInBlock = (block: Block, offset: number): Position | undefined => {\n if (offset < 0) return undefined\n let consumed = 0\n for (const run of block.children) {\n const next = consumed + run.text.length\n if (offset <= next) {\n return {\n node: run.id,\n offset: offset - consumed,\n affinity: offset === next ? 'after' : 'before',\n }\n }\n consumed = next\n }\n return undefined\n}\n\n/**\n * The range covering the `length` characters before `position` in its block, or\n * `undefined` when the position does not resolve, `length` is not positive, or fewer\n * characters precede it. The inverse of `textBefore`: an input rule or a menu deletes\n * what it matched with this range, so removing the match and acting on it commit as one\n * action (§124 §5). Endpoints land at run boundaries with `after` affinity, which is\n * where a caret that typed that character would sit.\n */\nexport const textRangeBefore = (\n document: Document,\n position: Position,\n length: number,\n): Selection | undefined => {\n if (length <= 0) return undefined\n const found = locateRun(document, position.node)\n if (found === undefined) return undefined\n const block = blockAtPath(document, found.path)\n if (block === undefined) return undefined\n const lead = block.children\n .slice(0, found.index)\n .reduce((total, run) => total + run.text.length, 0)\n // Clamped to the run as `textBefore` clamps, so an overlong offset never reads into the next run.\n const end = lead + Math.min(found.run.text.length, Math.max(0, position.offset))\n const start = end - length\n if (start < 0) return undefined\n const anchor = positionInBlock(block, start)\n const focus = positionInBlock(block, end)\n return anchor === undefined || focus === undefined ? undefined : { type: 'Range', anchor, focus }\n}\n\n/** Every node a block subtree owns, block and run alike, keyed by identity. */\nconst indexNodes = (blocks: ReadonlyArray<Block>, nodes: Map<NodeId, Block | Text>): void => {\n eachBlock(blocks, block => {\n nodes.set(block.id, block)\n for (const run of block.children) nodes.set(run.id, run)\n })\n}\n\nconst isKnownMarkName = Schema.is(Mark)\n\n/** A mark this vocabulary does not define, kept verbatim on its text run. */\nexport interface UnknownMark {\n readonly node: NodeId\n /** The mark's name; its props, if any, stay on the run. */\n readonly mark: string\n}\n\n/** Lists unknown marks per text run; empty means the document publishes cleanly. */\nexport const findUnknownMarks = (document: Document): ReadonlyArray<UnknownMark> => {\n const unknown: Array<UnknownMark> = []\n eachBlock(document.children, block => {\n for (const text of block.children) {\n for (const mark of text.marks) {\n const name = markName(mark)\n if (!isKnownMarkName(name)) unknown.push({ node: text.id, mark: name })\n }\n }\n })\n return unknown\n}\n\n/** A block this vocabulary does not implement, retained for migration. */\nexport interface UnknownNode {\n readonly node: NodeId\n readonly originalType: string\n}\n\n/** Lists preserved unknown blocks; empty means the document publishes cleanly. */\nexport const findUnknownNodes = (document: Document): ReadonlyArray<UnknownNode> => {\n const unknown: Array<UnknownNode> = []\n eachBlock(document.children, block => {\n if (block.type === 'Unknown') {\n unknown.push({ node: block.id, originalType: block.originalType })\n }\n })\n return unknown\n}\n\n/** UTF-16 offset in one text run, with insertion affinity at that offset. */\nexport const Position = Schema.Struct({\n node: NodeId,\n offset: Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0)),\n affinity: Schema.Literals(['before', 'after']),\n})\nexport type Position = typeof Position.Type\n\n/** A reusable identity resolved against an explicit document, without owning its content. */\nexport interface NodeReference {\n readonly id: NodeId\n /** Returns the current node, or undefined if this document does not contain it. */\n readonly read: (document: Document) => Block | Text | undefined\n /** Describes a text position; application of an edit checks the target and bounds. */\n readonly at: (offset: number, affinity: Position['affinity']) => Position\n}\n\nexport const Node = {\n /** Declares an immutable reference. Does not insert a node or reserve its ID. */\n make: (id: string): NodeReference => {\n const nodeId = NodeId.make(id)\n return Object.freeze({\n id: nodeId,\n read: (document: Document): Block | Text | undefined => {\n const nodes = new Map<NodeId, Block | Text>()\n indexNodes(document.children, nodes)\n return nodes.get(nodeId)\n },\n at: (offset: number, affinity: Position['affinity']): Position =>\n Position.make({ node: nodeId, offset, affinity }),\n })\n },\n}\n\nexport const Selection = Schema.Union([\n Schema.Struct({ type: Schema.Literal('Range'), anchor: Position, focus: Position }),\n Schema.Struct({ type: Schema.Literal('Node'), node: NodeId }),\n])\nexport type Selection = typeof Selection.Type\n\n/** Every node of a document by identity, with where each block and run sits. */\nexport interface NodeIndex {\n readonly nodes: ReadonlyMap<NodeId, Block | Text>\n /** Each run's block. */\n readonly blockOf: ReadonlyMap<NodeId, Block>\n /** Each block's parent block, `null` at the top level. */\n readonly parentOf: ReadonlyMap<NodeId, NodeId | null>\n}\nconst nodeIndexes = new WeakMap<Document, NodeIndex>()\n/** The document's `NodeIndex`, built once per document: documents are immutable. */\nexport const nodeIndex = (document: Document): NodeIndex => {\n const cached = nodeIndexes.get(document)\n if (cached !== undefined) return cached\n const nodes = new Map<NodeId, Block | Text>()\n const blockOf = new Map<NodeId, Block>()\n const parentOf = new Map<NodeId, NodeId | null>()\n const visit = (blocks: ReadonlyArray<Block>, parent: NodeId | null): void => {\n for (const block of blocks) {\n nodes.set(block.id, block)\n parentOf.set(block.id, parent)\n for (const run of block.children) {\n nodes.set(run.id, run)\n blockOf.set(run.id, block)\n }\n if (block.type === 'Node' && block.blocks !== undefined) visit(block.blocks, block.id)\n }\n }\n visit(document.children, null)\n const index = { nodes, blockOf, parentOf }\n nodeIndexes.set(document, index)\n return index\n}\n\n/** Validates references without sorting range endpoints or changing direction. */\nexport const selectionIsValid = (document: Document, selection: Selection | null): boolean => {\n if (selection === null) return true\n const { nodes } = nodeIndex(document)\n if (selection.type === 'Node') return nodes.has(selection.node)\n return [selection.anchor, selection.focus].every(position => {\n const node = nodes.get(position.node)\n return (\n node?.type === 'Text' &&\n Number.isInteger(position.offset) &&\n position.offset >= 0 &&\n position.offset <= node.text.length\n )\n })\n}\n\nexport const EditorState = Schema.Struct({\n document: Document,\n selection: Schema.NullOr(Selection),\n}).check(\n Schema.makeFilter(\n state => selectionIsValid(state.document, state.selection) || 'Unresolved selection',\n ),\n)\nexport type EditorState = typeof EditorState.Type\n\nconst decodeBlock = Schema.decodeUnknownSync(Block, { onExcessProperty: 'error' })\nconst decodeSelection = Schema.decodeUnknownSync(Schema.NullOr(Selection), {\n onExcessProperty: 'error',\n})\n/**\n * Blocks and documents that have passed validation. They are immutable, and an edit copies\n * only the blocks on the path to what it touches, so a keystroke re-validates that path\n * rather than the document or a whole container.\n */\nconst validBlocks = new WeakSet<Block>()\nconst validDocuments = new WeakSet<Document>()\n\n/**\n * Throws unless `block` decodes as a `Block`, caching every block that passes, nested ones\n * included. A block's validity does not depend on where it sits (the codec has no placement\n * or depth rules; identity is checked document-wide by the caller), so a node block is valid\n * exactly when its own fields are and each nested block is: those are checked separately, the\n * fields by decoding the block with its nested blocks emptied.\n */\nconst assertBlock = (block: unknown): void => {\n if (typeof block !== 'object' || block === null) return void decodeBlock(block)\n if (validBlocks.has(block as Block)) return\n const nested = Object.getOwnPropertyDescriptor(block, 'blocks')\n if ((block as { type?: unknown }).type === 'Node' && Array.isArray(nested?.value)) {\n // Every other own key, enumerable or not, symbol or not, stays, so the decoder sees\n // what it would see in `block` itself; a spread would drop some of them.\n decodeBlock(\n Object.create(Object.getPrototypeOf(block), {\n ...Object.getOwnPropertyDescriptors(block),\n blocks: { ...nested, value: [] },\n }),\n )\n for (const child of nested.value) assertBlock(child)\n } else decodeBlock(block)\n validBlocks.add(block as Block)\n}\n\nconst hasOnlyKeys = (value: object, keys: ReadonlyArray<string>): boolean =>\n Object.keys(value).every(key => keys.includes(key))\n\n/**\n * Whether `input` decodes as an `EditorState`, with no excess properties, as\n * `Schema.decodeUnknownSync(EditorState, { onExcessProperty: 'error' })` decides, but\n * remembering each block and document that passed. Throws on invalid input.\n */\nexport const assertEditorState = (input: unknown): void => {\n if (typeof input !== 'object' || input === null || !hasOnlyKeys(input, ['document', 'selection']))\n throw new Error('Invalid editor state')\n const { document, selection } = input as { document?: unknown; selection?: unknown }\n if (typeof document !== 'object' || document === null) throw new Error('Invalid document')\n if (!validDocuments.has(document as Document)) {\n const { version, children } = document as { version?: unknown; children?: unknown }\n if (\n version !== 1 ||\n !Array.isArray(children) ||\n !hasOnlyKeys(document, ['version', 'children'])\n )\n throw new Error('Invalid document')\n for (const block of children) assertBlock(block)\n const ids = new Set<NodeId>()\n for (const block of children as ReadonlyArray<Block>) {\n for (const id of subtreeIds(block)) {\n if (ids.has(id)) throw new Error('Duplicate node identity')\n ids.add(id)\n }\n }\n validDocuments.add(document as Document)\n }\n decodeSelection(selection)\n if (!selectionIsValid(document as Document, selection as Selection | null))\n throw new Error('Unresolved selection')\n}\n\n/**\n * Counts semantic nodes and UTF-16 text units, and reports nesting depth. Depth\n * counts levels of content: an empty document is 0, blocks are 1, runs inside a\n * block are 2, and a block nested inside a block adds a level (§116).\n */\nexport const inspect = (document: Document) => {\n let nodeCount = 0\n let textLength = 0\n let depth = 0\n eachBlock(document.children, (block, path) => {\n nodeCount += 1 + block.children.length\n for (const text of block.children) textLength += text.text.length\n depth = Math.max(depth, path.length + (block.children.length > 0 ? 1 : 0))\n })\n return { nodeCount, textLength, depth }\n}\n\nconst words = new Intl.Segmenter(undefined, { granularity: 'word' })\nconst graphemes = new Intl.Segmenter(undefined, { granularity: 'grapheme' })\n\n/**\n * What a reader would count: words and user-perceived characters, as `Intl.Segmenter` splits\n * them in the default locale, so a word in a script without spaces still counts. Runs are\n * joined within a block, so a word that changes mark midway is one word, and blocks never\n * join, so the last word of one block and the first of the next are two.\n */\nexport const count = (document: Document): { words: number; characters: number } => {\n let wordCount = 0\n let characterCount = 0\n eachBlock(document.children, block => {\n const text = block.children.map(run => run.text).join('')\n for (const segment of words.segment(text)) if (segment.isWordLike) wordCount += 1\n for (const _ of graphemes.segment(text)) characterCount += 1\n })\n return { words: wordCount, characters: characterCount }\n}\n"],"mappings":";;;AAGA,MAAa,SAAS,OAAO,eAAe,KAAK,OAAO,MAAM,yBAAyB,CAAC;;AAIxF,MAAa,OAAO,OAAO,SAAS;CAAC;CAAQ;CAAU;AAAM,CAAC;;;;;;AAW9D,MAAa,YAAY,OAAO,OAAO;CACrC,MAAM,OAAO;CACb,OAAO,OAAO,YAAY,OAAO,UAAU;AAC7C,CAAC;;;;;;;AASD,MAAa,UAAU,OAAO,MAAM,CAAC,OAAO,gBAAgB,SAAS,CAAC;;AAItE,MAAa,YAAY,SAA2B,OAAO,SAAS,WAAW,OAAO,KAAK;;;;;;AAO3F,MAAa,cAAc;AAC3B,MAAa,eAAe;AAiB5B,MAAa,OAAO,OAAO,OAAO;CAChC,MAAM,OAAO,QAAQ,MAAM;CAC3B,IAAI;CACJ,MAAM,OAAO;CAIb,OAAO,OAAO,MAAM,OAAO,CAAC,CAAC,MAC3B,OAAO,YACL,UAAS,IAAI,IAAI,MAAM,IAAI,QAAQ,CAAC,CAAC,CAAC,SAAS,MAAM,UAAU,eACjE,CACF;AACF,CAAC;AAGD,MAAa,YAAY,OAAO,OAAO;CACrC,MAAM,OAAO,QAAQ,WAAW;CAChC,IAAI;CACJ,UAAU,OAAO,MAAM,IAAI;AAC7B,CAAC;AAGD,MAAa,UAAU,OAAO,OAAO;CACnC,MAAM,OAAO,QAAQ,SAAS;CAC9B,IAAI;CACJ,OAAO,OAAO,SAAS;EAAC;EAAG;EAAG;EAAG;EAAG;EAAG;CAAC,CAAC;CACzC,UAAU,OAAO,MAAM,IAAI;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