Skip to content

Latest commit

 

History

History
411 lines (296 loc) · 103 KB

architecture.md

File metadata and controls

411 lines (296 loc) · 103 KB

Architecture (v0)

How the editor works: the decisions behind it, how the code carries them out, and where to find it.

Principles

The editor is a Markdown block editor: a block editor whose storage format is Markdown. Every design decision below follows from these five rules. A change that breaks one of them needs a decision recorded here first.

  1. Markdown is the stored format; blocks are the editing model. Loading parses Markdown into blocks. Every edit is an operation on blocks. Saving writes the blocks back to Markdown. There is no second format (no JSON document) for an app to store.
  2. Every block type has a Markdown form. The editor adds no block type that Markdown as GitHub renders it cannot write (no columns or colored text): callouts are GitHub alerts, and collapsible sections are <details> HTML. Syntax outside CommonMark and GFM enters only through an extension that defines how it is written (see "Syntax extensions"), and is saved exactly as written.
  3. Nothing is lost on save. Blocks the user did not edit are saved byte for byte. Markdown the block model cannot hold is kept as a raw block, edited as source and saved verbatim, never flattened or dropped.
  4. After parsing, the editor behaves like a block editor. Whole blocks can be selected, deleted, copied, cut, pasted over, duplicated and changed in type together (see "Block selection"). A block-editor feature is added only when it is needed, and only when its result can be written as Markdown.
  5. Edits are pure functions on immutable blocks. Each command in commands.ts takes a state and returns a new one, replaces only the blocks it changes, and keeps block IDs. Rendering, undo, the React wrapper and source-preserving save all rely on this.

Other products confirm the split behind rules 1 and 2. Editors that keep Markdown as the stored format (Milkdown, MDXEditor, Tiptap's Markdown extension) limit their block types to what Markdown can write. Block editors with types Markdown cannot write (Notion, BlockNote) store their own format, and BlockNote's documentation calls its Markdown export "lossy".

Summary of decisions

Area Decision
Package One package, @usememos/editor: plain TypeScript with zero runtime dependencies. A thin React wrapper is the @usememos/editor/react subpath, with React and React DOM 18 or later as optional peer dependencies.
Document model A flat list of immutable blocks. Each block has a stable ID. Inline content is a list of text spans with marks, a link or an image.
Editing surface One contentEditable root that the editor owns completely. Table cells are nested editing hosts.
Input Cancel beforeinput and apply a model command. IME composition is the one exception: the browser edits the DOM, and the editor reads the result back into the model on every input.
Rendering Keyed reconciliation. A block whose object did not change keeps its DOM element.
Undo Whole-document snapshots. They are cheap because unchanged blocks are shared.
Source mode A view of the same editor, not a second editor: the document becomes one internal code block holding the Markdown, edited through the same input pipeline. Switching loads or serializes; undo history spans both modes.
Markdown Our own CommonMark 0.31.2 + GFM parser and a normalizing serializer. Saving is stable: serialize(parse(md)) is a fixed point.
Public API Modeled on Tiptap and ProseMirror: editor.commands, isActive, getAttributes, on() events, JSON-safe selections, and extensions as plain objects that add syntax, keys, decorations, autocomplete popups and input hooks. Markdown is the only content format. The parser's syntax tree (parseAst, visit, sourceRange) is public too, for a host that reads a document as data with the dialect the editor shows; its node shapes follow the spec, while syntax, pieces and source details serve source mode and are not promised.
UI Slash menu, block handle and block menu, formatting toolbar, image toolbar, link popover and link card. All plain DOM, styled with CSS custom properties.
Icons Lucide icons, copied into the source as SVG data rather than imported from a package, so the core keeps zero runtime dependencies. The icons option replaces any of them.

Source map

Path Contents
packages/editor/src/model.ts Block and span types, constructors, inline helpers, positions.
packages/editor/src/commands.ts Every edit as a pure function (state) => state.
packages/editor/src/history.ts Undo and redo.
packages/editor/src/sourceMode.ts Source mode: the source block, its text edits, and caret mapping between the modes.
packages/editor/src/sourceHighlight.ts Source mode's highlighting: decorations from the markup, the text as spans split at syntax for decorators, and the decorations moved through an edit while the exact ones are computed.
packages/editor/src/editor.ts The Editor class: events, selection sync, menus, clipboard, public API.
packages/editor/src/keymap.ts Parsing key names such as Mod-Shift-x and matching them to key events.
packages/editor/src/decorations.ts, packages/editor/src/widgets.ts Text decorations, and app UI placed between blocks.
packages/editor/src/view/dom.ts Rendering blocks to DOM, and mapping DOM points to model positions and back.
packages/editor/src/view/reveal.ts Which rendered views show their source for a given selection.
packages/editor/src/ui/ Popup and Menu, the formatting toolbar and the input popover (link URLs and alt text), the image toolbar, the block handle, the resize handles.
packages/editor/src/suggest/ The autocomplete popup: the session and keys (controller.ts), finding the token at the caret (match.ts), item requests (source.ts) and placement (anchor.ts).
packages/editor/src/markdown/ Parser (blocks.ts, inline.ts, autolink.ts, lower.ts), serializer (serialize.ts), source-preserving save (source.ts), source maps from a block's text to where it was written (sourceMap.ts), the markup ranges of a text for highlighting (markup.ts), dialect options and syntax extensions (options.ts), entity tables, the syntax tree's public walker and source positions (tree.ts), and an HTML renderer used only by the spec tests (html.ts).
packages/editor/src/clipboard/ Document to HTML for copy (toHtml.ts), pasted HTML to document (fromHtml.ts).
packages/editor/src/extension.ts, packages/editor/src/extensions/ The Extension interface, and the built-in extensions: math(), footnotes(), tags(), mentions(), suggestion(), textDecorator(), fileHandler() and defaultKeymap().
packages/editor/src/theme.ts The theme option's types, and merging class maps from extensions and the editor.
packages/editor/src/base.css, theme.css, style.css Layout and block spacing; the default look; both together.
packages/editor/src/labels.ts Every UI string, for localization.
packages/editor/src/icons.ts Every built-in icon, as Lucide SVG data, and building them into elements.
packages/editor/src/react/index.tsx <MarkdownEditor>, useEditor, <EditorContent> and useSuggestion.

Document model

  • A document is { blocks: Block[] }. Blocks are never nested.
  • Block types: paragraph, heading (level 1–6), listItem (listType bullet, ordered or task; indent 0–5; checked; start on the first ordered item; quote and callout on an item in a quote or callout), quote (a paragraph of a blockquote; callout on each paragraph of a callout: note, tip, important, warning or caution), code (language, plain text), raw (Markdown kept as source, plain text; syntax is html, markdown or an extension's name), table (align per column; rows of cells; row 0 is the header), divider, details (a collapsible section's title, plain text, with open) and detailsEnd (where the section ends; no content). A list item, heading, code block, raw block, table or divider inside a blockquote carries the Quoted fields, quote: true, callout and quoteStart (QuotableBlock, isQuotable); a paragraph inside one is a quote block instead. withQuote moves any block into or out of a blockquote, and unquote is the block as it is inside it.
  • Inline content is an array of spans { text, marks, link?, linkTitle?, image? }. A link's title (linkTitle) shows as a tooltip; spans are in the same link when both the destination and the title match (sameLink). Marks are bold, italic, strike, code and html (inline raw HTML). A hard line break is "\n" in the text. An image is the single character U+FFFC with an image attribute: src, alt, and optionally title, align, width and height. A paragraph whose only content is one image, with no link or marks and only spaces or tabs around it, is an image block (isImageBlock): it is derived, not a block type, so typing a letter beside the image would turn it back into a paragraph, and the Markdown is the same either way. Selecting an image means a selection that covers exactly that character; commands.selectedImage finds it. The resize handles (ui/resizeHandles.ts) live in the popup container like the other floating UI, so the document's DOM holds only the <img>.
  • A position is { blockId, offset, cell? }. offset counts UTF-16 code units in the block's (or cell's) plain text. cell is { row, col } inside a table.
  • Every edit returns new objects for the blocks it touches and reuses the rest. Rendering, history and the React wrapper all depend on this.
  • Quotes are the one container the flat list keeps, as a mark on each block: adjacent quote blocks and quotable blocks with quote (list items, headings, code blocks, raw blocks, tables and dividers) that have the same callout (or none) form one blockquote (quoteKind and sameQuote in model.ts), unless the later one has quoteStart: two blockquotes with a blank line between them in Markdown load as two, and the first block of the second carries the flag. Edits keep the boundary: splitting that block leaves the flag on its first part, Enter at its start moves it to the new empty line, and changing its type inside the quote keeps it (keepQuoteStart). A list in a quote is a separate list from one outside it, for nesting, numbering and saving. Enter on an empty item at the top level of a quoted list gives an empty paragraph of the quote; Enter again leaves the quote. Backspace at the start of such an item does the same one step at a time. In a quote, list markers (- , 1. , [ ] ) start a list in the quote. Toggling a list off in a quote keeps the text in the quote; toggling the quote or a callout on list items keeps them list items. The same holds for every block in a quote (decided 2026-10-28, for a web clipper whose template quotes the whole page): the block type commands keep a block in its quote, so a heading made from a paragraph of a quote is a heading in the quote, and a heading or list item in a quote made a paragraph is a paragraph of the quote; a paragraph of a quote made a paragraph leaves the quote, as Backspace at its start does, and the quote toggle takes any block out of the quote with its type kept. Enter at the end of a quoted heading gives a paragraph of the quote; Backspace at the start of a quoted heading or code block makes it one; # , a fence and --- typed in a quote make a heading, code block or divider in it; the slash menu's table and divider go into it. Only a quote inside a quote, and a list the model cannot hold, stay out of reach: each is one quoted raw block, so its siblings are still blocks (see "Lowering"). The renderer draws a quoted heading, code block, raw block, divider or table as a blockquote holding the block's usual element as its .mbe-content, as it draws a quoted list item, so the quote's and callout's rules style it and the element inside keeps the block's own (renderBlock in view/dom.ts).

Why flat: block editors convert, duplicate, delete and select whole blocks. A flat list makes those operations array edits and gives every block a stable ID for the block menu. The cost is that some Markdown structure has no block form; it is kept as a raw block of source (see "Lowering" below).

Editing surface and rendering

One contentEditable root, not one per block, so native selection crosses block boundaries and Shift+Arrow and select-all work without custom code.

  • Each root child is a block element with data-block-id. The element marked data-content holds the inline content. List markers, checkboxes, the code-language input and other chrome sit outside it with contenteditable="false".
  • A table block is contenteditable="false"; each cell is its own editing host with data-row and data-col. Selection does not cross cell boundaries.
  • BlockRenderer.render reuses the element of every block whose object is unchanged, inserts new elements in order, and removes anything else, including nodes the browser inserted on its own. Ordered list numbers are recomputed after each render and cached per element.
  • Loading a document (new Editor, setMarkdown) builds all elements in a fragment and marks them content-visibility: auto, so blocks off screen skip layout. Blocks rendered while editing never get that property: Chrome treats a new content-visibility block as skipped until the next frame, and an arrow key pressed before then put the caret in the wrong place (found by the browser tests under load).

Read-only and task toggling. editable: false makes the root and every table cell contenteditable="false", sets aria-readonly="true" and the class mbe-readonly, and disables every <input>. run(), undo, redo, paste, cut, drop and beforeinput do nothing, the caret does not reveal any view's source, and the toolbar, menus and block handle do not show. Copy works, and links open on a plain click, unless onLinkClick handles them. taskToggle: true keeps all of that except for task checkboxes: they stay enabled, are Tab stops (tabIndex 0, while editing they are -1), take their accessible name from the item's text, and the root also gets the class mbe-tasks. A press on a checkbox (mousedown, or a keyboard click with detail 0 from Space) applies toggleTask through the same path as an edit: it is recorded in undo history, re-renders the item and emits change. The press is cancelled, so focus, the selection and the scroll position do not move. taskToggle has no effect while editable is true, and isEditable stays false with it.

Input pipeline

  1. beforeinput, cancelled. insertText, insertParagraph, insertLineBreak, all delete* types, historyUndo/historyRedo and format* map to commands. Word and line deletes use the browser's getTargetRanges(), so they follow the platform's word boundaries. So does insertText when its target range covers text while the selection is a caret: that is how mobile autocorrect and word suggestions replace a word. insertParagraph picks the item of an open autocomplete popup, because Android keyboards send Enter with keyCode 229, which keydown ignores.
  2. IME composition, not cancelled. While composing, the editor does not re-render the composed block or move the selection, and hides the toolbar. On each input it compares the block's DOM text with the model and applies the difference as one delete and one insert, so change, getMarkdown(), isEmpty and an open autocomplete popup follow the composed text (on Android every word is a composition). The renderer adopts the browser's DOM for the new block object instead of rebuilding it, and only updates its empty state, so the placeholder does not cover composed text. Marks stored before composing (Mod+B, then compose) apply to all of the composed text. The first change records one undo step for the whole composition. On compositionend the committed text is read once more; the block is rendered from the model on the next frame, so input that arrives after compositionend in the same task (Firefox sends the last input then) still counts as the composition, and nothing is re-rendered between two compositions in one keystroke (Korean syllables). A selection inside one text container stays available to the IME for reconversion. Selections across blocks, table cells or source lines are joined first. That edit shares the composition’s undo step. The unchanged suffix of the composed text container determines the caret after a commit, so a Japanese clause selection does not move later typing into the word. A pointer press outside that container ends the composition before the caret moves, even if the browser did not send compositionend.
  3. Fallback. An input event the editor did not cancel goes through the same read-back, and typed text then runs the Markdown shortcuts. A beforeinput that cannot be cancelled (from some Android keyboards) for typed text, a replacement, or a deletion inside one text container is left to the browser and read back, so it is not applied twice.
  4. keydown: an open menu takes the navigation keys first. A block selection takes its own keys next (see "Block selection"). Then extension key bindings run in order, ending with defaultKeymap() (marks, block types, Mod+K, undo/redo, Tab, submit, Escape). A binding that returns true stops the rest and prevents the browser default. Mod+/ (block menu) and Mod+Shift+V (plain paste) are handled by the editor itself. ArrowDown on the last line of a code block, table or divider that ends the document adds an empty paragraph below it, and ArrowUp on the first line of one that starts the document adds one above it (exitBlock). Elsewhere the browser moves the caret. When it passes over a block that holds a caret (Firefox skips list items, which are flex boxes, and WebKit skips code blocks and tables), the editor moves the caret into that block at the same horizontal position. After any caret key the editor keeps the caret 8 px clear of the scroll container's edge. Backspace at the start of a block is handled on keydown, because WebKit sends no beforeinput there when no editable text comes before the caret. A click in the empty space below such a final block also adds a paragraph. Enter three times at the end of a code block still leaves it.
  5. Markdown shortcuts run after typed text: block rules on a space at the start of a block (#, -, *, +, 1., [ ], [x], >, ```lang, ---) and inline rules when a closing *, _, ` or ~ is typed. A delimiter after an odd number of backslashes is escaped and does not count, as in CommonMark; inside inline code a backslash is literal. Undo restores the typed characters, and so does Backspace right after a shortcut, before any other edit or caret move (undoShortcut, as ProseMirror's undoInputRule). The autolink rule on a space works the same way.

Selection: on selectionchange, the DOM selection is read into the model. After each change, the model selection is written back to the DOM, only when it differs.

Block selection

Escape selects the blocks the selection touches as whole blocks: the block with the caret, or every block a text selection crosses. A table, code block or divider is selected the same way. The selected blocks are highlighted (mbe-block-selected on each block element, mbe-block-selecting on the root).

Keys While blocks are selected
ArrowUp, ArrowDown Select the block above or below the selection
Shift+ArrowUp, Shift+ArrowDown Extend or shrink the selection by one block
Mod+A Select every block
Backspace, Delete Delete the selected blocks
Mod+C, Mod+X Copy or cut them as Markdown
Paste Replace them with the pasted blocks
Mod+D Duplicate them; the copies become the selection
Block type keys, Tab, Shift+Tab, mark keys Apply to every selected block; the same blocks stay selected
Enter Back to editing text, with the caret at the end of the last selected block
ArrowLeft, ArrowRight Back to editing text, at the start of the first selected block or the end of the last
Escape Leave the editor (the escape hatch from Tab-trapping that memos relies on)
Typing Nothing

A click in the text, a blur, setSelection, setMarkdown or turning editing off ends the block selection.

How it works:

  • The editor holds the block selection as the IDs of its anchor and head blocks (blockSel in editor.ts). It is not part of EditorState, so commands stay unaware of it.
  • While it is set, the model selection spans the selected blocks, from the start of the first to the end of the last (spanBlocks). That is why block type, indent and mark commands need no special case: they already act on every block a selection touches. After each change the span is recomputed from the same IDs, which commands keep.
  • The browser selection is a collapsed caret at the start of the head block, hidden with caret-color: transparent. Focus stays in the editor, so keys still arrive, and there is no native text highlight. Selection changes from the browser are ignored while blocks are selected: the browser may move that caret out of a divider, and a click ends block selection on mousedown anyway.
  • Delete, duplicate and paste are pure commands on a block range: deleteBlocks, duplicateBlocks and replaceBlocks. Each re-nests list items that would end up deeper than the item above allows, for example the nested items of a deleted parent.
  • Copying whole blocks uses serializeBlocks, so a selected empty line is copied as &nbsp; rather than dropped as trailing whitespace.

Copying text. A text selection is copied as Markdown (text/plain) and as HTML that carries the same Markdown (data-mbe-markdown), so a paste into the editor is lossless and a paste elsewhere gets Markdown. A selection inside one block is copied as its inline content, as a paragraph: a word of a heading pastes as a word, not as a heading, as in Notion and ProseMirror, and a selection inside one table cell does the same. Inside one code or raw block, text/plain is the text as written, so it pastes into a terminal or another code block as code, while the HTML carries the escaped Markdown for a paste into a paragraph. A selection across blocks copies the blocks, cut at its ends. Whole blocks, with their type, are copied through the block selection (Escape, then Mod+C).

Source mode

mode: 'source' shows the whole document as its Markdown text (see README "Source mode" for what the user sees). It exists because Markdown is the stored format: every editor we compared that stores Markdown (GitHub, GitLab, Discourse, Reddit, Joplin, Obsidian, Typora, MDXEditor) lets people see and edit the text itself, and memos users edited it as text in CodeMirror before this editor.

One editor, one pipeline. Source mode is not a <textarea> or a second editor. The state holds one code block with the fixed ID mbe-source (sourceMode.ts) whose text is the Markdown, so typing, deleting, input methods, the selection, the clipboard and undo go through the same code as a code block. The renderer draws that block as div.mbe-source with no language bar, copy button or views, one div.mbe-source-line per line (see "Highlighting"), in the body font at the body's size. The editor checks mode where a code block would behave differently in rich mode:

  • It is plain text editing that knows Markdown lists: Markdown shortcuts and autolinks do not run after typing, and the formatting keys are text edits (see "Formatting keys" below). suggestion() popups open as in rich mode: the controller (find in suggest/controller.ts) takes the source block's text as the spans sourceInline splits at its syntax (Editor.sourceSpans, cached per text by SourceHighlighter, moved through the edit in a long text), so excluded is true in code, a URL, raw HTML and extension syntax, and the allow context's mode says 'source'. The slash menu's config has richOnly, as may any suggestion whose items create blocks, and it never opens there.
  • Enter runs sourceEnter instead of leaving the block after two empty lines, and Shift+Enter inserts a line break. Backspace at the start of the text and Delete at its end do nothing. ArrowDown on the last line and a click below the text add nothing.
  • indent and outdent run sourceIndentList, or indentCode, as Tab does in a code block, when the selection is not on list items. The mark commands, setParagraph, toggleHeading, the list commands, toggleBlockquote and toggleCodeBlock run the text edits of "Formatting keys" below. The link, image, table, divider, callout, section and selectBlocks commands return false, so their keys do nothing. isActive() is false for every name.
  • insertText and insertMarkdown insert text as written (insertSourceText, insertSourceAt). Paste writes HTML as Markdown (pastedMarkdown: the editor's own data-mbe-markdown, else htmlToDoc and the serializer, as rich mode's pastedBlocks), plain text as written, and the text as written inside a fence (inFence); a URL pasted over a selection makes it a link (sourceLink). Copy writes the selected text. There is no block selection, block handle, block menu, toolbar or link card.

Lists (sourceEnter, sourceIndentList). With smartLists (the default), Enter and Tab read the lines around the selection as list items and make ordinary text edits, recorded in history like any other edit, so the source text stays the only state. A line is an item when, after any quote markers (>) and indentation, it starts with -, *, +, or a number and . or ), followed by a space or the end of the line; a thematic break such as * * * and every line of fenced code are not. Enter continues an item only when a space follows the marker, so a line such as 2023. or a lone - stays text. Nesting follows CommonMark: Tab moves an item to the text column of the item before it at the same indentation, Shift+Tab to its parent's indentation, and the lines indented under the item move by the same amount. After a change, each ordered list it touched is numbered from its first number, or from 1 when an item has just started it; a list numbered 1., 1., 1. keeps that style. Enter on an empty item matches rich mode's Enter in an empty list item: it outdents a nested item and removes a top-level item's marker. Not done: continuing a quote line that is not a list item, and removing a marker with Backspace.

Formatting keys (sourceToggleWrap, sourceSetHeading, sourceToggleList, sourceToggleQuote, sourceToggleFence, sourceLink). Each is a pure function on the state, run as one command, so one undo step. sourceToggleWrap wraps the selection in **, *, backticks or ~~, trimmed of whitespace, or unwraps it when runs of the marker's character stand around it, the markers selected or not: strong and strike need runs of two, italic odd runs (so italic inside strong adds its star and a run of three gives one up), and a code span's run equal runs, with the run it writes one longer than any inside the code and a space when the code starts or ends with a backtick. With no selection it takes the word at the caret, or writes the pair with the caret between. The line edits act on the lines the selection touches (a selection ending at a line's start leaves that line out), after each line's quote markers, through sourceLines: fenced code is skipped, and a blank line among others. A line's prefix is its list marker with a task box, or its #s; sourceSetHeading replaces it with the level's #s (none for level 0, or a level every line has), sourceToggleList with the kind's marker (lines that are the kind already keep theirs and are only numbered again through finish, new ordered items from the list they join or 1; markers go when every line is the kind). sourceToggleQuote adds > to each line, or takes one marker off each when every line with text is quoted. sourceToggleFence wraps the lines in fences with their quote prefix, makes an empty fence on a blank line, or removes the fence around a selection in fenced code. The browser's own formatBold, formatItalic and formatStrikeThrough input events go through the same commands.

Switching. Rich to source: getMarkdown() becomes the text. Source to rich: the text is loaded with loadMarkdown, as setMarkdown does, so it saves byte for byte. Neither records history or emits change. Collapsed sections, the block selection and open popups are cleared. A switch during a composition is applied when it settles.

Source ranges. The inline parser records where every node sits in the content it parsed (pos on each InlineNode in ast.ts), where its markup is (syntax: the delimiter runs, brackets and backticks, a link's (destination "title") or [label] with the destination and title in it, a bare URL), a code span's text between its backtick runs (content), and for a text node whose value is not written as such, its verbatim pieces, so the gaps between them are escapes and entities. Emphasis uses the innermost delimiters of a run: the opener's last and the closer's first. The block parser records where each line of a leaf's content came from (ContentSource: the source line, the column after the block's prefixes, and the spaces that stand in for a partly consumed tab) and how much was cut from the content's start (reference definitions, a task marker, a fence's info line, trimmed whitespace). A table records where each cell was written (sources): the pieces of its row between the pipes, an escaped pipe (\|) starting a new piece, so a cell's content maps like a line's. Nothing scans the text a second way: what source mode will dim is exactly what the parser read as syntax.

Source maps (markdown/sourceMap.ts). Loading joins the two as lowering pushes spans (lowerInto with a SegmentBuilder) and keeps, per block that holds text, a list of segments (MarkdownSource.mapOf): runs of the block's text paired with the source range each was written in. A linear segment maps offset for offset. An atomic one stands for its source as a whole: a soft break with the next line's indentation and prefix, an escape or entity, an image, a code span's line ending that became a space, a tab the prefix consumed only partly. The source between two segments is syntax. Raw, code and HTML blocks map line by line; a raw Markdown block holding a group's source maps as it is; tables have no map.

Highlighting (markdown/markup.ts, sourceHighlight.ts). markdownMarkup walks the parsed tree with the source ranges above and lists every range of markup in the text with a kind: marker for delimiter runs, brackets, backticks, list, quote, task and heading markers, fences and table pipes; heading, strong, em, strike, code, link and url for the text they mark; html, token, escape and lang (a fence's info string); and the code of each fenced or indented block, for codeDecorations. A table's cells are walked like paragraphs, from their sources, and an escaped pipe in a row is an escape. Nothing scans the text a second way, so what is dimmed is exactly what the parser read as syntax. highlightDecorations turns the ranges into decorations with the classes mbe-src-* (and the theme's source classes), sourceInline presents the text as spans split at the syntax with markup, code, URLs, HTML, tokens and escapes as excluded spans, so the extensions' decorators see the prose runs rich mode gives them, and the editor runs codeDecorations on each fence's code with the offsets moved and clipped to it. The renderer's decorateSource hook returns all three; sourceHighlighting: false leaves out the first.

The block is one div.mbe-source-line per line, without the line endings (the text's \n is the boundary between two lines; an empty line holds a filler <br>), each a block box with dir="auto". patchSourceText brings the element up to date in place: lines whose text and decorations are the same keep their element, so a keystroke in a 100 KB document replaces one line and the browser lays out only that one. domText, offsetIn and positionToDom know the shape and count the lines before a point by length instead of walking every text node. The block itself has no dir="auto": Chrome resolves a block's auto direction again on every child inserted, which took a second per 100 KB. Computing the decorations parses the whole text and runs every decorator over it, about a quarter of a frame per 100 KB, so above 20 KB (SYNC_LIMIT) a keystroke gets the previous decorations moved through its edit (shiftRanges: unchanged text keeps its ranges, the edited range loses its own) and SourceHighlighter computes the exact ones right after, rendering the block again only when they differ. The perf gate types into 100 KB of Markdown in source mode: p95 under 16 ms.

Caret mapping (toSourceOffset, fromSourceOffset). Both directions are lookups in the segments: a caret on syntax goes to the text after it, and one inside an atomic segment before it, except after a line break when it is on the next line. The block for a source offset is the one whose text holds it; an offset on syntax belongs to the block whose source starts last before it (a group's first block owns the group's start, a later block its line). A block without a map (a table, a collapsible section's tag) is placed by its group's range and the text search of placeBlocks, and a position in a table cell goes to the start of the table.

Undo across modes. History entries keep the MarkdownSource that was current when they were recorded. An entry from the other mode is converted when it is restored: a rich entry is serialized with its own source, so unedited blocks keep their text; a source entry is loaded. Restoring a rich entry in rich mode also restores its source, so undo after setMarkdown(md, { history: 'keep' }) saves the earlier blocks byte for byte too.

Widgets. In source mode a widget shows after the one block, below the text, and remembers a text offset: entering source mode puts it at the end of its block's source; after each edit the offset moves by the length change when the edit was before it. Leaving source mode attaches it to the block at its offset.

Requirements (each has a test):

  1. mode is accepted by the constructor, setOptions and the React component, defaults to 'rich', is readable as editor.mode, and the React prop does not recreate the editor.
  2. For every round-trip fixture, rich → source → rich with no edits leaves getMarkdown() unchanged and emits no change.
  3. In source mode, the text of the source block equals getMarkdown().
  4. After source → rich, getMarkdown() returns exactly the text that was in source mode, including lines edited there.
  5. After an edit in one mode and a switch, one Mod+Z undoes that edit and the mode stays. A switch adds no undo step.
  6. The caret stays in the same block across a switch and at the same place in its text, past any syntax before it and on continuation lines of a paragraph, quote or list item.
  7. Every row of README's source mode table works in Chromium, Firefox and WebKit.
  8. Composed text (IME) in source mode is inserted once; a switch during composition waits for it to end.
  9. With mode unset, every existing test passes unchanged.
  10. Enter and Tab on list items edit only the lines described under "Lists", and smartLists: false restores a plain line break and code block indenting.
  11. For every CommonMark and GFM spec example, each block's source map is in order in both texts, its linear segments read the same in both, every offset maps there and back, and the caret of every block comes back to that block (test/sourceMap.test.ts). The timing gates (test/conformance/timing.test.ts) hold with ranges recorded.
  12. The markup ranges of a text cover its inline syntax, headings, quotes, lists, tasks, breaks, tables, fences and raw HTML, a literal * is not markup, including the syntax inside table cells, and tags() over the text split at syntax finds the tags rich mode finds, in every kind of block (test/markup.test.ts). In the browser, the highlighting classes show on the text while it stays getMarkdown(), sourceHighlighting: false shows none of them, codeDecorations reach each fence's code, and typing keeps the highlighting current (e2e/source.spec.ts). Typing into 100 KB of Markdown in source mode stays under the keystroke budget (e2e/perf.spec.ts).
  13. In source mode a tag popup opens while typing and a pick inserts the tag as one undo step, no popup opens inside a code span, a fence or a URL, Ctrl+Space opens one, the slash menu does not open, the emoji suggestion's command works, and allow sees mode: 'source' and the source block (e2e/source.spec.ts). Finding the token at the caret in 100 KB of Markdown in source mode stays under a millisecond (e2e/perf.spec.ts).
  14. The formatting keys wrap and unwrap as described, with the markers selected or not, on the word at the caret and on whitespace, and the block keys set and remove headings, toggle each list kind with numbering, quote and fence lines, all after quote markers and never in fenced code (test/sourceMode.test.ts). In the browser each key is one undo step, the commands return true and the others false, isActive stays false, and paste writes HTML as Markdown, plain text as written and in a fence, the editor's own HTML as its Markdown, and a URL over a selection as a link (e2e/source.spec.ts).

Scope. Anything added to source mode must keep requirements 3 and 4. So it is either a decoration, which styles the text and never changes it, or an ordinary text edit recorded in history, as the list keys are.

Every step of the plan for source mode (source ranges, highlighting, autocomplete, formatting keys and paste) is in; memos needs only the toggle control, its shortcut and the checklist chip.

Non-goals: a split or side preview, line numbers, search and replace, hiding or collapsing markup (rich mode does that), auto-pairing of brackets and emphasis markers, smart punctuation or any other rewriting of the text, and a code editor dependency such as CodeMirror.

Undo and redo

Each history entry is a snapshot of { doc, selection } from before a change, with the MarkdownSource current at the time (see "Source mode"). Typing within one second is one step. Moving the caret, a committed composition, or any other command starts a new step. setMarkdown clears the history.

UI

  • Popups use position: fixed and are appended to document.body, so a parent with overflow: hidden (a chat input, a card) does not clip them. Inside an open <dialog> or an aria-modal element they are appended there instead, so they show above the modal and are not inert; the popupContainer option picks the element. When an ancestor of the container has a transform, filter or contain style, position: fixed is relative to that ancestor: each popup measures its offset at left: 0; top: 0 and subtracts it, as Floating UI does. Popups copy the editor's theme variables, stay inside the visual viewport (the on-screen keyboard shrinks it), and flip above the anchor when there is no room below. Their z-index is var(--mbe-popup-z, 1000).
  • Autocomplete (suggestion()); see Autocomplete.
  • Slash menu is a suggestion. It opens on / (or the full-width / from Japanese IMEs) at the start of a block or after a space. Typing filters it. Picking a text type (paragraph, heading, list, quote, callout, code) converts the current block in place and keeps its text; a table or divider goes below the block, or replaces it if empty. A collapsible section makes the current block its title (a block with no text gets a new section below it), with an empty line as its body. It shows "No results" until the query passes three characters with no match, then hides. The menu is a listbox wired to the editor with aria-activedescendant. It rebuilds only when the query changes, so a late selectionchange does not reset the highlighted item.
  • Block handle is a grip icon. It appears on hover next to tables, code blocks, image blocks and callouts only (by a callout's icon, whichever of its paragraphs is hovered), and follows the caret into them on touch devices. It opens the block menu, whose entries are block actions: Duplicate, Delete and, with the caret in a table cell, row and column actions and an Align submenu for the column; on an image block, an Align submenu, Alt text and Reset size (shown only when the image has a width); on a callout, its five types with the current one checked, and Delete for the whole callout (no Duplicate, because a copy right after a callout would join it). Clicking a callout's icon opens the same menu under the icon. Alt text opens the same input popover as the link popover (Mod+K), under the image; Enter applies, Escape cancels, and the image stays selected either way. Mod+/ opens the block menu from the keyboard inside those blocks, and on an image block it selects the image. Opening the block menu puts focus in the editor. Escape, a pick, or a press anywhere outside the block menu and the block handle closes it, a press in the editor's own text included. Other blocks have no block handle; they change type through the slash menu or Markdown shortcuts.
    • Submenus follow Notion: a row with a submenu ends in a chevron and opens it on hover, ArrowRight or Enter. The submenu opens beside the row, top-aligned with it, on the right unless there is no room, and highlights the current choice, which has a check mark. ArrowLeft and Escape close only the submenu; ArrowUp, ArrowDown and Enter work in it while it is open.
    • Image blocks hold no caret. A caret that lands in one (a click beside the image, an arrow key from the block before or after) selects the image instead, Backspace or Delete at the edge of the next or previous block selects it first, and a second press deletes the block. Printable keys do nothing while it is selected; Enter adds a paragraph after it. At the end of the document, ArrowDown adds a paragraph below it, as for a table.
  • Formatting toolbar appears over a non-empty selection. It has nine controls in three groups, with a divider between groups: a text style menu (Text, Heading 1–4); bold, italic, strikethrough, inline code and link; quote, code block and a list menu (bulleted, numbered, to-do). Linear's toolbar was the reference; underline and collapsible sections are left out because Markdown has no syntax for them. The toolbar option's items picks controls, which keep this order.
    • Names, not shortcuts. Each control is an icon button named by its label (aria-label). A tooltip shows the label after 500 ms of hover, and at once while moving between buttons. No shortcut is shown anywhere; buttons and menu rows carry them in aria-keyshortcuts. Buttons show their state with aria-pressed; a menu button shows the icon of the current choice and aria-expanded.
    • Block controls act on every text block the selection touches. Text style sets a style, and picking the current one changes nothing. Quote and the list types toggle, as their shortcuts do. Code block turns adjacent blocks into one code block, a line per block, and drops their formatting (one undo brings it back). A control shows as active only when every selected block has that type. In a table cell only the inline controls show.
    • Menus open on the side of the toolbar away from the selection, flipping when there is no room, and preview each heading style. As in the block menu, focus stays in the editor: ArrowUp and ArrowDown move, Enter picks, Escape closes the menu and leaves the toolbar open, and a press outside the toolbar and the menu closes it.
    • On touch devices the toolbar sits below the selection, away from the native selection menu. Wider than the screen, it scrolls sideways instead of wrapping.
  • Image toolbar appears over a selected image, where the formatting toolbar would be for text: the image's own actions are found by clicking it, not by knowing about the block handle (memos users could not find the alt text, usememos/memos#6480). It shows for every image, inline and inside a quote or list item too, which have no block menu. Its buttons are icon buttons with their label as the name and the tooltip, as the link card's are: on an image block, Align left, Align center and Align right (aria-pressed for the current one; Left removes the alignment word); then Alt text, which opens the input popover under the image; Reset size, only when the image has a width; and Delete, which removes an image block whole and an inline image alone, as Backspace does. It sits over the part of the image its scrolling container shows, with the resize handles' visibleRect, and hides while a handle is dragged, during composition, while a menu, autocomplete popup or the input popover is open, in a block selection and when read-only. Escape closes it until the selection changes, as for the formatting toolbar. toolbar: false turns it off with the formatting toolbar. The block menu keeps the same actions for the keyboard (Mod+/) and touch.
  • Callouts are GitHub alerts (> [!NOTE]). Each paragraph is a quote block with callout set, so editing, Enter, Backspace and the block commands work as in a quote. The renderer gives a callout block a non-editable icon (.mbe-callout-icon, labelled with the type's name, labels.calloutNote and the others) and puts the text in .mbe-content, as a list item does with its marker. The look follows Notion's and Linear's callouts rather than GitHub's alerts: a box tinted with the type's color token, no border, no visible title, and the icon in the type's color, in a column level with the first line. data-quote-joined (on a quote that follows one of the same type) and data-quote-continued (on one followed by one of the same type) hide the icon on every paragraph but the first, and pad and round only the outer edges, so the paragraphs read as one box. Typing [!tip] in a quote converts the whole quote (setCallout acts on the run of adjacent quotes with the same type). Notion and Linear let a callout hold any block; here it holds paragraphs and lists, like a quote, because GitHub's syntax is a blockquote. A list item in a callout is a listItem with callout set, rendered as a blockquote with the callout's attributes, so it takes the same box; the icon shows on the first block whatever its type.
  • Collapsible sections are <details> elements. The model stays flat: a details block is the title, the blocks after it are the body, and a detailsEnd block closes it, so sections nest by pairing like brackets. Every edit runs balanceSections (after clampListIndents): an end with no title is dropped and a title with no end becomes a paragraph, so deleting a title or an end unwraps its section, and a caret on an end moves to the text before it. An end holds no text (isTextless, like a divider): Backspace after it moves into the section's last line, Delete before it does nothing, and copying closes the sections a selection cuts through (closeSections). The renderer marks each block with its section depth (--mbe-section-depth and data-in-section, for the indent) and hides the blocks of a collapsed section (data-section-hidden); the title gets data-collapsed and a toggle button with aria-expanded. Which sections are collapsed is view state in the editor (collapsed, by title ID), not in the model, so collapsing is not an edit and never reaches the Markdown or the history. Sections without open start collapsed on load. Arrow keys and block selection pass over hidden blocks, a block selection that touches a title or an end grows to the whole section, and a caret that lands in a hidden block expands the sections around it (expandAroundSelection). The collapsed state is not saved, so reading a note never changes its Markdown.
  • Link card follows Linear's link toolbar: a small toolbar under a link, with its URL as written and buttons to open, copy, edit and remove it. It shows when the pointer rests on a link for 300 ms, and when the caret is inside a link, not at its edges, so typing next to a link does not bring it up. The pointer wins over the caret. It stays for 250 ms after the pointer leaves, so the pointer can move from the link onto it. Open and a click on the URL go through onLinkClick, as Mod+click on the link does; a link that resolveUrl dropped cannot be opened. Edit selects the link and opens the link popover (Mod+K); Remove keeps the text, as one undo step, and leaves the selection where it was. A text selection, an open menu or autocomplete popup, a block selection, composition and read-only hide it. Clicks on it keep focus and the selection in the editor. linkCard: false turns it off.

Autocomplete

One general popup; the caller owns the syntax. The editor implements the behavior once: opening and closing, keys, async items, placement, IME and accessibility. Each suggestion() brings its triggers, how to find its token (match), where it may open (allow), its items and what a pick writes (command). The slash menu is the only built-in caller.

Finding the token. A matcher gets the text of the block or cell, the caret offset, the formatted content and the triggers, and returns { from, to, query } or null. The default matcher reproduces the original rules for any trigger string: the nearest trigger before the caret at the start of a line or after whitespace, then a query without whitespace (single spaces with allowSpaces); the token ends at the next whitespace. matchToken(scan) builds a matcher from the scanner used for highlighting: it inserts a probe letter at the caret, scans the line around it, and takes the token that covers the probe. The probe lets a scanner see a token the user is still typing (#, or #work/) without a "partial token" mode. It scans other triggers of the same length as the first, so a scanner for # also finds #. A caret inside a character cluster (before a variation selector, as in the keycap #️⃣) is in no token. The controller then checks that the token starts with a trigger, that the query is within maxLength, and allow (by default, not in code, links, images, raw HTML or tokens). Code and raw blocks never run matchers. When two suggestions match, the token that starts closest to the caret wins; on a tie, the earlier extension.

Session. There is at most one session: a suggestion, its block and cell, and its trigger offset. Opening is driven by events and staying open by state, as in CodeMirror:

  • Typed text, and composed text that grows, run the matchers; a match opens a session. Moving the caret into a token, pasting and deleting do not open one. Ctrl+Space (editor.suggestion.open) opens one for the token at the caret even where allow refused, and tells allow and items that the open was explicit.
  • After every change of the document, the selection or focus, the controller finds the session's token again. It stays open while the token is in the same block or cell with the same trigger offset; a text change before the trigger may move the offset. Otherwise, or when the selection is not collapsed, the editor loses focus, becomes read-only, blocks are selected or setMarkdown runs, it closes.
  • Escape closes it and records the token as dismissed: typing in that token does not open it again until the caret leaves it.
  • A pick closes the session, then runs command with the range from the trigger to the token end. Without a command it writes the first trigger, the item's value and a space, as one insertText, so it is one undo step.

Items. SourceRunner (source.ts) owns one request per suggestion. A new query aborts the previous request's AbortSignal, waits out debounce, and calls items. Each request has a number; a result is shown only if it is still the latest. While a newer request is pending, the items shown stay usable and the listbox has aria-busy. With nothing shown after 300 ms, a "Loading…" row appears; it is not an option. A rejection counts as no items. With no items, the popup hides but the session keeps tracking, so it comes back when the query matches again; with emptyLabel it shows that label for queries up to three characters. The editor never filters or sorts; at most limit items are shown. When new items arrive, the highlight stays on the item with the same id.

Keys. The controller sees keydown before block selection and extension key bindings, and only while the popup shows something: ArrowUp and ArrowDown (wrapping; Ctrl+P and Ctrl+N on macOS), Page Up and Page Down, Enter and Tab to pick, Escape. Shift+Tab, Space, ArrowLeft and ArrowRight keep their meaning, and the session follows the caret. With a loading row or the empty label, Enter closes the popup and splits the block. For 75 ms after a popup appears because async items arrived, only Escape is taken, so a key pressed before the user saw it does not pick (CodeMirror's interactionDelay). Ctrl+Space, and Option+Escape on macOS, where Ctrl+Space usually switches input sources and Cmd+I is italic, are bindings in defaultKeymap().

Placement (anchor.ts). The popup's start edge lines up with the trigger's (its right edge in right-to-left text), 4 px below the caret's line, so it does not move sideways while the query is typed. When the token wraps, it lines up with the caret. It keeps its side while open unless it no longer fits. It follows scrolling of any ancestor (the document scroll listener in the capture phase), and window and visualViewport resizes once per animation frame. It hides while the trigger is outside every clipping or scrolling ancestor.

IME. keydown with isComposing or keyCode 229 never reaches the popup. The editor also checks its active composition. Once it ends, an ordinary Enter or arrow key works immediately. While composing, the model follows the composed text, so the query does too; items gets composing: true, and an empty result does not hide a list that is shown (a Pinyin reading matches nothing until it is converted). The query is asked again once the composition ends. Showing or moving the popup never touches the composed block: the popup is outside the editor root. A click on an item while composing first reads the composition into the model and renders the block, which ends the browser's composition, then picks the suggestion.

Accessibility. The root keeps role="textbox" and has aria-autocomplete="list" when any suggestion exists. While the popup shows something, the root also has aria-haspopup="listbox", aria-controls (the listbox) and aria-activedescendant (the highlighted option). aria-expanded is not supported on a textbox, so, as in CodeMirror, the listbox carries aria-expanded="true". The listbox is named by the suggestion's label.

Headless. With render: false there is no Menu. The controller keeps the items and the highlighted index itself and reports them through editor.suggestion.state and the suggestionChange event; an app draws the popup with the listbox and option IDs from the state, so the root's ARIA attributes point at it. setOptions({ extensions }) swaps the callbacks of suggestions with the same names, so React apps can pass callbacks that close over state.

Icons

Every icon in the editor's UI comes from Lucide, the icon set memos uses through lucide-react, so the editor's menus match the app around it. Before this, the UI used Unicode characters (⋮⋮, 🗑, ⊞), which look different in every font and operating system, and an emoji such as 🗑 renders in color.

Decisions

  • The icons are copied, not imported. icons.ts holds the SVG data of the icons the editor uses, taken from lucide-static, with the Lucide version and its ISC license notice in a /*! … */ comment that the build keeps. A dependency on lucide or lucide-react would break the "zero runtime dependencies" rule (see "Summary of decisions") for 26 icons, and lucide-react would tie the core to React. To update an icon, copy its new data from the same package and change the version in the comment.
  • Icons are built with createElementNS, never from markup. This keeps the editor working under a Content Security Policy with Trusted Types, and no host string is ever parsed as HTML. Each icon is an <svg class="mbe-icon"> with Lucide's attributes (24×24 view box, stroke="currentColor", stroke width 2, round caps and joins), aria-hidden="true", and its size set in CSS. The control around the icon carries its accessible name.
  • Icons take the color of the text around them (currentColor), so theme.tokens, a highlighted menu row and the danger color of "Delete" apply to the icon too. base.css sets the icon size (16px); theme.css gives menu icons the muted color, except in a danger row such as "Delete", where the icon takes the row's color.
  • The icons option replaces any built-in icon. It maps an icon name to either a string, shown as text (an emoji or a letter, as before), or an Element, such as an <svg> from another icon set, which is cloned for every place it appears. Names are the keys of labels for the same control, so icons.delete goes with labels.delete. Like labels, the option is fixed for the editor's lifetime. The React wrapper passes it through as a prop that is read on mount.
  • Suggestion items take the same kinds of icon. SuggestionItem.icon is a string (text, as before) or an Element (cloned). An extension's menu can therefore show Lucide icons next to the built-in ones.

The built-in icons

Where Icon name (key of icons and labels) Lucide icon
Slash menu text, heading1, heading2, heading3, heading4 type, heading-1, heading-2, heading-3, heading-4
Slash menu bulletList, numberedList, todoList list, list-ordered, list-todo
Slash menu quote, callout, details, code, table, divider text-quote, info, list-collapse, square-code, table, minus
Callout icon and the callout's block menu calloutNote, calloutTip, calloutImportant, calloutWarning, calloutCaution info, lightbulb, message-square-warning, triangle-alert, octagon-alert
Block menu duplicate, delete copy, trash
Block menu, table cell addRowAbove, addRowBelow, addColumnLeft, addColumnRight arrow-up, arrow-down, arrow-left, arrow-right
Block menu, table cell align text-align-start
Block menu, table cell, Align submenu alignLeft, alignCenter, alignRight text-align-start, text-align-center, text-align-end
Block menu, image block, the Align row and submenu imageAlignLeft, imageAlignCenter, imageAlignRight align-start-vertical, align-center-vertical, align-end-vertical
Block menu, image block altText, resetImageSize text-cursor-input, rotate-ccw
Block menu, a row that opens a submenu chevronRight chevron-right
Collapsible section, the toggle before the title chevronRight chevron-right, turned down when expanded
Block menu, table cell deleteRow, deleteColumn trash
Footnotes collected at the end, the backlink to each reference backToReference arrow-up
Formatting toolbar bold, italic, strike, inlineCode, link bold, italic, strikethrough, code, link
Formatting toolbar, menu buttons and menus text, heading1, heading2, heading3, heading4, bulletList, numberedList, todoList the slash menu's icons
Formatting toolbar quote, code the slash menu's icons
Formatting toolbar, menu buttons and menus chevronDown, selected chevron-down, check
An image that did not load imageUnavailable image-off
Block handle blockHandle grip-vertical
Code block bar copyCode, copied copy, check
Link card openLink, copyLink, editLink, removeLink, copied external-link, copy, pencil, unlink, check

That is 64 places and 45 distinct icons. chevronDown, chevronRight, selected and the three imageAlign* names are the only icon names that are not also labels keys. The image Align choices share the table's labels (alignLeft and the others) but not its icons, because aligning a picture is not aligning text.

The playground is an app built on the editor, so it imports Lucide the way an app would: its formatting bar uses the lucide package (a root devDependency, pinned to the same version as icons.ts) and builds each button's icon with createElement. Each button is named by its title (aria-label). Buttons that are words (Read-only, Theme, Save) stay text. The package never imports lucide.

Not icons. The bullet list marker (•) is part of the rendered document, styled like the text, and stays a character. The checkmark in a checked task box is already Lucide's check path; it stays a data URI in theme.css because it is drawn as the checkbox's background.

Requirements

  • No Unicode glyph remains as an icon in the editor's UI: every menu row, toolbar button and the block handle renders an svg.mbe-icon, unless the host replaced it with a string.
  • The built-in icons add at most 3 KB gzipped to dist/index.js.
  • An icons entry replaces exactly that icon, in every place it appears, and leaves the others as built in.
  • Toolbar buttons keep their accessible names, tooltips and aria-pressed state; tests find them by name, not by text.
  • The core still has no dependencies in package.json.

Non-goals. React elements as icons (<Trash2 /> from lucide-react) are not accepted: the core is not React, and rendering React into every menu row costs more than it gives. The built-in icons are already Lucide's, so memos needs no override. An app that wants another set passes <svg> elements. Icon size and stroke width are CSS, not options.

Extension points

  • Key bindings (keymap): see "Input pipeline".
  • Decorations (decorations): a function from one text container (a paragraph, heading, list item, quote or table cell) to CSS classes on ranges of its text. The context lists the ranges of inline code, links, images and tokens, which textDecorator skips. Decorations are computed while rendering a block, so they only run for blocks that changed, and they are wrapped in span.mbe-deco elements that the DOM-to-model mapping walks through like mark elements. codeDecorations does the same for the code of a code block (syntax highlighting); other decorators never see code blocks. editor.redecorate() re-renders every block with fresh decorations, after the composition ends if one is running, for decorations that read state outside the document.
  • Views (views): a function that renders the source of a token or raw block of one syntax into an element the renderer provides (a span or a div). A token with a view renders as one contenteditable="false" atom that counts as many characters as its source (data-source holds it), so DOM-to-model mapping and the IME read-back still see the source. Raw HTML's view is not an extension's: the editor builds the html view from the sanitizeHtml option (htmlView in view/html.ts), which parses the source into the inert content of a <template> of the editor's document, hands the fragment to the host's sanitizer, and attaches what comes back; nothing returned shows the source, and without the option there is no html view, so the editor renders no HTML at all (an extension's html view is ignored, and the type rejects the key). Inline raw HTML has no token, so the view takes runs instead (htmlRuns in view/dom.ts): an opening tag span through its matching closing tag span in the same container, or one tag span alone; a run is one atom as long as its text, and it reveals like a token. The sanitizer gets only the run's tags, parsed, with a slot marker (slotMarker, private-use characters) in the text where the text between them was; the renderer renders that text itself, with its marks, decorations and tokens, and puts it in place of the marker once the sanitizer has run (fillSlots), never before, or the sanitizer would strip the editor's own markup. An HTML section renders the same way (splitHtmlSection): its source is parsed again, the HTML blocks are joined with one marker per run of Markdown blocks, and each run renders as the editor's blocks in a .mbe-flow container. Those blocks are content of the section, not blocks of the document: the renderer strips their block ids, content markers and contenteditable, and makes their inputs inert. A slot whose marker the sanitizer removed, with the element around it, follows the rest, so no Markdown the user wrote is lost. The stylesheet's block rules select :is(.mbe-root, .mbe-flow) >, so section blocks look like top-level ones, and a re-rendered section keeps which <details> the reader opened. Raw Markdown blocks (syntax: 'markdown') have a built-in view, MARKDOWN_VIEW in view/dom.ts, that the renderer draws itself with the editor's blocks (renderMarkdown): it parses the source again, renders each run of nodes the model can hold as blocks, and draws a quote or list item the model cannot hold as a container (blockquote.mbe-quote, or .mbe-list-item with its marker and a .mbe-flow of its blocks), recursively. Like an HTML section's Markdown, these blocks are content, not blocks of the document. An extension's markdown view replaces it. A raw block with a view renders as a contenteditable="false" block with no content element, like a divider, and so does a code block whose language has a code:<language> view; both reveal their source the same way. A view may return a promise: the renderer caches the element it filled in at once, records which blocks show it, and when the promise settles asks the editor to render those blocks again (on the next frame, or when a composition settles), from the finished element or, after a rejection, as source. Which views show their source is a pure function of the state (view/reveal.ts): a token that either end of the selection touches (edges included) and a raw block that holds either end, only while editable and focused. The renderer keeps each block's revealed views next to its element and rebuilds a block when they change, the same way it rebuilds a block whose object changed. Every render goes through Editor.paint, which recomputes them; selection, focus and editability changes call refreshRevealed, which paints only when they differ. While a mouse button is down nothing changes until mouseup, so a drag is not disturbed. A click on a view puts the caret in its source, and an arrow key that would skip a rendered block steps into its source instead. Rendered elements are cached by source (least recently used, 500 entries) and cloned, so typing next to a formula does not re-run the renderer; listeners a view attaches are lost in the clone, so a view's interaction is CSS or a listener on editor.root from onCreate. A view gets the editor as its last argument: its element is not in the page when it runs, so a view that lays out text (a diagram) reads the font from editor.root and measures on a canvas. The renderer notes which blocks showed each cached, failed or declined view (viewBlocks); dropViews(syntax?) forgets those views and returns the blocks, and Editor.refreshViews(syntax?) renders only them again (after a composition, through unsettled, as settled promises are). A promise still pending when its view is dropped settles into nothing: a later render of the same source owns the cache key. The editor refreshes every view itself when a theme change touches a font token (FONT_PROPERTIES), since the colors are CSS variables but a measured layout is not.
  • Block views (blockView): an extension draws whole blocks of the document that its match picks, for UI that needs data from outside the document, such as a bare link shown as a preview card. Unlike a syntax view, the result is not cached by source and cloned: the renderer keeps one element per block ID (hosted in BlockRenderer) while the block object is the same, and hands the same element back on every render of that block, so app UI mounted into it (a React portal) survives renders the block itself did not cause. The element is the child of a fresh div.mbe-block.mbe-view-block.mbe-block-view root, which carries the editor's own classes and attributes, so the app's element is its own. A block object that changed (its content) gets a new element, and the old one's dispose function (what render returned) runs; so does a block that is gone after a render, every block on dropViews (so refreshViews(name), with the extension's name, draws them again) and on destroy. A view that declined (false) is remembered for that block object, so it is not asked again until the block changes. A hosted block reveals like a raw block with a view: revealedViews marks it REVEAL_BLOCK when the selection is in it, and it then renders as the editor draws it, editable, while the element waits detached; viewEntry puts the caret at its start or end. Blocks inside an HTML section or raw Markdown view are content, not blocks of the document, and never go through a block view, nor does source mode's text block. With placement: 'after' the block renders as the editor draws it and the element follows it in a div.mbe-block-view.mbe-block-after wrapper, contenteditable="false", placed by the renderer between the block's element and its widgets (afterView), with the same lifetime and the same reveal rule as a replacing view: while the selection is in the block the wrapper waits detached, so a link being typed is not previewed on every keystroke, and when the selection leaves the same element is placed again. The block's own element never carries mbe-view-block, so the caret moves through it as through any paragraph, and the wrapper is app UI like a widget: events from it are not editor input (APP_UI in editor.ts), and a click on it reveals nothing. This is the editor's answer to a link on its own line of a paragraph: the line stays a span (a card is block-level, and a span has no identity to keep an element by), the parser never splits the paragraph (the model would then disagree with every other renderer, and a save after an edit would turn the line break into a blank line), and the app finds the line with inlineLines, which splits inline content at "\n".
  • Widgets (addWidget): elements placed after a block element by the renderer, contenteditable="false", and ignored by input handling. A widget follows its block's ID; when a change removes that block, the widget moves to the nearest earlier remaining block (after setMarkdown, the block at the same index). Widgets are not in the document, so they are never saved and undo does not touch them.
  • Paste and drop (handlePaste, handleDrop): run before the editor's own handling. fileHandler is built on them. Dropped text with no handler is parsed as Markdown and inserted at the drop position.
  • Commands are pure functions (state) => state in commands.ts; editor.run(fn) applies any of them, and editor.commands binds the common ones. run treats a command that rebuilt the block list without changing any block as a no-op, so commands.* return false when nothing changed. Two of them carry editing rules an app would otherwise reimplement from model details: insertFragment with block: true replaces an empty paragraph at the target instead of leaving an empty line above the inserted blocks, and insertToken inserts #tag-like text at the selection's focus spaced as a word, reusing a space that follows; commands.insertToken also refuses during IME composition, when an insert would break the composed text.
  • Selections as JSON are block indexes and offsets. Loading the same Markdown always gives the same blocks, so a stored selection fits after a reload; a value that does not fit is clamped and a value that is not a selection is ignored.

Styling

Paragraphs, headings, quotes, list items and table cells have dir="auto", so each takes its direction from its first letter: a Hebrew or Arabic line reads right to left, its list marker moves to the right, and the CSS uses logical properties (padding-inline-start, border-inline-start, text-align: start) so indents and borders follow. Code and raw blocks keep the editor's direction.

style.css imports base.css (layout the editor needs, and every margin between blocks) and theme.css (colors, fonts, borders and backgrounds). base.css sets no colors or fonts; its menus use system colors (Canvas, Highlight) so they stay readable without theme.css. Its spacing selectors are at least two classes strong, so a host's single utility class with a margin cannot change the rhythm. The theme.classes option adds host classes to elements in the same pass that builds them (renderBlock, wrapMarks, renderSpan), so they apply when editing and when read-only alike. Changing the classes re-renders every block; setting the same classes again does nothing. Colors are light-dark() values that read --mbe-<name>-light and --mbe-<name>-dark with the default palette as fallback, so one rule covers both schemes and theme.tokens only sets those variables on the root (tokens.colors sets both, for var() values that pick their own scheme); an app can set the same variables in CSS on any ancestor, since they inherit. theme.colorScheme sets the root's color-scheme, and theme.css also sets it from data-theme or a light or dark class on an ancestor, the class being how Tailwind-style theming toggles it. Neither re-renders. Type sizes other than the body's are ratios of --mbe-font-size (1.5, 1.25 and 1.125 for h1 to h3, 0.875 for code and tables, 0.75 for the code language label), and their line heights add --mbe-leading, the body's line height minus its font size, to their own font size (calc(1em + var(--mbe-leading)); tables and the language label take a fraction of it), so the default 16px/24px look computes to the same pixel sizes as before (24/32, 20/28, 18/26, 14/22, 14/20, 12/16) and the rhythm an app sets for the body carries to headings and code. The floating UI keeps its own fixed sizes. Popups live in document.body, so they copy the computed variables and the root's color-scheme when they open. The default look styles the document like a rendered Markdown view, and the same rules apply when editing and when read-only: read-only adds no visual change except the pointer cursor on links and checkboxes. Checkboxes use appearance: none, so a disabled checkbox is not greyed out by the browser, and the code block language field has the same color when disabled. Every block has the block gap above and below, and vertical margins collapse, so blocks sit one gap apart and a heading's or divider's larger margin wins. Blocks are siblings in one flat list, so list and quote grouping depends on neighbours. The renderer marks it with attributes after each render (data-list-start on the first item of a list, including where a numbered list meets a bullet list, data-quote-joined on a quote block that follows another of the same callout type, and data-quote-continued on one followed by such a block), and the CSS uses those: list items sit 2px apart with the gap around the list, joined quote blocks show one unbroken bar, and a callout's blocks one tinted box. A list item in a quote renders as a blockquote with the list item's class, so the quote's rules style it; its indent moves from the item's padding, which is the quote's, to the marker's margin. Between the parts of a quote the margins are 0 and padding makes the space, so the bar never breaks. See the sibling selector note under Performance. A browser test compares screenshots of the sample document in both modes.

Clipboard

  • Copy and cut write text/plain as Markdown and text/html as rendered HTML. With a block selection they copy the whole blocks. The HTML carries the Markdown in a data-mbe-markdown attribute, so copying between editors is lossless.
  • Paste tries, in order: the editor's own HTML, other text/html (htmlToDoc, which reads tags and inline styles, including Google Docs' wrapper), then text/plain as Markdown. HTML from a code editor or terminal, which only colors the source (VS Code's has its own vscode-editor-data type; others are <div>s and <span>s with no formatting, see isStyledText), is skipped, so Markdown copied from them pastes formatted, not as # Title text. Mod+Shift+V pastes plain text. Inside inline code or a code/raw block, paste inserts the clipboard text literally and keeps the code format. A URL pasted over a selection outside code becomes a link. A URL is a scheme with //, such as https:// or obsidian://, or mailto:, that resolveUrl allows (linkableUrl). Pasted on its own, such a URL that Markdown does not autolink, like obsidian://…, becomes a link too, saved as <obsidian://…>.

Markdown

Parser. The two-phase algorithm from the CommonMark spec, structured like the reference implementation: phase one builds the block tree line by line; phase two parses inline content with all link reference definitions known. GFM adds tables, task items, strikethrough and autolink literals. A www. or http(s):// literal is matched where its text run starts, as cmark-gfm does, so it can run over _ and &; e-mail literals are found afterwards in the final text nodes outside links. Typing a space after a literal links it (applyAutolinkInputRule), and the serializer writes a literal link bare when the output reads back the same. All 652 CommonMark 0.31.2 examples (checked with autolinks: false) and the GFM table, task, strikethrough and autolink examples pass, checked by rendering the syntax tree to HTML and comparing with the spec output. Nesting is capped at 100 levels for blocks and for inline brackets, so hostile input cannot overflow the stack.

Lowering (lower.ts) turns the syntax tree into the flat model. The rules are part of the spec:

  • Soft line breaks become spaces; hard line breaks become "\n". With the breaks option, soft line breaks become "\n" too, and the serializer writes a line break as a plain line ending (a backslash only where a plain one would not read back: after an empty line or a trailing space). The setext: false option turns off setext headings in the parser.
  • Each list item becomes a listItem block with indent equal to its nesting depth.
  • In a block quote each paragraph becomes one quote block, and a paragraph holding only a no-break space an empty one. A list in it becomes list items with quote. When the first line is a GitHub alert marker ([!NOTE] alone on its line, any case), the marker is dropped and every block gets callout; markdown.callouts: false turns this off.
  • A <details> HTML block whose only content is the opening tag and a plain-text <summary>, paired with a later </details> HTML block, becomes a details block and a detailsEnd block, with the blocks between them lowered as usual (detailsSections in markdown/htmlSection.ts, run by loadMarkdown before HTML sections are joined). Pairing uses a stack, so sections nest; an HTML block between them that leaves an element open cancels the pairing, so the element's HTML section wins. markdown.details: false turns this off.
  • Structure the flat model cannot hold is not flattened. A top-level list is kept as one raw block with syntax: 'markdown', holding its source, when an item holds more than one paragraph, any block other than a nested list, or lists nested deeper than five levels. In a quote, every child becomes its own quoted blocks: a paragraph a quote block, a list its quoted items, and a heading, code block, table, divider, HTML or extension block the block with the Quoted fields. A quote inside a quote, or a list the model cannot hold, becomes one quoted raw block holding its source with one quote marker (up to three spaces, > and a space) taken off each line (quotedSource), so only that block is edited as source and the rest of the quote stays blocks; the serializer puts the markers back. The parser records the source lines of quote and list nodes for this (lines). A raw block is edited as source and saved verbatim. It is shown rendered when the caret is elsewhere and when read-only (see "Views" under "Extension points").
  • An HTML section, from an HTML block that leaves an element open to the HTML block that closes it, is one raw block with syntax: 'html', holding all its source lines (htmlSectionEnd in markdown/htmlSection.ts). CommonMark would end the HTML block at the first blank line and parse what follows as Markdown. The tag scan keeps a stack of open element names; a closing tag pops to its element, as a browser closes what was opened inside it. Rendered, each HTML block is parsed on its own, so an element a block never closes ends with the block, where a renderer that concatenates every block into one page would let it swallow the blocks after it; the conformance tests record those cases.
  • Reference-style link labels are not kept. Links are saved inline, with their title.
  • A top-level paragraph holding only a no-break space (&nbsp;) becomes an empty paragraph. This is how empty lines are saved (see "Serializer").

Source-preserving save (source.ts). Loading records, for each top-level Markdown block, its source lines and the model blocks it became (a "group"). Blocks are immutable and every edit replaces the blocks it touches, so a group whose blocks are all still the same objects, in the same order, was not edited. Saving writes such a group's original text, and the original text between two groups that are still neighbours. Other blocks go through the serializer. A kept list, or a quote next to an edited quote of the same callout type, is rewritten too, because Markdown would merge them, and so is a code fence without its closing line that is no longer last. The same check applies to two kept groups that were not neighbours in the source, which happens when the blocks between them are deleted: two lists that now meet are rewritten as one list, and a kept group that starts with indentation right after a list is rewritten so it does not become part of the list's last item. Link reference definitions that are no longer written are added at the end, so reference links in kept blocks still resolve. With no edits, saving returns the input byte for byte; a test checks this for every spec example. A group whose only change is the checked state of task items (each changed block is a task item with the same ID, indent and content object) keeps its source too, with the character between the brackets of each changed item rewritten ( or x). The patched source is parsed again and kept only if it serializes the same as the current blocks; otherwise the group goes through the serializer. So ticking a box changes one byte of the saved Markdown, in a quote or callout too. A block quote's group also records each child of the blockquote (QuoteSource: the source lines of each, quote markers included and trailing blank quote lines left out, and the blocks it became, reported by lowerQuote through SourceText.onQuoteChild). When some blocks of a quote changed, quoteChunk writes the quote child by child: a child whose blocks are all still the loaded objects is written as it was, with the original text between it and a neighbouring kept child; the other blocks go through the serializer, as they are inside the quote, with the markers put before every line, and a blank quote line separates them from a kept child. The lead (blank quote lines, and a callout's marker line as written) stays before a kept first child, and the tail after a kept last child; a callout whose first child changed or went gets its marker line written. As at the top level, a kept child next to a piece that was not its neighbour is written through the serializer when the two would read as one list, when it starts with indentation after a list, or when its fence has no closing line. So editing one block of a clipped page leaves the other blocks of the quote byte for byte, Turndown's _italic_ and * included.

Syntax extensions (markdown/options.ts). An extension can add Markdown syntax that the editor keeps as source, so a renderer that knows it (remark-math, footnotes in remark-gfm) shows it and the editor never breaks it.

  • An inline syntax names its trigger characters and a match(text, pos) function that returns where the construct ends, or -1. The inline parser tries it before the built-in rules at each trigger character. The match becomes a token span (span.token holds the syntax name): shown in a muted monospace style, saved verbatim, and not parsed for emphasis or links.
  • A block syntax has an open(line) function that returns a matcher, and the matcher's next(line) says whether each following line continues the block, closes it (the line is part of it), or ends it (the line is not). interruptsParagraph says whether it can start without a blank line before it. The match becomes a raw block whose syntax is the syntax name.
  • escape lists characters the serializer must escape in plain text, so typed text cannot start the syntax by accident (math escapes $). Where an inline syntax reads a backslash escape as its own token (tags() keeps \#), the serializer writes a character reference instead (&#35;).
  • Typing the closing character of an inline construct turns the text into a token span, the same way **bold** becomes bold.

math({ render }) renders formulas through the host's renderer (the playground uses KaTeX); without render math stays source. math() follows Pandoc's rules for dollar math: an inline opener followed by a space, or a single-dollar closer preceded by a space or followed by a digit, is a plain dollar sign, so "costs $5 and $10" stays text. Block math is a $$ fence. footnotes() adds [^label] references and [^label]: text definitions, and views that show a reference as a superscript label and a definition as a small note with its label. A definition continues after a blank line only in lines indented four spaces, as on GitHub, so a note can hold several paragraphs and a code block; the matcher continues through the blank line, and the parser drops blank lines left at the end of any raw block, as it does for an indented code block. The renderer draws a definition's text itself (renderFootnote in view/dom.ts): the view gets the label part and a slot marker, and the text, with the four-column continuation indent removed, renders as Markdown into the slot, inert, as an HTML section's Markdown does: inline when it is one paragraph, as blocks otherwise, with the label in a column beside it. Read-only, the renderer collects footnotes as GitHub does (footnoteSection): every definition's block gets mbe-footnote-collected, which hides it, and a section.mbe-footnotes at the end of the root shows the referenced definitions in order of first reference, rendered through the same view, each with a button.mbe-footnote-backref per reference (data-label, data-ref; the backToReference icon, a small arrow); definitions nothing references are left out, and labels are shown as written, not renumbered. The section is kept while the definitions and references are the same, and goes when the editor is editable again (setOptions({ editable }) paints when the footnote view exists). Clicking a reference scrolls to its note and a backlink to its reference, in the same editor. tags() and mentions() add no syntax of their own except the \# and \@ escape tokens: tags and mentions are plain text, highlighted by a decorator that scans each run of text with one format separately, so formatting, code, links, images and tokens split or exclude them.

Serializer (serialize.ts) writes normalized Markdown for edited and new blocks: **, *, ~~, ATX headings, - bullets, renumbered ordered lists, fenced code, ---, GFM tables, tight lists. Markdown has no empty paragraph, so an empty line in the editor is written as &nbsp;: it renders as an empty line in any CommonMark renderer and reads back as an empty paragraph. Empty lines at the end of the document render as nothing and are not written. An empty quote is written as > &nbsp;. A section title is written as <details> (or <details open>) and <summary>…</summary> on the next line, with &, < and > escaped, and its end as </details>, each a block of its own with blank lines around it. A callout starts with its marker line in capitals (> [!NOTE]); quotes of different callout types are separate blockquotes, with a blank line between. It escapes only characters that would change meaning. Where an escape is not enough, it writes a character reference: for example a letter right after closing bold (**three!**&#98;). Spaces at the edge of a bold, italic or strike run move outside it, because **a ** is not emphasis, except spaces in a code span, where the delimiter sits next to the backtick. Spaces and tabs at the start or end of a line of text are dropped instead, because Markdown strips them and a reader sees nothing: a space typed first or last, as after picking an autocomplete item, leaves no &#32; in the saved Markdown. A line of only whitespace keeps it, written as references, so the line is not lost. The tests check save stability for every spec example.

Entities. Named character references (&copy;) need the WHATWG list of 2,125 names. Node gets it as a table (entities.ts, about 11 KB gzipped). Browsers use their own HTML parser instead (entities.dom.ts): it decodes &name; inside a detached <textarea>, whose content is parsed as text, never as elements. The #entities import in packages/editor/package.json picks the built file through the browser condition. In development, aliases in tsconfig.json, the playground's Vite config and vitest.config.ts point it at the source files instead. A browser test checks that both give the same result for every name.

React wrapper

<MarkdownEditor> creates one Editor per mount and forwards its ref to it. onChange fires at most once per animation frame. The wrapper keeps a short queue of the values it emitted, and calls setMarkdown only when a new value prop is not one of them, so a parent that re-renders with a slightly stale value does not overwrite newer typing. It calls onChange inside flushSync, so the parent renders each emitted value at once, as React does for a native input's onChange. Otherwise the update could still be queued when the parent sets a value that equals the one it last rendered, such as clearing the box right after fast typing and Mod+Enter, and the wrapper would not see a new value and would keep the typed text. A new value that arrives while an IME is composing waits for the editor to reconcile the final native input, including input delivered after compositionend. placeholder, editable, taskToggle, attributes, resolveUrl, onLinkClick and theme go through setOptions, and so does extensions, which updates the callbacks of suggestion() extensions. The editor is recreated, keeping its Markdown, only when the names of its extensions change. The editor is created with wrappers that call the latest onChange, onSubmit, onFocus and onBlur props, so a parent may pass inline functions without recreating the editor or keeping refs. useSuggestion(editor, name?) subscribes to suggestionChange for apps that draw their own popup. onSubmit(markdown) receives the current Markdown after flushing pending changes.

useEditor(options, deps) creates an editor on a detached element and <EditorContent> moves that element into the page, as in Tiptap. Autofocus waits until the element is mounted.

Performance

Measured on 2026-10-12 in headless Chromium in the development container (npm run test:perf):

Gate (spec) Result
Keystroke handling under 16 ms at p95 in a 2,000-block document 13.4 ms p95, 8.7 ms median, with a frame between keystrokes. Pass.
100 KB of Markdown parsed and rendered in under 100 ms 211–221 ms on a cold first load. Fail. It was 101–125 ms at v0.

Bundle size has no fixed limit (decided 2026-10-12). The goal is a normal size for a Markdown editor, not the smallest possible one. npm run size prints what each published entry adds to an app, bundled for browsers with esbuild, minified and gzipped (1 KB = 1,000 bytes); CI writes the same table to each run's summary. Check it when a change adds a lot of code.

Entry (2026-10-28) Minified and gzipped
Core, Editor only 91.8 KB
Core, every export 95.7 KB
React entry, on top of the core 1.3 KB
style.css 5.8 KB

The emoji entry (@usememos/editor/emoji, 2026-10-15) adds 1.0 KB on top of the core. Its list of 1,870 emoji is a separate file of 18.1 KB that loads the first time the popup opens, so an app that adds emoji() pays for the list only when someone types an emoji.

The core was 33.8 KB at v0, before the extensions, theme, autolinks, icons and the autocomplete popup, and 55.9 KB on 2026-10-13. The two weeks after that added source mode with its highlighting, source maps and autocomplete, callouts, collapsible sections, block views, footnotes, the image toolbar and resize handles, the link card and the theme tokens, which took it to 90 KB; an app measured 95 KB with the React entry and an extension. Nearly all of it is editing code: editor.ts (23%), rendering (10%), the commands (9%), the Markdown parser (11%) and serializer (4%), source mode and its highlighting (7%), the autocomplete popup (3%), the toolbar and popups (6%) and HTML paste (3%). The 26 Lucide icons are 2.8 KB minified. The published files are minified (decided 2026-10-28, asked for by a clipper that pins the package), with source maps beside them for readable stack traces: dist/index.js is 294 KB, 96 KB gzipped, where the unminified file was 551 KB. An app's bundler minifies them again either way, so this changes the install size and what npm run size measures, not what the app ships; re-minifying costs about 1 KB gzipped on the core, since the short names are already taken.

For comparison, the same measurement of other editors set up for Markdown with tables, task lists and undo (versions from npm on 2026-10-13, React not included):

Setup Minified and gzipped
This editor, Editor only 92 KB (56 KB on 2026-10-13, when the others were measured)
Milkdown 7.22 (@milkdown/kit: core, CommonMark and GFM presets, history, listener) 141 KB
Tiptap 3.31 (StarterKit, @tiptap/markdown, tables, task lists) 155 KB
Lexical 0.52 (rich text, history, Markdown, lists, links, code, tables) 160 KB
CodeMirror 6, as memos sets it up today (lang-markdown with GFM, which also loads the HTML, CSS and JavaScript parsers; autocomplete, history, highlighting) 185 KB
memos' read view today (react-markdown, remark-gfm, remark-breaks, remark-math, rehype-raw, rehype-sanitize) 104 KB

memos plans to use this editor for both editing and viewing memos, so it can drop both of the last two rows.

Many read-only editors on one page are cheap: in the same container, creating 200 read-only editors with taskToggle, each showing a 12-line memo with a task list, a table, tags and math, took 2.5 ms per editor. Typing in another editor on the same page took 2 ms longer per keystroke at the median and 4 ms longer at p95 than with no read-only editors.

What made the difference:

  • No ::selection rule and no sibling selectors in the CSS. Both made every selection update restyle the whole document. A + rule that can match any block also made each keystroke restyle and re-lay out every block after the caret (typing p95 went from about 10 ms to 25 ms in the 2,000-block test), so spacing that depends on the block above comes from attributes the renderer sets (see Styling).
  • List indentation uses attribute selectors, not an inline custom property per item. Inline styles stop Chrome from sharing computed styles, which doubled style time on load.
  • content-visibility: auto on loaded blocks (see "Editing surface").
  • Full renders build a fragment and insert it once; read-only state is applied only when it changes.

The cold-load result depends on the JavaScript engine warming up: about half of it is the first parse. The container is shared and noisy, so the number should be re-measured on a typical laptop before deciding whether more work is needed.

Testing

Command What it runs
npm test Unit, spec and round-trip tests (vitest, Node), including every example in docs/syntax.md.
npm run test:e2e Browser tests in Chromium: editing, block selection, menus, toolbar, links, tables, clipboard, IME, extensions, themes, React, entity decoding.
npm run test:e2e:themed The playground, clipboard and fuzz browser tests with a class on every theme.classes key, to show theme classes change no behavior. The editor never reads class names, so these specs, which cover every block type, copy and paste, and random editing, are enough.
npm run test:perf The two timing gates, run alone.
npm run test:timing Inputs that make Markdown parsers slow (test/conformance/timing.test.ts), run alone because other test files running in parallel skew the timings. Four times the input must take less than twelve times as long, and 100 KB less than a second. CI runs it after the unit tests.
npm run typecheck TypeScript in strict mode.
npm run build The published files in packages/editor/dist: ES modules bundled with esbuild (index.js, react.js, the two entity files), the stylesheets, and type declarations from tsc. Members marked @internal are left out of the declarations.
npm run size The size table under "Performance". A report, not a gate.

npm test includes the conformance tests (packages/editor/test/conformance). They check 1,032 Markdown inputs against what other renderers give for them, never against the editor's own output. The inputs come from public test suites (CommonMark, cmark-gfm, cmark, commonmark.js, markdown-it, and micromark's fixtures with the HTML github.com rendered for them, listed in vendor/SOURCES.md) and from realistic notes (realistic.json). The expected HTML is github.com's where a fixture has it, and otherwise cmark-gfm's (GitHub's parser) where micromark gives the same. cmark-gfm follows CommonMark 0.29; where micromark and commonmark.js agree on something else (and, for the CommonMark, commonmark.js and markdown-it suites, the suite's own result does too), the expected HTML is theirs, CommonMark 0.31.2 (decision D7). Where the references disagree, the case has no expected result and shows as a todo. Two layers are checked: the parser's output (html.ts) and what the editor shows, read back from its DOM by render.ts. Both sides go through canonical.ts, which drops differences a reader cannot see, such as whitespace between blocks, how marks nest, and tight or loose list items. A third layer saves each case with every block written by the serializer, as if all were edited, and checks that the saved Markdown shows the same as the original. A fourth layer renders the cases that memos' dialect (line breaks, no setext headings) changes in that dialect, and compares them with the old memos pipeline: micromark with setext underlines disabled and remark-breaks' line breaks, built into corpus.json as memos. It runs where micromark gives the expected result in the default dialect. A fifth layer renders each case's saved Markdown (every block written by the serializer) with micromark and the GFM extensions, and checks that it reads as the original does, where micromark gives the expected result for the original. Known differences are listed with their reason in known-failures.json and run as expected failures, so a fix makes its test fail until the entry is removed. npm run conformance:corpus rebuilds corpus.json from the vendored suites; it needs Node and python3 -m pip install cmarkgfm==2025.10.22. fuzz.test.ts builds 20,000 random documents from fragments that meet at edge cases and compares the parser (and every tenth document, what the editor shows) with commonmark.js and micromark where those two agree. It takes about 45 seconds; FUZZ_RUNS and FUZZ_SEED run more. A difference fails with the smallest input that still shows it; known ones are in fuzz-known.json. tags.test.ts checks which tags and mentions the default tags() and mentions() highlight, with memos' Markdown options, for 696 inputs in tags.json: twitter-text's conformance cases, the memos server's tests, the memos web tests removed when memos moved to this editor, realistic notes, and one case per Markdown context (headings, lists, quotes, callouts, tables, emphasis, links, code, raw HTML, math, footnotes, escapes, URLs, e-mail addresses). The expected results follow the memos server's grammar, with Unicode cases from twitter-text and GitHub deciding what is a link or code. unsafe.test.ts ports mdast-util-to-markdown's unsafe patterns: text holding each character where it could be read as syntax is saved from a paragraph, heading, list item, quote and table cell, and must load back as the same text and show as that text in micromark. urls.test.ts renders 72 inputs from markdown-it's, micromark's, commonmark.js's and memos' URL safety tests, plus URLs a browser reads differently from how they are written (java&#9;script:), and checks that no href, src or other URL attribute has a scheme outside the default policy, and no script, event handler or frame renders.

The browser tests run against the playground built with Vite and served as static files, not the dev server. Each test opens a new page, and the dev server's 55 module requests made that load about half of each test's time. The build is unminified, so stacks and CSS read as in the source.

e2e/fuzz.spec.ts runs two fixed seeds with the other browser tests. A nightly workflow (.github/workflows/fuzz.yml) runs 30 new seeds in Chromium, Firefox and WebKit, numbered from the date. A failure prints its seed; FUZZ_SEED=<seed> replays it.

CI (.github/workflows/ci.yml) runs the typecheck, unit tests, timing suite, build and the browser tests in Chromium (plain and themed), Firefox and WebKit on every push to main and every pull request. Firefox and WebKit each run in two shards, as four jobs side by side. Tests that drive IME through the Chrome DevTools Protocol run in Chromium only. The timing gates are left out because shared runners are too noisy for them.

IME is simulated through the Chrome DevTools Protocol. Real input methods are covered by the manual checklist in docs/ime-checklist.md.

Risks and gaps

  • Firefox and WebKit are Playwright's builds, not the Firefox and Safari people use. They run the whole browser suite in CI, but on Linux, so macOS and iOS key bindings (Cmd+arrows, Option+Backspace) are not covered.
  • IME was simulated, not typed with a real IME. e2e/ime.spec.ts drives composition through the Chrome DevTools Protocol and dispatches the events mobile keyboards send; docs/ime-checklist.md lists what still needs a real device. The manual checklist needs an owner before release.
  • Spellcheck and autocorrect replacements (insertReplacementText, and insertText over a word) are tested with script-made events in Chromium and Firefox. WebKit drops the target ranges of such events, so its test is skipped; real devices are on the IME checklist.
  • The load-time gate fails (see "Performance"). Load time should be measured on a laptop before deciding what to optimize.