@latentic/live-markdown-vue
v0.7.1
Published
WYSIWYG markdown editor for Vue 3 on CodeMirror 6: a component with v-model over @latentic/live-markdown-core.
Maintainers
Readme
@latentic/live-markdown
WYSIWYG markdown editing for React — where the markdown is still the document.
A markdown editor built on CodeMirror 6. Headings, tables, LaTeX math, Mermaid diagrams, images, footnotes and code blocks render inline as you type — there is no split-screen preview pane to sync, and no syntax left on screen to read past.
And unlike rich-text editors built on ProseMirror, Tiptap, Slate or Lexical, there is no intermediate document model to translate through. value in and onChange out are the same markdown string, byte for byte, YAML frontmatter included.
import { CodeMirrorMarkdownEditor } from "@latentic/live-markdown";
<CodeMirrorMarkdownEditor
value={markdown}
onChange={setMarkdown}
mode="wysiwyg" // or "source" for raw markdown
/>| Package | For |
|---|---|
| @latentic/live-markdown | React: the component above |
| @latentic/live-markdown-vue | Vue 3: <MarkdownEditor v-model="markdown" /> |
| @latentic/live-markdown-core | Any page: createMarkdownEditor(element, options) |
The React and Vue packages export everything the core does, so an app installs one of the three. See Vue and Without a framework.
Why @latentic/live-markdown
Most markdown editors fall into two camps:
| Camp | Examples | Trade-off |
|------|----------|-----------|
| Raw editors | CodeMirror, Monaco, Ace | Fast, plain text — but users see ## Heading, not a heading |
| Rich editors | Tiptap, ProseMirror, Slate, Lexical | WYSIWYG — but the internal model is a custom AST, not markdown. Round-tripping to .md is lossy or fragile |
@latentic/live-markdown sits in between. The source of truth is the raw markdown string. CodeMirror parses it with Lezer, and a decoration engine replaces syntax tokens with rendered widgets in real time — ## Heading becomes a styled heading, - item becomes a bullet,  becomes an inline image. You edit the rendered form directly — no syntax on screen, no preview pane to keep in sync — while value in and onChange out stays a plain markdown string. No AST translation, no serialization bugs, no format lock-in.
The boundary semantics this demands — what every keystroke does at every construct edge — are specified in docs/interaction-spec.md and enforced by its conformance matrix (interactionMatrix.test.ts); block-level behaviors are specified executably in packages/core/src/codemirror/features/*.feature.
How it compares
| Feature | @latentic/live-markdown | Tiptap / ProseMirror | ink-mde | @mdxeditor/editor | Novel | |---------|-----------|---------------------|---------|-------------------|-------| | Source of truth | Markdown string | Custom AST | Markdown string | MDX AST | ProseMirror AST | | Rich rendering | Inline decorations | DOM nodes | Syntax highlight only | DOM nodes | DOM nodes | | Round-trip fidelity | Byte-for-byte | Lossy (serializer) | Byte-for-byte | MDX subset | Lossy | | YAML frontmatter | Preserved, never stripped | Plugin (varies) | No | Plugin | No | | LaTeX math | Inline KaTeX | Plugin | No | Plugin | No | | Mermaid diagrams | Rendered inline | Plugin | No | Plugin | No | | Large files (1 MB+) | Fast (CodeMirror) | Slow (DOM-per-node) | Fast | Slow | Slow | | Tables | GFM, cell navigation | Plugin | Basic | Plugin | Slash command | | Image paste/drop | Built-in | Plugin | No | Plugin | Plugin | | Framework | React | React / Vue / vanilla | Vanilla / adapters | React | React | | Bundle size | 67 KB gzipped* | ~120 KB+ | ~40 KB | ~150 KB+ | ~200 KB+ |
* The whole surface. The package ships one module per source file rather than one bundle, so a host pulls only what it reaches — Compose reaches 90 of 113 — at the cost of ~10 KB in lost cross-module minification if you use all of it. CodeMirror, KaTeX and Mermaid are external, so you pay for a renderer only where your documents use one — the other figures are the projects' own published numbers and are not all drawn on the same basis.
Key differentiators
Markdown in, markdown out. No AST translation layer. The
valueprop is a markdown string;onChangereturns a markdown string. What you put in is exactly what you get out, byte for byte. YAML frontmatter is preserved and never stripped.Rich editing without leaving markdown. Headings, bold, italic, strikethrough, inline code, block code, bullet lists, ordered lists, task lists, tables, horizontal rules, images, footnotes, LaTeX math, and wikilinks all render inline. The user never sees raw syntax unless they switch to source mode.
Fast on large files. Built on CodeMirror 6's virtual viewport — only visible lines are rendered. A 1 MB document opens instantly and scrolls at 60 fps. ProseMirror/Tiptap-based editors create a DOM node per text node and degrade on large documents.
Per-tab state caching. When used with tabbed interfaces, editor state (cursor position, scroll offset, undo history) is cached per file and restored instantly on tab switch — a pointer swap, not a re-parse.
Extension system. Add custom markdown rendering by contributing
NodeRules — one function per syntax node deciding how it paints (line class, styled span, hidden marker, or widget). Built-in extensions: highlight marks, footnotes, math (KaTeX), tables (cell navigation + resize), wikilinks.Toolbar slot, not toolbar opinions. The editor renders a host-supplied
toolbararound the liveEditorView, andselectionActionsaround the current selection — both are render props ((ctx) => ReactNode). The host app owns Save, Export, Comments, or whatever actions it needs — the editor stays agnostic.
Features
Inline rendering
- Headings (ATX
#only — setext---/===disabled for predictability) - Bold, italic, strikethrough, inline code
- Block code with language label
- Bullet lists, ordered lists, task lists (interactive checkboxes)
- Tables — GFM syntax, cell-by-cell Tab navigation, column resize
- Images — inline preview, drag-and-drop, clipboard paste
- Horizontal rules
- Footnotes — inline marker with hover preview
- LaTeX math — inline
$...$and display$$...$$via KaTeX - Mermaid diagrams — a
```mermaidfence renders as a live diagram; click to select, double-click for the source - Wikilinks —
[[Page]]and[[Page|alias]]with Cmd/Ctrl-click navigation - Links — Cmd/Ctrl-click to open, auto-detection
Editing
- Rich / Source mode toggle — switch between rendered and raw markdown
- Smart list continuation — Enter continues the current list item tightly (no blank-line gap)
- Cursor model — arrow keys skip hidden syntax markers, land on visible content
- Delete normalizer — Backspace/Delete removes visible content, collapses empty format spans
- Format commands — Cmd+B (bold), Cmd+I (italic), Cmd+E (inline code)
- Block commands — Cmd+1..3 (heading levels), Cmd+Shift+7..9 (lists, blockquote)
- Click model — Cmd/Ctrl-click on links and wikilinks to navigate; single click places caret at visible content, never inside a hidden marker
- Image insert — toolbar button opens a file picker, inserts at caret
Data
- Frontmatter — YAML frontmatter is parsed, held aside during editing, and recombined on save. Never stripped, never corrupted, never shown in the editor body.
- Autosave debounce —
onChangefires 500ms after the last keystroke (configurable) - State caching — per-file
EditorStatecache for instant tab switching
Installation
npm install @latentic/live-markdown
# or
pnpm add @latentic/live-markdownPeer dependencies: react and react-dom (18+).
All in-editor styling (headings, code, lists, tables, image widgets, links) ships with the editor as a CodeMirror theme and applies automatically — no CSS import needed. For the outer container layout (so the editor fills its parent and scrolls), import the small stylesheet once:
import "@latentic/live-markdown/styles.css";Skip it if your app already lays the editor out as a flex child.
Mathematics needs no import either. KaTeX and its stylesheet load together, the first time a document has math in it. To have the styles before that, import them yourself:
import "@latentic/live-markdown/katexStyles";Do not install KaTeX for its stylesheet: a second version ships the library twice.
Usage
Basic
import { useState } from "react";
import { CodeMirrorMarkdownEditor } from "@latentic/live-markdown";
function Editor() {
const [doc, setDoc] = useState("# Hello\n\nStart writing...");
return (
<CodeMirrorMarkdownEditor
value={doc}
onChange={(newValue) => setDoc(newValue)}
/>
);
}Source mode
<CodeMirrorMarkdownEditor value={doc} onChange={setDoc} mode="source" />With toolbar actions
The toolbar render prop receives the live EditorView, so host buttons can drive editor commands:
<CodeMirrorMarkdownEditor
value={doc}
onChange={setDoc}
toolbar={({ view }) => <button onClick={() => save(view.state.doc.toString())}>Save</button>}
/>A button that edits the text must leave the focus in the editor, or the next key goes nowhere. Stop the mouse-down from taking it:
import { formatCommands } from "@latentic/live-markdown";
toolbar={({ view }) => (
<button onMouseDown={(event) => event.preventDefault()} onClick={() => formatCommands.toggleBold(view)}>
Bold
</button>
)}Hooks, for your own frame
The component is useMarkdownEditor with a toolbar and selection slots around it. A host that lays out its own frame uses the hooks directly:
import { formatCommands, useCaretContext, useEditorSelection, useMarkdownEditor } from "@latentic/live-markdown";
function NoteEditor({ doc, setDoc }: { doc: string; setDoc: (doc: string) => void }) {
const { ref, view } = useMarkdownEditor({ value: doc, onChange: setDoc });
const caret = useCaretContext(view); // what the caret sits in: bold, heading level, list…
const selection = useEditorSelection(view); // the selected text, or null for a caret
return (
<article>
<button aria-pressed={caret.bold} onMouseDown={(event) => event.preventDefault()} onClick={() => view && formatCommands.toggleBold(view)}>
Bold
</button>
<div ref={ref} />
{selection && <p>{selection.text.length} characters selected</p>}
</article>
);
}editor is null until the editor mounts, then has flush(), getValue(), setMode() and the rest of the framework-free editor. useCaretContext re-renders only when the context changes, not on every key typed inside one paragraph.
Wikilinks
<CodeMirrorMarkdownEditor
value={doc}
onChange={setDoc}
linkTargets={new Set(["notes/Daily.md", "notes/Ideas.md"])}
onNavigateToLink={(path) => openFile(path)}
/>Props
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| value | string | — | The markdown content (controlled) |
| onChange | (value: string, changes: DocumentTextChange[]) => void | — | Called after edits, debounced |
| mode | "wysiwyg" \| "source" | "wysiwyg" | Rich rendering or raw markdown |
| extensions | readonly MarkdownExtension[] | — | Host-contributed extension modules, merged after the built-ins |
| toolbar | (ctx: { view, contributions }) => ReactNode | — | Host-rendered toolbar, given the live editor view and any toolbar items the extensions contributed |
| selectionActions | (ctx: { selection, dismiss }) => ReactNode | — | Host-rendered actions for the current selection (e.g. a comment bubble) |
| linkTargets | ReadonlySet<string> | — | Known file paths for wikilink resolution |
| onNavigateToLink | (path: string) => void | — | Called on Cmd/Ctrl-click of an internal link |
| workspaceRoot | string | — | Root path for resolving relative image URLs |
| filePath | string | — | Current file path (for image resolution context) |
| resolveImageSrc | ResolveImageSrc | render as-is | Map a markdown image src to a loadable URL |
| saveImageBytes | SaveImageBytes | inline as data: | Persist a pasted/dropped image at a workspace-relative path |
| onOpenExternalUrl | OpenExternalUrl | new browser tab | Open a clicked external link |
Extensions
A MarkdownExtension bundles everything a feature needs: a grammar (new syntax), NodeRules (how syntax nodes paint), CM6 extensions, a keymap, lineKeys and lineKinds (rules for the line keys), and optional toolbar contributions. Rules are merged into the painter through a facet, so an extension adds a construct without touching the core rules table.
Built-in extensions:
highlightExtension— highlight/mark renderingfootnoteExtension— footnote markers with inline previewmathExtension— LaTeX math via KaTeXtableExtension— GFM tables with cell navigationwikilinkExtension—[[wikilink]]rendering and navigation
The built-ins load themselves. To add your own, hand the editor your modules:
<CodeMirrorMarkdownEditor value={md} onChange={setMd} extensions={[myExtension]} />They are merged after the built-ins, so a module can deliberately override a construct — the merger warns when a node rule is redefined, so an accidental shadow is not silent. Modules apply in source mode as well as wysiwyg: a keymap or a plain CM6 extension is not a markdown-rendering concern, and node rules simply go unread while the painter is off.
The prop is read when an editor state is built, not on every render, so building the array inline costs nothing and cannot remount the editor. Changing it mid-session takes effect at the next rebuild.
To merge modules yourself — composing a preset, or feeding a CodeMirror view you
own — mergeExtensions is the same function the editor uses:
import { mergeExtensions, mathExtension, tableExtension } from "@latentic/live-markdown";
const merged = mergeExtensions([mathExtension, tableExtension()]);
// merged.extensions — CM6 Extension[] (each module's node rules ride along via
// a facet, so this is all a view needs)
// merged.toolbar — merged ToolbarContribution[]
// merged.grammar — what the modules add to the parser, for editingStackWithA custom extension
A rule is one function per Lezer node name, returning how that node paints. The mark combinator covers the common "style this span" case. Rules merge last-wins, so an extension can introduce a construct from its own grammar or deliberately restyle a built-in one:
import { mark, type MarkdownExtension } from "@latentic/live-markdown";
const fancyEmphasis: MarkdownExtension = {
name: "fancy-emphasis",
version: "1.0.0",
rules: {
// override how the built-in Emphasis node paints
Emphasis: mark("cm-fancy-emphasis"),
},
};
<CodeMirrorMarkdownEditor value={md} onChange={setMd} extensions={[fancyEmphasis]} />Paint is a closed set — line class, span mark, hide, widget, or nothing — while node names grow, so styling a construct is always one rule in one place.
CodeMirror, from the editor's own copy
A module is written against CodeMirror, and CodeMirror does not recognise an extension made with another copy of itself. Import it from the package, not from a copy of your own:
import { EditorView, keymap } from "@latentic/live-markdown/cm/view";
import { Prec } from "@latentic/live-markdown/cm/state";cm/state, cm/view, cm/language and cm/commands are the @codemirror/* packages; cm/markdown is @lezer/markdown.
New syntax
grammar adds to the markdown parser, and rules paints the nodes it makes:
import { mark, type MarkdownExtension } from "@latentic/live-markdown";
import type { MarkdownConfig } from "@latentic/live-markdown/cm/markdown";
const tagSyntax: MarkdownConfig = {
defineNodes: ["Tag"],
parseInline: [{
name: "Tag",
parse(cx, next, pos) {
if (next !== 35 /* # */) return -1;
const word = /^#[a-z][\w-]*/.exec(cx.slice(pos, cx.end));
return word ? cx.addElement(cx.elt("Tag", pos, pos + word[0].length)) : -1;
},
}],
};
const tags: MarkdownExtension = {
name: "tags",
version: "1.0.0",
grammar: [tagSyntax],
rules: { Tag: mark("cm-tag") },
};Keys
A module's keymap runs ahead of CodeMirror's stock keys and the editor's own, and a later module's ahead of an earlier one's. A binding that returns false passes the key on.
const submit: MarkdownExtension = {
name: "submit",
version: "1.0.0",
keymap: [{ key: "Mod-Enter", run: (view) => send(view.state.doc.toString()) }],
};Enter, Tab and Shift-Tab are the exception, with Backspace, Delete and a typed marker: one table decides them (packages/core/model/README.md). Change those with lineKeys. A rule names the key, and may name the kind of line, the kind of the line beside it and the place of the caret. It runs one of the editor's actions by name, or a command of its own; a command that returns false passes the key to the next rule and then to the table. lineKinds names kinds of line the editor does not know:
const definitions: MarkdownExtension = {
name: "definitions",
version: "1.0.0",
lineKinds: [(_state, line) => (line.text.startsWith(": ") ? "definition" : null)],
lineKeys: [
// Enter at the end of a definition starts the next one.
{
key: "Enter",
line: "definition",
at: "end",
run(view, { pos, line }) {
if (line.text === ": ") return false;
view.dispatch({ changes: { from: pos, insert: "\n: " }, selection: { anchor: pos + 3 } });
return true;
},
},
// Backspace at the start of a heading keeps the heading.
{ key: "Backspace", line: "heading", at: "start", run: "nothing" },
],
};A reader may also say where the line's text starts, so the caret's place is counted from there: { kind: "definition", textFrom: line.from + 2 }.
Checking a module's rules
The editor's line keys are checked as a whole: every state has one outcome, Backspace always makes progress, Enter can be undone. checkLineKeys runs the same checks with your modules mounted, in your own test (jsdom or a browser):
import { checkLineKeys } from "@latentic/live-markdown/testing";
const report = await checkLineKeys({
modules: [definitions],
lines: [[": ", "word text"], [": ", ""]], // a line of each kind you name, as [marker, text]
keys: ["Backspace", "Enter", "Tab", "Shift-Tab", "Delete"],
});
expect(report.failures).toEqual({});
expect(report.uncovered).toEqual([]);report.tla is the rules as a TLA+ module. Save it as LineKeysRules.tla beside model/LineKeys.tla and model/LineKeys.cfg from this package, and TLC checks it:
java -cp tla2tools.jar tlc2.TLC -config LineKeys.cfg LineKeys.tlaThe definition list above with only its Enter rule fails there: EnterUndone is false, because Backspace on the new empty definition takes one character, not the marker. packages/core/src/codemirror/lineKeys/hostExample.test.ts is that module with the Backspace rule it needs, and CI runs TLC on it.
Vue
pnpm add @latentic/live-markdown-vue<script setup lang="ts">
import { MarkdownEditor } from "@latentic/live-markdown-vue";
import "@latentic/live-markdown-vue/styles.css";
import { ref } from "vue";
const markdown = ref("# Hello");
</script>
<template>
<MarkdownEditor v-model="markdown" mode="wysiwyg" @open-external-url="open" />
</template>The model is the whole file and updates 500 ms after the last edit. A template ref gives flush(), getValue() and view(). The toolbar slot gets { view, contributions }; the selection slot gets { selection, dismiss }. The other props are those of the React component.
On a server the component renders its empty container, and the editor mounts in the browser.
Without a framework
pnpm add @latentic/live-markdown-coreimport { createMarkdownEditor } from "@latentic/live-markdown-core";
import "@latentic/live-markdown-core/styles.css";
const editor = createMarkdownEditor(document.querySelector("#editor")!, {
value: "## Hello\n\n- one",
onChange: (markdown) => save(markdown),
});
editor.setValue(markdown); // new content; the editor's own output is ignored
editor.setDocument(markdown, "b.md"); // another document, with its own caret and undo
editor.setMode("source");
editor.flush(); // emit a pending edit now, before a save
editor.destroy(); // a pending edit is dropped: flush firstThis is what the React and Vue components call. The package imports in Node with no document; the editor itself needs a browser.
With no build step, load it from a CDN:
<link rel="stylesheet" href="https://esm.sh/@latentic/live-markdown-core/styles.css" />
<div id="editor"></div>
<script type="module">
import { createMarkdownEditor } from "https://esm.sh/@latentic/live-markdown-core";
createMarkdownEditor(document.querySelector("#editor"), { value: "# Hello", onChange: console.log });
</script>There, KaTeX's stylesheet is linked from jsDelivr, at the version of KaTeX that typesets the math. A page that links KaTeX's stylesheet itself keeps its own.
A file of any size
createPagedMarkdownView shows and edits a file a few windows at a time. It holds about a megabyte of the file, whatever the size of the file. The host reads the file; the view asks it for windows by byte.
import { createPagedMarkdownView, type PagedSource } from "@latentic/live-markdown-core";
const source: PagedSource = {
size, // bytes in the file
window: (around, target) => read(around, target), // about `target` bytes with the byte `around` in them
windowFrom: (from, target) => readFrom(from, target),
windowBefore: (end, target) => readBefore(end, target),
edit: (from, to, text) => replace(from, to, text), // leave out for a read-only view
};
const paged = createPagedMarkdownView(document.querySelector("#editor")!, source, {
onEdit: () => scheduleSave(),
onMove: (byte) => remember(byte), // pass it back as `startAt` to open there
});
await paged.sent(); // every edit made so far is at the source: save now- A window is
{ from, to, firstLine, text, exact }. Start each window where a top-level block starts, so its text reads as it does in the whole file. - Edits arrive one at a time, in the order made. No window is asked for while one is on its way.
memorySource(text)is a source over a string, for tests and trials.
In a CodeMirror view you own
The editing rules alone, for a view the host builds:
import { EditorState } from "@latentic/live-markdown-core/cm/state";
import { EditorView } from "@latentic/live-markdown-core/cm/view";
import { editingStackWith, editorBaseTheme, markdownDecorationsPlugin, mergeExtensions, tableExtension } from "@latentic/live-markdown-core";
const merged = mergeExtensions([tableExtension(), tags]);
new EditorView({
parent: document.querySelector("#editor")!,
state: EditorState.create({
doc: "# Hello",
extensions: [...editingStackWith(merged.grammar), markdownDecorationsPlugin, editorBaseTheme, ...merged.extensions],
}),
});Frontmatter, the emit delay and the per-file state cache belong to createMarkdownEditor and are not in this stack.
Architecture
value (markdown string)
│
├─ parseFrontmatter() ─→ frontmatter (held in ref) + body
│
body ─→ CodeMirror EditorState
│
├─ Lezer markdown parser (tokenizes)
├─ Paint engine (each node's NodeRule → Decoration)
├─ Extension plugins (math, tables, footnotes, ...)
└─ EditorView (renders only the visible viewport)
│
onChange ─→ serializeMarkdown(frontmatter + body)
│
└─ markdown string outThe decoration engine walks the Lezer syntax tree on every document change, asks each node's NodeRule how to render, and applies the returned paint as Decoration.replace, Decoration.mark, or Decoration.line. Widgets are stateless — they read from the document and write dispatch calls back. No intermediate AST, no custom document model.
Roadmap
- [x] Host-injected toolbar and selection-action slots (bring your own UI)
- [x] Host-environment seams (image storage/resolution, link opening) with browser defaults
- [x] Self-themed editor surface (CodeMirror theme ships with the package)
- [x] Public extension API for contributing node rules (
MarkdownExtension.rules→nodeRulesFacet) - [ ] Ship the engine without React — the editor is React only at its edge: of 195 source files, one component and one
type ReactNodeimport name it. Splitting/reactinto a subpath entry frees the engine for any framework, or none - [ ] Frontmatter as a toggleable extension (default on, disable via prop)
- [ ] Collaborative editing (CM6 collab extension)
- [ ] Slash commands (
/menu for inserting blocks)
Development
pnpm install
pnpm --filter @latentic/live-markdown-core exec playwright install webkit # once, for the browser tier
pnpm check # typecheck + build + both test tiersTests run in two tiers, and the split is deliberate:
| tier | command | what it is for |
|---|---|---|
| default | pnpm test | everything that does not need layout — jsdom and node |
| browser | pnpm test:browser | real WebKit, for what jsdom cannot judge |
jsdom has no layout engine, so caret geometry, click placement, drawn selection
and KaTeX metrics all pass in it whatever they do on screen. Anything that
depends on where a box actually lands belongs in a *.browser.test.ts.
pnpm build is part of the gate rather than a release step: tsc --noEmit
never emits, so the errors that appear only when rolling up declarations — an
exported anonymous class, an inferred type naming a transitive dependency by
its package-manager path — stay invisible until a publish fails.
Releasing
Publishing is caused by green CI, not preceded by it. cargo-style local
publishing is not wired up on purpose: a published version cannot be taken
back.
# 1. bump the version in every packages/*/package.json, land it on main
# 2. tag the merged commit
git tag v0.6.0 && git push origin v0.6.0The tag triggers publish.yml, which refuses to build at all if the tag is not
an ancestor of main or disagrees with any package's version, runs the full CI
workflow against the tagged commit as a job it needs, and only then publishes
the three packages, the core first. A package whose version is already on npm
is skipped, so a release that stopped half way can be run again.
There is no npm token anywhere — not in the repository, not on a laptop. Publishing uses trusted publishing: npm accepts a short-lived OIDC token minted for this workflow in this repository, so the credential cannot be leaked, reused, or forgotten about, and provenance is generated automatically from it.
