Rich text / foldkit-richtext-dom

richtext-dom

Rebuilding a contenteditable element on every keystroke through a virtual DOM fights the browser's typing, selection, IME composition, and clipboard handling. You want your application state to stay the single source of truth while only the changed DOM nodes update in place.

foldkit-richtext-dom bridges foldkit-richtext documents and the browser DOM. It mounts a real contenteditable subtree once, converts user input into Foldkit Messages (events sent to your update function), and patches only the nodes named by each edit's ChangeSet. Your application owns the document in its Model (your app's state) and draws any surrounding toolbars or menus. See the editor running in the rich-text playground.

Install

bash
pnpm add foldkit-richtext-dom foldkit-richtext foldkit-bundle foldkit effect

A first editor on a page

Place an editor Bundle (a self-contained unit of state, update, and view) on a page, decode an initial document, and embed the runtime:

ts
import { Bundle } from 'foldkit-bundle'
import * as RichText from 'foldkit-richtext'
import * as Runtime from 'foldkit/runtime'
import { editorAt, Model, type ParentMessage } from 'foldkit-richtext-dom/editor-bundle'

const body = editorAt('body', {
  rendering: RichText.standardRendering,
  vocabulary: {
    marks: RichText.markRegistry(RichText.standardMarks),
    nodes: RichText.nodeRegistry(RichText.standardNodes),
  },
  placeholder: 'Write something…',
})
const app = Bundle.assemble<Model, ParentMessage>()([body])
const document = RichText.decodeDocument({
  version: 1,
  children: [{ type: 'Paragraph', id: 'p', children: [{ type: 'Text', id: 't', text: 'Hello', marks: [] }] }],
})

Runtime.embed(
  Runtime.makeElement({
    Model,
    container: window.document.getElementById('app')!,
    init: () => app.initial({ document }),
    update: app.update(),
    view: (model, h) => h.main([], [body.view(model, h)]),
  }),
)

When embedded, body.view renders <foldkit-richtext id="body"> showing "Hello" inside a paragraph. Typing or pressing shortcuts dispatches Messages to update, which validates the edit against vocabulary, stores the new document in model.document, and returns a Command that patches only the changed DOM nodes.

Three boundaries keep state predictable:

  • Your application owns model.document and all chrome around the editor (toolbars, menus, handles).
  • foldkit-richtext-dom owns the <foldkit-richtext> subtree, converting browser events into Messages and syncing DOM selections back to positions.
  • foldkit-richtext owns the pure document codec, commands, and validation.

editorAt(hostId, placement) registers rendering and vocabulary rules under hostId without performing I/O or rendering yet. Model holds { document, editor } where editor tracks selection, stored marks, undo history, and the slash menu index. Because the document is never read back from the DOM, unsupported browser edits are prevented before they mutate the tree.