Rich Text Editor — Front-End System Design for a WYSIWYG Composer
A deep dive into designing a single-user rich text editor with a formatting toolbar, undo/redo, image embeds, mentions, and code blocks with syntax highlighting — the foundation every collaborative editor is built on.
FrontendX Engineering · System Design Series
0. What Are We Building?
A rich text editor — the kind Medium uses for its story composer, the Gmail compose window, or the content area of a CMS. A single user edits text, applies formatting (bold, italic, headings), embeds images, tags colleagues with @mentions, and writes code snippets with syntax highlighting.
This is not a collaborative editor. No CRDTs, no WebSocket sync, no cursor awareness. We are building the foundation — the single-player mode that every collaborative editor starts as before the networking layer is added. If you can not build a solid single-user editor, the collaboration layer has no hope of working.
Key Insight
The rich text editor is one of the most deceptively hard UI challenges in frontend engineering. A textarea is a few lines of HTML. A rich text editor with bold, italic, images, and undo is a months-long project. Browsers give us contenteditable, which looks like a shortcut — but it is actually a trap that has swallowed countless engineering teams.
1. Requirements & Scoping
Let us scope the editor. We are not building Google Docs — we are building a focused, single-user WYSIWYG composer for long-form content.
Accessibility: WCAG 2.1 AA — toolbar keyboard navigation, ARIA roles
Out of Scope
No real-time collaboration, no comments or suggestions, no version history, no offline support, no drag-and-drop block reordering. We are deliberately restricting scope to the single-user editing surface. Collaboration is a separate system design problem (covered in the Collaborative Text Editor article).
Tip
If you are interviewing, do not try to solve both the editor and the collaboration layer at once. Focus on the editor foundation first — the data model, the formatting pipeline, and the undo stack. Those are the hard parts. The networking layer is a separate system on top.
2. Architecture — contenteditable vs Framework
The number one decision in any rich text editor is: do we use raw contenteditable or a framework like ProseMirror, Slate, or Lexical? This single choice determines your development speed, bug count, and cross-browser compatibility for the entire project.
Raw contenteditable gives full control but enormous complexity. Framework-based editors trade bundle size for a predictable, cross-browser document model
The contenteditable Trap
contenteditable looks perfect on paper. It is a native browser feature — zero dependencies, full WYSIWYG out of the box. In practice, every browser implements it differently. The same keystroke produces different HTML in Chrome vs Firefox vs Safari. The Selection API is inconsistent across browsers. IME composition for CJK languages behaves differently. There is no standard data model — just whatever HTML the browser decides to produce.
Teams that go the raw contenteditable route inevitably end up building their own abstraction layer on top of it — which is exactly what ProseMirror, Slate, and Lexical already are, but battle-tested and maintained by people who have spent years on the problem.
Framework Comparison
Feature
ProseMirror
Slate
Lexical
Data Model
Schema-driven tree
JSON-like nested tree
Immutable node tree (React-like)
Framework
Framework-agnostic (React/Vue via wrappers)
React-first
Framework-agnostic (React bindings)
Collaboration
First-class (prosemirror-collab)
Community plugins
Built-in collaboration primitives
Plugin Ecosystem
Mature, large ecosystem
Moderate
Growing, official plugins
Bundle Size
~50KB gzipped (core + basic schema)
~35KB gzipped
~25KB gzipped (core)
Learning curve
Steep (schema, transform, state)
Moderate
Moderate (React-like mental model)
Decision: Lexical
For this design, we choose Lexical (Meta's open source editor framework). Why? It is the modern choice — built with an immutable node tree that mirrors React's mental model, it has a smaller core bundle than ProseMirror, and it provides first-class primitives for undo/redo, selection, and collaboration if we ever want to add it later. The tree-based document model maps naturally to the node types we need (headings, paragraphs, code blocks, mentions).
Key Insight
If you are in a React codebase and starting fresh, Lexical is the right call. If you need mature collaboration with OT and a battle-tested ecosystem, ProseMirror (+ TipTap) is safer. If you are building a block-based editor like Notion, Slate's nested structure is more natural. There is no universal winner — it depends on your constraints.
3. Data Model — Immutable Node Tree
The document model is the foundation of every editor. In Lexical, every document is an immutable tree of nodes. Each node has a type, properties, and children. The tree is never mutated — every edit produces a new tree.
// Lexical node types for our editor
const EDITOR_NODES = [
RootNode,
ParagraphNode,
HeadingNode, // h1, h2, h3
TextNode, // text with marks
ListNode, // bullet + ordered
ListItemNode,
QuoteNode,
CodeNode, // code block with language
ImageNode, // inline image
MentionNode, // @mention pill
AutocompleteNode,
];
// Text formatting is handled by TupleMark (not separate nodes):
interface TextFormat {
bold?: boolean;
italic?: boolean;
underline?: boolean;
strikethrough?: boolean;
code?: boolean;
link?: string; // URL if this text is a link
fontSize?: number; // for headings
}
// Serialized document format (JSON):
interface SerializedDocument {
root: {
children: SerializedNode[];
direction: "ltr" | "rtl" | null;
format: "left" | "right" | "center" | "justify";
};
}
interface SerializedNode {
type: string; // "paragraph" | "heading" | "code" etc.
children?: SerializedNode[];
format?: number; // bitmask for text formatting
detail?: number;
mode?: "normal" | "token" | "segmented";
style?: string;
text?: string;
value?: string;
// Type-specific fields:
tag?: "h1" | "h2" | "h3"; // for HeadingNode
language?: string; // for CodeNode
src?: string; // for ImageNode
alt?: string; // for ImageNode
mentionName?: string; // for MentionNode
}
Note
Lexical uses a bitmask for text formatting rather than separate mark nodes. Bits 1=bold, 2=italic, 4=underline, 8=strikethrough, 16=code, 32=superscript, 64=subscript. This makes format toggling a simple XOR operation on the bitmask. A bold+italic text node has format bits 1|2 = 3.
Why Not HTML?
You might wonder: why not just store the document as HTML? Because HTML is terrible as a data model. The same visual output can be represented in dozens of different HTML structures. A bold word might be <strong>, <b>, or <span style="font-weight:bold"> depending on browser, paste source, and editor history. A JSON tree eliminates this ambiguity — one document, one canonical representation. HTML becomes a serialization format, not the data model.
Block vs Inline
The document tree distinguishes block nodes (paragraph, heading, list, code block, quote) from inline content (text, mention placeholder, line break). Block nodes are top-level children of the root. Inline nodes are nested inside block nodes. This distinction is enforced by the Lexical schema — a text node cannot be a direct child of the root.
4. Plugin Architecture
Lexical's power comes from its plugin architecture. Everything is a plugin — the toolbar, the history stack, image handling, mentions, code highlighting. The core editor provides the node tree, selection model, and command system. Plugins register node types, listen to commands, and add UI components.
Plugin architecture — each plugin registers node types, command listeners, and UI components; the core editor provides the framework for coordination
Plugin Contract
Each plugin follows a simple contract: register node types, register command listeners, and optionally render React components in the editor UI. The core editor manages execution order — plugins cannot interfere with each other's nodes.
The formatting pipeline translates user intent — clicking "Bold" or pressing Ctrl+B — into a change in the document tree. This is the most frequently executed code path in the editor and must be fast.
Formatting pipeline — toolbar click triggers a format command, the editor checks selection state, transforms the node tree, and patches the DOM
Toolbar Architecture
The toolbar is a floating or fixed bar above the editor containing format buttons. Each button dispatches a format command when clicked. The toolbar is selection-aware— it reads the current selection's formatting state and highlights active buttons. If the cursor is inside a bold word, the Bold button is highlighted.
// Toolbar component — selection-aware format buttons
function ToolbarPlugin() {
const [editor] = useLexicalComposerContext();
const [activeFormats, setActiveFormats] = useState<Set<string>>(new Set());
useEffect(() => {
// Update toolbar state on every selection change
return editor.registerUpdateListener(({ editorState }) => {
editorState.read(() => {
const selection = $getSelection();
if (!$isRangeSelection(selection)) return;
const formats = new Set<string>();
if (selection.hasFormat("bold")) formats.add("bold");
if (selection.hasFormat("italic")) formats.add("italic");
if (selection.hasFormat("underline")) formats.add("underline");
if (selection.hasFormat("strikethrough")) formats.add("strikethrough");
if (selection.hasFormat("code")) formats.add("code");
setActiveFormats(formats);
});
});
}, [editor]);
return (
<div className="toolbar" role="toolbar" aria-label="Text formatting">
<ToolbarButton
format="bold"
icon={BoldIcon}
active={activeFormats.has("bold")}
shortcut="Ctrl+B"
/>
<ToolbarButton
format="italic"
icon={ItalicIcon}
active={activeFormats.has("italic")}
shortcut="Ctrl+I"
/>
<Separator />
<ToolbarButton
format="h1"
icon={H1Icon}
active={blockType === "h1"}
action={() => $toggleHeading("h1")}
/>
<Separator />
<ToolbarButton
format="image"
icon={ImageIcon}
action={() => openImageUpload()}
/>
</div>
);
}
// Each button dispatches a format command:
function ToolbarButton({ format, icon, active, shortcut }: ToolbarButtonProps) {
const [editor] = useLexicalComposerContext();
const handleClick = () => {
editor.dispatchCommand(FORMAT_TEXT_COMMAND, format);
};
return (
<button
onClick={handleClick}
aria-pressed={active}
aria-label={\`\\${format} (\\${shortcut})\`}
style={{
background: active ? "var(--fx-surface-selected)" : "transparent",
fontWeight: format === "bold" ? 700 : 400,
}}
>
{icon}
</button>
);
}
Keyboard Shortcuts
Lexical registers default keyboard shortcuts for common formatting actions (Ctrl+B for bold, Ctrl+I for italic, etc.). We also register editor-specific shortcuts: Tab to indent list items, Shift+Tab to outdent, and Ctrl+Shift+F to open the formatting menu. Each shortcut dispatches the same command as the corresponding toolbar button — the formatting pipeline is identical regardless of input method.
Note
Do not hardcode keyboard shortcuts by listening to raw keydown events. Use Lexical's command system. This ensures consistency — the same command handler runs whether the user clicked a toolbar button, pressed a keyboard shortcut, or triggered a format change programmatically. It also makes the editor extensible: a plugin can override or add shortcuts by registering the same command with a different priority.
6. Text Styling — Marks & Nodes
Rich text inside a block is styled through marks — lightweight formatting annotations that apply to text ranges. Marks are not nodes; they are properties on a TextNode. A single TextNode can carry multiple marks: bold + italic + code, for example.
Mark Application Semantics
When a user selects text and clicks "Bold", the editor applies the bold mark to the selected range. If the selection spans multiple TextNodes, each TextNode in the range gets the mark. If part of a TextNode is selected, the TextNode is split — the selected portion becomes a separate TextNode with the mark applied.
// Before: one TextNode, no formatting
// "Hello World" — TextNode { text: "Hello World", format: 0 }
// Select "World", click Bold:
// "Hello " — TextNode { text: "Hello ", format: 0 }
// "World" — TextNode { text: "World", format: 1 } // bold bit set
// Lexical does this split automatically via $splitNodeAtSelection
// Format toggle behavior:
// Clicking Bold again on "World" toggles format to 0 (unbolded).
// This is a bitwise XOR on the format mask:
function toggleFormat(currentFormat: number, formatBit: number): number {
return currentFormat ^ formatBit;
}
// When the selection is empty (cursor only),
// the editor enters "format mode" — the next typed character
// will have the mark applied. Undo removes the mark + the character.
Serialization to HTML
// Export handler: Lexical node tree → HTML
function exportToHtml(editorState: EditorState): string {
let html = "";
editorState.read(() => {
const root = $getRoot();
html = root.getTextContent(); // simplified — real handler walks tree
});
return html;
}
// Import handler: HTML → Lexical node tree
// Paste handler strips non-allowlisted tags via DOMPurify, then
// converts the sanitized HTML into the node tree.
// Example mapping:
// <strong>text</strong> → TextNode format={BOLD_BIT}
// <h1>text</h1> → HeadingNode { tag: "h1", children: [TextNode] }
// <ul><li>item</li></ul> → ListNode → ListItemNode → ParagraphNode → TextNode
Tip
The paste handler is the most security-critical code in the editor. Users paste from Word, Google Docs, web pages — all of which inject arbitrary HTML with inline styles, custom CSS classes, and potentially malicious script tags. Always run pasted content through DOMPurify before importing into the editor. Lexical's paste plugin does this by default, but configure it restrictively.
7. Undo/Redo — History Stack
Undo/redo is the feature users notice most when it breaks. A broken undo stack is the hallmark of a poorly implemented editor. Lexical's history plugin manages this for us, but understanding how it works is essential.
Undo/redo stack — editor states pushed on each mutation; continuous typing is coalesced into a single undo step, while explicit mark boundaries create separate entries
Stack of States
The history stack stores snapshots of the EditorState — not operations (deltas) or inverse operations. Each time the user makes a change, the current state is pushed onto the undo stack. Ctrl+Z pops the stack and restores the previous state. This is simpler and more reliable than operation-based undo because you never need to compute inverse operations — you just restore a snapshot.
Coalescing
If we pushed a state on every keystroke, a user typing a paragraph would need 50+ Ctrl+Z presses to undo it.Coalescing merges adjacent changes within a time window (default: 500ms) into a single undo step. While the user is typing continuously, new states replace the most recent undo entry instead of adding a new one. The undo boundary is marked when typing pauses, or when a non-text change happens (like applying bold or inserting an image).
// History stack with coalescing (simplified)
class HistoryStack {
private undoStack: EditorState[] = [];
private redoStack: EditorState[] = [];
private lastChangeTime = 0;
private readonly COALESCE_WINDOW = 500; // ms
push(state: EditorState) {
const now = Date.now();
if (now - this.lastChangeTime < this.COALESCE_WINDOW) {
// Coalesce: replace the top of the stack instead of pushing
this.undoStack[this.undoStack.length - 1] = state;
} else {
// New undo boundary
this.undoStack.push(state);
this.redoStack = []; // clear redo on new change
}
this.lastChangeTime = now;
}
undo(currentState: EditorState): EditorState | null {
const previous = this.undoStack.pop();
if (previous) {
this.redoStack.push(currentState);
}
return previous ?? null;
}
redo(currentState: EditorState): EditorState | null {
const next = this.redoStack.pop();
if (next) {
this.undoStack.push(currentState);
}
return next ?? null;
}
// Mark a manual boundary (called after paste, image insert, etc.)
markBoundary() {
this.lastChangeTime = 0; // Force next change to create a boundary
}
}
Key Insight
State-snapshot undo is simple and correct, but it has a memory cost. Each snapshot is the entire document tree. For a 50-page document, a 100-entry undo stack could use significant memory. In practice, Lexical optimizes this with structural sharing — snapshots share unchanged subtrees. This keeps memory usage low while maintaining snapshot simplicity.
8. Image Embed — Upload & Rendering
Image embedding is deceptively complex. The user picks a file, we upload it (possibly to a CDN), show a placeholder while uploading, render the final image, and allow resizing and alt text editing. All of this must work within the editor's undo stack.
When the user selects an image, we immediately insert a placeholder ImageNode with uploading: true. The upload happens in the background. Once the server returns a URL, we update the node's src and set uploading to false. If the upload fails, we show an error state with a retry button. The undo stack covers the entire flow — Ctrl+Z after inserting an image removes it, even if the upload is still in progress.
Warning
Images are the number one source of XSS in rich text editors. Never trust the src attribute from user input. Validate that the URL points to an allowed domain. Strip EXIF data on the server. Use a content security policy that restricts image loading to your CDN domain. And always, always sanitize the alt text — users paste alt text from untrusted sources.
9. Mentions — @ Autocomplete
Mentions are the most UX-sensitive feature in the editor. The user types "@", a dropdown appears with matching users, they select one, and "@username" transforms into a styled pill that is atomically selected and deleted.
Trigger Detection
The mentions plugin listens to keystrokes. When the user types "@" preceded by whitespace or at the start of a block, the plugin activates. It captures subsequent characters as the search query and shows a filterable dropdown. Pressing Escape cancels the mention, returning the "@" as plain text.
// Mentions plugin — @ autocomplete
function MentionsPlugin(): JSX.Element | null {
const [editor] = useLexicalComposerContext();
const [query, setQuery] = useState<string>("");
const [suggestions, setSuggestions] = useState<User[]>([]);
const [isOpen, setIsOpen] = useState(false);
useEffect(() => {
const unregister = editor.registerNodeTransform(TextNode, (textNode) => {
const text = textNode.getTextContent();
// Check for "@" trigger
const match = text.match(/(?:^|\s)@(\w*)$/);
if (match) {
const queryStr = match[1] ?? "";
setQuery(queryStr);
setIsOpen(true);
fetchSuggestions(queryStr).then(setSuggestions);
} else if (isOpen) {
setIsOpen(false);
}
});
return () => unregister();
}, [editor, isOpen]);
const selectMention = (user: User) => {
editor.update(() => {
// Replace "@query" text with MentionNode
const mentionNode = $createMentionNode({
mentionName: user.name,
userId: user.id,
avatar: user.avatar,
});
$getSelection()?.insertNodes([mentionNode]);
});
setIsOpen(false);
setQuery("");
};
if (!isOpen) return null;
return (
<div className="mentions-dropdown" role="listbox" aria-label="Mentions">
{suggestions.map((user) => (
<div
key={user.id}
role="option"
onClick={() => selectMention(user)}
className="mention-item"
>
<img src={user.avatar} alt="" className="mention-avatar" />
<span>{user.name}</span>
<span className="mention-email">{user.email}</span>
</div>
))}
</div>
);
}
// MentionNode — renders as a non-editable pill
class MentionNode extends DecoratorNode<ReactNode> {
__mentionName: string;
__userId: string;
__avatar: string;
decorate(): ReactNode {
return (
<span
className="mention-pill"
contentEditable={false}
data-mention={this.__mentionName}
data-user-id={this.__userId}
>
<img src={this.__avatar} alt="" className="mention-avatar" />
@{this.__mentionName}
</span>
);
}
// Arrow key at mention boundary: cursor jumps over the entire pill
// Backspace: deletes the entire mention at once
isToken(): boolean {
return true; // treated as a single atomic unit
}
}
Mention as Token Node
The mention node is marked as a token, meaning Lexical treats it as an atomic unit. Arrow keys skip over it entirely — the cursor moves from before the pill to after it in one press. Backspace at the start of the pill deletes the entire mention, not character by character. This is the expected UX for mentions across all major editors.
10. Code Blocks — Syntax Highlighting
Code blocks are the most technically interesting feature in a rich text editor. Unlike regular text, code must preserve whitespace exactly, disallow rich formatting, and show syntax highlighting with language-specific coloring.
Code Node — Plain Text Within a Block
The code block node is a plain-text container. Inside a code block, all rich formatting (bold, italic, headings) is disabled. Tab inserts spaces (not focus navigation). Enter creates a new line within the same code block (does not split the block). The editor applies syntax highlighting by parsing the code text and overlaying colored spans.
// CodeNode — plain text with syntax highlighting
class CodeNode extends ElementNode {
__language: string; // "javascript" | "python" | "rust" | ...
__highlightedCode: string; // cached HTML from shiki
static getType(): string {
return "code";
}
// Disable rich formatting inside code blocks
canInsertTextBefore(): boolean {
return false;
}
canInsertTextAfter(): boolean {
return false;
}
// Tab inserts spaces instead of moving focus
canTab(): boolean {
return false;
}
}
// Syntax highlighting — using shiki for SSG, or highlight.js for runtime
// shiki generates highlighted HTML at build time (SSG-friendly):
async function highlightCode(code: string, language: string): Promise<string> {
const highlighter = await getHighlighter({
theme: "github-dark",
langs: [language],
});
return highlighter.codeToHtml(code, { lang: language });
}
// Or for client-side highlighting, use a lighter library:
function highlightClientSide(code: string, language: string): string {
// Use highlight.js or prism.js — lighter bundles than shiki
// Return array of { text, color } tokens for the editor to render
const tokens = tokenize(code, language);
return tokens.map(t => \`<span style="color:\${t.color}">\${escapeHtml(t.text)}</span>\`).join("");
}
// Language selector in the toolbar:
function CodeLanguageSelector({ language, onChange }: {
language: string;
onChange: (lang: string) => void;
}) {
return (
<select
value={language}
onChange={(e) => onChange(e.target.value)}
aria-label="Code language"
className="code-lang-selector"
>
<option value="javascript">JavaScript</option>
<option value="typescript">TypeScript</option>
<option value="python">Python</option>
<option value="rust">Rust</option>
<option value="css">CSS</option>
<option value="html">HTML</option>
</select>
);
}
Inline Code vs Code Block
These are two different features. Inline code is a mark applied to a text range — it renders with a monospace font and a subtle background, but lives inline within a paragraph. Code blocks are block-level nodes with language selection, syntax highlighting, and whitespace preservation. The editor handles both: inline code is a toggleable mark (like bold), while code blocks are inserted as separate block nodes.
Tip
Use shiki for SSG/SSR syntax highlighting — it generates deterministic HTML at build time with zero runtime cost. For client-side editors, use highlight.js or Prism (much smaller bundle). Never ship a full shiki highlighter to the browser unless you absolutely need live language switching in a code playground.
11. Editor Engine — State Machine Deep Dive
Behind the UI, the editor engine runs a tight state machine loop. Understanding this loop is essential for debugging performance issues and subtle editing bugs.
Editor engine pipeline — user input is translated into editor commands, applied to the immutable node tree, and reconciled to the contenteditable DOM
The Loop
Input event (keydown, compositionupdate, paste) fires on the contenteditable element. Lexical intercepts it and prevents the browser from modifying the DOM directly.
Event translation converts the DOM event into an editor command. A "B" keydown with Ctrl becomes FORMAT_TEXT_COMMAND with payload "bold".
Command dispatch routes the command through the registered listener chain. Each plugin gets a chance to handle it, ordered by priority.
Editor update runs inside editor.update(). Plugin handlers read the current state, modify the node tree via transforms, and produce a new EditorState.
State reconciliation diffs the old and new EditorState, computes the minimal set of DOM mutations, and applies them to the contenteditable element.
Selection Model
Lexical maintains its own selection model independent of the browser's Selection API. The $getSelection() function returns one of: a RangeSelection (cursor or range), a NodeSelection (entire node selected), a GridSelection (table cells), or null. The selection model is part of the EditorState, meaning undo also restores the previous selection position.
// Selection API — always use $getSelection inside editor.read/update
editor.read(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
const { anchor, focus } = selection;
// anchor: { key: string, offset: number, type: "text" | "node" }
// focus: { key: string, offset: number, type: "text" | "node" }
const text = selection.getTextContent();
const hasBold = selection.hasFormat("bold");
}
if ($isNodeSelection(selection)) {
// Entire node(s) selected — e.g., clicking on an image
const nodes = selection.getNodes();
}
});
// Setting selection programmatically:
editor.update(() => {
const paragraph = $getRoot().getFirstChild();
if (paragraph) {
// Move cursor to end of first paragraph
const endPoint = $createPoint(paragraph.getKey(), paragraph.getTextContentSize(), "text");
$setSelection($createRangeSelection(endPoint, endPoint));
}
});
12. Performance Optimization
Rich text editors have unique performance challenges. Every keystroke triggers the full pipeline — event capture, tree transform, reconciliation, DOM patching. A 10-page document must respond as snappily as a blank page.
Structural Sharing
Lexical's immutable node tree uses structural sharing — nodes that did not change in an edit are reused by reference in the new EditorState. This makes state snapshots cheap. A 100KB document where the user typed one character creates a new EditorState that shares ~99.9% of its nodes with the previous one. Memory overhead for undo stacks is minimal.
DOM Reconciliation
The reconciliation engine computes the diff between the old DOM state and the new EditorState, then applies only the changed elements. If the user adds a single character, only that TextNode's DOM element is updated — not the entire paragraph, not the entire document. Lexical uses a custom tree diff algorithm optimized for editor DOM structures.
Plugin Lazy Loading
Not all plugins need to be loaded at editor initialization. The mentions plugin loads only when the user types "@". The image plugin loads only when the user clicks the image button. Lazy loading via dynamic imports keeps the initial bundle small and startup time fast.
The single biggest performance win is avoiding unnecessary reconciliation. Lexical's reconciliation only touches DOM nodes whose EditorState representation changed. If you are building on raw contenteditable, you are responsible for this yourself — and most teams get it wrong, causing the entire document to re-render on every keystroke. This is the number one reason to use a framework.
13. Security Considerations
A rich text editor is an XSS machine. Users paste content from everywhere — Word docs with VBA macros, emails with tracking pixels, web pages with script tags. The editor must be a fortress.
Paste Sanitization
Every paste event runs through DOMPurify with a restrictive allowlist. Only a tiny set of HTML tags survive: b, i, u, s, a, code, pre, blockquote, ul, ol, li, h1-h3, p, br, img. All attributes except href on links and src/alt on images are stripped. Inline styles are stripped entirely — no font-family, no color, no background.
The page hosting the editor should have a strict CSP that disallows inline scripts and restricts image sources. Even if XSS somehow bypasses the paste sanitizer, the CSP catches it. The editor's rendered output (when displayed to readers, not editors) should be run through an additional sanitization pass.
Warning
Client-side sanitization is UX, not security. An attacker can bypass the browser's paste handler entirely by sending malicious content via the API. Always sanitize on the server before storing. The client sanitizer is there to give users immediate feedback and to catch accidental paste of rich content. The server sanitizer is the real security boundary.
14. Testing Strategy
A rich text editor is a state machine with an enormous state space. Testing it requires a combination of unit, integration, and visual regression tests.
Unit Tests — Node Transforms & Serialization
Every custom node type must have unit tests for its serialize/ deserialize methods. These tests verify that the round-trip (node → JSON → node) preserves all properties.
describe("ImageNode serialization", () => {
it("round-trips through JSON", () => {
const node = new ImageNode("https://cdn.example.com/photo.jpg", "A photo", 800, 600);
const json = node.exportJSON();
const restored = $importNode(ImageNode, json);
expect(restored.getSrc()).toBe("https://cdn.example.com/photo.jpg");
expect(restored.getAlt()).toBe("A photo");
expect(restored.getWidth()).toBe(800);
});
it("marks uploading state", () => {
const uploading = new ImageNode("", "", 0, 0, true);
expect(uploading.isUploading()).toBe(true);
});
});
describe("History coalescing", () => {
it("coalesces rapid typing into one undo step", () => {
const stack = new HistoryStack();
stack.push(state("a"));
stack.push(state("ab")); // within 500ms
stack.push(state("abc")); // within 500ms
expect(stack.undoStack.length).toBe(1); // coalesced
});
it("creates a boundary after paste", () => {
const stack = new HistoryStack();
stack.push(state("hello"));
stack.markBoundary();
stack.push(state("hello world"));
expect(stack.undoStack.length).toBe(2); // two separate entries
});
});
Integration Tests — Toolbar & Keyboard
The most bug-prone area is the interaction between selection, formatting, and the toolbar. Integration tests simulate user actions: type text, select a range, click bold, verify the DOM and the toolbar state.
Snapshots of rendered editor output (HTML) are compared against baselines. This catches unintended formatting changes when refactoring serialization code. Use Playwright screenshot tests for the final rendered output in different themes.
Tip
The hardest bugs in rich text editors are selection bugs — the cursor ends up in the wrong place after a format toggle, or a mention is split by an errant backspace. These are almost impossible to catch with unit tests. Invest in Playwright integration tests that simulate real user interactions step by step. A suite of 20 interaction tests will catch 90% of your regression bugs.
15. Accessibility
Rich text editors are notoriously difficult to make accessible. Screen readers must announce formatting changes, toolbar buttons must be keyboard navigable, and custom nodes (mentions, images) must have proper role semantics.
Toolbar: Uses role="toolbar" with aria-label="Text formatting". Buttons use aria-pressed for toggle state and aria-label with keyboard shortcut hint.
Editor area:role="textbox" with aria-multiline="true". The contenteditable inherits these from Lexical by default.
Mentions: The mention pill uses role="button" or is simply treated as text with an accessible name. The dropdown uses role="listbox" with aria-activedescendant.
Images: The image wrapper has role="img" with aria-label set to the alt text. The resize controls are hidden from screen readers (use alt text editing instead).
Keyboard: All toolbar buttons are reachable via Tab. Arrow keys navigate the editor content. Escape closes the mentions dropdown. Enter selects a mention. Ctrl+Z / Ctrl+Shift+Z for undo/redo.
Tip
Load a screen reader (VoiceOver on Mac, NVDA on Windows) and try to write a formatted article using only the keyboard. You will discover gaps in your accessibility implementation within minutes. Common issues: the toolbar is not announced as a toolbar, format toggles are not announced, and mention pills are read as separate characters instead of a single token.
Live Demo
Here is a live demo of the rich text editor. Try the formatting toolbar, undo/redo, image embed, @mentions, and code blocks with syntax highlighting.
A fully functional rich text editor with toolbar formatting, code blocks, mentions, and image embedding. Type, format, and experiment.
Editable example loads when this section enters view.
16. Key Takeaways
Seven things to remember when building a rich text editor:
Do not use raw contenteditable
It looks like a shortcut but it is a trap. Browser inconsistencies, no standard data model, and custom selection handling will consume your team.
Immutable node tree is the backbone
A predictable data model makes undo, serialization, and collaboration trivial. Structural sharing keeps memory in check.
Format pipeline: command → tree → DOM
Toolbar, keyboard shortcuts, and programmatic changes all go through the same command system. Single code path, consistent behavior.
Selection-aware toolbar is a must
The toolbar must read the current selection's formatting and highlight active buttons. Users should see at a glance what formatting is applied.
Undo needs coalescing
Every keystroke cannot be a separate undo step. Merge continuous typing within a time window. Mark explicit boundaries on paste, formatting, and image insert.
Security is not optional
Paste sanitization with DOMPurify, URL validation, CSP headers. Client-side sanitization is UX — server-side is security. Images and links are the biggest XSS vectors.
Integration tests > unit tests for editors
Selection bugs are the hardest to catch. Playwright interaction tests that type, select, format, and verify DOM state catch 90% of regression bugs.