Skip to content

Markdown editor

A labeled textarea upgraded in place to a markdown editor with toolbar, link palette and slash menu.

Installation

// package.json: "capsomer": "github:DrDustinEdwards/capsomer#v0.152.2"
import "capsomer/tokens.css";
import "capsomer/base.css";
import "capsomer/markdown-editor.css";
import { enhance } from "capsomer/behavior/markdown-editor";

enhance();

Usage

<div class="cap-md cap-field" data-cap="markdown-editor">
  <label class="cap-field-label" for="body">Body</label>
  <p class="cap-field-help" id="body-h">Markdown. Ctrl or Cmd + K links to a page.</p>
  <textarea class="cap-input cap-md-source" id="body" name="body" aria-describedby="body-h" spellcheck="true">## Why the checks moved to the edge

The monitors now run from three regions.</textarea>
</div>
import { enhance, getMarkdownEditor } from "capsomer/behavior/markdown-editor";

enhance(document, {
  linkTargets: [{ href: "/writing/first-incident", title: "The first incident write-up" }],
  scaffolds: [
    { id: "figure", label: "Figure", hint: "An image with a caption", icon: "M3 4h18v13H3zM3 14l4-4 5 5M6 21h12",
      text: ':::figure{src="" alt=""}\nA caption.\n:::', cursorAfter: 'src="' },
  ],
  // image is { alt, decorative }: send both, so the file is stored described.
  onUpload: async (file, image, signal) => ({ url: await sendToBucket(file, image, signal) }),
  imageMarkdown: ({ url, alt }) => `:::figure{src="${url}" alt="${alt}"}\n:::`,
  onSave: (value) => saveDraft(value),
});
<MarkdownEditor
  label="Body"
  name="body"
  value={body}
  onChange={setBody}
  onSave={save}
  help="Markdown. Ctrl or Cmd + K links to a page."
  error={errors.body}
  linkTargets={posts.map((p) => ({ href: `/writing/${p.slug}`, title: p.title, note: p.live ? undefined : "not live yet (draft)" }))}
  scaffolds={scaffolds}
  onUpload={async (file, image, signal) => ({ url: await sendToBucket(file, image, signal) })}
/>

API reference

MarkdownEditor

PropTypeRequiredDoes
labelReactNodeYesThe visible label above the editor.
ariaLabelstringThe surface's accessible name; defaults to the label's text plus ", markdown".
namestringThe field's name in a form: the markdown is posted in a hidden textarea of this name.
idstring
valuestringControlled: the text. Without it the editor keeps its own, starting at defaultValue.
defaultValuestring
onChange(value: string) => void
placeholderstring
readOnlyboolean
disabledboolean
requiredboolean
maxLengthnumberA hint, not a stop: the footer counts characters against it and says when the text is over.
helpReactNodeHelp, between the label and the editor, read as its description.
errorReactNodeWhat is wrong and what to do; shown below the editor, and marks it invalid.
onReady(handle: MarkdownEditorHandle) => voidCalled once with the handle when CodeMirror has loaded.
noncestringThe CSP nonce for the styles CodeMirror injects. Defaults to the nonce on the page's first script that has one.
acceptstringThe file chooser's accept list.
scaffoldsScaffold[]
linkTargetsLinkTarget[] | ((query: string) => LinkTarget[] | Promise<LinkTarget[]>)Pages to offer, or a function that searches them (it may be async; the newest answer wins).
onUpload(file: File, image: ImageDescription, signal: AbortSignal) => Promise<UploadResult>Uploads a pasted, dropped or chosen image once the person has described it, and says where it went. The signal aborts when they cancel while it is on its way. Without it, the image button, the drop hint and the describe step are absent.
imageMarkdown(image: { url: string; alt: string; decorative: boolean; name: string; }) => stringThe markdown that goes into the text once the image is uploaded.
lineNumbersboolean
wordsPerMinutenumber
onSave(value: string) => voidCtrl or Cmd + S. The key is always claimed (the browser's save-page is no use here); the page's own handler on window still sees it.

Functions

FunctionSignatureDoes
mountMarkdownEditor(host: HTMLElement, options?: MarkdownEditorOptions): Promise<MarkdownEditorHandle>Upgrades one editor: the element carrying data-cap="markdown-editor", holding a label and a textarea. Resolves once CodeMirror has loaded and the surface is mounted; if it cannot load, the textarea simply stays, and the promise rejects.
getMarkdownEditor(host: Element): MarkdownEditorHandle | undefinedThe handle of an editor that has finished loading, or undefined while it is still the plain textarea (listen for the bubbling cap-md-ready event to know when).
enhance(root?: ParentNode, options?: MarkdownEditorOptions): () => voidUpgrades every [data-cap="markdown-editor"] under root not yet upgraded. The textarea is the editor until CodeMirror has loaded, and again if it cannot. options apply to each one; to give editors different options, pass a narrower root. Returns a function that undoes it.

CSS variables

VariableDefault
--cap-md-min16rem

Parts and data attributes

ClassIs
.cap-mdthe root
.cap-md-foota part
.cap-md-framea part
.cap-md-hinta part
.cap-md-limita part
.cap-md-option-hinta part
.cap-md-option-notea part
.cap-md-palettea part
.cap-md-palette-labela part
.cap-md-palette-notea part
.cap-md-sepa part
.cap-md-slasha part
.cap-md-slash-hinta part
.cap-md-slash-itema part
.cap-md-sourcea part
.cap-md-statsa part
.cap-md-surfacea part
.cap-md-toola part
.cap-md-toolbara part
.cap-md-toolbar-hinta part
.cap-md-uploada part
.cap-md-upload-actionsa part
.cap-md-upload-errora part
.cap-md-upload-fieldsa part
.cap-md-upload-thumba part
.cap-md-upload-waita part
AttributeValues
data-activepresent or absent
data-overpresent or absent
StateRead from
:activethe platform
:disabledthe platform
:emptythe platform
:focus-visiblethe platform
:hoverthe platform
[aria-disabled="true"]an attribute
[aria-invalid="true"]an attribute
[aria-readonly="true"]an attribute

Accessibility

KeyDoes
TabEnters the toolbar at its one stop; the next Tab enters the surface; Tab in the surface leaves it
Left arrow, Right arrow, Home, EndMoves between the toolbar's buttons, wrapping
Ctrl or Cmd B, I, EBold, italic or code around the selection; with none, the cursor lands between the marks
Ctrl or Cmd KOpens the link palette, the selection as its query
Down arrow, Up arrow (palette)Moves the active option, wrapping
Enter (palette)Links the active option, or the typed address; the cursor lands after the link
/ alone on a lineOpens the block menu (when the app supplies blocks)
Down arrow (surface, menu open)Enters the block menu
Up arrow, Down arrow, Home, End (block menu)Moves between blocks, wrapping
Enter (block menu)Replaces the / with the block, the cursor where the block says
EscCloses the link palette or the block menu and returns to the text; with neither open it is not claimed
Ctrl or Cmd SCalls onSave and fires cap-md-save; focus stays in the editor
Ctrl or Cmd Z, Ctrl or Cmd YUndo, redo
Enter (alt field), EscInserts the image once it has alt text; Esc discards it and returns to the text
  • The surface is a textbox that is multiline, named "Label, markdown", described by the field's help and error, and carries aria-required, aria-invalid, aria-readonly and aria-disabled from the textarea.
  • The toolbar is a toolbar named "Markdown formatting"; the link palette is a group holding a combobox named "Link to" with aria-activedescendant over a listbox; the block menu is a named list of buttons.
  • The upload step is a group named "Describe the image", aria-busy while uploading; its progress and result are said in a status region, a failure in an alert.
  • Single-key shortcuts of other components (j, k, /, z) never act inside the editor: the surface is editable text, which the shortcuts registry treats as typing. The slash menu is typed text, not a shortcut, so data-cap-single-keys="off" does not change it; Ctrl or Cmd keys are modifiers, not single keys.
  • Hit areas are at least --target; the toolbar's buttons grow with the density.
  • Forced colors: the focus ring, the active option and the focused block keep an outline; an invalid frame gets a thicker edge.
  • Under a strict style-src, pass the CSP nonce (nonce), or the page's first <script nonce> is read; without it CodeMirror's injected styles are dropped.