UI

Text editor

A lightweight rich text editor with markdown shortcuts, a floating selection toolbar, a slash menu for blocks, undo history, and clean HTML and Markdown output.

import { TextEditor } from '@uthereal/ui/text-editor'

Text editor playground

Loading interactive preview…

Overview

TextEditor provides a zero-dependency contentEditable writing surface with live Markdown shortcuts, a floating selection toolbar that morphs into an inline link field, a / slash command menu, a dedicated undo/redo stack, strict HTML sanitization, and clean HTML plus Markdown output. Floating layers mount through ThemedPortal with resolved --ui-* tokens so the editor works standalone without global stylesheets.

Use TextEditor for comments, release notes, posts, and short-to-medium documents with headings, lists, quotes, code blocks, and links. Use Text for plain text, Mention when the only rich structure is @ or # tags, and Code to display syntax-highlighted source listings.

CapabilityBehavior
Supported blocksParagraphs (p), headings (h1–h3), bulleted and numbered lists (ul, ol), blockquotes, fenced code (pre), hr
Inline marksBold (strong), italic (em), strikethrough (s), inline code (code), and validated links (a)
Floating toolbarTracks text selection; morphs in place into an inline URL input validated through normalizeUrl
Slash menu (/)Opens at line start or after whitespace to filter and insert any supported block type
Undo & sanitationKeeps up to 300 HTML snapshots (merging typing within 1s) and strips scripts, unsafe attributes, and unsafe URL schemes

Usage

'use client'
import { useState } from 'react'
import { TextEditor, type TextEditorValue } from '@uthereal/ui/text-editor'

export function ReleaseNotesEditor() {
  const [doc, setDoc] = useState<TextEditorValue | null>(null)

  return (
    <>
      <TextEditor
        label="Release notes"
        placeholder="Write your update"
        defaultMarkdown={
          '# Release notes\n\n- Faster search\n- New **dark** theme'
        }
        onChange={setDoc}
      />
      <button
        type="button"
        disabled={!doc || doc.empty}
        onClick={() => console.log(doc?.markdown)}
      >
        Publish
      </button>
    </>
  )
}

Omit value for an uncontrolled editor seeded from defaultMarkdown or defaultValue. When controlled via value, the editor only rewrites its DOM if the incoming HTML differs from the last emitted value, so feeding onChange's html back into value is safe.

Controlled HTML and undo history

Pair ref (TextEditorHandle), value, onChange, and onHistoryChange to wire host undo/redo controls:

'use client'
import { useRef, useState } from 'react'
import {
  TextEditor,
  type TextEditorHandle,
  type TextEditorHistoryState,
} from '@uthereal/ui/text-editor'

export function ControlledDraftEditor() {
  const editor = useRef<TextEditorHandle>(null)
  const [html, setHtml] = useState('<p>Draft</p>')
  const [history, setHistory] = useState<TextEditorHistoryState>({
    canUndo: false,
    canRedo: false,
  })

  return (
    <>
      <button
        type="button"
        disabled={!history.canUndo}
        onClick={() => editor.current?.undo()}
      >
        Undo
      </button>
      <button
        type="button"
        disabled={!history.canRedo}
        onClick={() => editor.current?.redo()}
      >
        Redo
      </button>
      <TextEditor
        ref={editor}
        label="Draft"
        value={html}
        onChange={(next) => setHtml(next.html)}
        onHistoryChange={setHistory}
      />
    </>
  )
}

Examples

Use <SchemaPlayground /> above to edit seeded Markdown with headings, lists, blockquotes, code blocks, slash commands, and the floating selection toolbar. The examples below show read-only and themed surfaces.

Read-only and themed surfaces

Set readOnly to present sanitized HTML or Markdown without editing chrome while keeping text selectable. Pair recipe="soft" with theme tokens to adapt the writing surface and portalled overlays to dark or branded containers.

Shortcuts and slash commands

Markdown shortcuts

Type a block prefix at the start of a paragraph or wrap inline text with delimiters to format immediately.

InputResultScope
# , ## , ### Heading 1, 2, or 3Block
- , * , + Bulleted listBlock
1. or 1) Numbered listBlock
> BlockquoteBlock
```Code block (pre)Block
---Horizontal divider (hr)Block
**text**, __text__Bold (strong)Inline
*text*, _text_Italic (em)Inline
~~text~~Strikethrough (s)Inline
`code`Inline code (code)Inline

Slash commands (/)

Type / at the start of a line or after whitespace, then type to filter by label or keyword.

CommandShortcutInserts
Text—Paragraph (p)
Heading 1#Heading 1 (h1)
Heading 2##Heading 2 (h2)
Heading 3###Heading 3 (h3)
Bulleted list-Unordered list
Numbered list1.Ordered list
Quote>Blockquote
Code block```Fenced code block
Divider---Horizontal rule

API reference

Serializable schema arguments and defaults come directly from textEditorConfigSchema.

ArgumentType / defaultDescription
labelstringDefault: "Text editor"Accessible name of the editing surface (applied as aria-label on the textbox).
defaultValuestring—Initial HTML content when uncontrolled, sanitized on load. Later edits do not reset a mounted instance; use value and onChange to control it.
defaultMarkdownstring—Initial content written in Markdown, converted to canonical HTML when defaultValue is omitted. Later edits do not reset a mounted instance.
placeholderstringDefault: "Start writing"Shown on the first line while the document is empty.
blockHintstringDefault: "Type / for blocks"Quiet hint shown on an empty block line while the editor is focused and non-empty.
readOnlybooleanDefault: falseDisables editing, markdown shortcuts, the floating toolbar, and the slash menu while keeping text selectable and copyable.
autoFocusbooleanDefault: falseFocuses the editor on mount and places the caret at the end of the content.
minHeightintegerDefault: 180Minimum height of the writing surface in pixels (80–1200).
recipestudio | softDefault: "studio"Visual treatment. Both studio and soft recipes share identical editing behavior.
themeTextEditorTheme—Color mode, accent, and semantic design tokens for the writing surface, floating toolbar, and slash menu.
motionnone | subtle | expressiveDefault: "subtle"Toolbar presence, face morph, position glide, and slash menu springs. none makes every update immediate; system reduced motion keeps subtle opacity crossfades.
motionOptionsTextEditorMotionOptions—Toolbar and slash menu presence transition, entrance/exit poses, indicator glide, and toolbar face morph overrides. Durations are milliseconds.
dirltr | rtl—Reading direction. Omit to inherit the page direction.

React integration

PropPurpose
valueControlled HTML string. Rewrites the DOM only when it differs from the last emitted HTML.
onChange(value)Fires after each edit with { html, markdown, text, empty }. HTML contains canonical tags and safe hrefs only.
onHistoryChange(state)Reports { canUndo, canRedo } whenever the editor's undo stack changes.
refImperative TextEditorHandle: focus, getHTML, getMarkdown, getText, setHTML, setMarkdown, clear, undo, redo, element.
presetApplication defaults overridden by explicit instance props.
tokens--ui-* CSS variables applied on the root and every portalled toolbar or slash menu.
portalContainerOptional portal mount target, such as an element inside a modal dialog.
className, style, nativeForwarded to the root container; aria-label overrides label on the textbox element.

Exported utilities

@uthereal/ui/text-editor exports the editor's standalone conversion and sanitization helpers:

UtilityPurpose
markdownToHtml(markdown)Converts Markdown to canonical editor HTML (h1–h3, nested lists, quotes, fenced code, rules, inline marks/links).
htmlToMarkdown(input)Converts an HTML string or HTMLElement to Markdown (browser only).
sanitizeHtml(html)Keeps only supported tags, promotes bold/italic/strike spans, strips unsafe attributes, and validates link schemes.
normalizeUrl(input)Adds https:// to bare domains, mailto: to email addresses, allows / and #, and rejects unsafe schemes.

Keyboard & accessibility

KeyAction
Cmd/Ctrl+B, Cmd/Ctrl+IToggles bold or italic.
Cmd/Ctrl+Shift+X, Cmd/Ctrl+EToggles strikethrough or inline code (within a single block).
Cmd/Ctrl+KOpens the floating link face for the selection or the link under the caret.
Cmd/Ctrl+Z, Cmd/Ctrl+Shift+Z, Cmd/Ctrl+YSteps backward or forward in the editor's undo history (Cmd/Ctrl+U is blocked).
/Opens the slash menu. ArrowUp/ArrowDown move, Enter/Tab insert, Escape closes.
Tab / Shift+TabIndents or outdents list items; in code blocks, Tab inserts two spaces.
Enter / Shift+EnterStarts a new block or inserts a soft break; empty list/quote exits; two Enters exit code.
BackspaceAt the start of a heading, quote, code block, or list item, converts to paragraph or outdents.
Alt+F10Moves focus into the open floating toolbar (ArrowLeft/ArrowRight navigate; Escape exits).

The editing surface exposes role="textbox", aria-multiline="true", aria-label, and aria-readonly when readOnly is set. While the slash menu is open, the textbox connects to the role="listbox" menu via aria-controls and aria-activedescendant. The floating toolbar uses role="toolbar" with aria-pressed toggle buttons that prevent mousedown so selections survive clicks. A pre-mounted polite role="status" live region announces formatting, link updates, block insertions, and undo/redo results.

In dir="rtl", block borders, list padding, placeholder alignment, toolbar keyboard arrows, face slide directions, and viewport anchoring mirror along the inline axis. Under forced-colors: active, borders, links, pressed toggles, and active slash options map to system colors.

Motion and theming

  • Floating toolbar: Pops in on the snappy spring with a 160ms fade, glides smoothly across selections on motionOptions.indicator, and morphs width, height, and blurred face transitions on motionOptions.morph when switching between formatting tools and the link input.
  • Slash menu: Opens from the / anchor, springs its height as results filter, and glides the row highlight under pointer movement while snapping instantly for keyboard navigation.
  • Reduced motion: prefers-reduced-motion: reduce disables travel, scale, blur, and springs while keeping short opacity crossfades. motion="none" makes every update immediate (0ms).

theme accepts mode, accent, and the semantic tokens listed below. An optional UtherealProvider supplies application-wide defaults.

Token group / keysUsed for
core (surfaceRaised, foreground, mutedForeground, textSecondary, border, highlight, accent, accentForeground, focusRing, radius, borderWidth, shadow, fontFamily, fontSize, fontWeight)Writing surface typography, caret, selection tint, toolbar and slash menu chrome
accentTones (accentStrong, accentSubtle)Links and pressed formatting toggle states
surfaceSunken, borderStrong, borderSubtleInline code chips, code block wells, blockquote bars, and dividers
radiusSm, popupRadius, itemRadius, fontFamilyMono, shortcutSizeCode corners, soft recipe popups, monospace code blocks, and slash hints

Composition

TextEditor is a leaf component. Its HTML value is persisted host state initialized from defaultValue or defaultMarkdown and reconciled across configuration edits. Images, tables, and underline are intentionally omitted so stored HTML and Markdown stay predictable.

{
  "type": "TextEditor",
  "props": {
    "label": "Release notes",
    "placeholder": "Write your update",
    "defaultMarkdown": "# Release notes\n\n- Faster search\n- New **dark** theme"
  },
  "children": []
}

On this page