Rich text / foldkit-richtext

richtext

Storing raw contenteditable HTML strings couples saved content to browser quirks, loses node identities across edits, and breaks structured validation or concurrent collaboration. You want a document format that lives in application state as plain versioned data while edits remain deterministic and reversible.

foldkit-richtext models rich text as an immutable tree of blocks and runs with caller-supplied IDs. Each edit takes a state ({ document, selection }) and returns the next state, a mapped selection, and a ChangeSet naming what changed. Browser editing lives in foldkit-richtext-dom. See it running in the rich-text playground and collaborative pages.

Install

bash
pnpm add foldkit-richtext effect

A first edit

Build a validated paragraph document and insert text into it with RichText.apply:

ts
import * as RichText from 'foldkit-richtext'

const Text = RichText.Node.make('text-1')
const paragraph = RichText.Paragraph.make({
  type: 'Paragraph',
  id: RichText.NodeId.make('paragraph-1'),
  children: [RichText.Text.make({
    type: 'Text',
    id: Text.id,
    text: 'Hello',
    marks: ['Bold'],
  })],
})
const document = RichText.Document.make({ version: 1, children: [paragraph] })
const result = RichText.apply({ document, selection: null }, [
  RichText.Edit.insertText(Text.at(5, 'after'), '!'),
])

if (result.ok) {
  // result.state.document holds "Hello!" and result.changeSet marks text-1 dirty.
  const editedDocument = result.state.document
  void editedDocument
}

Your application Model owns the Document and local Selection, calling apply or run from update as pure state transitions. apply validates the input state and runs operations in array order: if any operation fails, the whole transaction returns { ok: false, error } with a stable diagnostic code and leaves the original state untouched. Schema constructors validate structure immediately, and node IDs must be unique across all blocks and text runs in a document.