Skip to content
Aditya Bhalsod
← Open Source
Open SourceAdvanced

Handling Contenteditable Input Without Trusting the DOM

How Trevixal, my from-scratch rich-text editor, turns beforeinput events, IME composition and stray DOM mutations into transactions on a document model it owns.

  • #typescript
  • #contenteditable
  • #rich-text-editor
  • #ime
  • #dom
Contents
  1. The DOM is a render target
  2. Layer one: cancel beforeinput and replay it
  3. Layer two: let the IME lead
  4. Layer three: repair what nobody announced
  5. Testing input you cannot fake
  6. Where this approach stops

Trevixal is a WYSIWYG rich-text editor engine I wrote from scratch in TypeScript. There is no ProseMirror, Lexical or Slate underneath it, so the input layer those libraries normally provide was mine to write: getting a keystroke out of a contenteditable element and into a document, without letting the browser edit that document itself.

The engine is the @trevixal/core package. Its package.json declares no dependencies and no peerDependencies, only four dev tools, and every import under its src/ is a relative path. This post covers one part of it: the three layers the view uses to turn browser input into edits on a model the editor owns.

The DOM is a render target

The rule everything else follows from sits in a comment on the state class: the DOM is never the source of truth. The document is an immutable tree held in an EditorState, next to the selection. A command is a function of type (state) => Transaction | null. Dispatching a transaction produces a new state, and the view renders that state into the page.

That leaves the contenteditable element two jobs: show the model, and report what the user is trying to do. The second job is the hard one, because edits can reach the page in three different ways. All three are handled in editor-view.ts, and the reasoning is written down in ADR-0005.

ChannelWho writes the DOMHow the model hears about it
beforeinput intentsThe editor's renderer, after the model changesThe event is cancelled and a command runs
IME compositionThe browser, until the composition endsA text diff of the composed block
Everything elseThe browser or an extensionA MutationObserver, then the same diff

Layer one: cancel beforeinput and replay it

Browsers fire beforeinput before they touch the DOM, with an inputType that names the intent. The view cancels the event and runs the matching command instead:

TypeScript
const consume = (command: Command | null): void => {
  event.preventDefault()
  if (command) this.editor.exec(command)
}

switch (type) {
  // ...
  case 'insertParagraph':
    consume(
      chainCommands(splitBlockInPreformatted, splitListItem, escapeWrapperOnEnter, splitBlock),
    )
    break
  // ...
  case 'historyUndo':
    event.preventDefault()
    this.editor.undo()
    break
  // ...
  default:
    // Unknown intent must not corrupt the DOM the model owns.
    event.preventDefault()
}

chainCommands tries each command in order and stops at the first one that returns a transaction. Enter is therefore four separate commands: one for code blocks, one for list items, one for leaving a wrapper such as a blockquote, and the plain paragraph split. Even historyUndo is cancelled and sent to the editor's own history.

The default branch matters as much as the cases. An intent the editor does not understand is cancelled too, because letting the browser apply it would put something in the DOM that the model never agreed to. keydown is left with shortcut chords, such as bold, undo and Tab, through a keymap where Mod means Cmd on Apple platforms and Ctrl elsewhere.

Layer two: let the IME lead

An input method editor, the kind used to type Japanese, builds a word inside the DOM over several keystrokes before committing it. The view cannot treat that like layer one. It neither cancels those events nor re-renders underneath an open composition.

So between compositionstart and compositionend the view stands down. A composing flag makes the beforeinput, keydown, selectionchange and mutation handlers return early, and the render method does nothing:

TypeScript
update(): void {
  if (this.destroyed || this.composing) return
  this.withDOMUpdate(() => this.renderer.renderDoc(this.editor.state.doc, this.dom))
  this.updatePlaceholder()
  this.syncSelectionToDOM()
}

While the composition is open, the half-typed reading is in the DOM and deliberately not in the document. At compositionend the flag is cleared, the view finds the textblock under the caret, and hands it to the repair routine described next.

Layer three: repair what nobody announced

Some changes never arrive as an intent the view can cancel. The comments in the code name autocorrect and browser extensions writing to the DOM directly. A MutationObserver watches the editing surface for child list and character data changes to catch those. The first problem is that the editor's own renderer mutates the same DOM all the time. The fix is small:

TypeScript
private withDOMUpdate(fn: () => void): void {
  this.updatingDOM = true
  try {
    fn()
  } finally {
    // Drop the mutation records our own render just produced.
    this.observer?.takeRecords()
    this.updatingDOM = false
  }
}

The render pass and every selection write go through this wrapper. takeRecords() empties the observer's queue before its callback can run, so the callback only sees changes the editor did not make.

When records do arrive, the view maps each one to the textblock element around it. If they all point at one block, that block is repaired with a prefix and suffix diff between the text in the DOM and the text in the model:

TypeScript
const newText = content.textContent ?? ''
const oldText = block.textContent
// ...
let start = 0
while (start < oldText.length && start < newText.length && oldText[start] === newText[start]) {
  start++
}
let oldEnd = oldText.length
let newEnd = newText.length
while (oldEnd > start && newEnd > start && oldText[oldEnd - 1] === newText[newEnd - 1]) {
  oldEnd--
  newEnd--
}
const inserted = newText.slice(start, newEnd)
const from = inlineOffsetFromText(block.content, start)
const to = inlineOffsetFromText(block.content, oldEnd)

The result is a single ReplaceInlineStep from from to to. The inserted text takes the marks found at the edit point, so a correction inside bold text stays bold, and the caret is read back from the DOM selection. From there it is an ordinary transaction: it goes through the same dispatch, lands in the undo history, and the renderer redraws the block from the model.

If the records touch more than one block, or the number of inline atoms in the block has changed, the diff cannot describe the edit. The view does not guess: it calls update() and the model stays as it was.

Testing input you cannot fake

The first and third layers are easy to unit test. The tests in view.test.ts run in happy-dom, dispatch a synthetic beforeinput or rewrite a text node behind the view's back, and assert on the model.

Composition is different, because a hand-fired compositionstart only tests my simulation of an IME. So ime.spec.ts drives Chromium's real composition machinery from Playwright, through the DevTools Protocol command Input.imeSetComposition, and checks that the reading stays out of the model until the word is committed.

Where this approach stops

I would use this design again for any editor that has to treat its document as data. Every input path, however odd, ends as a transaction on the model, so undo and serialization never need to know where an edit came from.

It has limits, and they are visible in the code. deleteWordBackward and deleteSoftLineBackward are currently mapped to the single-character delete, so a delete-word shortcut removes one character. That is the first thing I would fix. The text diff describes one changed span in one textblock, and anything wider is ignored rather than understood. Input.imeSetComposition is a Chrome DevTools Protocol command, so the IME spec skips on Firefox and WebKit.

The engine is also single-user: the design record for the collaboration binding I built is marked superseded. If you need collaborative editing, or an engine with years of production use behind it, pick one of the established ones.

Found this useful? Share it with your team.

Keep reading

More from Open Source and beyond