Skip to content

How to design a rich text editor (frontend)

The first sections are free. The deep dives, level expectations and quiz are part of Pro.

On this page
Asked at
  • Sigma Computing
Practice this question

The problem

A rich text editor for the web: bold, lists, links and headings, pasting from other apps, undo and redo, and saving what was written. The answer turns on where the truth lives. The editor keeps its own document, a tree of blocks whose text is a flat sequence of runs carrying marks, and draws the editable area from it; the browser keeps what it is good at, which is typing, the caret, spell check and input methods, and each edit becomes a small, invertible step in the document: the editor applies the edits it can cancel itself, and reads back the few it cannot. That one decision is what makes paste, undo and saving behave in a document of 10,000 blocks.

Clarifying questions

AskWhy it mattersA typical answer

Is one person editing a document at a time, or several at once?

Two people at once turns each edit into an operation that has to merge with someone else's, and undo into a per-person history. That is a different round.

One person at a time. Several people editing at once is out of scope; be ready to say what would change if it were added.

Which formats must it support, and which may it refuse?

The set of block types and marks is the schema. Tables and images change the model and the paste path far more than another mark does.

Bold, italic, links, headings and lists. Tables, embedded media, comments in the margin and spell check beyond the browser's are out.

Who reads what we save, and does it have to reopen exactly as written?

If other parts of the product render the saved document, the saved form is a contract. Exact reopening rules out saving whatever markup the browser happened to write.

Other parts of the product show it, and it must open again exactly as it was. The server offers GET and PUT on a document with a version.

Where does pasted content come from, and how much of its formatting should survive?

Content copied out of a word processor or a web page carries inline styles, images and sometimes scripts. The answer decides between an allow-list and plain text.

From other apps and web pages. Keep the formatting the editor supports, drop the rest, and nothing unsafe may reach the page.

How large can a document get, and what are the speed targets?

The size decides whether a keystroke may touch the whole document, and the targets decide how much work fits in a frame and in a click.

Documents of up to 10,000 blocks. The editor's own work on a keystroke stays under 10 milliseconds of the frame, a toolbar click answers within 200 milliseconds, and undo keeps 100 events, each one a grouped change rather than a single step.

Which languages and assistive tools must keep working?

The editable surface the browser provides is what supplies input methods, spelling correction, screen reader support and touch keyboards. Replacing it means rebuilding them.

Any language, Japanese through an input method included. Spell check, screen readers and touch keep working inside the editor.

May I build on an existing editor library?

Naming a library can be a building block or a way to skip the design. Saying which you mean avoids the wrong reading.

Yes, as a building block. You still have to explain the document model, how typing reaches it, how paste is cleaned and how undo works.

The requirements menu

RequirementScopeWhy

Format text: bold, italic, links, headings and lists

Core

These are the marks and block types the schema must name; everything else in the design is built around them.

Paste content copied from other apps and web pages, keeping the formatting the editor supports

Core

Paste is the path on which formatted content from outside arrives, and it is the one that brings untrusted markup into the page.

Undo and redo every change, formatting and pastes included

Core

People rely on undo to recover from a bad paste or a wrong format, and the browser's own undo does not know about the editor's changes.

Save what was written and open it again exactly as it was

Core

The saved form is a contract with the rest of the product, which is why it has to be the editor's own document rather than whatever markup the browser wrote.

Accept typing in any language, input methods for scripts such as Japanese included

Core

Input methods decide how much of typing the editor may take over: a composition in progress has to be left to the browser.

Keyboard shortcuts for formatting, such as Ctrl+B for bold

Optional

Take it if there is time: it is one keymap that dispatches the same commands the toolbar does, and it shows the commands are separate from the buttons. Leave it if the core paths are not done.

Markdown-style shortcuts, such as a hash and a space turning a paragraph into a heading

Optional

Take it for a product whose users already write Markdown. It is an input rule that rewrites one block on a matching keystroke. Leave it for a general editor, where a hash at the start of a line may be meant literally.

Autosave while typing, with a saved or unsaved indicator

Optional

Take it if people write for a long time without saving. It needs a debounce off the keystroke path and a version check on the server. Leave it if an explicit save button meets the product.

Export the document as HTML or Markdown

Optional

Take it if other systems need the content. It is a one-way rendering from the model, not a second source of truth. Leave it if the product's own pages render the model directly.

Drag a block to reorder it

Out of scope

It is a block-level move on the tree plus a drop target in the page. Good to mention as a natural extension of the block model, but it crowds out typing and paste in a short round.

Several people editing at once

Out of scope

It turns transactions into operations that must merge and gives each person their own undo history. Name it as the follow-on question, not part of today's design.

Comments and suggestions in the margin

Out of scope

Comments anchor into the text and have to move whenever earlier text changes. A good design leaves room for it by keeping positions in the document, but it is its own feature.

Tables and embedded media

Out of scope

Tables add nested block structure and a selection model of their own; media adds uploads. Both widen the schema and the paste path beyond what this round covers.

Spell check beyond what the browser gives

Out of scope

The browser's spell check keeps working inside the editable area for free. A custom one needs its own underline rendering and a dictionary service.

Non-functional requirements

RequirementWhat it forces

A keystroke shows in the same frame, the editor's own work under 10 milliseconds

A display refreshing 60 times a second gives each frame about 16.66 milliseconds, and the browser needs part of that, which is where the 10 milliseconds for the page's own work comes from. So typing itself is usually left to the browser, which inserts the letter into the page without the editor's code in the way; the editor's work on a key is to turn the change into a step that touches one block and to redraw that block. Parsing or serializing the whole document on the key path is ruled out.

A click on a toolbar button answers within 200 milliseconds

Interaction to Next Paint measures from the click to the next frame, with 200 milliseconds or less counted as good. A format command builds one transaction over the selection and redraws the blocks it touched, so a bold over a long selection, or a large paste, has to be bounded work or show a pending state rather than block the frame.

Pasted content never runs a script or carries unsafe markup into the page

The editor takes over the paste event, reads the clipboard data itself, cleans the HTML with a sanitizer that permits a short set of safe tags and the attributes they need, while it is still off the page, maps it onto the schema, and inserts the result through a transaction. Nothing from the clipboard is written into the live page as markup.

Spell check, screen readers and touch keep working inside the editor

The editing surface stays a contenteditable element, since these come with it and would have to be rebuilt in a surface the editor draws itself. The editor must not redraw a node under an active input method composition, and the cursor it writes back to the page has to match what the person left, or the browser's own features fight the editor.

Core entities

EntityWhat it holds

Document

The saved unit: a versioned tree of blocks the editor renders and the server stores.

Block

One node of the tree: a paragraph, heading, list or list item with its own attributes and content.

Inline text

A run of characters inside a textblock, carrying the set of marks that apply to all of it.

Selection

Where the cursor or highlight is, held as positions in the document rather than as nodes in the page.

History

The undo and redo stacks: for each event, the steps that made it and the steps that reverse it.

The API

EndpointNotes

GET /documents/{id} → { id, version, content }

Loads the editor's own JSON, not HTML. The editor parses it against the schema; a block type it does not register has to be handled rather than dropped in silence. The version comes back so the next save can name what it was based on.

PUT /documents/{id} { content, base_version } → { version }

Saves the model as JSON. In this design the server compares base_version with its current version and refuses a save built on an older one, so a stale tab does not overwrite a newer save. The error body is a choice to state out loud; we'd have the editor keep its state and offer a reload.

Editor props: initial content, read only, the formats it allows, onChange(content)

Initial content is applied one time, when the editor is constructed; later changes go through commands. In this design the allowed formats decide which marks and block types the schema registers, so a product that wants no headings gets a schema without them. We'd call onChange with the model after a transaction is applied, and whoever wires it to the server would debounce the saves.

Editor commands: toggleMark(bold), setBlock(heading, level), insertLink(url), undo(), redo()

In this design each command builds a transaction from the current selection and dispatches it; the toolbar and the keyboard shortcuts call the same functions. undo() and redo() go through the editor's history, not the browser's.

The high-level design

JSONinnerHTMLEditable areaEditor stateServer

Step 1 of 5

An editable area that is its own document

Start with the obvious build: a contenteditable element, a toolbar that calls the browser's formatting commands, and a save that reads the area's HTML and sends it to the server. It shows the data flow end to end, and it already has the problem the rest of the design answers: the page's markup is the document, so a bold word is stored however the browser chose to write it, and each save serializes the whole area.

beforeinputmutationpaste eventknown edits asstepsdifference asstepsschema-fittedstepschecksnew snapshotsteps andinversesinversetransactionchanged node,selectionJSON withversionloadKeys, inputmethod, toolbarEditable areaInput handlerChange readerPaste cleanerTransactionSchemaEditor stateHistoryServer
The whole design

What breaks first

The deep dives

How formatted text is stored. Walk through how your editor holds one paragraph that has a bold word and a link, field by field, and what it sends to the server when the document has grown to thousands of blocks.

A concept that helps here: Rich text document modelsA concept that helps here: Where state lives

Typing and selection, beside the browser's own editing. Someone types Japanese with an input method in the middle of a bold phrase, and a spell-check fix lands on the next word. What does your editor do with each key, and where is the cursor when it is done?

A concept that helps here: Rich text document modelsA concept that helps here: Core Web Vitals

Pasting from anywhere, safely. Someone copies half a web page, with inline styles, images and a hidden script tag, and pastes it into the middle of a bulleted list. What lands in the document, what is dropped, and what does one undo remove?

A concept that helps here: Rich text document models

Undo and redo. Someone types a sentence, makes one word bold, pastes a paragraph, then presses undo three times in a row. What do they see after each press, and what does your editor keep to make that happen?

A concept that helps here: Undo and redoA concept that helps here: Rich text document models

Concepts this guide uses

Sources

  1. ProseMirror guide
  2. ProseMirror reference manual
  3. Lexical: Editor state
  4. Lexical: Compared with ProseMirror
  5. MDN: Element beforeinput event
  6. MDN: InputEvent getTargetRanges()
  7. MDN: Element paste event
  8. DOMPurify README
  9. CKEditor blog: ContentEditable, the good, the bad and the ugly
  10. web.dev: Rendering performance
  11. web.dev: Interaction to Next Paint (INP)
  12. techinterview.org: Frontend system design, a Notion-style block editor
Sign in to report a mistake