Markdown editor
A markdown textarea with a formatting toolbar that inserts at the selection, ⌘B, ⌘I and ⌘K, and a Write/Preview toggle drawn by your own renderer.
Demo
Usage
import ReactMarkdown from 'react-markdown'
import { Field, MarkdownEditor, Prose, proseComponents } from '@tuttn/slant'
// Uncontrolled, in a Field: the label names the textarea, which submits
// `name` with its form in either mode. The preview is your renderer's.
<Field>
<Field.Label>Body</Field.Label>
<MarkdownEditor name="body" defaultValue={draft}
renderPreview={text => <Prose size="sm"><ReactMarkdown components={proseComponents}>{text}</ReactMarkdown></Prose>}
onImage={async () => ({ url: await upload(), alt: 'Screenshot' })} />
</Field>
// Controlled, with fewer tools and no Write/Preview switch.
const [text, setText] = useState('')
<MarkdownEditor label="Comment" value={text} onValueChange={setText} tools={['bold', 'italic', 'code', 'link']} />
// The mode controlled too: open in Preview, or flip to it before a save.
<MarkdownEditor label="Body" value={text} onValueChange={setText}
mode={mode} onModeChange={setMode} renderPreview={render} />
// Textarea's own props pass through: rows (6 here), autosize, maxRows, mono,
// placeholder, and the ref, which reaches the <textarea>.
<MarkdownEditor ref={bodyRef} label="Prompt" autosize rows={3} maxRows={12} mono />Props
| Prop | Type | Default | Description |
|---|---|---|---|
value | string | — | The markdown. Pass it with onValueChange to control the editor; leave it out and it keeps its own. |
defaultValue | string | '' | The markdown an uncontrolled editor starts with. |
onValueChange | (value: string) => void | — | Called with the new markdown as the reader types and whenever a tool or shortcut changes it. |
renderPreview | (text: string) => ReactNode | — | Draws the preview of the markdown, with your own renderer (react-markdown in Prose, say), so the editor needs no parser. Without it there is no Write/Preview switch. |
mode | Mode | — | Write or Preview. Pass it with onModeChange to control the switch; leave it out and the editor keeps its own. |
defaultMode | Mode | 'write' | The mode an uncontrolled editor starts in. |
onModeChange | (mode: Mode) => void | — | Called with the new mode when the switch changes it, or when the browser finds the field invalid while previewing. |
tools | readonly MarkdownTool[] | every tool but 'image', and 'image' last when onImage is given | The formatting tools, in order. `image` shows only with `onImage`. |
onImage | () => Promise<MarkdownImage | null | undefined> | MarkdownImage | null | undefined | — | Called by the image tool for the picture to insert, as `` at the caret: open your picker or upload, then resolve with its URL and alt text. Null or undefined inserts nothing. |
label | string | — | The textarea's accessible name, unless a Field's label or `aria-labelledby` names it. |
size | 'sm' | 'md' | 'lg' | 'md' | The text size: `sm` (13px) for comments and side panels, `md` (14px), and `lg`, which also pads the field more and draws the tools at the md control height. |
rows | number | 6 | The visible lines of text: the height, or with `autosize` the smallest height. |
autosize | boolean | — | Grows the textarea with its content, from `rows` lines up to `maxRows`, and drops the resize handle. |
maxRows | number | no limit | With `autosize`, the most lines it grows to before it scrolls. |
invalid | boolean | — | Sets aria-invalid and a danger border. Inside a Field, the field's `invalid` does this and points the textarea at its error. |
mono | boolean | — | Monospace text, for code, logs and keys. |
…rest | TextareaProps | — | The ref, name, placeholder, rows (6 by default), autosize, maxRows, mono, invalid, onChange, onKeyDown and every other textarea attribute reach the <textarea>, with the Field wiring; className and style go on the frame around the toolbar and the field. |
Keyboard
| Mod+B / Mod+I / Mod+K | in the field, bold, italic or link over the selection (⌘ on a Mac, Ctrl elsewhere), while that tool is in the toolbar |
| Tab | reaches the toolbar once (the tool last used, else the first), then the Write/Preview switch, then the field |
| ← → | on a tool, the previous or next tool, wrapping at the ends; swapped under right-to-left text |
| Home / End | on a tool, the first or the last tool |
| Enter / Space | on a tool, applies it and puts focus back in the field with the new selection |
| ← → on the switch | chooses Write or Preview; choosing Write puts focus in the field |
Accessibility
- The toolbar is
role="toolbar", named bymessages.markdownToolbar(“Formatting”) andaria-controlsthe textarea. It is one tab stop, as the APG toolbar is. - Each tool is an icon button named from the root’s messages (
markdownBold,markdownBulletListand so on). Bold, Italic and Link carryaria-keyshortcuts, and every tool’s Tooltip reads its name and, for those three, the key caps. - A tool returns focus to the textarea with the new selection, so typing carries on and a screen reader stays in the text. A pointer press on a tool never takes focus from the field at all.
- The textarea is named by a Field label,
aria-labelledbyorlabel, in that order, and takes the Field’s description, error, invalid, required, disabled and read-only states. - The switch is a Segmented named
messages.markdownMode(“Editor mode”). The preview is a region namedmessages.markdownPreview(“Preview”), in the tab order only while it scrolls; blank text readsmessages.markdownNothingToPreview. While previewing, disabled or read-only, the tools are disabled.
Insertion
Each tool works on the selection. Bold wraps it in **, Italic in _, Code in backticks (one more than the longest run inside), and the text stays selected; with no selection the marks go in at the caret with the caret between them. Spaces at the selection’s ends stay outside the marks. Pressing a wrap tool on text already inside its marks, or on a selection that holds them, takes them off, so each tool toggles.
Code over several lines fences the whole lines. Link writes [selection]() with the caret in the parentheses for the URL; with no selection, []() with the caret in the brackets; a selected URL becomes the target with the caret in the brackets for its text; a selected link, or a link’s text, goes back to plain text. Bulleted list, Numbered list and Quote put - , 1. , 2. … or > on every line the selection touches, and take them off when every line already has them. In a list, blank lines stay blank; in a quote they become >, so it stays one quote. A bullet replaces a number, and a number a bullet.
Undo
Every edit goes in as typing would (insertText over the selection), so the browser’s undo takes it back. Where that isn’t available the editor sets the text directly and sends an input event, so onValueChange and onChange still hear it, controlled or not.
Preview and forms
Without renderPreview there is no switch. With it, Preview hides the textarea, which stays mounted and still submits its name, and shows your renderer’s output in its place, at the field’s height (at least, with autosize). If the browser finds the textarea invalid on submit while it is hidden, the editor goes back to Write so the reader can fix it.
Images
The image tool shows only with onImage. Pressing it calls onImage, which may open your picker or upload and return a promise; the button is busy meanwhile. It resolves with { url, alt? }, inserted at the caret as  with the alt text’s brackets escaped and the URL’s spaces and parentheses encoded; the selection, if any, is the alt text when alt is left out, and with no alt text at all the caret waits in the brackets for one. Null inserts nothing.