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
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.
| Capability | Behavior |
|---|---|
| Supported blocks | Paragraphs (p), headings (h1–h3), bulleted and numbered lists (ul, ol), blockquotes, fenced code (pre), hr |
| Inline marks | Bold (strong), italic (em), strikethrough (s), inline code (code), and validated links (a) |
| Floating toolbar | Tracks 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 & sanitation | Keeps 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.
| Input | Result | Scope |
|---|---|---|
# , ## , ### | Heading 1, 2, or 3 | Block |
- , * , + | Bulleted list | Block |
1. or 1) | Numbered list | Block |
> | Blockquote | Block |
``` | 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.
| Command | Shortcut | Inserts |
|---|---|---|
| Text | — | Paragraph (p) |
| Heading 1 | # | Heading 1 (h1) |
| Heading 2 | ## | Heading 2 (h2) |
| Heading 3 | ### | Heading 3 (h3) |
| Bulleted list | - | Unordered list |
| Numbered list | 1. | Ordered list |
| Quote | > | Blockquote |
| Code block | ``` | Fenced code block |
| Divider | --- | Horizontal rule |
API reference
Serializable schema arguments and defaults come directly from textEditorConfigSchema.
| Argument | Type / default | Description |
|---|---|---|
label | stringDefault: "Text editor" | Accessible name of the editing surface (applied as aria-label on the textbox). |
defaultValue | string— | Initial HTML content when uncontrolled, sanitized on load. Later edits do not reset a mounted instance; use value and onChange to control it. |
defaultMarkdown | string— | Initial content written in Markdown, converted to canonical HTML when defaultValue is omitted. Later edits do not reset a mounted instance. |
placeholder | stringDefault: "Start writing" | Shown on the first line while the document is empty. |
blockHint | stringDefault: "Type / for blocks" | Quiet hint shown on an empty block line while the editor is focused and non-empty. |
readOnly | booleanDefault: false | Disables editing, markdown shortcuts, the floating toolbar, and the slash menu while keeping text selectable and copyable. |
autoFocus | booleanDefault: false | Focuses the editor on mount and places the caret at the end of the content. |
minHeight | integerDefault: 180 | Minimum height of the writing surface in pixels (80–1200). |
recipe | studio | softDefault: "studio" | Visual treatment. Both studio and soft recipes share identical editing behavior. |
theme | TextEditorTheme— | Color mode, accent, and semantic design tokens for the writing surface, floating toolbar, and slash menu. |
motion | none | 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. |
motionOptions | TextEditorMotionOptions— | Toolbar and slash menu presence transition, entrance/exit poses, indicator glide, and toolbar face morph overrides. Durations are milliseconds. |
dir | ltr | rtl— | Reading direction. Omit to inherit the page direction. |
React integration
| Prop | Purpose |
|---|---|
value | Controlled 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. |
ref | Imperative TextEditorHandle: focus, getHTML, getMarkdown, getText, setHTML, setMarkdown, clear, undo, redo, element. |
preset | Application defaults overridden by explicit instance props. |
tokens | --ui-* CSS variables applied on the root and every portalled toolbar or slash menu. |
portalContainer | Optional portal mount target, such as an element inside a modal dialog. |
className, style, native | Forwarded 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:
| Utility | Purpose |
|---|---|
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
| Key | Action |
|---|---|
Cmd/Ctrl+B, Cmd/Ctrl+I | Toggles bold or italic. |
Cmd/Ctrl+Shift+X, Cmd/Ctrl+E | Toggles strikethrough or inline code (within a single block). |
Cmd/Ctrl+K | Opens the floating link face for the selection or the link under the caret. |
Cmd/Ctrl+Z, Cmd/Ctrl+Shift+Z, Cmd/Ctrl+Y | Steps 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+Tab | Indents or outdents list items; in code blocks, Tab inserts two spaces. |
Enter / Shift+Enter | Starts a new block or inserts a soft break; empty list/quote exits; two Enters exit code. |
Backspace | At the start of a heading, quote, code block, or list item, converts to paragraph or outdents. |
Alt+F10 | Moves 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
160msfade, glides smoothly across selections onmotionOptions.indicator, and morphs width, height, and blurred face transitions onmotionOptions.morphwhen 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: reducedisables 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 / keys | Used 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, borderSubtle | Inline code chips, code block wells, blockquote bars, and dividers |
radiusSm, popupRadius, itemRadius, fontFamilyMono, shortcutSize | Code 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": []
}