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