headless-mde v0.1.0

Markdown editing for a plain <textarea>

Lists that continue on Enter, Tab that indents, quotes that keep their markers, toolbar commands and shortcuts. No UI of its own, no rendering, and undo works the way it should. Try it below, and switch the behaviors on and off to see what each one does.

Preview

Getting started

headless-mde turns a plain <textarea> into a comfortable place to write markdown. It doesn't render anything and it doesn't bring its own UI. You keep your textarea, your styles and your markdown parser; the library adds the small things that make typing markdown pleasant: lists that continue when you press Enter, Tab that indents instead of leaving the field, toolbar commands that wrap your selection, and so on.

Every edit goes through the browser's own editing machinery, so Ctrl+Z / Cmd+Z undoes it like anything you typed, and the textarea scrolls to keep the caret in view.

Install

npm install @can3p/headless-mde

The package is ESM only.

Without React

Point it at any textarea. You get back trigger to run commands (for your toolbar buttons), cursor to read and edit the text yourself, and dispose to remove every listener.

import { bootstrapTextareaMarkdown } from '@can3p/headless-mde/headless';

const textarea = document.querySelector('textarea');

const { trigger, dispose } = bootstrapTextareaMarkdown(textarea, {
    options: { enableBlockquoteExtension: true },
});

document.querySelector('#bold').addEventListener('click', () => trigger('bold'));

The headless entry point doesn't import React, so you won't see peer dependency warnings.

With React

TextareaMarkdown renders a textarea and takes every prop a textarea does, plus options and commands. The ref is the textarea element with trigger and cursor added.

import { useRef, useState } from 'react';
import TextareaMarkdown, { TextareaMarkdownRef } from '@can3p/headless-mde';

function Editor() {
    const [value, setValue] = useState('');
    const ref = useRef<TextareaMarkdownRef>(null);

    return (
        <>
            <button onClick={() => ref.current?.trigger('bold')}>Bold</button>
            <TextareaMarkdown ref={ref} value={value} onChange={(e) => setValue(e.target.value)} />
        </>
    );
}

Already have a textarea component, such as an autosizing one? Wrap it in TextareaMarkdown.Wrapper instead; no extra DOM element is added.

Options and commands

Behaviors are switched on and off with enable*Extension options, and commands can be given shortcuts, disabled, or added with your own handler:

bootstrapTextareaMarkdown(textarea, {
    options: { enableEmDashExtension: false, preferredUnorderedListSyntax: '-' },
    commands: [
        { name: 'code', shortcut: ['command+/', 'ctrl+/'], shortcutPreventDefault: true },
        { name: 'shrug', handler: ({ cursor }) => cursor.insert(`¯\\_(ツ)_/¯${cursor.MARKER}`) },
    ],
});

An entry named after a built-in command changes only the fields it sets: { name: 'bold', enable: false } turns bold off, and the rest, such as its Ctrl/Cmd+B shortcut, stays as it was.

In a handler, cursor.MARKER marks where the caret lands after the edit; two markers select the text between them. The full list of options, commands and their defaults is in the README. What each behavior actually does is described in How the editor behaves.

How the editor behaves

This page describes what happens when you type, press a key or click a command. It is the reference for how the editor is supposed to behave: if you change a behavior, change this page in the same pull request.

Throughout the page, │ marks the caret.

A few ground rules

Commands

Commands are what you wire to toolbar buttons with trigger('bold'). A few also have shortcuts.

Bold, italic, strike-through and inline code wrap the selection in markup. Bold, italic and strike-through have shortcuts: Ctrl/Cmd+B, Ctrl/Cmd+I and Ctrl/Cmd+Shift+X (or Alt+Shift+F5). With nothing selected, they insert a placeholder such as **bold** and select the word, so you can type over it. Run the same command on text that is already wrapped and the markup comes off again.

Headings (h1–h6) turn the current line into a heading, replacing any heading level it had. Running the same level again turns the heading back into a plain line.

Lists (ordered and unordered) put a marker in front of every selected line, numbering them 1., 2., 3. for an ordered list. If every line already is such a list item, the markers are removed instead, so the button works as a toggle. The unordered list command only recognizes its own marker (* unless preferredUnorderedListSyntax says otherwise), so on a - item line it adds a * rather than removing the -. An indented item counts as a nested list, so the command adds a marker rather than removing one.

Block quote adds a > level to the selected lines. If every line that has text is already quoted, it removes one level instead. On an empty line it inserts > quote with the placeholder selected. The caret stays on the same character it was on.

Code block wraps the selection in ``` fences. Code picks for you: a code block when the selection spans several lines, inline code otherwise.

Link and image insert [text](url) and ![text](image.png), using the selection as the text and selecting the URL so you can paste over it.

Commands inside quotes

Commands understand quote markers. A list, heading, code block or indent goes after the > markers, so > a becomes > * a, not * > a. A code block inside a quote wraps whole lines, because its fences need the markers too.

Extensions

Extensions are the behaviors that react to typing. Each one has an option, and you can try every one of them on and off in the playground.

Lists continue on Enter and join on Backspace — enablePrefixWrappingExtension (on by default)

Press Enter at the end of a list item and the next line starts with the next marker:

Before After Enter
* milk│ * milk, * │
1. first│ 1. first, 2. │
1.2. nested│ 1.2. nested, 1.3. │
- [x] done│ - [x] done, - [ ] │
* deep│ keeps the indentation
> * quoted│ > * quoted, > * │

A checked task continues as an unchecked one. Pressing Enter on an empty item ends the list: the marker is removed, leaving an empty line, and the caret moves to the line below (inside a quote, you stay in the quote). With the caret before the item's text, Enter is a plain line break.

The customPrefixWrapping option adds your own prefixes to continue, such as // or | .

Backspace with the caret right after a list marker (and its checkbox) works on the item as a whole instead of breaking the marker into a stray -:

Before After Backspace
- a, - │b - a │b joins the item above, with one space
- a, - │ - a│ removes the empty item, undoing an Enter
> - a, > - │b > - a │b the same inside a quote
- a, - │b - a, - │b a nested first item moves out one level
- │b (no item above) │b removes the marker and its indent

Only an item right above counts: after a blank line (a loose list) or a continuation line, the marker is removed instead. Ordered lists aren't renumbered, as with Enter. Indents are compared in spaces. With just enableBlockquoteExtension on, this happens only for lists inside quotes, the same as Enter.

Ordered list auto-correct — enableOrderedListAutoCorrectExtension (off by default)

Some people type 1) for numbered lists. With this on, pressing Enter on such a line rewrites the marker to 1.. If list continuation is on too, the next line gets 2.; otherwise Enter is a plain line break. Either way, the correction and the new line are one undo step.

Quotes take care of themselves — enableBlockquoteExtension (off by default)

Without this extension, quote markers are just text and you type them yourself. With it on, they behave the way you'd expect in an email client:

Caret Key Result
> text│ Enter > text, > │, at the same depth (>> stays >>)
> - item│ Enter > - item, > - │
> - │ (empty item) Enter > │: leaves the list, stays in the quote
> │ after a line with text Enter >, > │: a paragraph break inside the quote
> │ after an empty > line Enter leaves one quote level, keeping a blank line
> a, > │b Backspace > a │b: joins the two lines
>, > │b after a paragraph break Backspace removes the break
> │b on the first line of a quote Backspace │b: removes one quote level
inside a quote Paste of several lines every line after the first gets the markers, blank lines become >
> │, pasting > a and > b Paste of several lines > a, > b: the lines are already quoted, so they stay as they are

Pasted lines count as already quoted when every line with text has at least the caret line's quote depth (>> and > > are the same depth). The first one then loses the markers the caret is already after. When only some lines are quoted, say a copy that started in the middle of a quoted line, every line is quoted again as usual. A single pasted line is always pasted as it is.

Inside a code block that sits in a quote, only the markers of that quote are kept; a code block outside any quote is left completely alone.

Tab indents — enableIndentExtension (on by default)

Tab inserts four spaces at the caret instead of moving focus out of the textarea. With a selection, even one inside a single line, every line it touches is indented as a whole and the selection is kept; inside a quote, that indentation goes after the > markers. Shift+Tab removes up to four spaces from the start of each line (after the markers in a quote).

Keep in mind that this means keyboard users can't Tab out of the editor. If that matters for your page, turn the extension off or give people another way out.

Pasting a link onto a selection — enableLinkPasteExtension (on by default)

Select some text and paste a URL: the text becomes [text](url) followed by a space, with the caret after it. If the URL ends in .png, .jpg, .jpeg or .gif, you get an image, ![text](url). Anything the browser accepts as an absolute URL counts, mailto: links included. Nothing special happens when nothing is selected, when the selection is itself a URL, or when it is already inside a link.

Ctrl/Cmd+Backspace on an empty line — enableProperLineRemoveBehaviorExtension (on by default)

On an empty line, Ctrl+Backspace (Cmd+Backspace on a Mac) removes just that line instead of whatever the browser would delete. On a line with text, the browser's usual behavior applies. An empty first line goes with the line break after it, so the caret lands at the start of the next line. With a selection, the browser deletes the selection as usual, even when it starts on an empty line.

Em dashes — enableEmDashExtension (on by default)

Type two dashes and a space, -- , and they become an em dash and a space: — . This doesn't happen inside a fenced code block, where -- is usually a command-line flag.

When extensions meet

Several extensions listen to the same keys, and they are set up in a fixed order so their behavior is predictable:

  1. Enter is handled in one place. The rules are tried in turn: your custom prefixes, then lists, then quotes. The first that applies wins, so a list inside a quote continues as a list, and only an empty quote line triggers the paragraph-break behavior. The ordered list auto-correct happens before any of them.
  2. Backspace is handled in one place too: lists, then quotes. With the caret after > - , the list rule takes it; with the caret right after > , the quote rule does.
  3. Paste goes to the quote extension first, then to the link paste. A single URL pasted onto a selection inside a quote still becomes a link.