Skip to content

Rich text document models

A rich text editor keeps its own document, a tree of blocks holding marked text runs or a flat list of operations, and paints it into the editable DOM. Edits become described changes that drive rendering, undo and collaboration.

On this page

What it is

A rich text document model is the editor's own description of the content: which blocks exist and in what order, what text each holds, and how that text is formatted. The editable element on screen is a rendering of that model, not the source of truth. The older approach left the browser in charge. contenteditable is an enumerated attribute that makes an element editable and hands the editing widget to the browser, and pasting into a contenteditable="true" element keeps whatever formatting the clipboard carried. Quill's design notes describe that generation of editors as passing HTML to the application and leaving it to work out what the markup meant, with results that differed between browser vendors.

Two shapes are worth knowing. A tree has a root, container nodes (paragraph, quote, list item) and leaf text nodes. Slate's documentation describes this Editor, Element and Text hierarchy and names mirroring the DOM as one of its principles, with elements nesting to any depth so that tables or figures with captions can be modeled. A flat list of operations describes the document as the changes that would build it from an empty one: a Quill Delta is a JSON object whose ops array holds insert operations, each with optional attributes, where an embed such as an image is an object that counts as length one.

The main place these models part from HTML is inline formatting. HTML nests a strong element inside a paragraph and an emphasis element inside the strong one. ProseMirror instead stores a paragraph's inline content as a flat sequence of text nodes with marks attached as metadata. That lets a position inside a paragraph be a character offset rather than a path into a tree, and makes splitting or restyling a range arithmetic instead of tree surgery. It also gives each document a single valid form: neighboring text nodes with equal marks are merged, empty text nodes are disallowed, and the schema fixes the order in which marks appear. The flat operation list reaches a single form another way: a Delta must be compact and canonical, so two equal Deltas describe equal content and a deep compare tells you whether two documents match.

ts
// Illustrative only: the same paragraph in two shapes.
// "Hello world" with "world" in bold, centered.

// 1. A tree: blocks hold runs of text; formatting is a property on the run.
const tree = {
  type: 'doc',
  children: [
    {
      type: 'paragraph',
      align: 'center',
      children: [
        { text: 'Hello ' },
        { text: 'world', bold: true },
      ],
    },
  ],
};

// 2. A flat list of operations. The line's format rides on its newline.
const delta = [
  { insert: 'Hello ' },
  { insert: 'world', attributes: { bold: true } },
  { insert: '\n', attributes: { align: 'center' } },
];

// A change in the same vocabulary, applied to the plain "Hello world":
// skip 6 characters, then bold the next 5.
const change = [
  { retain: 6 },
  { retain: 5, attributes: { bold: true } },
];

Addressing matters because the selection, the cursor and each change need to say where. One convention gives each document position an integer: 0 is before the first content, stepping into or out of a node that holds content counts one, each character counts one, and a leaf such as an image counts one, so a document holding a single paragraph with the text One has positions 0 through 5. In a flat operation list the index is the count of characters and embeds before the point, which is why embeds are fixed at length one and why a Delta is required to end with a newline: each line then has a character to carry its block-level attributes, and deleting a newline has a defined meaning.

Edits are described, not performed in place. In ProseMirror nodes are values: an update yields a new document that shares its unchanged sub-nodes with the old one, and each update is a transaction built from steps such as ReplaceStep or AddMarkStep. A step applies to a document to produce a new one, and applying it can fail when the result would not fit the schema. The trail of steps is what the rest of the editor builds on: the undo history stores them and applies their inverses, the collaboration module sends them to other editors and reorders them when needed, and plugins inspect each one to keep their own state current. Lexical describes the same idea at the level of whole states: a current editor state is what you see on screen, a pending one is being built, there are at most two at a time, and when the pending state is ready it swaps in and reconciliation patches the DOM.

Input still arrives through the browser's editable element rather than through the model, so the editor has to turn what the browser did, or wants to do, into a change against its own document and then bring the DOM back in line with the result. Lexical, for instance, watches its editor element with DOM mutation observers and either reverts an outside change to the current state or reads it as an intent that becomes a further update.

When to use it

Reach for an explicit model as soon as the editor needs anything beyond showing what the browser produced: formats with rules (a heading that allows no bold, a link that must not sit inside another link), custom nodes such as mentions, embeds or tables, dependable undo, saving to a format other than HTML, or more than one person editing at once. A schema carries the rules: it declares which node types may occur and how they nest, which marks each node allows (a heading can allow none while a paragraph allows all), and, in the simplest setup, how each node renders through a toDOM entry on its spec. Slate's node model adds a block-or-inline flow to each element, treats void elements such as images as uneditable boxes, and inserts empty text nodes around inline elements during normalization so that an inline is not the first or last child of its block.

Pick the tree when the content has structure: nested lists, tables, figures with captions, blocks that carry attributes. Pick a flat operation list when the content is mostly lines of styled text and you want a document and a change to share one format. A document is then the set of inserts that build it from nothing; a change against a live document uses retain to skip over content, insert to add and delete to remove, and a retain that carries attributes is how a format change is written, with null as the value that removes a format.

Plan for one valid shape from the start. Decide which normalization runs after each change (merge adjacent runs with equal formatting, remove empty text, fill in required children) and run it before anything else sees the document. The reason is practical: without it two documents with the same content compare as different, and consumers such as diffing and collaboration have more variants to handle.

When not to

A comment box, a chat message or a short form field does not need a document model. A textarea, or contenteditable="plaintext-only", which edits the raw text and removes formatting from anything pasted in, gives you a plain string, and we'd store that as it is.

If the content comes from trusted authors and is displayed but not edited after publication, store the markup you render; a model earns its cost when content is edited over time, diffed, merged or exported to several formats. Markdown in a plain text box is the lighter answer when the audience is comfortable with it: the model is the string and a position is an index into it.

Compared

ModelShapeReach for it whenWhat it costs

Browser-owned contenteditable

The DOM is the document; the browser edits it and a paste keeps its source formatting

A small editable region where any markup is acceptable and nothing reads the content back

Markup differs by browser; positions live in the DOM rather than in a model you control; undo and collaboration are harder to build without a stable unit of change

Plain text (textarea or plaintext-only)

A string

Comments, chat, Markdown authoring

No inline formatting beyond what a text markup language gives

Tree with marks (ProseMirror, Slate)

Root, container nodes, text runs with formatting as marks or properties

Nested structure: lists, tables, captions, custom nodes with attributes

Tree positions need a convention such as integer tokens

Flat operations (Quill Delta)

An object whose ops array holds insert, retain and delete operations with attributes; line formats on the newline

Line-oriented styled text; one format for both document and change

Nesting beyond lines is harder to express; an embed is length one, so there are no partial edits inside it

In a picture

Types b afterHelloEditable element

Step 1 of 4

The browser reports an edit

Someone types a letter inside the editable element. The browser's widget handles the keystroke; the editor is told, through the DOM, that something changed or is about to.

How to say it in an interview

The common mistake

Quiz

Why do tree editors store bold as a mark on a text run rather than as a nested node?
In a flat operation list, where does a centered line's alignment live?
An editor records each edit as a step and applies it to produce a new document. What does that trail of steps make possible beyond rendering?
Two documents both hold the bold text 'ab', but one stores it as two bold runs, 'a' and 'b'. What rule stops this from happening?

Related

Sources

  1. ProseMirror Guide
  2. Quill: Designing the Delta Format
  3. Slate documentation: Nodes
  4. Lexical's Design
  5. MDN: contenteditable HTML global attribute
Sign in to report a mistake