# Markdown editor

> A Markdown source editor on a native textarea - a formatting toolbar of pure text commands that keep native undo, shortcuts, link / image / table dialogs, an app-supplied preview, uploads, a count and fullscreen.

Canonical: https://salmonui.dev/docs/editors/markdown-editor

`MarkdownEditor` from `@salmonui/editors/markdown-editor` edits Markdown source
in a native `<textarea>` with a formatting toolbar. It is its own component,
not an `editorMode` of a rich text editor: `value` is always
Markdown, and the component does not wait on a rich text engine.

```tsx
import { MarkdownEditor } from '@salmonui/editors/markdown-editor';
import '@salmonui/editors/markdown-editor/styles.css';

<label htmlFor="body">Body</label>
<MarkdownEditor
  id="body"
  name="body"
  value={markdown}
  onValueChange={setMarkdown}
  defaultPreview="split"
  renderPreview={(source) => <MyMarkdown source={source} />}
  onUpload={async (file, { signal }) => ({ src: await uploadImage(file, signal) })}
  maxLength={20000}
  showCount
/>
```

The stylesheet carries the `Button` and `Menu` rules the toolbar and its
menus render, so it is the only stylesheet besides
`@salmonui/core/styles.css` (the theme, once per app).

### Live demo: Markdown editor

Live demo: https://salmonui.dev/demos/editors/markdown-editor

A Markdown textarea with a formatting toolbar, keyboard shortcuts, link / image / table dialogs, a split preview from an app-supplied renderer, a character count and fullscreen.

`Demo.tsx`:

```tsx
'use client';

import { useState, type ReactNode } from 'react';
import { MarkdownEditor } from '@salmonui/editors/markdown-editor';

const initial = `# Release notes

Salmon UI **v1** ships the *Data Grid*.

- Virtualized rows
- Excel-like editing
`;

/** A deliberately tiny renderer (no HTML strings): headings, list items, bold and italics. */
function renderLite(source: string): ReactNode {
  const inline = (text: string, key: number): ReactNode[] =>
    text.split(/(\*\*[^*]+\*\*|\*[^*]+\*)/g).map((part, i) =>
      part.startsWith('**') ? <strong key={`${key}-${i}`}>{part.slice(2, -2)}</strong> : part.startsWith('*') && part.length > 2 ? <em key={`${key}-${i}`}>{part.slice(1, -1)}</em> : part,
    );
  return source.split('\n').map((line, i) => {
    const heading = /^(#{1,6})\s+(.*)$/.exec(line);
    if (heading) {
      const level = heading[1]!.length;
      return level === 1 ? <h3 key={i}>{inline(heading[2]!, i)}</h3> : <h4 key={i}>{inline(heading[2]!, i)}</h4>;
    }
    if (/^[-*+]\s/.test(line)) return <div key={i}>• {inline(line.slice(2), i)}</div>;
    return line.trim() ? <p key={i} style={{ margin: '4px 0' }}>{inline(line, i)}</p> : null;
  });
}

export default function MarkdownEditorDemo() {
  const [value, setValue] = useState(initial);
  return (
    <div style={{ display: 'grid', gap: 8 }}>
      <label htmlFor="markdown-demo">Release notes</label>
      <MarkdownEditor id="markdown-demo" value={value} onValueChange={setValue} defaultPreview="split" renderPreview={renderLite} maxLength={2000} showCount rows={10} />
    </div>
  );
}
```

## Value and the textarea

`value` / `defaultValue` / `onValueChange(value, { source, reason })` follow
the shared triad; `reason` is `'input'` (typing), `'command'` (a
toolbar command) or `'reset'` (the owning form was reset). For a
change on blur, use `onBlur` on the component.

The editing surface is a native `<textarea>`, so IME, spell check,
mobile keyboards, clipboard, `Ctrl+A` and constraint validation are
the browser's. Every textarea attribute passes through: `name`, `required`,
`form`, `placeholder`, `readOnly`, `disabled`, `rows`, `id`,
`aria-*`, `onFocus`, `onBlur`. Without `aria-label`, `aria-labelledby` or
`id` (for a `<label htmlFor>`), the textarea is labelled
`localeText.editor`. `maxLength` limits the text; `showCount` shows
`n / max` and announces "Approaching the character limit" at 90 % and
"Character limit reached" at the limit in a polite status, never per
keystroke. `resizable` (default true) gives the textarea a
vertical resize handle; size the component with `className` / `style`.

## Toolbar

`toolbar` lists built-in item ids, `'|'` separators and custom items
`{ id, label, icon?, disabled?, onSelect(api) }`. The default is
`MARKDOWN_DEFAULT_TOOLBAR`:

```ts
['bold', 'italic', 'strikethrough', '|', 'heading', 'blockquote', 'code',
 'orderedList', 'unorderedList', '|', 'link', 'image', 'table', '|',
 'undo', 'redo', 'preview', 'fullscreen']
```

| Item | Inserts | Shortcut |
| --- | --- | --- |
| `bold`, `italic`, `strikethrough` | `**`, `*`, `~~` around the selection; again removes them | Mod+B, Mod+I, Mod+Shift+S |
| `superscript`, `subscript` | `<sup>` / `<sub>` | Mod+Shift+=, Mod+= |
| `uppercase`, `lowercase` | the selection in the `locale` case | Mod+Shift+U, Mod+Shift+L |
| `heading` | a menu: Paragraph, Heading 1 to 6 (`#` markers) | |
| `blockquote` | `> ` on each line | |
| `code`, `codeBlock` | backticks, a fenced block | |
| `orderedList`, `unorderedList` | `1. ` / `- ` on each line; switches between them | Mod+Shift+O, Mod+Alt+O |
| `link`, `image`, `table` | a dialog | Mod+K, Mod+Shift+I, Mod+Shift+E |
| `undo`, `redo` | undo / redo | Mod+Z, Mod+Y |
| `preview` | toggles the preview | |
| `fullscreen` | toggles fullscreen | Mod+Shift+F |

Mod is Ctrl, or Cmd on Apple platforms. Shortcuts work whether or not their
item is in the toolbar. Enter on a list item continues the marker (the next
number, an unchecked task box); Enter on an empty item ends the list.

`toolbarOverflow` decides what happens to items that do not fit:
`'menu'` (default) moves them into a More menu, `'wrap'` wraps the toolbar,
`'scroll'` scrolls it. `stickyToolbar` keeps the toolbar visible while the
page scrolls.

## Commands

Every command is a pure function over the text and the selection
(`applyMarkdownCommand(id, { text, start, end }, syntax?, locale?)` is
exported for server-side or test use). The editor applies the result as one
replacement with `document.execCommand('insertText')`, so a command is on
the browser's native undo stack together with typing; where an engine does
not support it, the component keeps its own bounded history (`undoLimit`,
default 100) for its commands and still leaves typing to the browser.
The textarea keeps its selection while the toolbar is pressed.

`undoLimit` bounds only that fallback history. Browsers expose no control
over how typing is grouped into undo steps or how deep the native stack is,
so both follow the browser; there is no undo grouping timer.

`syntax` overrides the markers per command, merged over the CommonMark /
GFM defaults (`DEFAULT_MARKDOWN_SYNTAX`):

```tsx
<MarkdownEditor syntax={{ bold: ['__', '__'], unorderedList: '* ', orderedList: ')' }} />
```

`ref` receives a `MarkdownEditorApi`: `runCommand(id)`
(built-in or custom), `insertText(text)`, `wrapSelection(before, after)`,
`focus()`, `blur()`, `getSelection()` (`{ start, end, text }`),
`setSelection(start, end)` and `element` (the textarea).
`onBeforeCommand({ id, source })` runs first and cancels with
`preventDefault()`; `onCommand({ id, source })` runs after.

### Live demo: Markdown editor commands

Live demo: https://salmonui.dev/demos/editors/markdown-editor-commands

Every MarkdownEditor toolbar command - superscript and subscript, upper and lower case, headings, quotes, inline and fenced code, lists, an image dialog with uploads, a custom item - plus the overflow modes, a syntax override, the ref API and the command events.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { MarkdownEditor, type MarkdownEditorApi, type MarkdownToolbarItem } from '@salmonui/editors/markdown-editor';
import { Select } from '@salmonui/dropdowns/select';
import { EventLog, useEventLog } from '../../components/demo-kit';

const TOOLBAR: readonly MarkdownToolbarItem[] = [
  'bold',
  'italic',
  'strikethrough',
  'superscript',
  'subscript',
  'uppercase',
  'lowercase',
  '|',
  'heading',
  'blockquote',
  'code',
  'codeBlock',
  'orderedList',
  'unorderedList',
  '|',
  'link',
  'image',
  'table',
  '|',
  'undo',
  'redo',
  '|',
  { id: 'signature', label: 'Insert signature', icon: (
      <svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="M11 2.5l2.5 2.5L6 12.5H3.5V10zM2 14.5h12" />
      </svg>
    ), onSelect: (api) => api.insertText('\n\n-- The release team\n') },
];

const initial = `Release notes

Select a word, then try the toolbar or a shortcut.
H2O and E = mc2 need sub- and superscript.
first item
second item
`;

const OVERFLOWS = ['menu', 'wrap', 'scroll'];

// Uploads become object URLs here; an application sends the file to its server and returns the stored URL.
const upload = async (file: File) => ({ src: URL.createObjectURL(file), alt: file.name.replace(/\.[^.]+$/, '') });

export default function MarkdownEditorCommandsDemo() {
  const [log, push] = useEventLog();
  const [overflow, setOverflow] = useState<'menu' | 'wrap' | 'scroll'>('menu');
  const [underscores, setUnderscores] = useState(false);
  const [blockHeadings, setBlockHeadings] = useState(false);
  const [narrow, setNarrow] = useState(false);
  const api = useRef<MarkdownEditorApi | null>(null);
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <div role="group" aria-label="Options" style={{ display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center' }}>
        <label>
          Toolbar overflow{' '}
          <Select aria-label="Toolbar overflow" data={OVERFLOWS} value={overflow} onValueChange={(value) => value != null && setOverflow(value as typeof overflow)} />
        </label>
        <Checkbox checked={underscores} onCheckedChange={(checked) => setUnderscores(checked)}>
          syntax: <code>__bold__</code>, <code>* </code> bullets, <code>1)</code> numbers
        </Checkbox>
        <Checkbox checked={narrow} onCheckedChange={(checked) => setNarrow(checked)}>
          Phone width (360 px)
        </Checkbox>
        <Checkbox checked={blockHeadings} onCheckedChange={(checked) => setBlockHeadings(checked)}>
          Cancel heading commands (onBeforeCommand)
        </Checkbox>
      </div>
      <label htmlFor="markdown-commands" style={{ fontWeight: 600 }}>
        Release notes
      </label>
      <MarkdownEditor
        id="markdown-commands"
        ref={api}
        defaultValue={initial}
        toolbar={TOOLBAR}
        toolbarOverflow={overflow}
        syntax={underscores ? { bold: ['__', '__'], unorderedList: '* ', orderedList: ')' } : undefined}
        onUpload={upload}
        rows={10}
        // The toolbar measures its own width: narrow it to see the overflow modes.
        style={{ maxInlineSize: narrow ? 360 : 760 }}
        onBeforeCommand={(event) => {
          if (blockHeadings && event.id.startsWith('heading')) {
            event.preventDefault();
            push(`onBeforeCommand: ${event.id} cancelled (${event.source})`);
          }
        }}
        onCommand={(event) => push(`onCommand: ${event.id} (${event.source})`)}
        onFocus={() => push('onFocus')}
        onBlur={() => push('onBlur')}
      />
      <div role="group" aria-label="Editor API" style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        <Button variant="outline" onClick={() => api.current?.runCommand('heading2')}>
          runCommand(&apos;heading2&apos;)
        </Button>
        <Button variant="outline" onClick={() => api.current?.wrapSelection('==', '==')}>
          wrapSelection(&apos;==&apos;, &apos;==&apos;)
        </Button>
        <Button variant="outline" onClick={() => api.current?.insertText(`Updated ${new Date().toISOString().slice(0, 10)}`)}>
          insertText(date)
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            const selection = api.current?.getSelection();
            if (selection) push(`getSelection(): ${selection.start}-${selection.end} "${selection.text}"`);
          }}
        >
          getSelection()
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            api.current?.setSelection(0, 13);
            api.current?.focus();
          }}
        >
          setSelection(0, 13) + focus()
        </Button>
      </div>
      <EventLog entries={log} />
    </div>
  );
}
```

## Dialogs and uploads

Link (text and URL), image (URL, alternative text, and a file field when
`onUpload` is set) and table (rows and columns, a GFM table on lines of its
own) open in modal native `<dialog>`s rendered outside the editor, so their
forms never nest in yours. The selected text fills
the link text or image alt; Escape cancels and focus returns to the
textarea. `onUpload(file, { signal })` resolves to `{ src, alt? }`; it also
receives image files pasted into the textarea, inserted where the paste
happened. Dialogs and menus are lazy chunks loaded on first use.

## Preview

`renderPreview(markdown)` returns the preview; no Markdown parser is bundled.
It receives `useDeferredValue(value)`, so typing never
waits on the parser. `preview` / `defaultPreview` / `onPreviewChange`
choose `'off'` (default), `'tab'` (the preview replaces the textarea; text
commands are disabled) or `'split'` (side by side, stacked below a 40 rem
container width). The `preview` item toggles between `'off'` and the last
shown layout. With a parser that emits HTML, sanitize in `renderPreview`:

```tsx
import { marked } from 'marked';
import DOMPurify from 'dompurify';

<MarkdownEditor renderPreview={(md) => <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(marked.parse(md) as string) }} />} />
```

A React-element renderer such as `react-markdown` avoids HTML strings
entirely.

## Fullscreen

`fullscreen` / `defaultFullscreen` / `onFullscreenChange` control the
fullscreen state (the editor covers the viewport); the item, Mod+Shift+F and
Escape in the textarea toggle it.

## Keyboard and accessibility

| Key | Action |
| --- | --- |
| Alt+F10 (Option+F10) in the textarea | Focus the toolbar |
| ArrowLeft / ArrowRight, Home / End in the toolbar | Move between items (mirrored in RTL) |
| Escape in the toolbar | Back to the textarea |
| Escape in a menu or dialog | Close it |
| Tab | Leaves the textarea; with `tabIndents` (*Salmon*), Tab / Shift+Tab indent and outdent |

The toolbar is an APG Toolbar (`role="toolbar"`, one tab stop, roving
focus, `aria-controls` pointing at the textarea). The heading and
More buttons are APG Menu Buttons; the dialogs are labelled modal dialogs;
the preview is a region labelled "Preview" with `aria-live="off"`. Axe and
ARIA snapshots run in light, dark and RTL.

## Styling, RTL and localization

`className` / `style` go to the root; `classNames` / `styles` reach the
`toolbar`, `textarea`, `preview` and `count` parts. Direction is
inherited: the toolbar mirrors, and the textarea and preview use
`dir="auto"` so mixed-direction content follows its first strong character.
`localeText` overrides every toolbar label, tooltip and dialog string, and
`locale` picks the case mapping of uppercase / lowercase (`MARKDOWN_DEFAULT_LOCALE_TEXT` holds the English defaults).

The toolbar, textarea and (for `'split'`) the preview render on the server
with the value; menus, dialogs and the overflow measurement exist only on
the client, with no hydration difference.

### Live demo: Markdown editor in a form

Live demo: https://salmonui.dev/demos/editors/markdown-editor-form

MarkdownEditor as a native form field - name, required, submit and reset - with placeholder, readOnly and disabled, a resizable textarea, a server-rendered split preview, right to left, the Turkish locale for case changes, localized labels and part styles.

`Demo.tsx`:

```tsx
'use client';

import { useState, type ReactNode } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { MarkdownEditor } from '@salmonui/editors/markdown-editor';
import { Radio } from '@salmonui/inputs/radio-group';

const TR_TEXT = {
  toolbar: 'Biçimlendirme',
  bold: 'Kalın',
  italic: 'İtalik',
  uppercase: 'Büyük harf',
  lowercase: 'Küçük harf',
  link: 'Bağlantı',
  preview: 'Önizleme',
  previewRegion: 'Önizleme',
  more: 'Daha fazla',
};

/** A tiny renderer for the preview (paragraphs only): the application owns Markdown parsing. */
const renderParagraphs = (source: string): ReactNode =>
  source
    .split(/\n{2,}/)
    .filter((block) => block.trim())
    .map((block, index) => (
      <p key={index} style={{ margin: '0 0 8px' }}>
        {block}
      </p>
    ));

export default function MarkdownEditorFormDemo() {
  const [state, setState] = useState<'editable' | 'readOnly' | 'disabled'>('editable');
  const [rtl, setRtl] = useState(false);
  const [turkish, setTurkish] = useState(false);
  const [submitted, setSubmitted] = useState<string | null>(null);
  return (
    <form
      style={{ display: 'grid', gap: 12 }}
      onSubmit={(event) => {
        event.preventDefault();
        setSubmitted(String(new FormData(event.currentTarget).get('summary') ?? ''));
      }}
      onReset={() => setSubmitted(null)}
    >
      <fieldset style={{ display: 'flex', flexWrap: 'wrap', gap: 12, border: 0, padding: 0, margin: 0 }}>
        <legend style={{ fontWeight: 600, padding: 0 }}>Options</legend>
        {(['editable', 'readOnly', 'disabled'] as const).map((option) => (
          <Radio key={option} name="md-state" value={option} checked={state === option} onChange={() => setState(option)}>
            {option}
          </Radio>
        ))}
        <Checkbox checked={rtl} onCheckedChange={(checked) => setRtl(checked)}>
          dir=&quot;rtl&quot;
        </Checkbox>
        <Checkbox checked={turkish} onCheckedChange={(checked) => setTurkish(checked)}>
          Turkish locale and labels
        </Checkbox>
      </fieldset>
      <div dir={rtl ? 'rtl' : 'ltr'} style={{ display: 'grid', gap: 6 }}>
        <label htmlFor="markdown-summary" style={{ fontWeight: 600 }}>
          Summary (required)
        </label>
        <MarkdownEditor
          id="markdown-summary"
          name="summary"
          required
          defaultValue={'The team meets in izmir next week.\n\nSelect "izmir" and press Upper case: the Turkish locale gives İZMİR, English gives IZMIR.'}
          placeholder="Write a short summary in Markdown"
          readOnly={state === 'readOnly'}
          disabled={state === 'disabled'}
          toolbar={['bold', 'italic', 'uppercase', 'lowercase', '|', 'link', 'preview']}
          defaultPreview="split"
          renderPreview={renderParagraphs}
          locale={turkish ? 'tr' : undefined}
          localeText={turkish ? TR_TEXT : undefined}
          resizable
          rows={6}
          style={{ maxInlineSize: 760 }}
          styles={{ preview: { fontStyle: 'italic' }, textarea: { fontFamily: 'ui-monospace, monospace' } }}
        />
      </div>
      <div style={{ display: 'flex', gap: 8 }}>
        <Button type="submit">Submit</Button>
        <Button type="reset" variant="outline">Reset</Button>
      </div>
      <p aria-live="polite" style={{ margin: 0 }}>
        {submitted === null ? 'Not submitted yet. Empty the editor and submit to see the required check.' : `Submitted summary: ${submitted.length} characters`}
      </p>
    </form>
  );
}
```

## Design notes

- `MarkdownEditor` is its own component, not a mode of `RichTextEditor`,
so a Markdown field never loads a rich text engine.
- Typing stays on the browser's native undo stack, which keeps IME
  composition, spell check replacements and platform undo gestures; see
  [Commands](https://salmonui.dev/docs/editors/markdown-editor#commands) for `undoLimit`.
- There is no built-in persistence: components never write to `localStorage`
  on their own, because hidden persistence breaks server rendering
  consistency. Persist the value from `onValueChange` (debounced by the
  application) and pass it back as `value` or `defaultValue`.
- There is no HTML sanitizer option: the editor edits plain text and renders
  no HTML itself, and bundling a parser and sanitizer would put them on
  every page with a Markdown field; sanitize in `renderPreview` if your
  parser emits HTML, as in the recipe above.
- `onValueChange` fires on every edit, not on blur; use `onBlur`
  for the blur timing.

## API reference

[`@salmonui/editors/markdown-editor`](https://salmonui.dev/docs/reference/editors/markdown-editor)
lists every prop, the `MarkdownEditorApi` ref and the exported command
helpers.
