Command palette

@yasinsensoy/web

Web · Components

RichTextEditor

Rich text editor: formatted text, headings, lists, tasks, quotes, highlighted code blocks, links, images and mentions.

33 exports

Live example

Preview

Weekly note

This editor supports bold, italic, underline, strikethrough, inline code and highlight. There are links too.

  • Finish the design
  • Write the tests
    • Mobile
Try the Markdown shortcuts: type ## , - , 1. , [ ] , > or ```ts at the start of a line.
export function Hello({ name }: { name: string }) {
  return <p>Hello {name}!</p>;
}

Type / on an empty line to add a block, mention someone with @.

Value (html)
<h2>Weekly note</h2>
<p>This editor supports <strong>bold</strong>, <em>italic</em>, <u>underline</u>, <s>strikethrough</s>, <code>inline code</code> and <mark>highlight</mark>. There are <a href="https://github.com/yasinsensoy/ui">links</a> too.</p>
<ul data-type="task"><li data-checked="true">Finish the design</li><li data-checked="false">Write the tests<ul data-type="task"><li data-checked="false">Mobile</li></ul></li></ul>
<blockquote>Try the Markdown shortcuts: type <code>## </code>, <code>- </code>, <code>1. </code>, <code>[ ] </code>, <code>&gt; </code> or <code>```ts</code> at the start of a line.</blockquote>
<pre data-language="tsx"><code>export function Hello({ name }: { name: string }) {
  return &lt;p&gt;Hello {name}!&lt;/p&gt;;
}</code></pre>
<p>Type <code>/</code> on an empty line to add a block, mention someone with <code>@</code>.</p>

Code

import { RichTextEditor, RichTextView } from "@yasinsensoy/web";

<RichTextEditor placeholder="Write something…"
  mentions={[{ trigger: "@", items: personSearch }, { trigger: "#", items: tags }]}
  onImageUpload={async (file) => (await upload(file)).url}
  onValueChange={setContent}
/>

// To display it (server component, code blocks with CodeBlock):
<RichTextView value={content} />

Events

  1. Events appear here when you interact with the preview.

Control with a ref and RichTextView

Control with a ref

Try the buttons.

Form field (required, 280 characters, Markdown)


0/280

Markdown shortcuts work; mention with @.

Read-only display (RichTextView)

Weekly note

This editor supports bold, italic, underline, strikethrough, inline code and highlight. There are links too.

  • Finish the design
  • Write the tests
    • Mobile
Try the Markdown shortcuts: type ## , - , 1. , [ ] , > or ```ts at the start of a line.
export function Hello({ name }: { name: string }) {
  return <p>Hello {name}!</p>;
}

Type / on an empty line to add a block, mention someone with @.

Import

import {
  RichTextEditor,
  RichTextField,
  RichTextView,
  richTextToHtml,
  richTextToMarkdown,
  richTextToDocument,
  richTextToPlainText,
  isRichTextEmpty,
} from "@yasinsensoy/web";

RichTextEditor

componentClient component

Rich text editor: formatted text, headings, lists, tasks, quotes, highlighted code blocks, links, images and mentions. Uses no external library.

  • Value: HTML, Markdown or JSON with format. All pasted and given content is sanitized; only known structures and safe URLs remain (safe against XSS).
  • Shortcuts: Mod+B/I/U, Mod+E code, Mod+Shift+X strike, Mod+Shift+H highlight, Mod+K link, Mod+Alt+1/2/3 headings, Mod+Shift+7/8/9 lists, Tab/Shift+Tab indent, Mod+Z/Mod+Shift+Z undo/redo, Mod+Shift+V paste without formatting. For Markdown shortcuts see markdownShortcuts.
  • Code blocks: The language can be picked; highlighted while typing (without touching the DOM, with the CSS Custom Highlight API); Tab indents, Mod+Enter exits the block. RichTextView draws code blocks with CodeBlock.
  • Paste: From Word, Google Docs and web pages with formatting; Markdown text is parsed; a URL pasted over selected text becomes a link.
  • Form: Submitted with the form via name; required and maxLength join browser validation. For label and error see RichTextField.
  • Mobile: The toolbar scrolls horizontally; task checkboxes are finger-sized; suggestion and link panels stay above the keyboard.
  • Server: The initial content is rendered on the server; no layout shift when the page opens.
RichTextEditor({ value, defaultValue, onValueChange, format, placeholder, toolbar, bubbleMenu, markdownShortcuts, slashCommands, mentions, onImageUpload, maxLength, showCount, readOnly, disabled, autoFocus, name, required, form, id, "aria-label": ariaLabel, "aria-describedby": ariaDescribedBy, "aria-invalid": ariaInvalid, spellCheck, onFocus, onBlur, messages: messagesProp, className, classNames, ref, variant, effect, }: RichTextEditorProps): JSX.Element

Examples

<RichTextEditor placeholder="Write something…" onValueChange={setHtml} />

<RichTextEditor format="markdown" defaultValue={"# Hello\n\n**World**"}
  toolbar={["bold", "italic", "link", "|", "bulletList", "codeBlock"]} />

<RichTextEditor name="comment" required maxLength={2000}
  mentions={{ items: (q) => searchPeople(q) }}
  onImageUpload={async (file) => (await upload(file)).url} />

RichTextField

componentClient component

RichTextEditor with its label, description and error message. Takes all props of the editor.

  • required stops the form on an empty document (whitespace only counts as empty too); the error shows on blur or on submit.
  • An error shows if maxLength is exceeded; the counter is at the bottom.
  • Server errors come from the nearest Form's state by name.
  • Clicking the label focuses the editor; screen readers read the editor with the label.
RichTextField(input: RichTextFieldProps): JSX.Element

Examples

<Form action={save}>
  <RichTextField label="Description" name="description" format="markdown" required maxLength={5000}
    description="Markdown shortcuts are supported."
    messages={{ valueMissing: "Description is required" }} />
  <SubmitButton>Save</SubmitButton>
</Form>

RichTextView

componentServer component

Shows rich text (HTML, Markdown or JSON). Uses the same typography as RichTextEditor; what is written and what is published look the same.

  • Server component: Needs no client JavaScript; HTML and Markdown are parsed on the server. Only code blocks run on the client with CodeBlock (highlighting and copying).
  • Safe: dangerouslySetInnerHTML isn't used; content is converted to React elements. Unknown tags, scripts and unsafe URLs are dropped.
  • External links open in a new tab with rel="noopener noreferrer nofollow".
RichTextView({ value, format, linkTarget, mentionHref, codeLineNumbers, empty, className, ...props }: RichTextViewProps): JSX.Element

Examples

<RichTextView value={post.content} />
<RichTextView value={comment} format="markdown" mentionHref={(m) => `/people/${m.id}`} />

Converts rich text to HTML. The input is sanitized; the output contains only known tags and safe URLs, so it can be shown with dangerouslySetInnerHTML. Also runs on the server.

richTextToHtml(value: RichTextValue, from?: RichTextFormat): string

Examples

richTextToHtml("**Hello** _world_", "markdown"); // "<p><strong>Hello</strong> <em>world</em></p>"
richTextToHtml('<p onclick="x()">Hi<script>…</script></p>'); // "<p>Hi</p>"

Converts rich text to Markdown. Also runs on the server.

richTextToMarkdown(value: RichTextValue, from?: RichTextFormat): string

Examples

richTextToMarkdown("<h2>Title</h2><ul><li>one</li></ul>"); // "## Title\n\n- one"

Converts rich text to a RichTextDocument object. Also runs on the server; for tasks like finding mentions or counting words.

richTextToDocument(value: RichTextValue, from?: RichTextFormat): RichTextDocument

Plain text of rich text: formats are dropped and blocks are separated by line breaks. For previews, search indexes and notification texts.

richTextToPlainText(value: RichTextValue, from?: RichTextFormat): string

Examples

richTextToPlainText("<p><b>Hello</b></p><ul><li>one</li></ul>"); // "Hello\none"

Is the rich text empty? A value made only of empty paragraphs (e.g. "<p></p>") counts as empty; images and dividers count as content.

isRichTextEmpty(value: RichTextValue | null | undefined, from?: RichTextFormat): boolean

Format of the editor value.

  • "html": sanitized HTML text. Can be shown on the page directly; contains only known tags and safe URLs.
  • "markdown": Markdown text (GFM). For places that store plain text, such as comments, READMEs or chat.
  • "json": a RichTextDocument object. The safest for processing on the server (e.g. finding mentioned people) and validating with a schema.
type RichTextFormat = "html" | "markdown" | "json"

Value type by format: a document object for json, text for the others.

type RichTextValue = string | RichTextDocument

Texts of the rich text editor; can be changed with messages.

NameTypeDefaultDescription
editorstring"Metin düzenleyici"Screen reader name of the editing area; used when there is no label (<label for>), aria-label or placeholder.
toolbarstring"Biçimlendirme"Screen reader name of the toolbar.
undostring"Geri al"
redostring"Yinele"
blockTypestring"Metin türü"Line kind picker.
paragraphstring"Metin"
heading1string"Başlık 1"
heading2string"Başlık 2"
heading3string"Başlık 3"
boldstring"Kalın"
italicstring"İtalik"
underlinestring"Altı çizili"
strikestring"Üstü çizili"
codestring"Satır içi kod"
highlightstring"Vurgula"
linkstring"Bağlantı"
unlinkstring"Bağlantıyı kaldır"
editLinkstring"Bağlantıyı düzenle"
openLinkstring"Bağlantıyı aç"
linkPlaceholderstring"Adres yapıştır ya da yaz"Placeholder of the link box.
linkTextstring"Görünen metin"Link text box.
applystring"Uygula"
invalidLinkstring"Geçerli bir adres gir"Invalid URL.
bulletListstring"Madde işaretli liste"
orderedListstring"Numaralı liste"
taskListstring"Yapılacaklar listesi"
quotestring"Alıntı"
codeBlockstring"Kod bloğu"
imagestring"Görsel"
dividerstring"Ayırıcı çizgi"
alignstring"Hizalama"
alignLeftstring"Sola hizala"
alignCenterstring"Ortala"
alignRightstring"Sağa hizala"
alignJustifystring"İki yana yasla"
indentstring"Girintiyi artır"
outdentstring"Girintiyi azalt"
clearFormattingstring"Biçimi temizle"
languagestring"Dil"Code block language picker.
plainTextstring"Düz metin"Code block without a language.
imageUrlstring"Görsel adresi"Image URL box.
imageUploadstring"Dosyadan yükle"Image upload button.
imageAltstring"Açıklama (alt metin)"Alternative text of the image.
imageSizestring"Boyut"Image size.
smallstring"Küçük"
mediumstring"Orta"
fullstring"Tam genişlik"
removeImagestring"Görseli sil"Delete the image.
imageFailedstring"Görsel yüklenemedi"The image could not be uploaded.
insertstring"Ekle"Slash menu title.
slashHintstring"Komutlar için / yaz"Hint on an empty line.
noResultsstring"Sonuç yok"No results in the suggestion list.
loadingstring"Yükleniyor…"While suggestions are loading.
counterstring"{count}/{max}"Character counter; {count} and {max} are replaced.
tooLongstring"En fazla {max} karakter yazılabilir"When the character limit is exceeded.
wordsstring"{count} kelime"Word count; {count} is replaced.
morestring"Diğer"More tools menu.
donestring"Tamamlandı"Screen reader name of the to-do checkbox.

Formats that can be applied to text.

type RichTextMark = "bold" | "italic" | "underline" | "strike" | "code" | "highlight"

Paragraph and heading alignment. Defaults to start (the start of the writing direction).

type RichTextAlign = "center" | "right" | "justify"

RichTextText

interface

Formatted text piece.

NameTypeDescription
type"text"Piece kind.
textstringText. Contains no line breaks outside code blocks; a line break is break.
marks?RichTextMark[]Applied formats.
link?stringLink URL.

Mention (@person, #tag). Deleted and moved as a single piece.

NameTypeDefaultDescription
type"mention"Piece kind.
idstringId of the mentioned item (e.g. user id).
labelstringDisplay name (without the trigger character).
triggerstring"@"Trigger character.

RichTextBreak

interface

Line break inside a paragraph (Shift+Enter).

NameTypeDescription
type"break"Piece kind.

Inline content piece.

type RichTextInline = RichTextText | RichTextMention | RichTextBreak

List kind: bulleted, numbered or to-do (with checkboxes).

type RichTextListStyle = "bullet" | "ordered" | "task"

List item.

NameTypeDescription
contentRichTextInline[]Text of the item.
checked?booleanChecked in a to-do list?
children?RichTextListNested list.

RichTextList

interface

List block.

NameTypeDefaultDescription
type"list"Block kind.
styleRichTextListStyleList kind.
start?number1First number of a numbered list.
itemsRichTextListItem[]Items.

Document block.

type RichTextBlock = { /** Block kind: paragraph. */ type: "paragraph"; /** Text alignment. */ align?: RichTextAlign; /** Inline content. */ content: RichTextInline[]; } | { /** Block kind: heading. */ type: "heading"; /** Heading level (h1–h3). */ level: 1 | 2 | 3; /** Text alignment. */ align?: RichTextAlign; /** Inline content. */ content: RichTextInline[]; } | { /** Block kind: quote. */ type: "quote"; /** Inline content. */ content: RichTextInline[]; } | { /** Block kind: code block. */ type: "code"; /** Highlighting language (e.g. `"tsx"`). */ language?: string; /** Code text. */ code: string; } | RichTextList | { /** Block kind: image. */ type: "image"; /** Image URL. */ src: string; /** Alternative text. */ alt?: string; /** Width as a percentage of the container (e.g. `50`). Natural size when omitted. */ width?: number; } | { /** Block kind: divider. */ type: "divider"; }

Rich text document. This is the editor value with format="json"; the safest format to store in a database and process on the server.

NameTypeDescription
type"doc"Document kind.
contentRichTextBlock[]Blocks.

Classes that can be passed to the inner parts of RichTextEditor.

NameTypeDescription
toolbar?stringToolbar.
content?stringWriting area (contentEditable). For height use min-h-*, max-h-*.
footer?stringCounter row at the bottom.

Props of the RichTextEditor component.

NameTypeDefaultDescription
variant?FieldVariant | CustomVariant<"field">Look: outline (bordered), filled, underline or ghost (plain). If omitted, the setting of the nearest data-field-variant container is used, otherwise outline. See FieldVariant.
effect?EffectPropEffect or effects of the field box (e.g. "glow", ["lift", "beam"]). The accent color is the focus color (--ui-field-focus). If omitted, UIProvider appearance.defaults.field.effect. See BuiltinEffect.
value?RichTextValueControlled value. Its format is set by format.
defaultValue?RichTextValueUncontrolled initial value.
onValueChange?(value: RichTextValue) => voidCalled with the new value when the content changes. An empty document arrives as "" (an empty document in json).
format?RichTextFormat"html"Format of the value: "html" (sanitized HTML), "markdown" or "json". See RichTextFormat.
placeholder?stringPlaceholder shown while the document is empty.
toolbar?boolean | readonly RichTextToolbarItem[]trueToolbar: true default tools, false hides it, an array shows only those tools (in order). "|" is a separator; for your own button pass a RichTextCustomTool.
bubbleMenu?booleantrueSmall format menu that opens above the selection when text is selected (bold, italic, link…). Allows formatting even when the toolbar is hidden.
markdownShortcuts?booleantrueMarkdown shortcuts: # heading, - list, 1. numbered list, [ ] task, > quote, ``` ` `` code block, --- rule, bold, italic, code , ~~strike~~, ==highlight==`. Typed URLs turn into links. Backspace right after a shortcut undoes it.
slashCommands?boolean | readonly RichTextSlashCommand[]trueSlash (/) menu: typing / at line start or after a space opens the block insert menu. true built-in commands; an array adds your own commands after the built-in ones. false turns it off.
mentions?RichTextMentionSource | readonly RichTextMentionSource[]Mention sources: e.g. person suggestions on @, tag suggestions on #. See RichTextMentionSource.
onImageUpload?(file: File) => Promise<string>Image uploader. If given, images can be pasted, dragged and dropped, and picked from files. Upload the file to your server and return the image URL. The image looks faded while uploading; it is removed on error.
maxLength?numberMaximum characters. Typing and pasting beyond it is blocked.
showCount?boolean | "words"Counter on the bottom row: true characters (and the limit if maxLength is set), "words" word count. Turns on automatically if maxLength is given.
readOnly?booleanRead-only: content can be selected and copied but not changed; the toolbar is hidden.
disabled?booleanDisabled.
autoFocus?booleanFocus when the page opens.
name?stringName submitted with the form; the value goes as text in the format format (json: JSON text).
required?booleanCan't be left empty in a form.
form?stringId of the form it belongs to.
id?stringField id (for label linking; RichTextField passes it itself).
aria-label?stringScreen reader name (if there is no visible label).
aria-describedby?stringIds of the description elements.
aria-invalid?boolean | "true" | "false"Mark as invalid.
spellCheck?booleantrueSpell check.
onFocus?(event: FocusEvent<HTMLDivElement>) => voidOn focus.
onBlur?(event: FocusEvent<HTMLDivElement>) => voidOn blur.
messages?Partial<RichTextMessages>Texts of this editor; for app-wide texts use the dictionary's ui.richText namespace. See RichTextMessages.
className?stringClasses added to the container.
classNames?RichTextEditorClassNamesClasses added to the inner parts.
ref?Ref<RichTextEditorHandle>For controlling the editor. See RichTextEditorHandle.

Props of the RichTextField component.

Extends: FieldOwnProps

NameTypeDefaultDescription
variant?FieldVariant | CustomVariant<"field">Look: outline (bordered), filled, underline or ghost (plain). If omitted, the setting of the nearest data-field-variant container is used, otherwise outline. See FieldVariant.
effect?EffectPropEffect or effects of the field box (e.g. "glow", ["lift", "beam"]). The accent color is the focus color (--ui-field-focus). If omitted, UIProvider appearance.defaults.field.effect. See BuiltinEffect.
value?RichTextValueControlled value. Its format is set by format.
defaultValue?RichTextValueUncontrolled initial value.
onValueChange?(value: RichTextValue) => voidCalled with the new value when the content changes. An empty document arrives as "" (an empty document in json).
format?RichTextFormat"html"Format of the value: "html" (sanitized HTML), "markdown" or "json". See RichTextFormat.
placeholder?stringPlaceholder shown while the document is empty.
toolbar?boolean | readonly RichTextToolbarItem[]trueToolbar: true default tools, false hides it, an array shows only those tools (in order). "|" is a separator; for your own button pass a RichTextCustomTool.
bubbleMenu?booleantrueSmall format menu that opens above the selection when text is selected (bold, italic, link…). Allows formatting even when the toolbar is hidden.
markdownShortcuts?booleantrueMarkdown shortcuts: # heading, - list, 1. numbered list, [ ] task, > quote, ``` ` `` code block, --- rule, bold, italic, code , ~~strike~~, ==highlight==`. Typed URLs turn into links. Backspace right after a shortcut undoes it.
slashCommands?boolean | readonly RichTextSlashCommand[]trueSlash (/) menu: typing / at line start or after a space opens the block insert menu. true built-in commands; an array adds your own commands after the built-in ones. false turns it off.
mentions?RichTextMentionSource | readonly RichTextMentionSource[]Mention sources: e.g. person suggestions on @, tag suggestions on #. See RichTextMentionSource.
onImageUpload?(file: File) => Promise<string>Image uploader. If given, images can be pasted, dragged and dropped, and picked from files. Upload the file to your server and return the image URL. The image looks faded while uploading; it is removed on error.
maxLength?numberMaximum characters. Typing and pasting beyond it is blocked.
showCount?boolean | "words"Counter on the bottom row: true characters (and the limit if maxLength is set), "words" word count. Turns on automatically if maxLength is given.
readOnly?booleanRead-only: content can be selected and copied but not changed; the toolbar is hidden.
disabled?booleanDisabled.
autoFocus?booleanFocus when the page opens.
name?stringName submitted with the form; the value goes as text in the format format (json: JSON text).
required?booleanCan't be left empty in a form.
form?stringId of the form it belongs to.
id?stringField id (for label linking; RichTextField passes it itself).
aria-label?stringScreen reader name (if there is no visible label).
aria-describedby?stringIds of the description elements.
aria-invalid?boolean | "true" | "false"Mark as invalid.
spellCheck?booleantrueSpell check.
onFocus?(event: FocusEvent<HTMLDivElement>) => voidOn focus.
onBlur?(event: FocusEvent<HTMLDivElement>) => voidOn blur.
ref?Ref<RichTextEditorHandle>For controlling the editor. See RichTextEditorHandle.
editorMessages?Partial<RichTextMessages>Texts of the editor (messages is the field's validation messages). See RichTextMessages.
editorClassNames?RichTextEditorClassNamesClasses for the editor's inner parts.

Props of the RichTextView component.

Extends: Omit<ComponentProps<"div">, "children">

NameTypeDefaultDescription
valueRichTextValue | null | undefinedContent to show: HTML, Markdown or RichTextDocument.
format?RichTextFormatFormat of the value. If omitted, text starting with < counts as HTML, otherwise Markdown; an object is a JSON document.
linkTarget?string"_blank"Target of links. "_blank" opens external links in a new tab.
mentionHref?(mention: RichTextMention) => string | undefinedTurns a mention into a link (e.g. a profile page). If omitted, drawn as a tag.
codeLineNumbers?booleanfalseLine numbers in code blocks.
empty?ReactNodeElement shown while the content is empty.

Built-in commands that can run in the editor (same on web and native).

type RichTextCommandName = "undo" | "redo" | "bold" | "italic" | "underline" | "strike" | "code" | "highlight" | "paragraph" | "heading1" | "heading2" | "heading3" | "bulletList" | "orderedList" | "taskList" | "quote" | "codeBlock" | "divider" | "image" | "link" | "unlink" | "alignLeft" | "alignCenter" | "alignRight" | "alignJustify" | "indent" | "outdent" | "clearFormatting"

Object obtained with ref to control the editor from outside.

NameTypeDefaultDescription
focus(): voidFocuses the editor; the caret returns to its last position.
blur(): voidRemoves focus from the editor.
getValue(format?: RichTextFormat): RichTextValuethe editor's `formatReturns the value in the requested format.
getDocument(): RichTextDocumentReturns the document.
getText(): stringReturns plain text.
setValue(value: RichTextValue, format?: RichTextFormat): voidChanges the value (undoable).
insertContent(value: RichTextValue, format?: RichTextFormat): voidInserts content at the caret; replaces the selection if any.
insertText(text: string): voidInserts plain text at the caret.
clear(): voidEmpties the editor (undoable).
exec(command: RichTextCommandName): voidRuns a built-in command.
isActive(command: RichTextCommandName): booleanWhether a command is active (e.g. is the caret in bold text).
insertImage(src: string, alt?: string): voidInserts an image.
setLink(href: string | null): voidApplies a link to the selection; null removes it.
elementHTMLElement | nullRoot contentEditable element.

Examples

const editor = useRef<RichTextEditorHandle>(null);
<RichTextEditor ref={editor} />
<Button onClick={() => editor.current?.insertContent("**Hello**", "markdown")}>Insert</Button>

Your own toolbar button.

NameTypeDescription
keystringUnique key.
labelstringName of the button (tooltip and screen reader).
iconIconPropIcon.
onClick(editor: RichTextEditorHandle) => voidCalled when clicked.
isActive?(editor: RichTextEditorHandle) => booleanWhether it looks active. Called on every selection change.

Toolbar item: built-in tool name, "|" separator or your own button. "blockType" is the text/heading picker, "align" the alignment menu.

type RichTextToolbarItem = Exclude<RichTextCommandName, "paragraph" | "heading1" | "heading2" | "heading3" | "unlink" | "alignLeft" | "alignCenter" | "alignRight" | "alignJustify"> | "blockType" | "align" | "|" | RichTextCustomTool

Mention suggestion.

NameTypeDescription
idstringId; stored in the value.
labelstringVisible name (without the trigger).
description?ReactNodeSmall description below the name (e.g. email).
avatar?stringAvatar image URL.
icon?IconPropIcon instead of an avatar.

Mention source.

NameTypeDefaultDescription
trigger?string"@"Trigger character.
itemsreadonly RichTextMentionItem[] | ((query: string, signal: AbortSignal) => Promise<readonly RichTextMentionItem[]> | readonly RichTextMentionItem[])Suggestions: an array or a function called with the typed query (server search). The function can cancel old searches with signal. An array is filtered by name.
label?ReactNodeTitle of the list (e.g. "People").

Your own command added to the slash (/) menu.

NameTypeDescription
keystringUnique key.
labelstringVisible name.
description?ReactNodeDescription below the name.
icon?IconPropIcon.
keywords?readonly string[]Extra words to match in search.
onSelect(editor: RichTextEditorHandle) => voidCalled when selected; the "/query" text has already been deleted.