foldkit-richtext 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -71,7 +71,8 @@ looks up that same ID there, without an ownership or authorization guarantee.
71
71
  `at` validates offset shape and affinity, but cannot prove the node exists, is
72
72
  text, or is long enough. `apply` checks those conditions against the current
73
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`
74
+ edits; a Node reference does not turn it into a collaborative anchor (see
75
+ [Shared documents](#shared-documents) for one that is). `read`
75
76
  performs a linear lookup, intended for application reads rather than bulk editing.
76
77
 
77
78
  ## Building operations
@@ -108,28 +109,198 @@ const ids = { mint: () => `new-${++n}` }
108
109
  RichText.run(state, { type: 'InsertText', text: 'hi' }, ids)
109
110
  RichText.run(state, { type: 'ToggleMark', mark: 'Bold' }, ids)
110
111
  RichText.run(state, { type: 'SplitBlock' }, ids)
112
+ RichText.run(state, { type: 'RetypeBlock', to: { type: 'Heading', level: 2 } }, ids)
111
113
  ```
112
114
 
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.
115
+ `InsertText`, `DeleteBackward`, `DeleteForward`, `SplitBlock`, `ToggleMark`, `SetMark`,
116
+ `ClearMark`, `SetSelection`, `Paste`, and the block commands below (`RetypeBlock`,
117
+ `WrapBlock`, `ConvertBlock`, `RetypeContainer`, `LiftBlock`) read the current selection; `MoveBlock` and `SetProps` name their
118
+ blocks instead. Each resolves to transactions applied as one step, usually one (Enter over
119
+ a range in a list item is two: the delete, then the split); the returned `ChangeSet` and
120
+ `positionMap` describe the effect, and `transactions` holds what was applied, in order, an
121
+ empty one for a command that changed nothing. Nothing mints
122
+ identity unless the caller's `mint` does, and replay applies transactions rather than
123
+ commands: folding `apply` over `transactions` from the starting state gives the same result.
124
+
125
+ An *action* is an ordered list of those commands committed as one step:
126
+
127
+ ```ts
128
+ RichText.runAction(state, [removeTheMarker, retypeTheBlock], ids)
129
+ ```
130
+
131
+ `runAction` runs the commands in sequence and returns one state, one `ChangeSet` (the
132
+ union of its commands'), and one identity stream. It stops at the first refusal and
133
+ returns that command's error; state is a value, so nothing partial escapes. One command
134
+ behaves exactly as `run` does.
135
+
136
+ An *input rule* turns what was just typed into such an action:
137
+
138
+ ```ts
139
+ interface InputRule {
140
+ name: string
141
+ match: (
142
+ textBefore: string,
143
+ within: ReadonlyArray<string>,
144
+ ) => { remove: number; commands: Action } | undefined
145
+ }
146
+ ```
147
+
148
+ `within` is the kinds of the node blocks around the caret's block, innermost first,
149
+ so a rule can tell `[ ] ` typed at the start of a list item from the same text at the
150
+ top level. `applyInputRules` takes it as `within`, defaulting to none, and the editor
151
+ fills it in.
152
+
153
+ `applyInputRules(rules, { textBefore, text, insertion })` builds the action — the insertion,
154
+ one `DeleteBackward` per character the rule consumed, then the rule's commands. The deletes
155
+ are what let a rule work without a range: `# ` is not in the document until the insertion
156
+ that completes it has run, so a range read before that would be the wrong range. A rule that
157
+ claims to consume more than the text it was shown throws, because those deletes would run
158
+ past the block's start and join it to the one before. `textBefore` for a selection that is
159
+ a range is read from `rangeStart(document, range)` — the end that comes first, whichever
160
+ way the range was made — since that is where what is typed over it lands.
161
+
162
+ `RetypeBlock` changes the type of the block the selection starts in — `Paragraph`, or
163
+ a `Heading` at a level — and keeps that block's runs, so identities and the caret
164
+ survive. Given a vocabulary that declares a node kind as holding text, it also takes a block
165
+ of that kind back out — a `CodeBlock` to a paragraph — the same way, keeping the block's and
166
+ its runs' identities. Any other node block, or preserved content, is refused, because its
167
+ content is not runs.
168
+
169
+ `WrapBlock` puts that same block inside new containers, listed outermost first —
170
+ `{ type: 'WrapBlock', containers: [{ kind: 'Quote' }] }`, or a `List` holding a `ListItem`
171
+ — built where the block stood, with identities from `mint`. The block moves rather than
172
+ being copied, so its identity, its runs, and the caret all survive. Given a vocabulary, a
173
+ wrap the vocabulary would not hold is refused with `UnexpectedChild`: the parent must accept
174
+ the outermost container, each container must be a kind declared to hold nested blocks, and
175
+ each must accept the next. A container's props must decode as its kind declares them, or the
176
+ wrap is refused with `InvalidInput`. With a vocabulary, a wrap whose outer container holds
177
+ items (as `List` holds `ListItem`) and whose block sits right after a container of that kind
178
+ and those props joins it: the block becomes its last item instead of starting a second list,
179
+ which Markdown would read back as the same one.
180
+
181
+ `ConvertBlock` makes a paragraph or heading a node kind that holds text —
182
+ `{ type: 'ConvertBlock', to: { kind: 'CodeBlock', props: { language: 'ts' } } }` — with its
183
+ text and marks. It is a retype: the block and its runs keep their identities, so the
184
+ selection, a decoration, a remote cursor, and another replica's edit to that text still
185
+ find them. Given a vocabulary, the kind must be declared to hold text and its
186
+ parent must accept it (`UnexpectedChild`), its props must decode as the kind declares them
187
+ (`InvalidInput`), and a kind that forbids marks refuses a block that carries any
188
+ (`ForbiddenMark`).
189
+
190
+ `RetypeContainer` retypes the container around that block — the node holding it, such as a
191
+ list item — to another node kind where it stands:
192
+ `{ type: 'RetypeContainer', to: { kind: 'TaskItem', props: { checked: false } } }` makes the
193
+ item a task without moving it, splitting its list, or touching what it holds, and the
194
+ container keeps its identity, so another replica's edit inside it survives. It acts only from
195
+ the container's first block, which is where a marker for the container is typed, and refuses
196
+ elsewhere, or with no container, with `InvalidInput`. Given a vocabulary, the new kind must
197
+ be declared to hold blocks, hold every block the container holds, and stand where the
198
+ container stands (`UnexpectedChild`), and its props must decode (`InvalidInput`).
199
+
200
+ `LiftBlock` is the inverse of a wrap: it moves the block the selection starts in out of its
201
+ container — before it when it was first, after it when it was last, and between the two halves
202
+ of a split container when it was in the middle — and deletes a container it leaves empty. With
203
+ a vocabulary, it keeps lifting while the new parent does not hold the block's kind, so a list
204
+ item's paragraph leaves both the item and the list; without one it takes a single step. It
205
+ never leaves a container declared `isolating`, such as the standard `TableCell`, and a block
206
+ with nothing to leave is refused with `InvalidInput`. The block keeps its identity, and the
207
+ caret with it.
208
+
209
+ `MoveBlock` moves a block, with everything it holds, before or after another block:
210
+ `{ type: 'MoveBlock', node, to: { before: other } }` or `{ after: other }`. It addresses blocks
211
+ by identity, not by the selection, so a block handle or a key sends it for the block it stands
212
+ for; identities are kept, and so is the selection, except a node selection on a container the
213
+ move empties and deletes, which moves to the moved block. `other` can be in any container the block may
214
+ move into. With a vocabulary, that container has to hold the block's kind, and the kind has to
215
+ stand in it by its `within` (otherwise `UnexpectedChild`). The move may not leave an
216
+ `isolating` container such as a table cell, or go inside itself (`InvalidParent`). A container
217
+ the move leaves empty is deleted with it, as a lift deletes one: an item moved out of a
218
+ one-item list takes the list too. A block that is not there is `InvalidInput`, and moving a
219
+ block beside itself changes nothing. `moveTargets(document, node, nodes?)` lists the blocks it
220
+ may move beside, in document order, which is what a drag offers.
221
+
222
+ `SetProps` sets props on a node block by identity and keeps the ones it does not name:
223
+ `{ type: 'SetProps', node: item, props: { checked: true } }` ticks a task item. Given a
224
+ vocabulary, props that decode as the kind declares them must still decode after, or the
225
+ command is refused with `InvalidInput`, as it is for a block that is not a node. Props that
226
+ already fail (a key an older version wrote, which cannot be deleted) can still be changed.
227
+
228
+ `DeleteBackward` at the start of a container's first block used to do nothing, having no
229
+ sibling to join. With a vocabulary it now lifts the block, which is how Backspace undoes a
230
+ `> ` or `- ` typed at a block's start. Without a vocabulary, in a table cell, and forwards, the
231
+ edge still does nothing. At the start of a kind the vocabulary declares as holding text, such
232
+ as a `CodeBlock`, Backspace retypes it to a paragraph instead of joining it to the block
233
+ above, which undoes a fence the way a lift undoes a list marker.
234
+
235
+ `SplitBlock` at the end of a heading starts a paragraph under it, since what follows a title is
236
+ text; in the middle of one, both halves stay headings. Over a selection, the range's end
237
+ decides, and one ending past the heading also starts a paragraph.
238
+
239
+ `SplitBlock` inside a list item works on the item, with a vocabulary to say what an item is: a
240
+ container its parent declares it holds (a `List` holds `ListItem`s), and not isolating. Enter
241
+ splits the block, and the second half, with every block after it in the item, becomes a new
242
+ item of the same kind and props right after; the caret lands at its start. Enter in an empty
243
+ block that is the item's whole content leaves the list instead, as Backspace does. Over a range
244
+ inside an item, the range is deleted first. The new item copies the old one's props, with the
245
+ kind's `splitProps` laid over them when it declares some: the standard `TaskItem`'s
246
+ `{ checked: false }` makes Enter in a done task start an open one. Together they must still
247
+ decode by the kind's `Props`, or the split is refused (`InvalidInput`), and a heading's rule
248
+ holds inside an item too. Without a vocabulary, in a quote, and in a table
249
+ cell, Enter splits only the block, as before.
118
250
 
119
251
  `InsertText` takes an optional `marks`. With it, the inserted text carries
120
252
  exactly that set wherever it lands; without it, the boundary rule decides and the
121
253
  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:
254
+ not declare is rejected, and so is one whose props its definition does not decode — a
255
+ `Link` named bare, with no `href` (`MarkRegistry.accepts` is the check). That is how *stored marks* stay the application's state:
123
256
  the caret's format belongs to the caller, and the command layer reads no hidden
124
257
  cursor state. A collapsed `ToggleMark` is likewise a no-op — the application
125
258
  decides what the caret carries and passes it back on the next `InsertText`.
126
259
 
260
+ A toggle can take a link off but cannot change where it points. `SetMark` puts exactly
261
+ the given mark on every run a range covers, replacing the props of a same-named mark,
262
+ and `ClearMark` takes a mark off by name. At a caret both act on the mark's extent
263
+ around it, so an editor changes or removes the link the caret sits in without selecting
264
+ it first; outside a mark they do nothing. `markExtent(document, position, name)` is that
265
+ extent as a read: the mark, and the range of adjacent runs carrying it with the same
266
+ props, which is what a link editor shows before it sends either command. `linkAt(document,
267
+ selection)` is the standard vocabulary's reading of it for `Link`: the `href` and extent of
268
+ the link a selection starts in, or undefined outside one.
269
+
127
270
  `marksInRange(document, selection)` is the read beside them, for a toolbar's active
128
271
  button: the marks every run the selection covers carries. A caret reports its run's
129
272
  marks — an empty run can carry them, which is how a caret holds a format — a range
130
273
  that straddles a marked run and a plain one reports neither, and a node selection
131
274
  reports what its whole subtree agrees on.
132
275
 
276
+ `textBlockAt(document, selection)` is the style of the block a selection starts in — a
277
+ paragraph, or a heading at its level — in the shape `RetypeBlock` takes, or undefined for any
278
+ other block (a code block) or a node selection, which is what a style picker presses.
279
+
280
+ `count(document)` is `{ words, characters }` as a reader counts them: `Intl.Segmenter`'s
281
+ word-like segments and graphemes, so an emoji is one character and a word in a script without
282
+ spaces still counts. Runs join within a block, so a word whose mark changes midway is one word;
283
+ blocks never join.
284
+
285
+ `blocksAt(document, selection)` is the chain of blocks a selection starts in, outermost first:
286
+ a caret in a list item's paragraph gives the list, the item, and the paragraph, and a node
287
+ selection gives the chain to its block. It is what a block handle picks its block from.
288
+
289
+ `isBlank(document)` says whether a reader would see nothing — no blocks, or a lone paragraph
290
+ or heading with no text — which is when an editor shows its placeholder.
291
+
292
+ `textBefore(document, position)` is the read for a menu: the text of the block the
293
+ position addresses, up to that position, across its runs. A query is typed into the
294
+ block's text between its start and the caret, so it never spans blocks; an offset
295
+ past a run's end clamps to it, a negative one reads as none of it, and a position
296
+ that resolves to nothing gives an empty string.
297
+
298
+ `textRangeBefore(document, position, length)` is its inverse, for a rule that removes
299
+ what it matched: the range covering the `length` characters before the position in its
300
+ block, or `undefined` when they do not all precede it. An offset past the run's end clamps
301
+ to it, as `textBefore` clamps. Endpoints land at run boundaries
302
+ at `after` affinity, where a caret that typed that character would sit.
303
+
133
304
  ## Mark definitions
134
305
 
135
306
  A mark is a definition, not a bare name. It says where typing continues it
@@ -298,6 +469,38 @@ scales linearly (5× the runs costs 5.3× the time, where it used to cost 8.2×)
298
469
  Differences under a few percent in the other rows are within this machine's
299
470
  run-to-run noise, not a claim either way.
300
471
 
472
+ `apply` validates its input once per block, not once per call. Blocks and
473
+ documents are immutable and an edit copies only the blocks it touches, so a
474
+ block or document that has passed validation is remembered, and the document's
475
+ index is built once per document. Typing into a 4,000-paragraph document
476
+ spent about 10 ms of each `apply` decoding the whole document; it now validates
477
+ the one block the last edit replaced. The input is still refused exactly as the
478
+ `EditorState` schema refuses it.
479
+
480
+ The collaborative path (`bench/replicated.bench.ts`) types one character into
481
+ the middle of a document of `n` paragraphs, as `examples/pages` does:
482
+ `RichText.run`, then `Replicated.translate`, `applyOps`, `project` and
483
+ `resolve`. The means below were measured back to back on one machine, before
484
+ and after four changes:
485
+
486
+ - `apply` validates by block (above).
487
+ - `applyOps` keeps a layered index of which blocks hold each insert, instead of
488
+ scanning every block to find a character or to check an id is free.
489
+ - `project` reuses a block's projection while its entry is unchanged.
490
+ - `translate` builds its shadow only for the blocks the edit touches.
491
+
492
+ ```text
493
+ paragraphs before after
494
+ 100 1.08 ms 0.17 ms
495
+ 1,000 8.70 ms 1.91 ms
496
+ 4,000 49.2 ms 9.61 ms
497
+ ```
498
+
499
+ What remains grows with the document because each new document gets its own
500
+ indexes: `apply`'s block and run paths, and the node index that `translate` and
501
+ selection checks read. `project` also rebuilds its run table and walks every
502
+ entry to reuse it.
503
+
301
504
  Two costs remain. A structural operation still rebuilds the document index, though
302
505
  a contiguous run of joins is now batched: deleting a range across B paragraphs
303
506
  emits B joins but `apply` consumes them as one structural edit, so the block array
@@ -406,10 +609,59 @@ renders the shipped way, and that is also the default (`noRendering`):
406
609
  `strong`/`em`/`code` for the shipped marks, `p`/`h1`–`h6` and
407
610
  `<div data-node="Kind">` for blocks, `data-marks` for anything else. Entries nest
408
611
  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
612
+ serializes the same way however it was assembled. A rendering that names a void element —
613
+ the standard `Image` is an `img`, a `ThematicBreak` an `hr` — is written as one open tag
614
+ rather than `<img></img>`. `runRendering(renderer, run)` and
410
615
  `nodeRendering(renderer, block)` are the lookups, exported so the view and the
411
616
  interpreter share this one answer.
412
617
 
618
+ ## Decorations
619
+
620
+ A decoration is derived, ephemeral presentation over a document range — a search match, a
621
+ lint warning, a remote cursor, a syntax token — and never document content (§64):
622
+
623
+ ```ts
624
+ const matches: RichText.DecorationSet = [{ from: at(0), to: at(7), kind: 'search' }]
625
+
626
+ RichText.decorationsIn(document, matches)
627
+ // → Map<runId, Array<{ from, to, decoration }>>, each cut at its run's edge
628
+ ```
629
+
630
+ `decoration.data` is the renderer's own payload and the core never reads it. A decoration
631
+ is not in the codec, not a Transaction, not undo, and not replicated: a caller computes a
632
+ set for one render and discards it. `decorationsIn` is the projection every interpreter
633
+ shares — a decoration crossing runs is cut at each run's edge, an endpoint that does not
634
+ resolve skips the decoration, a backwards range is honoured, and one run's spans come back
635
+ in text order.
636
+
637
+ A producer comes with it. `searchDecorations(document, query)` returns every occurrence of a
638
+ query as a decoration of kind `search` (`SEARCH_DECORATION`), changing nothing: one
639
+ decoration per occurrence, a match across two runs kept whole, and no match across two blocks,
640
+ because what a document has between blocks is structure rather than text. `positionInBlock(block,
641
+ offset)` is the read it shares with `textRangeBefore` — the position a block's own text offset
642
+ addresses — and the one any producer of ranges needs.
643
+
644
+ Code highlighting is the second producer. A `CodeBlock` holds its `language` and plain text,
645
+ and a `CodeTokenizer` — a pure `(text) => ReadonlyArray<{ from, to, kind }>` over that text —
646
+ says what is in it; `codeDecorations(document, tokenizers)` runs the tokenizer registered for
647
+ each block's language and returns the tokens as decorations, so the document never holds a
648
+ token. The registry is a `Map` keyed by language, and a block whose language nothing is
649
+ registered for yields nothing. A token outside its block's text, covering nothing, or at a
650
+ fractional offset throws, naming the language: a tokenizer's bug should not become a
651
+ highlight over the wrong text. The grammars themselves are not here — they are
652
+ format-specific, and belong to `foldkit-richtext-code` (§130).
653
+
654
+ ```ts
655
+ const numbers: RichText.CodeTokenizer = text =>
656
+ Array.from(text.matchAll(/\d+/g), match => ({
657
+ from: match.index,
658
+ to: match.index + match[0].length,
659
+ kind: 'syntax-number',
660
+ }))
661
+
662
+ RichText.codeDecorations(document, new Map([['json', numbers]]))
663
+ ```
664
+
413
665
  ## Clipboard slices
414
666
  Clipboard content is semantic, not HTML. A `Slice` is a versioned fragment with
415
667
  its own identities:
@@ -473,17 +725,175 @@ plain data, with no renderers or executable code:
473
725
  ```ts
474
726
  const ArticleKit = RichText.kit({
475
727
  nodes: [RichText.block('Paragraph'), RichText.block('Heading'), RichText.atom('Image')],
476
- marks: ['Bold', 'Italic'],
728
+ marks: [RichText.Bold, RichText.Italic],
477
729
  })
478
730
 
479
731
  RichText.validate(document, ArticleKit)
480
- // → [] when the document fits; otherwise UnknownNode / UnsupportedNode / UnknownMark
732
+ // → [] when the document fits; otherwise a diagnostic the caller decides on
481
733
  ```
482
734
 
735
+ `foldkit-richtext` also ships a standard vocabulary — the kinds and marks a document
736
+ uses to mean what Markdown and HTML also mean:
737
+
738
+ ```ts
739
+ RichText.kit({
740
+ nodes: [...RichText.standardNodes, Callout],
741
+ marks: [...RichText.standardMarks, Highlight],
742
+ })
743
+ ```
744
+
745
+ `standardNodes` is `Paragraph`, `Heading`, `Quote`, `List`, `ListItem`, `TaskItem`,
746
+ `CodeBlock`, `ThematicBreak`, `Image`, `Table`, `TableRow`, `TableCell`; `standardMarks`
747
+ is the shipped three plus `Strikethrough` and `Link`. `standardRendering` gives each kind
748
+ its element — a `List` an `ol` or `ul`, an `Image` an `img` with its `src`, a `TaskItem` its
749
+ `data-task` — and `renderingOver(base, extra)` builds a registry over another, so an
750
+ application adds its own kinds beside the standard ones. A `TableRow` that is the header
751
+ renders `data-header`, and a `Table`'s rows go in a `tbody` (the entry's `inner`), because an
752
+ HTML parser inserts one around bare rows, and markup sent from a server has to parse to the tree
753
+ that was rendered. A link's `href` and an image's `src` pass `safeUrl` again as they are
754
+ rendered, and one it refuses is left out, so a `javascript:` URL that reached the document
755
+ by decoding, sync, or `SetMark` rather than import is drawn inert.
756
+
757
+ A kind can state rules stricter than its content mode. `blocksOf(...kinds)` accepts only
758
+ those block kinds, `marks: 'none'` forbids marks on the kind's own runs, `isolating: true`
759
+ makes the kind a boundary a lift never crosses, as a table cell is, `splitProps` names
760
+ props an item split off one of this kind starts with (typed from the kind's `Props`), and `within` names the kinds it may stand
761
+ in, so a `ListItem` stands only in a `List` and never at the top level:
762
+
763
+ ```ts
764
+ RichText.node('List', { children: RichText.blocksOf('ListItem', 'TaskItem') })
765
+ RichText.node('CodeBlock', { Props: Language, children: RichText.textContent, marks: 'none' })
766
+ RichText.atom('Image', { Props: Schema.Struct({ src: Schema.String }) })
767
+ RichText.node('TaskItem', {
768
+ Props: Schema.Struct({ checked: Schema.Boolean }),
769
+ children: RichText.blockContent,
770
+ splitProps: { checked: false },
771
+ within: ['List'],
772
+ })
773
+ ```
774
+
775
+ `validate` reports those violations as `UnexpectedChild`, `ForbiddenMark`, and
776
+ `MisplacedNode` (a kind outside what its `within` names), and checks
777
+ an atom's props the same way it checks a node's. `run` refuses the edits that would create
778
+ an unexpected child, a forbidden mark, or a misplaced kind (a move, a wrap, or a paste), when it
779
+ is given the vocabulary — `nodes: RichText.nodeRegistry(kit.nodes)`, the node
780
+ counterpart of the `marks` option:
781
+
782
+ ```ts
783
+ RichText.run(state, { type: 'ToggleMark', mark: 'Bold' }, ids, {
784
+ nodes: RichText.nodeRegistry(kit.nodes),
785
+ })
786
+ // → { ok: false, error: 'ForbiddenMark' } when the caret is inside a CodeBlock
787
+ ```
788
+
789
+ The codec keeps a document a Kit would reject, and `apply` takes no vocabulary: a durable
790
+ transaction must not depend on a declaration that may have moved. Removing a mark is
791
+ always allowed, so a preserved document that already carries one has a way back.
792
+
483
793
  `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`.
794
+ diagnostic blocks publishing or shows a placeholder. The Kit does not drive parsing
795
+ or `apply`.
796
+
797
+ ## Shared documents
798
+
799
+ Several replicas can edit one document when the edits are ordered by a server, as
800
+ `foldkit-sync` and `foldkit-durable` order any durable Message. The difficulty is only that
801
+ an edit written as "insert at offset 12 of run `t`" means something else once another
802
+ replica's edit lands first. `RichText.Replicated` gives every character an identity that
803
+ outlives the edits around it, and restates each edit in those terms:
804
+
805
+ ```text
806
+ shared state --project--> Document --command--> result --translate--> ops
807
+ ^ |
808
+ +------------------------------ applyOps --------------------------+
809
+ ```
810
+
811
+ The editor, its commands and its renderers keep working on a plain `Document`. The state
812
+ holds the blocks, every character typed (deleted ones stay, as tombstones, because a later
813
+ op may be anchored on them, until a `Collect` removes them), and the marks on each:
814
+
815
+ ```ts
816
+ import * as RichText from 'foldkit-richtext'
817
+
818
+ const { Replicated } = RichText
819
+ const seed = RichText.decodeDocument({
820
+ version: 1,
821
+ children: [
822
+ { type: 'Paragraph', id: 'p', children: [{ type: 'Text', id: 't', text: 'hello', marks: [] }] },
823
+ ],
824
+ })
825
+
826
+ let shared = Replicated.fromDocument(seed, 'doc:seed')
827
+ const shown = Replicated.project(shared)
828
+ const caret = { node: shown.children[0]!.children[0]!.id, offset: 5, affinity: 'after' as const }
829
+ const result = RichText.run(
830
+ { document: shown, selection: { type: 'Range', anchor: caret, focus: caret } },
831
+ { type: 'InsertText', text: '!' },
832
+ { mint: () => crypto.randomUUID() },
833
+ )
834
+ if (result.ok) {
835
+ const { ops, selection } = Replicated.translate(shared, result, 'edit:1')
836
+ shared = Replicated.applyOps(shared, ops)
837
+ const next = { document: Replicated.project(shared), selection: Replicated.resolve(shared, selection) }
838
+ }
839
+ ```
840
+
841
+ - `fromDocument(document, key)` and `translate(state, result, key)` mint new identities under
842
+ `key`, which has to be unique to that call among everything the state will see, such as a
843
+ random id minted in a Command. The ids the command minted itself are replaced, so its
844
+ `mint` needs no care.
845
+ - `translate(state, result, key, { continues })` carries text typed right after the last
846
+ character of an insert that `continues` accepts on that insert, from its next index,
847
+ rather than starting a new one. `coalesce(ops)` then folds a run of such inserts into one
848
+ op, so a burst of typing sent together is one `Insert`. Accept only inserts this replica
849
+ minted: two replicas continuing one insert at once claim the same characters, and the
850
+ later-committed loses its text.
851
+ - `translate` is pure and reads nothing but its arguments. The `ops` are what travels: every
852
+ replica applies the same ops in the server's order and projects the same document.
853
+ - `applyOps` never throws. An op that no longer fits changes nothing: a block already
854
+ deleted, an id already taken, a move or an `Unjoin` that would put a block inside itself.
855
+ Text typed into a block another replica deleted is gone with it. An insert or split
856
+ anchored on a character that is gone (its insert was refused, or a `Collect` removed it)
857
+ lands at the end of the block it was typed in, or of the block that one was joined into.
858
+ - `applyOps` checks structure, not vocabulary: a `Retype` or `SetProps` op takes any node
859
+ kind and any JSON props. An application applying ops from replicas it does not trust
860
+ checks those against its own Kit before committing them.
861
+ - A selection travels as anchors (`translate`'s `selection`, or `anchor(state, selection)`),
862
+ and `resolve` places it again after other replicas' ops: after the same character, or the
863
+ nearest one before it still shown.
864
+ - Two replicas' concurrent inserts at one place both survive, the later-committed first.
865
+ A mark covers the characters it named, so text another replica typed inside the range
866
+ before the mark arrived stays unmarked.
867
+ - A `Collect` op removes deleted text, in two phases so a deletion is kept for one whole
868
+ interval: each removes what the previous one found deleted, then marks what is deleted
869
+ now. Commit it through the log like any op, so every replica removes the same text at
870
+ the same point. An op made by a replica offline across two collections, anchored on
871
+ removed text, takes the lost-anchor fallback, and an undo from before then finds less to
872
+ restore. An insert keeps one deleted character at its end, so its indexes are never
873
+ reused. Block records stay; only their text goes.
874
+ - `invert(state, ops)` gives the ops that undo `ops`, computed against `state`, the state
875
+ `ops` were applied to. Applied later, after anything else, they take back only what
876
+ `ops` did:
877
+ - characters it inserted are deleted, and characters it deleted come back
878
+ (`Undelete`);
879
+ - marks, block types and props return to what they were;
880
+ - a split is joined, and a join is split out again (`Unjoin`), with its text and
881
+ nested blocks;
882
+ - a deleted block returns (`UndeleteBlock`), and a moved one goes back beside the
883
+ sibling it followed.
884
+
885
+ Everyone else's edits stay. Collaborative undo is applying these as a new edit, which
886
+ converges like any other. The text an undone split joins back goes at the end of the
887
+ first half as it is then (a `Join` with `at: 'end'`), so what was typed there since stays
888
+ before it: split `ab` at its start, type `x` in the empty first half, and undoing the
889
+ split gives `xab`. A redone join goes right after the character its text followed, or at
890
+ the block's end when its text ended the block. A restored mark goes last among its run's marks,
891
+ whose order carries no meaning. A prop an edit added where there was none stays, since `SetProps`
892
+ cannot delete one. Inverting the inverse, against the state it was applied to, gives
893
+ the redo.
894
+
895
+ Run identities in the projection are the first character's, so they are stable while
896
+ text is added after them; block identities are stable for a block's whole life.
487
897
 
488
898
  ## Current semantics
489
899
 
@@ -540,9 +950,14 @@ not yet drive parsing or `apply`.
540
950
  the same index is a no-op. Run identities and selections are untouched, so no
541
951
  position steps are emitted. An optional `parent` moves it into a node block's
542
952
  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.
953
+ - `RetypeBlock` changes the type of a block whose content is its runs — to a paragraph,
954
+ a heading at a level, or a node kind with props (`RetypeTarget`) — keeping its run
955
+ values and identities. A node block holding nested blocks retypes only to another node
956
+ kind, keeping them. Same-shape sets are no-ops; retyping such a block to a paragraph or
957
+ heading, or retyping preserved content, is refused (`InvalidRange`).
958
+ - `SetProps` sets the props it names on a node block and keeps the others. Setting a
959
+ prop to the value it has is a no-op; a text block or preserved content is refused
960
+ (`InvalidRange`). Props cannot be deleted, only set.
546
961
  - `InsertNode` splices a caller-built block at an explicit index, or into a node
547
962
  block's nested blocks when `parent` is given; every carried identity must be
548
963
  fresh within the transaction. Positions need no mapping (they address runs, not
@@ -603,12 +1018,14 @@ into an application's Model; when decoding them directly, pass
603
1018
 
604
1019
  `apply` does not enforce limits: size-check untrusted operation payloads
605
1020
  (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.
1021
+ decoding untrusted payloads. `Replicated` is the pure core of collaboration;
1022
+ `examples/pages` wires it to `foldkit-sync` and `foldkit-durable`. Retain rejected
1023
+ source content for recovery; do not replace it with an empty document.
1024
+
1025
+ A transaction validates only the top-level blocks it has not seen validated before,
1026
+ so a container is checked again whenever anything inside it changes, and indexes its
1027
+ text runs. Edits copy the affected arrays and preserve untouched nodes. The
1028
+ performance section records the measured cases, the collaborative path included
1029
+ (`bench/replicated.bench.ts`).
613
1030
 
614
1031
  See the [design and phase status](../../docs/design/richtext-DESIGN.md#101-phase-1--pure-semantics-and-integration-feasibility).