WYSIWYG Markdown Editor (formatted typing, Markdown saved)
⚠️ Cookbook example — not live code. (KEEP THIS CALLOUT.) Every code block below is an example snippet, not part of the llamapress.ai codebase, and not running on this server. This is a reference recipe for a Leo instance (an AI coding agent) to implement in its own app — read it to understand the pattern, then recreate it there.
People want to write notes the way they write in Google Docs: bold, headings, bullets,
checkboxes, no syntax. Developers want Markdown in the database: it diffs, it versions, an
AI agent can read and write it, and it moves to Obsidian or GitHub unchanged. This editor
gives both. The person types into formatted text. A hidden <textarea> holds the
Markdown and is what gets saved. A Markdown button shows the raw source for edits the
toolbar cannot make.
When to use: a notes field, a scratch pad, a description, a README-style page, any column that should stay Markdown but is edited by non-technical people. When not to: you need images uploaded inline, comments, or several people typing at once (use Action Text / Trix, or a real collaborative editor). If plain HTML in the database is fine, Trix is less work.
The full controller (~600 lines, no dependency except marked) and its stylesheet ship as
an install package: wysiwyg-markdown-editor/INSTALL.md plus
wysiwyg-markdown-editor/files/. Copy those files rather than retyping the code below,
which shows only the parts you need to understand.
The 80/20 in one breath
- Keep your existing
<textarea>. It stays the single source of truth and is what your form or autosave sends. - Wrap it in
data-controller="markdown-editor"and mark itdata-markdown-editor-target="source". - On connect the controller hides the textarea, renders its Markdown with
markedinto acontenteditablediv, and cleans the HTML through a tag allow list. - On every edit it converts the div back to Markdown, writes it into the textarea, and
fires an
inputevent on it. Nothing else in your app changes. - A toolbar runs
document.execCommand, plus Markdown starts (#,-,1.,>,[],```) andCtrl/Cmd+B / I / K.
Layer 1 — The view
<%# app/views/notes/show.html.erb %>
<div data-controller="autosave markdown-editor"
data-markdown-editor-label-value="Notes">
<textarea data-markdown-editor-target="source"
data-autosave-target="input"
data-action="input->autosave#changed"
placeholder="Start typing"><%= @note.body %></textarea>
</div>
Your autosave controller listens to input on the textarea exactly as before. The editor
triggers that event; it never saves anything itself. It also dispatches
markdown-editor:change with { detail: { markdown } } if you prefer to listen for that.
Layer 2 — Stimulus: how the controller works
The shape of it (the full file is in the package):
// app/javascript/controllers/markdown_editor_controller.js (excerpt)
import { Controller } from "@hotwired/stimulus"
import { marked } from "marked"
export default class extends Controller {
static targets = ["source"]
static values = { placeholder: String, label: { type: String, default: "Text editor" } }
connect() {
this.ta = this.sourceTarget
this.build() // toolbar + contenteditable div; the textarea moves inside it
this.load(this.ta.value) // Markdown -> marked -> cleanHtml -> the div
}
load(md) {
// breaks: true here MUST match how you render the Markdown everywhere else,
// and htmlToMarkdown writes <br> back as a single newline to match it.
this.body.replaceChildren(cleanHtml(marked.parse(md || "", { gfm: true, breaks: true })))
}
changed() { // on every "input" in the div
this.fixLists() // Chrome nests <ul> inside <p>: lift it out
cancelAnimationFrame(this.raf)
this.raf = requestAnimationFrame(() => this.sync())
}
sync() {
const md = htmlToMarkdown(this.body)
if (md === this.ta.value) return
this.ta.value = md
this.syncing = true // so our own event does not re-render the div
this.ta.dispatchEvent(new Event("input", { bubbles: true }))
this.syncing = false
}
}
The converter is the real work. htmlToMarkdown(root) walks the DOM:
| HTML | Markdown written |
|---|---|
h1–h6 |
# … ###### |
strong/b, em/i, s/del, code |
**x**, *x*, ~~x~~, `x` |
a |
[text](url); a bare URL or email stays bare (GFM links it again) |
ul/ol (nested, start=) |
- / 1. , children indented by the marker's width |
li > input[type=checkbox] |
- [ ] / - [x] |
blockquote |
> on every line |
pre > code.language-x |
fenced block with the language |
table with align |
GFM table; ---: / :---: kept |
br |
a newline (matches breaks: true) |
| loose text and inline nodes | grouped into one paragraph |
Plain text is escaped so it cannot turn into formatting: *, `, \,
_ at a word edge, [ before a ], < before a letter, ~ when there are two, and a
line that starts like a block (# , - , > , 2026. , ---, |) gets its marker
escaped. The test for this: wrap each tricky string in a <p>, convert, parse it back with
marked, and assert the text is identical and has no child elements.
cleanHtml(html) is the only way HTML enters the editor (saved Markdown can contain raw
HTML, and paste is untrusted). It parses with DOMParser, then rebuilds allowed tags
as new elements, copying only a[href] (http, https, mailto, tel, /, #), img[src,alt],
th/td[align], ol[start], code.language-* and checkbox checked. script, style,
iframe, svg, event handlers and javascript: links never arrive. Never assign the
marked output to innerHTML directly.
Paste: if the clipboard's plain text looks like Markdown (from Obsidian, VS Code, a chat), it is parsed as Markdown; otherwise HTML is cleaned; otherwise plain text is inserted.
Gotchas (the hard-won stuff)
- Chrome puts a new list INSIDE the paragraph.
execCommand("insertUnorderedList")on a<p>produces<p><ul><li>…</li></ul></p>, which is invalid HTML, and a naive converter flattens it into one line. Two fixes, both needed: after every edit liftp > ul/ol/table/pre/blockquote/h*out of the paragraph (save the selection's nodes and offsets first, thensetBaseAndExtentback, because moving a node collapses ranges inside it); and make the converter treat any element with block children as a container. - Chrome's Tab (
indent) puts the nested list BESIDE the item, as<ul><li>one</li><ul><li>two</li></ul></ul>. A converter that only readslichildren silently drops "two". Treat aul/olthat is a direct child of a list as a sublist of the previous item. - Insert a checkbox, then move the caret after it.
li.prepend(box)leaves the caret at offset 0, which is now BEFORE the box, so the typed text lands in front of it and the next Enter carries the box to the wrong item. - Do the checklist Enter synchronously. A
setTimeout(0)that adds the box to the new item loses a race with fast typing (the test typed "send invoice" and got "voicesend in").preventDefault, thenexecCommand("insertParagraph"), then add the box. - Checkboxes inside
contenteditabledo not toggle reliably. Make themcontenteditable="false", toggle onmousedownwithpreventDefault, andpreventDefaulttheclicktoo, or the native toggle undoes yours. - Opening the page must not save. Do not sync on load. The first real edit rewrites the
whole document in the editor's normal form (table divider
|---|becomes| --- |, a blank line after headings). The meaning is identical; version history will show that one reformat, once. breaks: truehas to match both ways. If you render with single newlines as<br>, write<br>back as\n. Mixing the two makes every save add or remove line breaks. — contenteditable inserts U+00A0 for spaces. Replace it with a normal space in the converter, and when matching a Markdown start like[ ].- Markdown has no underline. Drop the U button and swallow
Ctrl/Cmd+U, or people underline text that silently loses its formatting on save. - Turbo cache. A restored snapshot already contains the built toolbar, so
connect()builds a second one. Remove any existing.mdeinside the element first. - Do not use
marked's output as trusted HTML, even for your own users' notes: the Markdown can carry raw<script>andonerror=attributes. Rebuild through the allow list. - Prove it in a real browser, not in Node.
execCommand,contenteditable,innerTextand the selection API only behave correctly in a browser. The source build used a 16-check Puppeteer test against a local harness page (round trip of a real 144-line note, typing each shortcut, paste, checklist, table, source view, script stripping) and a second live check that intercepted the save request so real data was never written.
Files this pattern touches
app/javascript/controllers/markdown_editor_controller.js (from the package)
app/assets/stylesheets/markdown_editor.css (from the package)
app/javascript/controllers/index.js (only if controllers are registered by hand)
config/importmap.rb (pin "marked", or import it by URL)
app/views/<your view> (wrap the textarea)
How to adapt to your schema
- Any
textcolumn that holds Markdown works. Point the textarea at it; nothing on the server changes. - Already showing a live preview pane next to the textarea? Remove it: the editor is the preview. Keep your "show saved version" pages rendering the Markdown as before.
- Want fewer buttons? Delete them from the
build()template; every command is independent. Keep Markdown (the source view): it is the escape hatch for anything the toolbar cannot do, such as editing a table's alignment. - Rendering Markdown elsewhere with different options (no
breaks, no GFM)? Change themarked.parseoptions inload()andpaste()and the<br>handling in the converter together. - Need HTML saved instead of Markdown? You do not need this pattern: use Action Text.