Skip to content
Engineering

Architecture

contenteditable is an input device

In this post

contenteditable gives you a lot for free: the caret, selection, scrolling, spell checking, autocorrect, and the input methods people use to type Japanese or Chinese. What it’s bad at is deciding what goes in your document.

We built Milieu’s editor on contenteditable, and the most useful thing we learned is to use it only as an input device. Cancel every beforeinput event, and make each change yourself, to a document you own.

What goes wrong when contenteditable edits the page

Left alone, contenteditable edits your markup however its browser sees fit.

Press Return and, depending on the browser and what’s already there, you get a new <div>, a <br>, or a copy of the paragraph you were in, attributes and all. Press ⌘B and you usually get a <b>, but sometimes a <span style="font-weight: bold">. Paste from a web page and you get that page’s markup, inline styles included.

If the page is your document, you then have to make sense of whatever markup the browser wrote, in every browser, and keep up as browsers change.

Treat contenteditable like a keyboard

So we don’t let the page be the document. We treat contenteditable the way you’d treat a keyboard: it tells us what the person wants, and it has no say over what’s in the file.

It’s a far better input device than a keyboard, though. A keyboard tells you which key was pressed. beforeinput tells you what someone meant: insert this text, delete the word before the caret, start a new paragraph. To get there, the browser has already handled the caret, the selection and the input method. We keep all of that, but we don’t let it write.

Milieu’s notes, to-dos and project descriptions all use this editor. It has bold and italic, headings, lists, checklists and mentions, and several people can type in it at once. The two demos below run the real editor in this page, opened up so you can see inside.

The loop: the browser asks, the editor refuses, Svelte redraws

Every change goes round the same loop:

  1. The browser asks. Before it changes the page, it fires beforeinput to say what it wants to do.
  2. The editor says no, and makes the change itself. It cancels the event and changes its own document.
  3. Svelte draws the document as HTML.
  4. The editor puts the caret back where the document says it is.

The page is drawn from the document, never the other way round.

The four panels under the editor show each turn of the loop: what came in, what the editor called, the document that resulted, and the HTML Svelte drew from it. Type a word, press Backspace, select some text and type over it, then press Return.

Input, replace, render Interactive

Buy milk

Call Sam about the venue

What came inWhat the editor called

  1. Type, delete, paste, press Return, or ⇧Return for a line break.

The document

“Buy milk\u2029Call Sam about the venue”

paragraphs
0 paragraph9 paragraph
bold
none
italic
none

The page

This is Milieu’s own editor. Everything you do comes out as a call on its document, and almost every call is replace(from, to, text).

Every text change is replace(from, to, text)

Look at what the editor called. Whatever you did, it was the same call:

  • Typing “a” at position 3 is replace(3, 3, "a"), which replaces nothing with “a”.
  • Backspace is replace(2, 3, ""), which replaces a letter with nothing.
  • Typing over a selection is replace(4, 8, "b").
  • Return is replace(8, 8, "\u2029"). U+2029 is Unicode’s paragraph separator.
  • ⇧Return is replace(8, 8, "\n"), a line break inside the paragraph.

Pasting plain text is one replace too. So is an autocorrection, and so is a word of Japanese once you’ve chosen it.

The browser has dozens of input types, from insertText to deleteSoftLineForward. Every one that changes text comes down to two questions: which range, and what goes there? In outline, the handler looks like this:

function onbeforeinput(event: InputEvent) {
	event.preventDefault();
	const [from, to] = rangeFor(event);
	replace(from, to, textFor(event));
}

Treating a paragraph break as a character pays off straight away. Backspace at the start of a paragraph deletes the separator before it, and the two paragraphs join, with no special case.

Having a single operation also means there’s a single thing to get right and test. Underneath, each replace becomes a few edits to characters by id: insert these after that one, delete those. Undo inverts them, and they’re what goes over the network when several people type in one note at once. Typing together without CRDTs covers that half of the editor.

Formatting and paragraph styles are separate operations

Bold isn’t text, and neither is a heading. Changing either never moves a character, so each gets an operation of its own. format turns bold or italic on or off across a range, and style sets whether a paragraph is plain, a heading or a list item.

In this demo, select a word and press ⌘B, or put the caret in the list and press Tab.

Formatting, styles and lists Interactive

Party

  • Chairs
  • Cake

Ask Sam about the venue

What came inWhat the editor called

  1. Select a word and press ⌘B, press Tab in the list, or type “- ” at the start of a line.

The document

“Party\u2029Chairs\u2029Cake\u2029Ask Sam about the venue”

paragraphs
0 heading6 bullet13 bullet18 paragraph
bold
22–25
italic
none

The page

The same editor with a heading, a list and some bold. Formatting and styling are calls of their own, but they change marks and styles, never the text.

⌘B and ⌘I are caught as keys, before the browser acts on them. Bold and Italic from the Format menu arrive as formatBold and formatItalic. Either way, the editor calls format.

Tab in a list calls style. So does Return in an empty list item, which moves the item a step out of the list instead of adding a paragraph.

Now look at the HTML. Bold and italic together always come out as <strong><em>, whichever you pressed first, because Svelte draws the page from the document and the same document always draws the same HTML.

The same goes for how the formatting got there. Make “H” bold and then “ello”, or have two people type a bold word between them, and the page still shows one <strong>Hello</strong>, never <strong>H</strong><strong>ello</strong>. Before drawing, the editor joins neighbouring text with the same marks into one run, so the HTML depends on what the document says, not on the edits that made it.

When you press Tab, the item moves into a list of its own inside the item above, the way you’d nest it by hand. In the document, though, nothing is nested. The item is still a paragraph in a row of paragraphs, with a style that says it’s a bullet and an indent that says how far in. The nesting only exists on the page.

Anything the document can’t hold is cancelled. Underline from the Format menu arrives as formatUnderline, and nothing happens, because the document has no underline to set.

The hard part is finding the range

Nearly all the difficulty is in working out the range, and that’s where the browsers disagree. Each of these rules is there because a browser gave us a range we couldn’t use as it was.

When deleting, ask the browser. event.getTargetRanges() says what it was about to remove, and it knows how far a word reaches.

Except on a Mac, where Safari deletes a mention beside the caret on its own, without asking. So on a Mac, the editor works out ⌥Backspace and ⌘Backspace itself, on keydown, before Safari gets the chance. It finds words with Intl.Segmenter. It finds the start of the line by moving the selection to the line boundary with selection.modify(), noting where it landed, and moving it back.

Firefox needs checking too. Beside empty paragraphs, its range for Delete or Backspace can start at the very beginning of the text, and taken at its word, one keystroke deletes every paragraph break before the caret. So a delete from the caret has to start or end at it, and one that deletes a single character can cross one paragraph break at most. Otherwise, the editor works it out from the caret.

When inserting, use the selection. Press Return in Safari and it says the new paragraph goes at the start of the paragraph you’re in.

Autocorrect is the exception. Type “teh ” on a Mac and autocorrect turns it into “the ”. That arrives as an insert whose range is the word behind the caret. Put it at the selection, like any other insert, and you get “teh the”. So for autocorrect, the editor uses the browser’s range, and leaves the caret after the space.

Sometimes there’s no range at all. A Backspace can arrive without one. The editor then steps back one grapheme with Intl.Segmenter, so 👩‍👩‍👧 is deleted whole instead of a piece at a time.

Keys can arrive faster than the page is drawn. Type a, Return and b quickly, and the later events can arrive before the first one is on the page. The browser’s selection then describes a page that’s out of date.

The editor knows which version of the document it last drew. If the document has moved on since, it trusts its own selection over the browser’s.

Mapping DOM positions to numbers without data attributes

The browser describes a place in the text as a node and an offset: three characters into this text node. The document describes it as a number: 42 characters in. The editor translates between the two on every keystroke.

You might expect the page to carry positions to help with that. It doesn’t need to. As the editor draws each paragraph, it keeps a reference to the element, in memory rather than on the page. The document can say where any paragraph starts, and which paragraph any position falls in.

<p>Buy milk</p>
<p>Call Sam about the venue</p>

Here, the paragraphs start at 0 and 9. To turn a place on the page into a number, the editor finds the paragraph element it’s in, asks the document where that paragraph starts, and counts the characters before the place. To go the other way, it asks the document which paragraph the number falls in, takes the element it drew that paragraph in, and walks its text.

Paragraphs also appear on the page in the same order as in the document. That matters during composition, when the browser can make a paragraph element the editor never drew. The editor finds that one by its place among the others.

The fiddly part is everything on the page that isn’t a character:

  • An empty paragraph needs a <br>, or the caret has no line to sit on. The <br> counts as nothing.
  • A mention of a person is one character in the document, but a link with their name in it on the page. It’s drawn with contenteditable="false", so the caret can go either side of it but never inside.
  • When someone else deletes the paragraph your caret is in, the browser leaves the selection between paragraphs, and the editor has to decide which one you’re in.

Redrawing on every keystroke without losing the caret

Redrawing the text under someone’s caret on every keystroke sounds as if it should break everything. You’d expect the caret to jump, and autocorrect and the spell checker to lose track of the word.

They don’t, because Svelte only touches what changed. Each paragraph is drawn as runs, stretches of text with the same formatting, keyed by their index:

{#each chunks as chunk (chunk.key)}
	<div class="editor-chunk">
		{#each chunk.groups as group (group.key)}
			<p>
				{#each group.paragraph.runs as run, index (index)}
					<!-- plain text, <strong>, <em>, or a mention -->
				{/each}
			</p>
		{/each}
	</div>
{/each}

Type a letter in the middle of a word, and the run at that index is still the same run, one letter longer. Svelte changes the text of the node that’s already there instead of making a new one. The caret, autocorrect and the spell checker are all attached to that node, so none of them notice.

Then the editor puts the caret back with selection.setBaseAndExtent(), but only if the browser disagrees about where it is. Setting a selection that’s already right isn’t harmless. It can move the caret from inside a text node to beside it, and then the arrow keys step over invisible nodes instead of letters.

Anything that isn’t text, apart from mentions, stays outside the editable element. That includes checkboxes, drag handles and other people’s carets. Inside contenteditable, a checkbox is something the caret can step into and Backspace can delete. Outside it, a checkbox is just a button, placed by measuring the text beside it.

Keying runs by index keeps the caret safe, but it doesn’t make a keystroke cheap. In our first version, a keystroke cost more the longer the note was, and at a million characters it took most of a second.

The chunks in the snippet above are part of how we fixed that. B-trees keep our text editor fast at a million words covers the rest.

IME composition is the one time the browser has to edit

When you type Japanese, Chinese or Korean, the keyboard composes. Type “ka” and you see か, underlined. Press Space and you’re offered カ or 課. Holding e on a Mac to choose é works the same way.

While that’s happening, the input method owns that part of the page. Cancel its events, redraw under it or move the caret, and you break it, usually by doubling the text or committing it too early.

So for the length of a composition, the editor does the opposite of everything above. It lets the browser edit, and it holds back other people’s edits so the page doesn’t shift under the input method.

When the composition ends, the editor reads the text off the page, compares it with the document, and turns the difference into one ordinary replace. Then it draws the paragraphs again from scratch. A composition can also stop without saying so, for example when you click somewhere else halfway through, so leaving the editor ends one too.

If you have a Japanese input method, try it in the first demo, and watch the single replace that comes out at the end.

Catching edits the browser makes without asking

Browsers don’t always ask. Sometimes they skip beforeinput, and sometimes they ignore the cancellation. Safari used to rewrite the page on ⌘Return, wrapping it all in a new <div>.

The input event fires after the page changes, whether the browser asked or not, so it catches these strays. When one happens, the editor keeps what was typed, the same way it does after a composition. Then it throws away the page the browser made and draws a new one from the document.

It also reports the stray to Sentry, with the input type and the last key pressed but never the letter. That way a new browser quirk shows up as an issue we can fix, instead of quietly damaging someone’s notes.

Property tests against a plain string, in three browsers

What matters is what real browsers do with real keys, so the editor’s tests run in Chromium, Firefox and WebKit, pressing keys through Playwright.

The most valuable of them isn’t written by hand. fast-check generates random sequences of typing, Return, Backspace, Delete, arrow keys, selections, clicks, bursts of keys faster than the page can draw, and edits from someone else.

Each sequence runs against the real editor and against a plain string with a caret. After every step, the page, the document and the browser’s selection must all agree with the string. When they don’t, fast-check shrinks the failure to the shortest sequence that still fails. One sequence runs every time as a fixed example: someone else deletes the letter your caret is after, and then you type.

That test depends on everything being a replace. Applying a replace to a string is one line of code, so the model is simple enough to trust.

The trade-offs

The alternative is to let the browser edit and read the document back out of the page. We didn’t, for the reasons at the top of this post, but our way has real costs.

You rebuild things every text field gets for free, like undo and deleting a word, and they have to feel exactly like every other text field on a Mac or a phone. Composition is a second path that has to be just as correct as the first. Every keystroke runs through your code and a redraw, so keeping it fast is your job. And browsers will keep surprising you.

In return, the document only ever holds what you allow, and the same keys do the same thing in every browser. Undo takes back your own typing, even with five people in a note. Every keystroke becomes a small, exact edit the moment it happens, ready to send. When a browser does something new, you hear about it from Sentry instead of finding it in someone’s notes.

If you’re building an editor

Here’s where we’d start:

  1. Cancel beforeinput, and turn each input type into a replace on a document of your own. insertText, insertParagraph and deleteContentBackward get you a long way.
  2. Use getTargetRanges() for deletes and the selection for inserts, check the browser’s ranges against the caret, and expect exceptions like autocorrect.
  3. Draw the page so that typing changes an existing text node and redraws only its paragraph. Set the selection only when the browser disagrees.
  4. Let IME composition through, and turn what it did into a replace when it ends.
  5. Listen for input to catch the edits that got past you, and report them.
  6. Property-test the whole thing against a string, in Chromium, Firefox and WebKit.

And let the browser keep the caret, the selection, scrolling, spell checking and input methods. It’s very good at those.