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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Patrick Glenn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,614 @@
1
+ # foldkit-richtext
2
+
3
+ Pure semantic documents and text transactions for Foldkit. Content is versioned
4
+ data with stable node IDs; edits return a new document, mapped selection, and an
5
+ invalidation summary. This package is **early**: 0.x, and its API may change
6
+ between minor versions.
7
+
8
+ The application Model owns the document and local selection. Call `apply` from
9
+ the application's `update`; it performs no I/O and holds no editor store. DOM
10
+ editing lives in [`foldkit-richtext-dom`](../richtext-dom); Form/CMS integration
11
+ and Sync replication are not implemented yet.
12
+
13
+ ```text
14
+ EditorState + Transaction → next EditorState + ChangeSet + positionMap
15
+ ↘ diagnostic, with no partial result
16
+ ```
17
+
18
+ ## A small edit
19
+
20
+ ```bash
21
+ pnpm add foldkit-richtext effect
22
+ ```
23
+
24
+ ```ts
25
+ import * as RichText from 'foldkit-richtext'
26
+
27
+ const Text = RichText.Node.make('text-1')
28
+ const paragraph = RichText.Paragraph.make({
29
+ type: 'Paragraph',
30
+ id: RichText.NodeId.make('paragraph-1'),
31
+ children: [RichText.Text.make({
32
+ type: 'Text',
33
+ id: Text.id,
34
+ text: 'Hello',
35
+ marks: ['Bold'],
36
+ })],
37
+ })
38
+ const document = RichText.Document.make({ version: 1, children: [paragraph] })
39
+ const result = RichText.apply({ document, selection: null }, [
40
+ RichText.Edit.insertText(Text.at(5, 'after'), '!'),
41
+ ])
42
+
43
+ if (result.ok) {
44
+ // The parent reducer installs result.state in its Model.
45
+ const editedDocument = result.state.document
46
+ void editedDocument
47
+ }
48
+ ```
49
+
50
+ Schema constructors validate the value; IDs are supplied by the caller and must
51
+ be unique across blocks and text runs. `apply` validates state and operations,
52
+ then applies operations in array order. A later invalid operation rejects the
53
+ whole transaction. No partially edited state is returned, and inputs are not
54
+ mutated. `result.error` is a stable diagnostic code, without raw validation internals.
55
+
56
+ ## Named node references
57
+
58
+ `Node.make('text-1')` declares a reusable identity. Its `.id` is a validated
59
+ `NodeId`, `.at(offset, affinity)` constructs a Position, and `.read(document)`
60
+ returns the node from that document or `undefined`. Narrow the returned node's
61
+ `type` before reading text or block-specific fields.
62
+
63
+ Keep references in application definitions; persist IDs and content, not reference
64
+ methods. The reference is immutable and holds no content. Read it against the next
65
+ document to see an edit, or against an older snapshot to inspect that version.
66
+ Two references with the same ID address the same node within a document; neither
67
+ reserves the ID or inserts anything. Document validation still rejects duplicate
68
+ content IDs. IDs are document-local: using a reference with another document
69
+ looks up that same ID there, without an ownership or authorization guarantee.
70
+
71
+ `at` validates offset shape and affinity, but cannot prove the node exists, is
72
+ text, or is long enough. `apply` checks those conditions against the current
73
+ document. A Position remains a resolved offset and must still be mapped through
74
+ edits; a Node reference does not turn it into a collaborative anchor. `read`
75
+ performs a linear lookup, intended for application reads rather than bulk editing.
76
+
77
+ ## Building operations
78
+
79
+ Prefer `Edit.*` over hand-written literals; the builder fills `type` and the
80
+ return type is narrowed to that variant:
81
+
82
+ ```ts
83
+ const result = RichText.apply(state, [
84
+ RichText.Edit.insertText(Text.at(5, 'after'), '!'),
85
+ RichText.Edit.addMark(Text, 'Bold'),
86
+ ])
87
+ ```
88
+
89
+ Builders accept a `NodeId` or a `Node.make` reference interchangeably and
90
+ validate shape immediately: a bad mark, offset, or `from > to` throws at the
91
+ call site. `Edit.splitBlock` additionally takes the two new identities as
92
+ strings or ids (`NodeId.make` rejects empties). Document-dependent failures —
93
+ missing nodes, block targets, out-of-bounds ranges, unresolvable selections,
94
+ reused split identities — still return `apply` diagnostics (`MissingText`,
95
+ `MissingNode`, `InvalidRange`, `InvalidSelection`, `InvalidInput`), and raw wire
96
+ input still decodes to `InvalidInput`. `Edit` builds values only; it reads no
97
+ document and owns no state.
98
+
99
+ ## Commands
100
+
101
+ Intent is resolved into operations by `run`, so durable history keeps its
102
+ meaning and identity comes from the caller:
103
+
104
+ ```ts
105
+ let n = 0
106
+ const ids = { mint: () => `new-${++n}` }
107
+
108
+ RichText.run(state, { type: 'InsertText', text: 'hi' }, ids)
109
+ RichText.run(state, { type: 'ToggleMark', mark: 'Bold' }, ids)
110
+ RichText.run(state, { type: 'SplitBlock' }, ids)
111
+ ```
112
+
113
+ `InsertText`, `DeleteBackward`, `DeleteForward`, `SplitBlock`, `ToggleMark`,
114
+ and `SetSelection` read the current selection, emit a Transaction, and apply it
115
+ in one step; the returned `ChangeSet` and `positionMap` describe the effect.
116
+ Nothing mints identity unless the caller's `mint` does, and replay applies
117
+ transactions rather than commands.
118
+
119
+ `InsertText` takes an optional `marks`. With it, the inserted text carries
120
+ exactly that set wherever it lands; without it, the boundary rule decides and the
121
+ text inherits the marks of the run it joins. A mark the caller's vocabulary does
122
+ not declare is rejected. That is how *stored marks* stay the application's state:
123
+ the caret's format belongs to the caller, and the command layer reads no hidden
124
+ cursor state. A collapsed `ToggleMark` is likewise a no-op — the application
125
+ decides what the caret carries and passes it back on the next `InsertText`.
126
+
127
+ `marksInRange(document, selection)` is the read beside them, for a toolbar's active
128
+ button: the marks every run the selection covers carries. A caret reports its run's
129
+ marks — an empty run can carry them, which is how a caret holds a format — a range
130
+ that straddles a marked run and a plain one reports neither, and a node selection
131
+ reports what its whole subtree agrees on.
132
+
133
+ ## Mark definitions
134
+
135
+ A mark is a definition, not a bare name. It says where typing continues it
136
+ (**boundary expansion**) and, when it carries data, what schema that data
137
+ satisfies. A Kit declares the vocabulary, so an editor extends it:
138
+
139
+ ```ts
140
+ const Link = RichText.mark('Link', {
141
+ Props: Schema.Struct({ href: Schema.String }),
142
+ expand: 'none',
143
+ })
144
+
145
+ const ArticleKit = RichText.kit({
146
+ nodes: [RichText.block('Paragraph'), RichText.block('Heading')],
147
+ marks: [RichText.Bold, RichText.Italic, RichText.Code, Link],
148
+ })
149
+
150
+ RichText.run(state, command, ids, { marks: RichText.markRegistry(ArticleKit.marks) })
151
+ ```
152
+
153
+ A run stores a mark as a bare name when it has no props, and as
154
+ `{ name, props }` when it does. Loading preserves the form it found, so a
155
+ names-only document round-trips byte-equal, and since a run carries a name at
156
+ most once it never holds both forms of one mark:
157
+
158
+ ```ts
159
+ Link.of({ href: '/docs' }) // { name: 'Link', props: { href: '/docs' } }
160
+ ```
161
+
162
+ `of` accepts decoded props and encodes them with the declared schema before
163
+ storing them as JSON. Transforming codecs therefore preserve their encoded
164
+ representation in the document. Encoding must require no services; invalid
165
+ props or a non-JSON-object encoded result throw at the builder call.
166
+
167
+ `markName(mark)` and `markProps(mark)` read either form, and `sameMark` decides
168
+ equivalence. Props are part of a mark's identity: two runs carrying the same name
169
+ with different props are not equivalent, so normalization does not merge them, and
170
+ `AddMark` is a *set* for its name — it appends, replaces props that differ, and
171
+ no-ops on the same value. `RemoveMark` keys on the name alone.
172
+
173
+ The shipped policy is `Bold`/`Italic` → `after`, `Code` → `none`, and a mark no
174
+ registry declares → `both` (so preservation never retargets an unknown mark
175
+ away). `resolveInsertion` retargets a boundary insertion when the current run
176
+ carries marks that forbid the edge and the neighbor carries exactly the marks
177
+ that remain; a registry changes which marks those are, not the rule. Declared
178
+ names are also what `run` may add, so a Kit's marks are usable by name or value.
179
+
180
+ `validate(document, kit)` is the publishing gate: it reports `UnknownMark` for a
181
+ name the Kit does not declare, and `InvalidProps` for a declared mark whose props
182
+ its `Props` schema refuses — including a mark that declares props but carries
183
+ none, and one carrying a field the schema does not declare.
184
+
185
+ The HTML fallback carries mark *names*; props travel in the slice format. A
186
+ declared mark with props gets real attributes once a Kit-aware renderer exists.
187
+
188
+ ## Application node blocks
189
+
190
+ A `Node` block is an application's own kind — a Callout, an Image, an embed. Its
191
+ `props` are JSON at the codec level, because the document codec cannot know an
192
+ application's schemas; a Kit's node definition validates them at that boundary,
193
+ and it also declares what content the kind holds:
194
+
195
+ ```ts
196
+ const ArticleKit = RichText.kit({
197
+ nodes: [
198
+ RichText.block('Paragraph'),
199
+ RichText.node('Callout', { Props: Schema.Struct({ tone: Schema.Literals(['info', 'warning']) }) }),
200
+ RichText.node('Image'),
201
+ RichText.node('List', { children: RichText.blockContent }),
202
+ ],
203
+ marks: [RichText.Bold],
204
+ })
205
+
206
+ RichText.validate(document, ArticleKit)
207
+ // → [] | UnsupportedNode (kind not declared) | InvalidProps (schema refused them)
208
+ // | MismatchedDefinition (declaration and document disagree)
209
+ ```
210
+
211
+ `children` defaults to `RichText.textContent`, so a node holds runs; `blockContent`
212
+ says it holds nested blocks (§116). `RichText.block(name)` declares one of the
213
+ built-in blocks and `RichText.atom(name)` declares a kind holding nothing, so an
214
+ atom is exactly an application node with no content. `validate` walks nested blocks
215
+ and reports `MismatchedDefinition` when a declaration and the document disagree
216
+ about the shape or the content — an atom holding runs, a `blockContent` kind held
217
+ as a run holder, or a `textContent` kind held as a container. An *empty*
218
+ application node is the one case it accepts either way, because the document
219
+ cannot say whether it is an atom or a run holder with no runs.
220
+
221
+ A node block's children are text runs, so positions, operations, selection,
222
+ clipboard slices, history, and the interpreters all work on it unchanged — a
223
+ split keeps its kind and props on both halves. `data-node="Kind"` is the default
224
+ rendering in HTML and in the view until a Kit renderer replaces it.
225
+
226
+ A node block may also accept **nested blocks** in `blocks` (§116), which is how a
227
+ List holds ListItems. The HTML serializer renders them inside the node's element
228
+ and `toText` gives one line per text block; the read-only view and the editable
229
+ adapter do the same, so a list keeps its items in every interpreter. HTML import
230
+ reads `data-node` back, and maps `<ul>`/`<ol>` to a `List` and `<li>` to a
231
+ `ListItem` when the Kit declares those names: an element holding block children
232
+ becomes a container, an element holding inline content becomes a run holder, and a
233
+ kind the Kit does not declare degrades to its content with a diagnostic. A
234
+ `blockContent` declaration settles the one ambiguous case — a container whose
235
+ element holds only inline content — because the declaration says what the content
236
+ is. Props are not carried by HTML; the slice format keeps them, so an imported
237
+ node starts with `{}` props.
238
+
239
+ ## Transforms
240
+
241
+ Normalization runs as a registry of transforms. Each is a pure function of the
242
+ document plus what the transaction touched, and returns the new document with
243
+ the position steps and identity bookkeeping that go with it:
244
+
245
+ ```ts
246
+ const DropEmptyRuns: RichText.Transform = {
247
+ name: 'dropEmptyRuns',
248
+ apply: (document, { dirtyNodes }) => ({ document: next, steps, removedNodes, dirtyNodes, textChanged }),
249
+ }
250
+
251
+ RichText.apply(state, transaction, [DropEmptyRuns])
252
+ RichText.apply(state, transaction) // defaultTransforms: mergeAdjacentRuns
253
+ ```
254
+
255
+ Two rules make a loop over them safe: a transform is **deterministic** and
256
+ **idempotent on normalized state**, so the loop knows it has settled when a pass
257
+ changes nothing. A pass that keeps changing the document is refused with
258
+ `UnstableNormalization` after `MAX_NORMALIZATION_PASSES` rather than spinning.
259
+
260
+ Three constraints follow from replay and from positions:
261
+
262
+ - **A transform cannot mint identities.** It may merge, move, or remove, never
263
+ create — so "ensure an empty Document has a Paragraph" belongs to a command
264
+ that mints, not to a transform.
265
+ - **Removing a run that positions address requires a step.** Report a
266
+ `RelocateStep` (or a collapse) for it, or the selection can be left dangling.
267
+ - **Only what the transaction touched is in scope.** `dirtyNodes` is how a
268
+ transform stays incremental; the shipped merge uses it and leaves every other
269
+ block alone.
270
+
271
+ `apply` folds a transform's report into the same `ChangeSet` and `positionMap`
272
+ it was already building, and maps the selection through the transform's steps,
273
+ so a caller cannot tell whether a change came from an operation or from
274
+ normalization.
275
+
276
+ ## Performance
277
+
278
+ `pnpm bench` measures the shapes an editor meets (`bench/operations.bench.ts`).
279
+ A transaction accumulates changes per block and copies each affected container
280
+ once, so N edits in one paragraph are O(N) rather than N copies of the same
281
+ array. Measured back to back on the same machine (mean), old per-operation
282
+ copying against the current accumulation:
283
+
284
+ ```text
285
+ before after
286
+ paste 50k characters into one run 0.021 0.023 ms
287
+ type one character into a 20k-character run 0.024 0.025 ms
288
+ toggle a mark over a 400-run selection 2.07 1.80 ms
289
+ toggle a mark over a 2000-run selection 16.99 9.59 ms
290
+ toggle a mark over 200 runs / 200 blocks 1.47 1.48 ms
291
+ delete a range spanning 100 paragraphs 3.06 3.27 ms
292
+ split a block inside a 400-run paragraph 1.14 1.35 ms
293
+ paste one paragraph into a 200-block document 1.13 1.22 ms
294
+ ```
295
+
296
+ The large formatting case is the one the change targets: it halves, and it now
297
+ scales linearly (5× the runs costs 5.3× the time, where it used to cost 8.2×).
298
+ Differences under a few percent in the other rows are within this machine's
299
+ run-to-run noise, not a claim either way.
300
+
301
+ Two costs remain. A structural operation still rebuilds the document index, though
302
+ a contiguous run of joins is now batched: deleting a range across B paragraphs
303
+ emits B joins but `apply` consumes them as one structural edit, so the block array
304
+ is copied once and the index rebuilt once instead of B times. That case measured
305
+ 3.06 ms before the batching and 1.77 ms after, on this machine in one session
306
+ (where runs vary by roughly a fifth), and it stays in the benchmark as its check.
307
+ Normalization also walks the whole dirty set — including run identities, which
308
+ cannot match a block — so a transaction that touches every run of a block does
309
+ O(dirty) lookups in the merge pass. Neither is measured as a problem at these
310
+ sizes; the benchmark exists so a claim about them can be checked rather than
311
+ asserted.
312
+
313
+ ## Migrations
314
+
315
+ Migrations move semantic data forward when a deployment changes its vocabulary
316
+ (§73) — a preserved node that is now implemented, a prop renamed, a kind
317
+ replaced:
318
+
319
+ ```ts
320
+ const Callout = Schema.Struct({ tone: Schema.Literals(['info', 'warning', 'critical']) })
321
+
322
+ RichText.migrate(document, [
323
+ RichText.promoteUnknown('EmbedToCallout', 'Embed', 'Callout', Callout),
324
+ RichText.migration('DangerToCritical', 'Callout', block =>
325
+ block.type === 'Node' && block.props.tone === 'danger'
326
+ ? { ...block, props: { ...block.props, tone: 'critical' } }
327
+ : undefined,
328
+ ),
329
+ ])
330
+ // → { document, applied: [{ name, node }], unused: ['…'] }
331
+ ```
332
+
333
+ They operate on blocks, never on DOM, and run at a boundary the application
334
+ chooses — loading, publishing, or an explicit upgrade — never automatically on
335
+ every read. The list order *is* the chain: a later migration sees what an
336
+ earlier one produced. A migration descends into containers, so a preserved block
337
+ nested in a list is rewritten where it sits.
338
+
339
+ Three rules are enforced rather than documented and hoped for:
340
+
341
+ - **Identity survives.** A migration returns the same `id`, so positions,
342
+ references, and selections keep addressing the same node; changing it throws
343
+ instead of silently breaking every reference. That holds for a nested block too.
344
+ - **The result is still content.** Returned blocks must decode, and the complete
345
+ document is validated after each changed migration pass. Non-JSON props,
346
+ unknown shapes, and identities duplicated across blocks are rejected.
347
+ - **Declining is allowed.** Returning `undefined` keeps the block as it is —
348
+ which is what `promoteUnknown` does when legacy data does not decode against
349
+ the target's schema, rather than half-converting it. `promoteUnknown` takes the
350
+ target's content mode, so promoting into a container kind yields a valid block
351
+ (`blocks: []`) rather than one `validate` would call a mismatch.
352
+
353
+ ## HTML export
354
+
355
+ `toHtml(blocks)` and `documentToHtml(document)` serialize to HTML for other
356
+ applications; `toText` / `documentToText` give the plain-text projection.
357
+
358
+ ```ts
359
+ RichText.documentToHtml(document)
360
+ // → '<p>plain <strong>bold</strong></p><h2><code><em>Title</em></code></h2>'
361
+ ```
362
+
363
+ Known marks become `strong`/`em`/`code` in a deterministic nesting order (not
364
+ the order they were added), unknown marks survive as `data-marks` on a span,
365
+ unknown blocks as a `<div data-unknown="Type">` placeholder, and text and
366
+ attribute values are escaped, so content cannot become markup. Importing HTML
367
+ is a whitelist walk over a `DOMParser` tree, and the read-only Foldkit view is
368
+ built with `inertHtml`; the importer, the view, and the editable DOM interpreter
369
+ all live in `foldkit-richtext-dom`, because this package stays DOM-free and
370
+ framework-free. Nothing parses HTML back into authority without that walk.
371
+
372
+ ## Rendering a declared mark or node kind
373
+
374
+ Three interpreters need to know which element a declared mark or node kind
375
+ produces — this serializer, the read-only view, and the editable DOM interpreter —
376
+ and they must not answer that three different ways (design §121). `rendering(...)`
377
+ is that answer: a vocabulary built *over* a Kit, never inside one, holding per-name
378
+ entries that are either fixed data or a function of the mark or block.
379
+
380
+ ```ts
381
+ const renderer = RichText.rendering({
382
+ marks: {
383
+ Link: mark => ({
384
+ tag: 'a',
385
+ attributes: { href: String(RichText.markProps(mark)?.href ?? '') },
386
+ }),
387
+ },
388
+ nodes: {
389
+ Callout: block => ({
390
+ tag: 'aside',
391
+ attributes: { 'data-tone': String(block.props.tone ?? '') },
392
+ }),
393
+ },
394
+ })
395
+
396
+ RichText.documentToHtml(document, renderer)
397
+ // → '<p><a href="https://example.test/x">docs</a></p>'
398
+ ```
399
+
400
+ An entry yields `{ tag, attributes }` — data about an element, not a view — so
401
+ this package gains neither a DOM nor a Foldkit dependency. Attribute *values* are
402
+ escaped. A tag or attribute *name* that would end the markup (one holding a quote,
403
+ a space, or `>`) is refused rather than written, because a name cannot be escaped;
404
+ a well-formed but unwise name is the application's decision. A name with no entry
405
+ renders the shipped way, and that is also the default (`noRendering`):
406
+ `strong`/`em`/`code` for the shipped marks, `p`/`h1`–`h6` and
407
+ `<div data-node="Kind">` for blocks, `data-marks` for anything else. Entries nest
408
+ outside the shipped marks and in alphabetical order, so the same set of marks
409
+ serializes the same way however it was assembled. `runRendering(renderer, run)` and
410
+ `nodeRendering(renderer, block)` are the lookups, exported so the view and the
411
+ interpreter share this one answer.
412
+
413
+ ## Clipboard slices
414
+ Clipboard content is semantic, not HTML. A `Slice` is a versioned fragment with
415
+ its own identities:
416
+
417
+ ```ts
418
+ const slice = RichText.sliceOf(document, selection) // → Slice | undefined
419
+ RichText.serializeSlice(slice) // → string for the clipboard
420
+ RichText.deserializeSlice(payload) // → Slice | undefined
421
+ RichText.withFreshIds(slice, mint) // identities that cannot collide
422
+ RichText.sliceFromText('plain\npaste', mint) // the text fallback
423
+ ```
424
+
425
+ `sliceOf` takes a whole block for a node selection, and for a range only the
426
+ covered part of each touched block, with runs trimmed to the selection — so a
427
+ partial copy never drags in an untouched block. `deserializeSlice` returns
428
+ `undefined` for anything this version did not write (bad JSON, another version,
429
+ excess fields, duplicate identities inside the slice) rather than guessing.
430
+ Identities always come from the caller, like every other identity a live edit
431
+ mints.
432
+
433
+ Paste is a command (`{ type: 'Paste', slice }`): it remints every identity, then
434
+ places the content relative to the caret — above the block at its start, below
435
+ it at its end, and mid-block by splitting the block and landing the content
436
+ between the halves, so text after the caret stays below what was pasted. A range
437
+ selection is replaced first, and the caret lands at the end of the pasted text
438
+ (or at the start of what follows when the pasted content has none). The DOM
439
+ clipboard events that carry these payloads are not wired yet.
440
+
441
+ ## Undo history
442
+
443
+ `History` is interaction state: snapshots of `EditorState` (document plus
444
+ selection), kept beside the selection in the application Model, never in
445
+ published content.
446
+
447
+ ```ts
448
+ let history = RichText.emptyHistory
449
+ history = RichText.commit(history, previousState, { group: RichText.groupFor(command) })
450
+ const back = RichText.undo(history, currentState) // → { history, state } | undefined
451
+ const forward = RichText.redo(back.history, back.state)
452
+ ```
453
+
454
+ Grouping is explicit and clock-free: `groupFor` returns `'typing'` for text
455
+ insertion and deletion, so a typing burst collapses into one undo step, while
456
+ every other command stands alone. `undo`/`redo` return `undefined` when there is
457
+ nothing to do, and a new commit after an undo clears the redo stack. History is
458
+ bounded (200 steps by default). Collaborative undo is a different operation and
459
+ is not implemented.
460
+
461
+ In the harness, the parent Model owns the history and the child commits it, so
462
+ one transition still commits document and interaction state together. Because
463
+ undo replaces the document rather than editing it, the child reports a
464
+ `Replaced` out-message with a whole-document `ChangeSet`
465
+ (`replaceChangeSet(previous, next)`): every surviving identity is dirty and every
466
+ departed one is removed, so the DOM cannot keep a stale element.
467
+
468
+ ## Kits
469
+
470
+ A `Kit` declares the vocabulary one editor accepts — node kinds and marks — as
471
+ plain data, with no renderers or executable code:
472
+
473
+ ```ts
474
+ const ArticleKit = RichText.kit({
475
+ nodes: [RichText.block('Paragraph'), RichText.block('Heading'), RichText.atom('Image')],
476
+ marks: ['Bold', 'Italic'],
477
+ })
478
+
479
+ RichText.validate(document, ArticleKit)
480
+ // → [] when the document fits; otherwise UnknownNode / UnsupportedNode / UnknownMark
481
+ ```
482
+
483
+ `validate` reads the document and never repairs it: callers decide whether a
484
+ diagnostic blocks publishing or shows a placeholder. Prop schemas, nested
485
+ children, transforms, and metadata arrive with node definitions; the Kit does
486
+ not yet drive parsing or `apply`.
487
+
488
+ ## Current semantics
489
+
490
+ - Documents contain paragraphs and headings (levels 1–6), each containing text
491
+ runs. The shipped marks are `Bold`, `Italic`, and `Code`, and a run carries a
492
+ mark name at most once. A mark with props is stored as `{ name, props }`; a
493
+ name the vocabulary does not define loads verbatim for forward compatibility
494
+ (see `findUnknownMarks`) and rides along through text edits. `Edit.addMark`
495
+ takes any mark; `run` is what refuses to add one the caller's vocabulary does
496
+ not declare — the shipped marks by default, or a Kit's through its registry.
497
+ - Empty documents, empty blocks, and empty text runs are valid. No normalization
498
+ creates nodes or merges text runs yet.
499
+ - A `Node` block may carry nested blocks in `blocks`, and its presence is what
500
+ says the kind accepts them (§116): a List holds ListItems, a Quote paragraphs.
501
+ Nested content decodes, round-trips byte-equal, is counted by `inspect` and the
502
+ decode limits, survives a deploy that lost its kind, and a selection or
503
+ reference inside it resolves. Commands reach a run wherever it sits, so typing,
504
+ grapheme deletion, marks, stored marks, undo, and the clipboard work inside a
505
+ container — a copy across its children carries the container — and every
506
+ interpreter renders one, with the HTML importer reading a container back.
507
+ Structural placement works at depth too: a split keeps its halves in the block's
508
+ own container, siblings join within theirs, and a move or insert takes an
509
+ optional `parent` to enter or leave a container. What is still refused with
510
+ `InvalidParent` is a range that would have to merge across containers, and a
511
+ parent that cannot hold blocks.
512
+ - `InsertText` targets one run and inherits that run's marks. When the command
513
+ carries `marks`, the inserted span is split out of its run and given exactly
514
+ that set instead — that is how a caller's stored marks reach the document.
515
+ - `DeleteText` removes a half-open range `[from, to)` within one run.
516
+ - `AddMark` sets one run's mark for that name: it appends when the name is
517
+ absent, replaces the value when its props differ, and no-ops when the mark is
518
+ already exactly this one. `RemoveMark` filters that name away whatever props it
519
+ carries. Redundant mark edits preserve state identity, and mark edits dirty the
520
+ run and its block without emitting position steps.
521
+ - `SplitNode` splits one block at a run offset into two: runs before the split stay (trailing runs move right with their ids), the split run keeps its id on
522
+ the left, and the right remainder takes the caller-supplied run id under a
523
+ caller-supplied block id of the same block type. Splitting an empty block is
524
+ rejected; split that via node insertion once it exists. New identities must be
525
+ fresh within the transaction.
526
+ - `SplitRun` divides one run at an offset so each side can carry different
527
+ marks; the left keeps the identity, the right takes the caller-supplied id
528
+ and inherits the marks. Splitting at 0 is a no-op. A bare split (no
529
+ subsequent difference) is normalized away by the merge pass, so a split is
530
+ only meaningful together with an edit that makes the sides differ.
531
+ - `JoinNode` moves every run of the removed block into the surviving previous
532
+ sibling, preserving run identities, marks, and range selections without
533
+ emitting position steps. No runs merge (that is future normalization's job);
534
+ the survivor keeps its block type. Node selections on the removed block
535
+ remap to the survivor. Only adjacent siblings join, and only compatible ones:
536
+ opaque content, application nodes of a different kind or props, and a container
537
+ with a run holder are all refused rather than merged lossily. Joining two
538
+ containers of the same kind concatenates their nested blocks.
539
+ - `MoveNode` reorders one block to an explicit post-removal index; moving to
540
+ the same index is a no-op. Run identities and selections are untouched, so no
541
+ position steps are emitted. An optional `parent` moves it into a node block's
542
+ nested blocks (and back out), and a parent that cannot hold blocks is refused.
543
+ - `SetNodeProps` retypes a heading's level today (the first block prop; Kit
544
+ definitions generalize this later). Same-level sets are no-ops; paragraphs
545
+ reject the operation.
546
+ - `InsertNode` splices a caller-built block at an explicit index, or into a node
547
+ block's nested blocks when `parent` is given; every carried identity must be
548
+ fresh within the transaction. Positions need no mapping (they address runs, not
549
+ indexes).
550
+ - `DeleteNode` removes one block and collapses its positions to the nearest
551
+ surviving run in document order — the first at or after the removed block's
552
+ place, else the last before it — or clears the selection when no run remains.
553
+ Node selections on the removed subtree remap to the collapse target. Collapse
554
+ steps in the position map carry the same rule to external positions.
555
+ - `decodeDocument` preserves blocks whose type this version does not implement
556
+ as `Unknown` nodes: original type, remaining JSON fields, and no text runs.
557
+ Unknown nodes are addressable structurally (move, delete) but never
558
+ text-editable; `findUnknownNodes` lists them. Non-JSON payloads, missing ids,
559
+ unknown top-level fields, and unsupported versions are rejected rather than
560
+ dropped.
561
+ - Marks carry boundary expansion (`Bold`/`Italic`: `after`, `Code`: `none`).
562
+ `resolveInsertion(document, position)` retargets edge insertions whose marks
563
+ forbid the edge to the neighbor carrying exactly the remaining marks; mixed
564
+ edges stay put rather than swapping formatting. Unknown marks default to
565
+ expanding both ways so preservation never retargets them away.
566
+ - Every transaction ends by running its transforms (by default
567
+ `mergeAdjacentRuns`): adjacent same-mark runs within touched blocks merge, the
568
+ first run keeping its identity and text and later equivalents retiring
569
+ (reported in `removedNodes` with `RelocateStep`s). Loading never normalizes,
570
+ so decoded documents stay verbatim until first edited; empty transactions
571
+ stay untouched to preserve state identity.
572
+ - Positions count **UTF-16 code units**. Low-level edits may split a surrogate
573
+ pair; grapheme-aware user commands are not implemented.
574
+ - `SetSelection` resolves against the document at that point in the transaction.
575
+ Ranges retain anchor/focus direction; node selections may target a block or run.
576
+ - Insertion at a range endpoint keeps `before` affinity on the left and moves
577
+ `after` affinity past the insertion. Deletion collapses covered positions to
578
+ its start. Other nodes' positions are unchanged.
579
+
580
+ `positionMap` records text replacements in sequential coordinates, plus split
581
+ relocations (`{ node, into, at }`): offsets above the split point move to the
582
+ new run, the split point itself follows affinity, lower offsets stay. Use
583
+ `mapPosition(position, result.positionMap)` for another position from the original
584
+ document. The returned selection is already mapped. `ChangeSet` names touched
585
+ text runs and their blocks, plus `insertedNodes`/`removedNodes` and
586
+ `structureChanged` once structural operations exist; it is neither a replication
587
+ packet nor proof of a net content change (insert-then-delete can cancel).
588
+ `selectionChanged` compares the final selection with the original. Empty edits
589
+ preserve state identity.
590
+
591
+ ## Loading and limits
592
+
593
+ Use `decodeDocument(input, limits?)` at a persistence boundary. It rejects excess
594
+ fields, duplicate IDs, empty or duplicate marks, invalid structure, unknown nodes,
595
+ and unsupported versions — but preserves unknown mark strings verbatim and
596
+ round-trips them. `findUnknownMarks(document)` lists them per text run for a
597
+ publishing gate; unknown nodes are still rejected, not preserved. Then enforces `limits` (default `DefaultDocumentLimits`: 10,000 blocks,
598
+ 50,000 text runs, 5,000,000 UTF-16 text units). A violation throws an `Error`
599
+ naming the exceeded bound. Tighten per document with
600
+ `{ ...DefaultDocumentLimits, maxBlocks: 100 }`. The exported Schemas also compose
601
+ into an application's Model; when decoding them directly, pass
602
+ `{ onExcessProperty: 'error' }` for the same strict policy.
603
+
604
+ `apply` does not enforce limits: size-check untrusted operation payloads
605
+ (notably inserted text) before applying, and apply byte-size limits before
606
+ decoding untrusted payloads. Nested children and collaboration are still
607
+ pending. Retain rejected source content for
608
+ recovery; do not replace it with an empty document.
609
+
610
+ Each transaction currently validates the whole input and indexes its text runs.
611
+ Edits copy the affected arrays and preserve untouched nodes. The performance
612
+ section records the measured cases; collaborative replay remains unmeasured.
613
+
614
+ See the [design and phase status](../../docs/design/richtext-DESIGN.md#101-phase-1--pure-semantics-and-integration-feasibility).