When to use it#
- Use it for text that will be published or sent and needs headings, lists or links: a news item, a case description in a staff tool, an association’s event text.
- Put it in a Field with a visible label. The Field’s label names the editable text, and its description, help text and error describe it.
- Not for a plain answer in a resident’s own words: use a Textarea. Residents rarely need formatting, and an editor is heavier to use with a keyboard and a screen reader. Not for showing saved text: render it as Prose.
- It is its own package,
@kvirn-ui/rich-text, built on Tiptap. Tiptap is a peer: you install it yourself, once, so your app has one copy. The install lines are in the API reference.
Example#
The text is published on the municipality’s website.
import { Field } from '@kvirn-ui/react'
import { RichTextEditor } from '@kvirn-ui/rich-text'
import { useRichTextEditorTexts } from './texts.ts'
export function DefaultRichTextEditor() {
const { texts } = useRichTextEditorTexts()
return (
<Field.Root>
<Field.Label>{texts.articleLabel}</Field.Label>
<Field.Prose>
<p>{texts.newsDescription}</p>
</Field.Prose>
<RichTextEditor.Root defaultValue={`<p>${texts.newsIntro}</p>`}>
<RichTextEditor.Toolbar />
<RichTextEditor.Content />
</RichTextEditor.Root>
</Field.Root>
)
}Use cases#
A news item sent with a form
An editor writes a news item for the municipality’s website. The form sends the text under name, and a form reset goes back to defaultValue. An empty editor sends an empty string, never an empty paragraph, so a required field works. Your form checks the text and sets invalid, and the ErrorSummary links to the editor.
import { Button, ErrorSummary, Field, Stack } from '@kvirn-ui/react'
import { RichTextEditor } from '@kvirn-ui/rich-text'
import { useId, useState } from 'react'
import { useRichTextEditorTexts } from './texts.ts'
export function InAForm() {
const { texts } = useRichTextEditorTexts()
const editorId = useId()
const [submitCount, setSubmitCount] = useState(0)
const [hasError, setHasError] = useState(false)
const [posted, setPosted] = useState<string | undefined>()
return (
<Stack className="kv-stack--gap-8">
{hasError ? (
<ErrorSummary.Root focusKey={submitCount}>
<ErrorSummary.Title />
<ErrorSummary.List>
<ErrorSummary.Item>
<ErrorSummary.Link controlId={editorId}>{texts.newsError}</ErrorSummary.Link>
</ErrorSummary.Item>
</ErrorSummary.List>
</ErrorSummary.Root>
) : null}
<form
noValidate
onSubmit={(event) => {
event.preventDefault()
const news = new FormData(event.currentTarget).get('news')
const html = typeof news === 'string' ? news : ''
setHasError(html === '')
setPosted(html === '' ? undefined : html)
setSubmitCount((count) => count + 1)
}}
onReset={() => {
setHasError(false)
setPosted(undefined)
}}
>
<Field.Root controlId={editorId} required invalid={hasError}>
<Field.Label>{texts.newsLabel}</Field.Label>
<Field.Prose>
<p>{texts.newsDescription}</p>
</Field.Prose>
<RichTextEditor.Root name="news" defaultValue={`<p>${texts.newsIntro}</p>`}>
<RichTextEditor.Toolbar />
<RichTextEditor.Content />
</RichTextEditor.Root>
<Field.ErrorMessage>{texts.newsError}</Field.ErrorMessage>
</Field.Root>
<div className="kv-button-group">
<Button type="submit" className="kv-button--primary">
{texts.publish}
</Button>
<Button type="reset">{texts.reset}</Button>
</div>
</form>
<output>
{posted === undefined ? null : (
<>
{texts.posted} <code>{posted}</code>
</>
)}
</output>
</Stack>
)
}Props in this example:
nameon RichTextEditor.RootdefaultValueon RichTextEditor.Root
Information: Did you know?
The form sends the HTML as it is. The editor never sanitizes it: clean it on your server before you store or publish it, and take any target off links.
A case note that your own state holds
A caseworker writes a note, and your code keeps the value, for example in your form library or as a draft. Use the JSON format, pass value and onValueChange, and set a new value when your code needs to change the text. An empty note is null.
import { Button, Field, Stack } from '@kvirn-ui/react'
import { RichTextEditor } from '@kvirn-ui/rich-text'
import type { RichTextValue } from '@kvirn-ui/rich-text'
import { useState } from 'react'
import { useRichTextEditorTexts } from './texts.ts'
export function ControlledCaseNote() {
const { texts } = useRichTextEditorTexts()
const [value, setValue] = useState<RichTextValue<'json'>>(null)
const [outcome, setOutcome] = useState('')
const standardNote: RichTextValue<'json'> = {
type: 'doc',
content: [
{
type: 'heading',
attrs: { level: 2 },
content: [{ type: 'text', text: texts.noteHeading }],
},
{ type: 'paragraph', content: [{ type: 'text', text: texts.noteBody }] },
],
}
return (
<Stack className="kv-stack--gap-8">
<Field.Root>
<Field.Label>{texts.noteLabel}</Field.Label>
<RichTextEditor.Root
format="json"
value={value}
onValueChange={(next) => {
setValue(next)
setOutcome('')
}}
>
<RichTextEditor.Toolbar />
<RichTextEditor.Content />
</RichTextEditor.Root>
</Field.Root>
<div className="kv-button-group">
<Button
onClick={() => {
setValue(standardNote)
setOutcome(texts.standardNoteInserted)
}}
>
{texts.useStandardNote}
</Button>
<Button className="kv-button--primary" onClick={() => setOutcome(texts.noteSaved)}>
{texts.saveNote}
</Button>
</div>
<output>{outcome}</output>
</Stack>
)
}Props in this example:
formaton RichTextEditor.Rootvalueon RichTextEditor.RootonValueChangeon RichTextEditor.Root
Information: Did you know?
The editor says nothing aloud when your code sets the text. Say what happened in words, as the line under the buttons does. In a staff tool, save drafts and warn before a session ends (2.2.1 Timing Adjustable).
A short toolbar for people who write once
An association describes its event for the municipality’s calendar. A smaller toolbar, with the name of each control beside its icon, is quicker to take in. Pick the controls with include and show the names with labels.
Tell people what happens, when it starts and what they need to bring.
import { Field } from '@kvirn-ui/react'
import { RichTextEditor } from '@kvirn-ui/rich-text'
import { useRichTextEditorTexts } from './texts.ts'
export function SmallToolbar() {
const { texts } = useRichTextEditorTexts()
return (
<Field.Root>
<Field.Label>{texts.eventLabel}</Field.Label>
<Field.Prose>
<p>{texts.eventDescription}</p>
</Field.Prose>
<RichTextEditor.Root name="event" labels="icon-and-text">
<RichTextEditor.Toolbar>
<RichTextEditor.DefaultControls
include={['undo', 'redo', 'bold', 'italic', 'bulletList', 'orderedList', 'link']}
/>
</RichTextEditor.Toolbar>
<RichTextEditor.Content />
</RichTextEditor.Root>
</Field.Root>
)
}Props in this example:
Information: Did you know?
Touch screens have no tooltips, so show the names. A full toolbar wraps onto several rows at a width of 320 pixels, and a short one leaves more room for the text. For one row on a phone, see the compact toolbar below.
One row of controls on a phone
A volunteer at an association writes the event text on a phone, with the on-screen keyboard open. The full toolbar wraps to several rows and leaves little room for the text. CompactControls keeps Bold, Italic and the lists on one row, and puts the rest behind a visible “More”.
Tell people what happens, when it starts and what they need to bring.
import { Field } from '@kvirn-ui/react'
import { RichTextEditor } from '@kvirn-ui/rich-text'
import { useRichTextEditorTexts } from './texts.ts'
export function CompactToolbar() {
const { texts } = useRichTextEditorTexts()
return (
<Field.Root>
<Field.Label>{texts.eventLabel}</Field.Label>
<Field.Prose>
<p>{texts.eventDescription}</p>
</Field.Prose>
<RichTextEditor.Root name="event-compact">
<RichTextEditor.Toolbar>
<RichTextEditor.CompactControls />
</RichTextEditor.Toolbar>
<RichTextEditor.Content />
</RichTextEditor.Root>
</Field.Root>
)
}Information: Did you know?
Every control is still there, in “More”, in the same order as the full toolbar. The button shows a word and not only an icon, because a touch screen has no tooltip. A text field is the simpler choice when formatting is not part of the task.
A text with a limit
A short description is shown in a list, and your form accepts at most 200 characters. The count says so before the user gets there, then how many are left, then how many are over. It counts the text a reader sees, not the HTML.
You can enter up to 200 characters.
This is the text shown in the list of events.
import { Field } from '@kvirn-ui/react'
import { RichTextEditor } from '@kvirn-ui/rich-text'
import { useRichTextEditorTexts } from './texts.ts'
export function CountedSummary() {
const { texts } = useRichTextEditorTexts()
return (
<Field.Root required>
<Field.Label>{texts.summaryLabel}</Field.Label>
<RichTextEditor.Root name="summary" maxLength={200} characterCount>
<RichTextEditor.Toolbar />
<RichTextEditor.Content />
</RichTextEditor.Root>
<Field.HelpText>{texts.summaryHint}</Field.HelpText>
</Field.Root>
)
}Props in this example:
characterCounton RichTextEditor.RootmaxLengthon RichTextEditor.Root
Information: Did you know?
Going over the limit is a warning, not an error: the count never blocks typing, so your form decides on submit. The count is announced politely from 80% of the limit and when it is crossed, and only while the text has focus.
Text and lists only
A service notice has room for text, not for a table or a picture. Turn tables and images off in defaultExtensions, and their buttons and the table group go with them. Keep the array in a constant, because Tiptap reads it once.
import { Field } from '@kvirn-ui/react'
import { defaultExtensions, RichTextEditor } from '@kvirn-ui/rich-text'
import { useRichTextEditorTexts } from './texts.ts'
// Tiptap reads the extensions when it creates the editor, so keep them in a constant.
const textOnly = defaultExtensions({ table: false, image: false })
export function WithoutTablesAndImages() {
const { texts } = useRichTextEditorTexts()
return (
<Field.Root>
<Field.Label>{texts.noticeLabel}</Field.Label>
<RichTextEditor.Root extensions={textOnly} defaultValue={`<p>${texts.noticeIntro}</p>`}>
<RichTextEditor.Toolbar />
<RichTextEditor.Content />
</RichTextEditor.Root>
</Field.Root>
)
}Props in this example:
extensionson RichTextEditor.Roottableon defaultExtensionsimageon defaultExtensions
A button of your own
An editor writes the contact details for a service page, with the address on separate lines. A touch screen usually has no Shift+Enter, so add a group of your own to the toolbar, with a button that runs a Tiptap command. isAvailable says when it can run, and onPress gets Tiptap’s editor.
import { Field } from '@kvirn-ui/react'
import { RichTextEditor } from '@kvirn-ui/rich-text'
import { useRichTextEditorTexts } from './texts.ts'
export function OwnToolbar() {
const { texts } = useRichTextEditorTexts()
return (
<Field.Root>
<Field.Label>{texts.addressLabel}</Field.Label>
<RichTextEditor.Root defaultValue={`<p>${texts.addressLines.join('<br>')}</p>`}>
<RichTextEditor.Toolbar>
<RichTextEditor.DefaultControls />
<RichTextEditor.Group aria-label={texts.lineBreakGroup}>
<RichTextEditor.CommandButton
label={texts.lineBreak}
isAvailable={(editor) => editor.can().setHardBreak()}
onPress={(editor) => {
// No focus(): the keyboard stays on the button, and the command acts at the selection.
editor.chain().setHardBreak().run()
}}
/>
</RichTextEditor.Group>
</RichTextEditor.Toolbar>
<RichTextEditor.Content />
</RichTextEditor.Root>
</Field.Root>
)
}Props in this example:
aria-labelon RichTextEditor.Grouplabelon RichTextEditor.CommandButtonisAvailableon RichTextEditor.CommandButtononPresson RichTextEditor.CommandButton
Warning: Don't forget
Give every control a name, and every group in a toolbar a name too (4.1.2 Name, Role, Value). Without them a screen reader user hears only “button” or “group”.
Accessibility#
What it does for you#
- APG pattern: Toolbar above a multi-line text, with toggle buttons, a select-only Listbox and non-modal dialogs for the link and image forms. The text is a
textboxwitharia-multiline(acontenteditable). There is no APG pattern for a rich text editor. - Deviations: two, both approved. (1) Shortcuts are on by default, limited to the platform's text-editing convention. (2) Tab acts inside the text: it indents a list item and moves between table cells, only where it can, and leaves the editor everywhere else, as in any field. There is no "Escape, then Tab" way out and no instruction under the box: the unmodified Tab always gets out, after as many presses as there are list levels or table cells to pass, and each press moves somewhere (it never stays put), which is what 2.1.2 No Keyboard Trap (A) asks. Escape in the text is consumed the first time (so a Dialog around the editor stays open).
- Native elements used: a
<div contenteditable role="textbox">made by Tiptap (ProseMirror),<button>for every control, a<div role="combobox">for the picker (the Listbox),<div popover role="dialog">for the forms (the Popover),<form>,<input>(TextInput, Checkbox) and<input type="hidden">for the posted value.
A RichTextEditor is the control of a Field: the Field's label names the editable text, and its description, the count, its help text and its error describe it. It adds a formatting toolbar, one Tab stop that a keyboard and screen reader user can operate, and posts its value with the form. Its output is never sanitized: sanitize it on the server.
| Part | Element / role | ARIA | Notes |
|---|---|---|---|
| Root | <div class="kv-rich-text">, no role | none | The box. data-focused, data-focus-visible, data-invalid, data-required, data-disabled, data-readonly, data-empty. It renders the count and a hidden <input type="hidden" name> after the box. The hidden input follows the value and a form reset, and is disabled while the editor is |
| Content (the editable) | <div contenteditable> → textbox | aria-multiline="true", aria-labelledby (the Field's label id), aria-describedby, aria-invalid, aria-required, aria-disabled, aria-readonly, id | Named by the Field's label: a <label for> can't name a <div>, so a click on the label focuses the text (the Root does it). Outside a Field give RichTextEditor.Content an aria-label or aria-labelledby (a warning in development without a name; 4.1.2 Name, Role, Value, A). Class kv-rich-text-content kv-prose. No dir of its own: the direction is the page's. No placeholder. Read-only: contenteditable="false" with tabindex="0". Disabled: contenteditable="false", no tabindex. Test: rich-text-editor.test.tsx |
| Toolbar | Toolbar.Root → toolbar | aria-labelledby (a visually hidden "Formatting", then the Field's label id) or aria-label outside a Field, aria-controls (the text's id), aria-keyshortcuts="Alt+F10" | "Formatting News text", so two editors on a page have different toolbars. Not rendered while read-only. The popovers' slot is a sibling after it, not inside it |
| Group | Toolbar.Group → group | aria-label | Undo and redo, Text style, Lists, Insert, and the Table group. A group in a toolbar needs a name |
| CommandButton | Toolbar.Button → button | aria-label (icon-only) or visible text, aria-keyshortcuts (Control+Z, or Meta+Z on macOS), aria-disabled="true" when unavailable | Undo, Redo, Increase indent, Decrease indent, Table, Clear formatting, the Table group. Unavailable controls stay focusable. A pointer press keeps focus in the text |
| CommandToggle | Toolbar.Toggle → button | aria-pressed, aria-label or visible text, aria-keyshortcuts, aria-disabled="true" when unavailable | Bold, Italic, Underline, Strikethrough, Code, Bulleted list, Numbered list, Header row. The name never changes with the state. In labels="icon-and-text" the visible name is the accessible name (2.5.3 Label in Name, A) |
| BlockFormat | Listbox.Trigger as a Toolbar.Item → combobox | aria-label ("Text type"), aria-expanded, aria-controls, aria-haspopup="listbox" | A Listbox with native="never". Its value is the block at the caret ("Normal text", "Heading 2"), or "Several types" over a mixed selection. Options: Normal text, the configured heading levels (2 to 6 by default, each with a decorative aria-hidden icon that is not part of the name), Quote, Code block. It takes no Field state (it is not the Field's control) |
| CompactControls | Toolbar.Item + Menu.Trigger → button ("More"), and a Menu.Popup → menu | aria-haspopup="menu", aria-expanded, aria-controls, name = its visible text; the menu is named by the button; groups group named by their label; Underline, Strikethrough, Code and Header row menuitemcheckbox with aria-checked; text types menuitemradio in a named group (heading items carry a decorative aria-hidden icon that is not part of the name); Add link and Add image menuitem with aria-haspopup="dialog"; unavailable items aria-disabled="true" and focusable; aria-keyshortcuts | Opt-in preset (RichTextEditor.CompactControls): Bold, Italic and the lists on the bar, everything else once in "More", in the default order. The split is fixed, so the arrows reach the same controls at every width. One left-over command stays on the bar with no "More"; none, no "More". Natively disabled with the editor. |
| LinkControl | Toolbar.Item + Popover.Trigger → button | aria-label, aria-keyshortcuts="Control+K", aria-haspopup="dialog", aria-expanded, aria-controls | Opens the link form. Not aria-pressed: it is a popup button, and the form's title ("Edit link") says it is on a link |
| ImageControl | Toolbar.Item + Popover.Trigger → button | as LinkControl | Opens the image form |
| Popover.Popup | <div popover> → dialog, in the slot after the toolbar | aria-labelledby (its title, a <p>, not a heading: the form adds nothing to the heading outline) | Non-modal. Holds a <form>, two or three Fields, and a ButtonGroup. Rendered only while open (the title stays). It is outside the toolbar's React tree for item registration (Popover.Popup provides no toolbar context) |
| CharacterCount | <p class="kv-field-help-text kv-character-count"> (the shared part) | in the editable's aria-describedby | Counts the text the user can read, one line break between blocks. Announced politely from 80% and when crossed, only while the editor has focus. Never blocks typing |
| Output (in the text) | h2–h6, ul, ol, blockquote, pre code, strong, em, u, s, code, a href, img alt, table with th | – | The HTML elements, so the structure is read by assistive technology and published as it is. An image can't be added without alt (empty only by the decorative choice; 1.1.1 Non-text Content, A) |
Message keys (the richText namespace, all five locales): toolbar, groupHistory, groupTextStyle, groupLists, groupInsert, groupTable, more, undo, redo, blockType, blockParagraph, blockHeading2, blockHeading3, blockHeading4, blockHeading5, blockHeading6, blockQuote, blockCode, blockMixed, bold, italic, underline, strike, code, bulletList, orderedList, indent, outdent, link, image, table, insertTable, clearFormatting, addRowAbove, addRowBelow, addColumnLeft, addColumnRight, deleteRow, deleteColumn, deleteTable, headerRow, linkAddTitle, linkEditTitle, linkUrl, linkUrlHint, linkText, linkTextHint, linkAdd, save, linkRemove, cancel, linkUrlMissing, linkUrlInvalid, linkTextMissing, imageAddTitle, imageEditTitle, imageUrl, imageUrlHint, imageAlt, imageAltHint, imageDecorative, imageDecorativeHint, imageAdd, imageRemove, imageUrlMissing, imageUrlInvalid, imageUrlNotAllowed, imageAltMissing, linkAdded, linkUpdated, linkRemoved, imageAdded, imageUpdated, imageRemoved, tableInserted, rowAdded, columnAdded, rowDeleted, columnDeleted, tableDeleted, listLevel, formattingCleared, undone, redone, formatOn, formatOff, imagePasteNotSupported, imageSourceNotAllowed. The count's keys are characterCount.*. Override per Root with messages (and countMessages), or per provider.
What you need to do#
- Put the editor in a Field with a
Field.Label(or giveRichTextEditor.Contentanaria-label). Give the Field's error text that names the fix. - Sanitize the output on the server. Tiptap's schema drops unknown tags and attributes, but that is not a security boundary, and the docs never call the output safe. The stored HTML can carry a pasted
targeton a link: striptarget. - Limit image origins with
imageSources(this site's own and relative addresses by default). An image from another server is fetched by every reader's browser (GDPR). - Offer a smaller toolbar to residents (
DefaultControls include=[…],labels="icon-and-text"): touch screens have no tooltips, and a wrapped full toolbar takes much of a 320px screen. - Keep the extensions array stable between renders (a constant or
useMemo), and install Tiptap's peers once (one copy of ProseMirror). - Save drafts in staff tools: a long text is the worst thing to lose to a session timeout (2.2.1 Timing Adjustable, A).
- Keep heading levels in order. The picker offers Heading 2 to 6. Tell authors not to skip levels (1.3.1 Info and Relationships, A; 2.4.6 Headings and Labels, AA).
- Mark other-language passages where the text is shown. The editor can't mark a passage in another language (3.1.2 Language of Parts, AA), so a mixed-language text is read in the page language. Keep other-language passages out of the editor, or mark them where the text is shown.
- To show saved text, render it as
Prose, not a read-only editor. - Lazy-load the package (
React.lazy): it is about 140 KB gzipped with ProseMirror.
Warning: Don't forget
Put the editor in a Field with a label, or give RichTextEditor.Content an aria-label. Without a name a screen reader user hears only that there is a text box (4.1.2 Name, Role, Value).
Visual and modes#
- Focus indicator: a 2px ring around the whole box when the text has keyboard focus, and on the focused button only when the toolbar has it, 2px offset (2.4.7 Focus Visible, AA; 2.4.13 Focus Appearance, AAA, is not counted toward AA). Any focus inside gives the box a 2px focus-coloured edge. A click in the text shows only the edge, as for text inputs. An invalid editor shows the ring on any focus in the text, keeping its
dangeredge. - Target size: every control is at least 24 × 24 CSS px, 44px by default and 32px in
kv-compacton wide screens (2.5.8 Target Size (Minimum), AA). - forced-colors behaviour: the box keeps an edge in the system's button-border colour, a pressed toggle is filled with the system's highlight colour, flat buttons keep an edge in the system's button-text colour, the gap cursor uses the system's text colour, and the selected image and cells use the system's highlight colour. The forced-colours sweep checks the boundaries and the focus ring.
- reduced-motion behaviour: fills and the popover change over short transitions, which are removed under reduced motion. The gap cursor stops blinking under
reduce. Nothing moves the layout: no slide for the Table group, no animated height. - Reflow: the toolbar wraps group by group in both label modes, a group of word buttons (the attached toolbar) also wraps inside itself, and icon-only groups stay one strip, the popover fits the viewport, and long words in the text wrap. Only a wide table scrolls, inside its own wrapper. The reflow sweep checks every story at 320 CSS pixels for horizontal overflow; the toolbar wrapping group by group is checked by eye.
- Right to left: logical properties only, the toolbar arrows flip, and the column buttons are named by what the user sees. The text direction is the page's (the provider's
dir, set on the page withuseLocale().localeProps): the editor has nodirprop and its blocks carry nodirattribute. - Tiptap injects its own small
<style>of ProseMirror's structural rules (injectCSS). The theme overrides the gap cursor.
Focus management#
- Initial focus: not moved. The first Tab enters the toolbar, then the text.
- Trap: no. Tab and Shift+Tab leave everywhere, after nesting or moving between cells where they can. Alt+F10 and Escape move between the toolbar and the text.
- After a toolbar command from the keyboard focus stays on the control, as APG's toolbar does, so several formats can be set in a row. A pointer press doesn't take focus from the text (the control prevents focus on
mousedown), so the caret and selection stay. - The picker and the popovers return focus to the text, at the selection, when they close with a choice, Cancel or Escape. A press outside a popover leaves focus where the user pressed.
- The compact toolbar's "More" menu: a command from the keyboard returns focus to "More" (as a bar button keeps it), a text type returns to the text (as the picker), Link and Image put it in the form's first field, Insert table in the new first cell, and Escape closes the menu onto "More". A pointer press on any item returns focus to the text at the selection, so stored formats survive and the on-screen keyboard stays. The toolbar's Escape handler ignores keys from inside the menu, so the first Escape closes the menu. The one exception: Delete table from the menu ends in the text, not on "More", because the Table group leaves the menu with the last table.
- Focus never lands on
body: when the focused Table group button goes with the group, focus goes to the text first. - Restore to: the text at the selection (Link, Image, the picker), the toolbar (nothing).
- Never obscured by: the toolbar is not sticky. A popover or tooltip is placed so it doesn't cover its trigger (2.4.11 Focus Not Obscured (Minimum), AA). The selection stays visible while focus is in the toolbar (the browser's inactive selection).
WCAG success criteria#
- 1.1.1 Non-text Content (A): an image needs a description or the decorative choice.
- 1.3.1 Info and Relationships (A): semantic output, named groups.
- 1.3.2 Meaningful Sequence (A).
- 1.4.1 Use of Color (A) and 1.4.11 Non-text Contrast (AA): a pressed toggle is a filled tile.
- 1.4.3 Contrast (Minimum) (AA).
- 1.4.10 Reflow (AA).
- 1.4.12 Text Spacing (AA).
- 1.4.13 Content on Hover or Focus (AA): the tooltips.
- 2.1.1 Keyboard (A).
- 2.1.2 No Keyboard Trap (A): Tab acts only where it can and leaves everywhere else, so the unmodified Tab and Shift+Tab always get out.
- 2.1.4 Character Key Shortcuts (A): modifier chords only, no single-key shortcut, typing rules off.
- 2.4.3 Focus Order (A), 2.4.4 Link Purpose (In Context) (A) (the help text for the link text), 2.4.7 Focus Visible (AA), 2.4.11 Focus Not Obscured (Minimum) (AA). 2.4.13 Focus Appearance (AAA) is not counted toward AA.
- 2.5.3 Label in Name (A), 2.5.8 Target Size (Minimum) (AA).
- 3.2.1 On Focus (A) and 3.2.2 On Input (A): the Table group changes only on the user's own action.
- 3.3.1 Error Identification (A): a refused pasted or dropped image is announced. 3.3.2 Labels or Instructions (A). 3.3.8 Accessible Authentication (Minimum) (AA): paste is allowed, and the count never blocks.
- 4.1.2 Name, Role, Value (A), 4.1.3 Status Messages (AA).
Keyboard#
- Focus
- roving tabindex
- Selection follows focus
- n/a
- Arrows wrap
- yes
- Shortcuts
- on by default, the platform's text-editing convention only (Control or Command with B, I, U, K, Z, Shift+Z, and Control+Y), plus Alt+F10 (Option+F10 on macOS) to the toolbar
The toolbar uses a roving tabindex and its arrows wrap (see the Toolbar page). The text is native: arrows, Home, End, PageUp, PageDown, Shift with them, Enter (a new paragraph, a new list item, and on an empty item the end of the list) and Shift+Enter (a line break) are the browser's and Tiptap's, and are never bound. Mod is Control on Windows and Linux, and Command on macOS. Never shortcuts: Control+Alt chords (AltGr on Windows: @ £ $ € { [ ] } \ on Swedish, Finnish and Norwegian layouts) and Command+Option, Control+E, Control+Shift+S, Control+Shift+B, Control+Shift+7 and 8 (Tiptap's defaults that clash with browsers and Nordic keyboards), and nothing uses Caps Lock, Insert, Scroll Lock or Control+Option on macOS. Every shortcut has a toolbar button.
| Key | Where | What happens |
|---|---|---|
| Tab | before the editor | Moves focus to the toolbar's remembered control (the first, the first time). The control's tooltip shows Test: rich-text-toolbar.test.tsx › Tab goes to the toolbar (one stop), then the text, then the next field; Shift+Tab goes back |
| Tab | on the toolbar | Moves focus to the text. The caret and the selection are where they were Test: rich-text-toolbar.test.tsx › Tab goes to the toolbar (one stop), then the text, then the next field; Shift+Tab goes back |
| Shift+Tab | on the toolbar | Moves focus to the previous focusable element before the editor Test: rich-text-toolbar.test.tsx › Tab goes to the toolbar (one stop), then the text, then the next field; Shift+Tab goes back |
| Escape | on the toolbar, a tooltip open | Hides the tooltip. Focus stays Test: rich-text-toolbar.test.tsx › Escape on the toolbar hides an open tooltip first, then goes back to the text at the selection |
| Escape | on the toolbar, nothing open | Moves focus to the text, at the selection. A control whose popup is open (the picker) closes it first Test: rich-text-toolbar.test.tsx › Escape on the toolbar hides an open tooltip first, then goes back to the text at the selection |
| Tab / Shift+Tab | in the text, outside lists and tables | Tab moves focus to the next focusable element after the editor, and Shift+Tab to the toolbar's remembered control. Tab at the start of a paragraph after a list pulls nothing into the list Test: kvirn-keymap.test.tsx › Tab leaves forwards, and Shift+Tab leaves backwards, kvirn-keymap.test.tsx › Tab at the start of a paragraph after a list leaves, and pulls nothing into the list |
| Tab | in a list item with an item above it at its level | Nests the item. Focus stays in the text. The new level is announced ("Level 2") Test: kvirn-keymap.test.tsx › Tab nests an item that has an item above it, and focus stays in the text |
| Tab | on the first item of a list | Moves focus to the next focusable element after the editor. Nothing is nested Test: kvirn-keymap.test.tsx › Tab on the first item of a list leaves the editor, and nests nothing |
| Shift+Tab | in a nested list item | Outdents it one level. Focus stays. The level is announced ("Level 1") Test: kvirn-keymap.test.tsx › Shift+Tab outdents a nested item one level, and focus stays in the text |
| Shift+Tab | in a top-level list item | Moves focus to the toolbar. It never lifts the item out of its list Test: kvirn-keymap.test.tsx › Shift+Tab in a top-level item leaves backwards, and never lifts it out of its list |
| Tab | in a table cell, not the last | Moves to the next cell, row by row, and selects its text Test: kvirn-keymap.test.tsx › Tab moves to the next cell and selects its text, focus staying in the text |
| Tab | in the last table cell | Moves focus to the next focusable element after the editor. It never adds a row Test: kvirn-keymap.test.tsx › Tab in the last cell leaves the editor, and never adds a row |
| Shift+Tab | in a table cell, not the first | Moves to the previous cell and selects its text Test: kvirn-keymap.test.tsx › Shift+Tab moves to the previous cell |
| Shift+Tab | in the first table cell | Moves focus to the toolbar Test: kvirn-keymap.test.tsx › Shift+Tab in the first cell leaves backwards |
| Escape | in the text | The first Escape is not passed on, so a Dialog around the editor stays open and the text is kept. The next Escape is passed on, so the Dialog closes. Escape during an IME composition is the IME's Test: kvirn-keymap.test.tsx › the first Escape is not passed on, so a Dialog around the editor stays open; a second one is |
| Alt+F10 (Option+F10 on macOS) | in the text | Moves focus to the toolbar's remembered control Test: rich-text-toolbar.test.tsx › Alt+F10 in the text moves to the toolbar’s remembered control |
| Enter / Shift+Enter | in the text | Enter: a new paragraph (in a list, a new item; on an empty item, the end of the list). Shift+Enter: a line break in the same paragraph Test: kvirn-keymap.test.tsx › Enter starts a new paragraph and Shift+Enter a line break |
| Control/Command+B / Control/Command+I / Control/Command+U | in the text | Bold, italic, underline on or off. Announces "Bold on" or "Bold off" Test: kvirn-keymap.test.tsx › Mod-b, Mod-i and Mod-u toggle bold, italic and underline, and report whether each is on |
| Control/Command+K | in the text | Opens the link form with focus in "Web address" Test: link-image-forms.test.tsx › Mod-k opens it from the text, with focus in "Webbadress" |
| Control/Command+Z; Control/Command+Shift+Z, Control+Y | in the text | Undo; redo Test: kvirn-keymap.test.tsx › Mod-z undoes, and Mod-Shift-z and Ctrl-y redo |
| Control+Alt + a key (AltGr) | in the text, Windows, sv, fi, nb, nn layouts | Types the character (@ £ $ € { [ ] } \). Never a shortcut, and never cancelledTest: kvirn-keymap.test.tsx › Control+Alt with %s is typed as text: the keydown is not handled or cancelled |
| Control+Shift+S, Control+E, Control+Shift+B, Control+Shift+7 / Control+Shift+8, Control+Alt+1 to 6 and C | in the text | Do nothing to the text: the removed Tiptap defaults Test: kvirn-keymap.test.tsx › %s does nothing to the text |
| ArrowRight / ArrowLeft | on the toolbar | Next and previous control, across groups and rows, wrapping. Flip in right-to-left text Test: rich-text-toolbar.test.tsx › the arrows wrap, and Home and End go to the ends, rich-text-toolbar.test.tsx › right to left: the toolbar arrows flip |
| Home / End | on the toolbar | First and last control Test: rich-text-toolbar.test.tsx › the arrows wrap, and Home and End go to the ends |
| ArrowDown, ArrowUp, Enter, Space, characters | on the picker | The Listbox's keys (see the Listbox page): ArrowDown opens, ArrowDown moves, Enter chooses and closes. Focus then goes back to the text. A closed picker leaves ArrowLeft and ArrowRight to the toolbar Test: rich-text-toolbar.test.tsx › the picker opens with ArrowDown, Enter chooses, and focus goes back to the text |
| Enter / Space | on Increase indent or Decrease indent | Nests or outdents the item at the caret, as Tab and Shift+Tab do, announcing the level. Focus stays on the button. Unavailable (aria-disabled) where they can't actTest: rich-text-toolbar.test.tsx › Enter on Öka indrag nests the item and focus stays on the button |
| Enter / Space | on Link or Image | Opens the popover and moves focus to its first field Test: link-image-forms.test.tsx › Enter on Länk opens the form with focus in its first field |
| Enter | in a popover field | Submits the form: the link or image is added, and focus goes back to the text. A form with an error stays open, with focus on the first invalid field Test: link-image-forms.test.tsx › adds the link to the selected text, announces it, closes, and puts focus back in the text, link-image-forms.test.tsx › %s is refused with an inline error, and the popover stays open with focus in the field |
| Escape | in a popover | Closes it without changes. Focus goes back to the text, at the selection Test: link-image-forms.test.tsx › Escape closes it without changes, and puts focus back in the text |
| Enter / Space | on Table | Inserts a 3 by 3 table with a header row and moves focus into its first cell. Announced Test: rich-text-toolbar.test.tsx › Enter on Tabell inserts a table and moves focus into it |
| Enter / Space | on a Table group button | Does it, and announces it. "Delete table" moves focus to the text where the table was, and the group goes with the last table Test: rich-text-toolbar.test.tsx › Table group buttons work with Enter, and Ta bort tabellen moves focus to the text |
| ArrowRight / ArrowLeft, End | in the compact toolbar | "More" is the last control: the arrows reach it and wrap, and they flip in right-to-left text Test: rich-text-toolbar.test.tsx › the compact toolbar › "More" is the last toolbar item, reached by ArrowRight and End, and the arrows wrap, rich-text-toolbar.test.tsx › the compact toolbar › right to left: ArrowLeft goes from Numbered list to "More" |
| Enter / Space / ArrowDown, ArrowUp | on "More" | Opens the menu: focus on its first item, and on its last with ArrowUp Test: rich-text-toolbar.test.tsx › the compact toolbar › Enter, Space and ArrowDown on "More" open the menu on its first item, and ArrowUp on its last |
| ArrowDown / ArrowUp, Home / End, a character | in the "More" menu | The Menu's keys: move, wrap, ends, typeahead Test: rich-text-toolbar.test.tsx › the compact toolbar › ArrowDown, ArrowUp, Home, End and typeahead move in the "More" menu |
| Enter / Space | on a command item in the menu | Runs it, closes the menu, focus on "More", announced as its bar button is Test: rich-text-toolbar.test.tsx › the compact toolbar › Enter on a command item runs it, closes the menu, keeps focus on "More", and announces it and rich-text-toolbar.test.tsx › the compact toolbar › Space on a menu item runs it as Enter does |
| Enter / Space | on Underline, Strikethrough, Code or Header row in the menu | Toggles the format, closes the menu, focus on "More", announces "<name> on" or "off" in the locale's words Test: rich-text-toolbar.test.tsx › the compact toolbar › Enter on Underline toggles it, closes the menu and announces "Understrykning på" and rich-text-toolbar.test.tsx › the compact toolbar › Space on a menu item runs it as Enter does |
| Enter / Space | on a text type in the menu | Applies it, closes the menu, focus goes back in the text Test: rich-text-toolbar.test.tsx › the compact toolbar › choosing a text type in the menu applies it and puts focus back in the text |
| Enter / Space | on an unavailable item in the menu | Nothing runs and the menu stays open: the item is focusable and read as unavailable Test: rich-text-toolbar.test.tsx › the compact toolbar › an unavailable item is focusable, read as unavailable, and Enter does nothing |
| Enter / Space | on Add link or Add image in the menu | Closes the menu and opens the form under "More", focus in its first field. Escape or Cancel puts focus in the text Test: rich-text-toolbar.test.tsx › the compact toolbar › "Add link" in the menu opens the link form with focus in "Web address", and Escape puts focus in the text |
| Enter / Space | on Insert table in the menu | Inserts the table, focus in its first cell. The Table group is then in the menu Test: rich-text-toolbar.test.tsx › the compact toolbar › "Insert table" moves focus into the new table, and the Table group is in the menu, unavailable outside a table |
| Escape | in the "More" menu | Closes it, focus on "More", nothing runs. A second Escape goes to the text Test: rich-text-toolbar.test.tsx › the compact toolbar › Escape in the menu closes it and focus goes to "More"; a second Escape goes to the text |
| Tab / Shift+Tab | in the "More" menu | Tab closes the menu and moves on to the text. Shift+Tab closes it, focus on "More" Test: rich-text-toolbar.test.tsx › the compact toolbar › Tab in the menu closes it and moves to the text; Shift+Tab closes it onto "More" |
| Control/Command+K | in the text, compact toolbar | Opens the link form under "More", focus in "Web address" Test: rich-text-toolbar.test.tsx › the compact toolbar › Mod-k opens the link form in the compact toolbar too |
The way out (2.1.2 No Keyboard Trap, A). Tab in the text acts only where it can (a list item that can be nested, a table cell that isn't the last), so everywhere else it moves focus as usual, and where it acts, the next Tab or Shift+Tab does so again until it can't: nesting and cell moves are finite, so the unmodified Tab and Shift+Tab always leave the editor, and no instruction is needed. Alt+F10 goes to the toolbar from anywhere in the text.
How it is built. The keys are decided in one ProseMirror plugin's handleDOMEvents.keydown, ahead of every Tiptap keymap: a handler there makes ProseMirror skip its own key handling, so no other Tab binding acts behind a "leave" and no event is stopped from propagating (except the first Escape). KvirnKeymap is part of defaultExtensions().
Information: Did you know?
You don’t need to teach a way out of the editor. In a list or a table, Tab nests an item or moves to the next cell, only where that is possible. Everywhere else it leaves the editor, so pressing it again always gets out (2.1.2 No Keyboard Trap, level A).
Announcements#
RichTextEditor tells screen reader users about these changes without moving focus. Each message waits until the screen reader is quiet (polite) or interrupts it (assertive).
| When | What it says | Message key | Politeness |
|---|---|---|---|
| Control/Command+B, I or U in the text | richText.formatOn richText.formatOff | Polite | |
| A list item nested or outdented (Tab, Shift+Tab or the buttons) | richText.listLevel | Polite | |
| Link added, changed or removed | richText.linkAdded linkUpdated linkRemoved | Polite | |
| Image added, changed or removed | richText.imageAdded imageUpdated imageRemoved | Polite | |
| A table inserted (focus moves into it) | richText.tableInserted | Polite | |
| Row or column added or deleted | richText.rowAdded columnAdded rowDeleted columnDeleted | Polite | |
| Table deleted, with how to undo | richText.tableDeleted | Polite | |
An image file, or an image from outside imageSources, pasted or dropped and left out | richText.imagePasteNotSupported data: richText.imageSourceNotAllowed | Polite | |
| Underline, Strikethrough, Code or Header row chosen in the compact toolbar's menu (the control that showed its state has gone) | richText.formatOn richText.formatOff | Polite | |
| Formatting cleared | richText.formattingCleared | Polite | |
| Undo or redo from the buttons (the shortcut is the browser's own) | richText.undone richText.redone | Polite | |
| The count, from 80% of the limit and when crossed, only while focused | characterCount.remaining characterCount.over | Polite |
The text in all five languages
Change the text#
For your whole app, pass messages to KvirnProvider. For one RichTextEditor, pass its messages prop.
<KvirnProvider messages={{ richText: { formatOn: '…' } }}>Warning: Don't forget
Announcements need a KvirnProvider around your app, outside any <form>, or an Announcer of your own. Without one nothing is announced, and a development warning says so.
What a screen reader reads#
| State or action | Read aloud | Politeness | Test |
|---|---|---|---|
| "More" collapsed | button, Mer, 1 control, not expanded, has popup menu (Mer: More) | none | rich-text-toolbar.test.tsx › the compact toolbar › read aloud: "More" is a collapsed menu button, then an expanded one with the menu, its groups and their states |
| "More" expanded, the menu and its groups | button, Mer, … expanded, has popup menu, menu, Mer, orientated vertically, group, Texttyp, group, Textstil: each group named once (Mer: More, Texttyp: Text type, Textstil: Text style) | none | same test, and the text types are one group named "Texttyp" once, with no dangling label and no warning |
| Radio and checkbox items | menuitemradio, Vanlig text, checked, position 1, set size 8, menuitemradio, Rubrik 5, not checked, position 5, set size 8, option, Rubrik 5, not selected, position 5, set size 8 (the picker's heading option, named by its label alone), menuitemcheckbox, Understrykning, checked, key shortcuts Control+U, … (Vanlig text: Normal text, Understrykning: Underline) | none | same read aloud test; the option phrase: the block type picker › read aloud: a heading option is named by its label alone, with its position in the list |
| An unavailable item, and a form item | menuitem, Ångra, disabled, key shortcuts Control+Z, …, menuitem, Lägg till länk, has popup dialog, … (Ångra: Undo, Lägg till länk: Add link) | none | same read aloud test |
| Underline on, by key or pointer | polite: Understrykning på (Underline on), once | polite | read aloud: Underline on from the keyboard is "Understrykning på", once, a pointer press on Underline announces "Understrykning på" |
| Underline off | polite: Understrykning av (Underline off) | polite | Underline off is announced "Understrykning av" |
| An image pasted or dropped and refused | polite: Bilder kan inte klistras in. Använd knappen Bild. (in English: Images can't be pasted. Use the Image button.), or the address message, once per paste | polite | rich-text-editor.test.tsx › a refused pasted or dropped image › a refused pasted image is read aloud as a polite status, and the text stays a textbox, one paste with several images is announced once |
API reference#
The package needs Tiptap, which it is built on. Install both, once, so your app has one copy of ProseMirror (the library under Tiptap).
pnpm add @kvirn-ui/rich-text
pnpm add @tiptap/core @tiptap/pm @tiptap/react @tiptap/starter-kit @tiptap/extension-table @tiptap/extension-image @tiptap/extensionsimport { RichTextEditor, defaultExtensions, useRichTextEditor } from '@kvirn-ui/rich-text'RichTextEditor.Root
Renders <div class="kv-rich-text">, the box around the toolbar and the text, then the character count and a hidden <input> that sends the value under name. It creates the Tiptap editor and wires it to its Field. It takes every attribute of a <div>. Also exported as RichTextEditorRoot. The default theme is described on Theming.
| Prop | Type | Default | Description |
|---|---|---|---|
extensions | Extensions | defaultExtensions() | The Tiptap extensions, as an array. Keep it the same array between renders (a constant, or useMemo): Tiptap reads it when it creates the editor. |
format | 'html' | 'json' | 'html' | The format of the value. HTML is a string, and an empty text is an empty string. JSON is Tiptap’s document, and an empty text is null. |
value | string | JSONContent | null | – | The value, when your own state holds it. The first value is the starting text. A later one that is not what the editor holds replaces the text. Typing never moves the caret. |
defaultValue | string | JSONContent | null | – | The starting text when the editor holds the value itself. A form reset goes back to it. |
onValueChange | (value, details) => void | – | Called after each change to the text, with the new value and details: editor, transaction, isEmpty, and with characterCount also length, limit and isOverLimit. It only reports. |
name | string | – | The name a form sends the value under, through a hidden input. The input follows a form reset and is disabled while the editor is. |
editable | boolean | true | false makes the text read-only, like readOnly. |
disabled | boolean | false | The text is not editable, not focusable and not sent. A disabled Field disables the editor too. |
readOnly | boolean | false | The text can be focused, selected and copied, but not changed. The toolbar is not rendered. |
maxLength | number | – | The limit the character count counts against. It never blocks typing, and it renders nothing without characterCount. |
characterCount | boolean | false | Shows a count under the box, against maxLength. It counts the text a reader sees, with one line break between blocks. Without maxLength a development warning says so. |
countCharacters | (value: string) => number | – | Counts the text your own way, for example the way your server counts it. |
messages | Partial<KvirnMessages['richText']> | – | Per-instance override of the toolbar, the forms and the announcements. |
editorOptions | Partial<EditorOptions> | – | The rest of Tiptap’s own options for the editor, for example injectCSS. The hook owns extensions, content and editable. |
labels | 'icon' | 'icon-and-text' | 'icon' | How the toolbar’s controls show their names. icon shows only the icon, with a tooltip. icon-and-text shows each name beside its icon, which suits small resident-facing editors and touch screens. A Toolbar can set its own. |
tooltips | boolean | true | Whether icon-only controls get a tooltip with their name and shortcut. Without tooltips the names are not visible, and a development warning says so. A Toolbar can set its own. |
countMessages | Partial<KvirnMessages['characterCount']> | – | Per-instance override of the count’s texts, with characterCount. |
ref | Ref<HTMLDivElement> | – | Reaches the box. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-rich-text | always | The part class. The default theme styles it. |
data-empty | present or absent | There is nothing to read. |
data-focused | present or absent | The editable text has focus, however it got it. |
data-focus-visible | present or absent | The text has focus from the keyboard. A click does not set it, except in an invalid editor. |
data-invalid | present or absent | The Field is invalid. |
data-required | present or absent | The Field is required. |
data-disabled | present or absent | The Field or the disabled prop disables the editor. |
data-readonly | present or absent | readOnly, or editable set to false. |
RichTextEditor.Toolbar
Renders A toolbar (the Toolbar) attached to the top of the box, with one Tab stop and the arrow keys between its controls. With the default controls it wraps group by group on a narrow screen. A group of word buttons also wraps inside itself, and a group of icon-only buttons stays in one strip. With CompactControls it stays one row. It is not rendered while the editor is read-only. It also takes the props of Toolbar.Root. Also exported as RichTextEditorToolbar.
| Prop | Type | Default | Description |
|---|---|---|---|
labels | 'icon' | 'icon-and-text' | the Root’s labels | How this toolbar’s controls show their names, instead of the Root’s setting. |
tooltips | boolean | the Root’s tooltips | Whether this toolbar’s icon-only controls get a tooltip, instead of the Root’s. |
aria-label | string | the message richText.toolbar, then the Field’s label | The toolbar’s own name. It replaces the default name, so give one that tells two editors on a page apart. |
aria-labelledby | string | – | The toolbar’s name from other elements. It replaces the default name. |
children | ReactNode | <RichTextEditor.DefaultControls /> | Your own groups and controls, or <RichTextEditor.CompactControls /> for one row on a phone. Without any, the toolbar holds the default ones. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-toolbar kv-toolbar--attached | always | The part classes. The toolbar joins the top of the box. |
kv-toolbar--labels | with labels="icon-and-text" | Each control shows its name beside its icon. |
kv-rich-text-toolbar-name | in a Field | The visually hidden first part of the toolbar’s name. |
kv-rich-text-more | on the "More" button of CompactControls | The part class of the menu button, next to kv-button. The menu is the Menu’s own. |
kv-rich-text-popups | always, after the toolbar | The place the link and image forms open in, next to the toolbar. |
aria-controls, aria-keyshortcuts | the text’s id, Alt+F10 | Set for you. They point at the editable text and name the key that reaches the bar. |
RichTextEditor.DefaultControls
Renders The default groups, in this order: undo and redo, the text type, text style, lists, link, image and table, clear formatting, and the table group while the text has a table. A control the extensions don’t provide is left out.
| Prop | Type | Default | Description |
|---|---|---|---|
include | readonly DefaultControlName[] | all of them | Only these controls: undo, redo, blockFormat, bold, italic, underline, strike, code, bulletList, orderedList, indent, outdent, link, image, table, clearFormatting, tableControls. A control the extensions don’t provide is left out anyway. |
exclude | readonly DefaultControlName[] | – | All of them except these. The names are the same as for include. |
RichTextEditor.CompactControls
Renders The same controls on one row, for a phone. Bold, Italic, Bulleted list and Numbered list stay on the bar, followed by a "More" menu button that holds every other control once, in the default order: Underline, Strikethrough and Code as checkboxes, the text types as a choice of one, Link and Image opening their forms under the button. The split is fixed, so the arrow keys reach the same controls at every width. With one control left over it stays on the bar, and with none there is no menu.
| Prop | Type | Default | Description |
|---|---|---|---|
include | readonly DefaultControlName[] | all of them | Only these controls: undo, redo, blockFormat, bold, italic, underline, strike, code, bulletList, orderedList, indent, outdent, link, image, table, clearFormatting, tableControls. A control the extensions don’t provide is left out anyway. |
exclude | readonly DefaultControlName[] | – | All of them except these. The names are the same as for include. |
RichTextEditor.Group
Renders A role="group" of controls (a ButtonGroup). Also exported as RichTextEditorGroup.
| Prop | Type | Default | Description |
|---|---|---|---|
aria-label | string | – | The group’s name, from your translations. Give this or aria-labelledby: a group in a toolbar needs a name. |
aria-labelledby | string | – | The group’s name from another element. |
RichTextEditor.CommandButton
Renders A <button> that runs a command with Tiptap’s editor. It has a tooltip when it shows only an icon. It also takes the props of Toolbar.Button.
| Prop | Type | Default | Description |
|---|---|---|---|
label | string | Required | The control’s name, from your translations. With labels="icon" it is the accessible name and the first line of the tooltip. With labels="icon-and-text" it is the visible text. A control with no icon always shows it as text. |
icon | ReactNode | – | The icon, such as <RichTextEditor.Icon name="bold" /> or one of your own. It is decoration: the label names the control. |
shortcut | readonly string[] | – | The shortcut, written as Tiptap writes it: ["Mod-b"]. Mod is Command on macOS and Control elsewhere. It sets aria-keyshortcuts and is shown in the tooltip. It does not bind the key: do that in your extension. |
isAvailable | (editor: Editor) => boolean | always | Whether the command can run now. When it can’t, the control is aria-disabled, still focusable, and pressing it does nothing. |
onPress | (editor: Editor) => void | Required | Runs the command with the Tiptap editor. After a keyboard press focus stays on the control, so several formats can be set in a row. |
RichTextEditor.CommandToggle
Renders A <button> with aria-pressed that turns a format on or off. It also takes the props of Toolbar.Toggle, except the ones that hold its state.
| Prop | Type | Default | Description |
|---|---|---|---|
label | string | Required | The control’s name, from your translations. With labels="icon" it is the accessible name and the first line of the tooltip. With labels="icon-and-text" it is the visible text. A control with no icon always shows it as text. |
icon | ReactNode | – | The icon, such as <RichTextEditor.Icon name="bold" /> or one of your own. It is decoration: the label names the control. |
shortcut | readonly string[] | – | The shortcut, written as Tiptap writes it: ["Mod-b"]. Mod is Command on macOS and Control elsewhere. It sets aria-keyshortcuts and is shown in the tooltip. It does not bind the key: do that in your extension. |
isAvailable | (editor: Editor) => boolean | always | Whether the command can run now. When it can’t, the control is aria-disabled, still focusable, and pressing it does nothing. |
onPress | (editor: Editor) => void | Required | Runs the command with the Tiptap editor. After a keyboard press focus stays on the control, so several formats can be set in a row. |
isPressed | (editor: Editor) => boolean | Required | Whether the format is on at the caret or in the selection, read from the editor on every change. It sets aria-pressed. |
RichTextEditor.BlockFormat, LinkControl, ImageControl, TableControls
Renders The default controls on their own, for a toolbar you build: the text type picker, the Link button and its form, the Image button and its form, and the table group. They take no props.
RichTextEditor.Icon
Renders An <svg> with aria-hidden that takes the control’s text colour. Also exported as ToolbarIcon.
| Prop | Type | Default | Description |
|---|---|---|---|
name | RichTextIconName | – | A built-in editor icon: undo, redo, bold, italic, underline, strike, code, bullet-list, numbered-list, indent, outdent, link, image, table or clear-formatting. |
paths | readonly string[] | – | Your own icon: path data on a 24 grid, drawn with a 1.5 stroke. |
mirrorInRtl | boolean | true for the icons that point in a direction | Flips the icon in right-to-left text. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-icon | always | The part class. |
aria-hidden | true | It is decoration: the control has its own name. |
RichTextEditor.Content
Renders Tiptap’s EditorContent, around the editable text. The editable text is a textbox with aria-multiline. It is created after the first render, so the server renders only the box. Also exported as RichTextEditorContent.
| Prop | Type | Default | Description |
|---|---|---|---|
aria-label | string | – | The editable text’s name, outside a Field. Inside one, the Field’s label names it. Without any name a development warning says so. |
aria-labelledby | string | – | The editable text’s name from other elements, outside a Field. |
aria-describedby | string | – | Extra ids that describe the text, after the Field’s own descriptions. |
ref | Ref<HTMLDivElement> | – | Reaches the wrapper around the editable text, not the editable element. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-rich-text-content kv-prose | on the editable text | The text is styled as the published Prose, so staff see what readers get. |
role="textbox", aria-multiline | on the editable text | Set by Tiptap and the hook. Not passed directly. |
aria-labelledby, aria-describedby, aria-invalid, aria-required | from the Field | Wired to the editable text, not to its wrapper. |
aria-disabled, aria-readonly | when it applies | A read-only text keeps tabindex="0" so it can be read and copied. A disabled one has no tabindex. |
defaultExtensions
Renders nothing: it is a function, defaultExtensions(options), that returns the extensions a KvirnUI editor starts with. Spread it into your own list. Keep the array in a constant or useMemo. These are its options.
| Prop | Type | Default | Description |
|---|---|---|---|
heading | StarterKitOptions["heading"] | { levels: [2, 3, 4, 5, 6] } | Heading options, or false for no headings. There is no level 1: the page owns it. { levels: [2, 3] } offers fewer levels and the block picker follows. |
link | StarterKitOptions["link"] | https, http, mailto and tel only | The Link mark’s options, or false for no links. By default links have no target, a click puts the caret in the link, and only the four schemes (and relative addresses) are accepted. |
table | Partial<TableKitOptions> | false | not resizable | The table options, or false for no tables. Columns can’t be dragged, because dragging has no keyboard alternative. |
image | Partial<ImageOptions> | false | a block image | The Image options, or false for no images. Without images the Image button is gone too. |
imageSources | readonly string[] | the page’s own origin | The origins images may come from, such as https://bilder.example.se, or ["*"] for any http or https address. The page’s own origin and relative addresses are always allowed. An address outside the list is refused in the form, and in pasted or dropped content with a polite announcement. In stored content or a value set from code it is dropped without a message. |
inputRules | boolean | false | Typing rules: "# " makes a heading, "* " a list and **x** bold. Off by default, because they change the text without telling a screen reader user. |
starterKit | Partial<StarterKitOptions> | – | Any other StarterKit option, such as underline: false or codeBlock: false. |
keymap | boolean | true | false leaves out the Kvirn keymap: Tab, Escape, Alt+F10, Control+K and the AltGr guard. Its Tab handling replaces every other Tab binding, so add your own after turning it off. |
Helper functions
Renders nothing: these are functions you import.
| Prop | Type | Default | Description |
|---|---|---|---|
isAllowedLinkAddress | (address: string, protocols?) => boolean | – | Whether a link address is relative or uses an allowed scheme: https, http, mailto and tel, or the protocols you pass. Never javascript:, data: or ftp:. |
isAllowedImageSource | (source, { sources, allowBase64, baseUrl }?) => boolean | – | Whether an image address may be used: relative, or https or http from the page’s own origin or an origin you list. It reads the page’s address when it is called, never when it is imported. |
ImagePasteGuard | Extension<ImagePasteGuardOptions, ImagePasteGuardStorage> | in defaultExtensions() | The extension that says so when a pasted or dropped image is refused: a file or data: image, or an address that is not allowed (RefusedImageReason: "file" or "source"). It takes the same options as imageSources and allowBase64 and does nothing in a text that cannot be edited. The Root sets storage.onRefused, so you only list it in your own extension array when you leave defaultExtensions() out. |
isDocumentEmpty | (document: Node) => boolean | – | Whether a Tiptap document has nothing to read: no text, and no image or table. An empty paragraph, heading or list item is empty. |
describeShortcut | (chords: readonly string[], isMac: boolean) => DescribedShortcut | – | A shortcut written as Tiptap writes it (Mod-b), ready for aria-keyshortcuts and for a tooltip: ariaKeyShortcuts, keys and text. Key names are not translated. |
getRichTextFeatures | (extensions: Extensions) => RichTextFeatures | – | What an array of extensions lets the text contain, read without making an editor. |
useRichTextEditorContext | () => RichTextEditorContextValue | – | The editor’s state and Tiptap’s editor, for a part of your own inside a RichTextEditor.Root. It throws outside one. |
KvirnKeymap | Extension | – | The extension that decides Tab, Escape, Alt+F10, Control+K and the AltGr guard. It is part of defaultExtensions(). canIndentListItem, canOutdentListItem, indentListItem and outdentListItem are exported with it. |
useRichTextEditor
It creates the Tiptap editor after the first render, so it is safe to render on the server, and it wires the editor to the nearest Field. Put rootProps on your box, contentProps on the element around Tiptap’s EditorContent, and hiddenInputProps on a hidden input.
Options
| Prop | Type | Default | Description |
|---|---|---|---|
extensions | Extensions | defaultExtensions() | The Tiptap extensions, as an array. Keep it the same array between renders (a constant, or useMemo): Tiptap reads it when it creates the editor. |
format | 'html' | 'json' | 'html' | The format of the value. HTML is a string, and an empty text is an empty string. JSON is Tiptap’s document, and an empty text is null. |
value | string | JSONContent | null | – | The value, when your own state holds it. The first value is the starting text. A later one that is not what the editor holds replaces the text. Typing never moves the caret. |
defaultValue | string | JSONContent | null | – | The starting text when the editor holds the value itself. A form reset goes back to it. |
onValueChange | (value, details) => void | – | Called after each change to the text, with the new value and details: editor, transaction, isEmpty, and with characterCount also length, limit and isOverLimit. It only reports. |
name | string | – | The name a form sends the value under, through a hidden input. The input follows a form reset and is disabled while the editor is. |
editable | boolean | true | false makes the text read-only, like readOnly. |
disabled | boolean | false | The text is not editable, not focusable and not sent. A disabled Field disables the editor too. |
readOnly | boolean | false | The text can be focused, selected and copied, but not changed. The toolbar is not rendered. |
maxLength | number | – | The limit the character count counts against. It never blocks typing, and it renders nothing without characterCount. |
characterCount | boolean | false | Shows a count under the box, against maxLength. It counts the text a reader sees, with one line break between blocks. Without maxLength a development warning says so. |
countCharacters | (value: string) => number | – | Counts the text your own way, for example the way your server counts it. |
messages | Partial<KvirnMessages['richText']> | – | Per-instance override of the toolbar, the forms and the announcements. |
editorOptions | Partial<EditorOptions> | – | The rest of Tiptap’s own options for the editor, for example injectCSS. The hook owns extensions, content and editable. |
aria-label | string | – | The editable text’s name, outside a Field. |
aria-labelledby | string | – | The editable text’s name from other elements, outside a Field. |
aria-describedby | string | – | Extra ids that describe the text, after the Field’s own. |
onFocusToolbar | () => boolean | void | – | Alt+F10 (Option+F10): move focus to your toolbar. Return false when there is none. |
onOpenLinkForm | () => boolean | void | – | Control+K: open your link form. Return false to let the key pass. |
Result
| Prop | Type | Default | Description |
|---|---|---|---|
editor | Editor | null | – | Tiptap’s editor. It is null until it mounts, because it is created after the first render. |
rootProps | RichTextRootPartProps | – | Spread on the box: the class, a ref and the data-* state. |
contentProps | RichTextContentPartProps | – | Spread on the element around the editable text: the focus handlers. |
RichTextHiddenInputPartProps | undefined | – | Spread on a hidden input. undefined without a name. | |
text | string | – | The text as the count counts it, with one line break between blocks. |
isEmpty | boolean | – | There is nothing to read. |
isFocused | boolean | – | The editable text has focus, however it got it. |
isFocusVisible | boolean | – | The editable text has focus from the keyboard. A click does not set it. |
isDisabled | boolean | – | The editor is disabled. |
isReadOnly | boolean | – | The text can’t be changed but can be read and copied. |
isInvalid | boolean | – | The Field is invalid. |
isRequired | boolean | – | The Field is required. |
isEditable | boolean | – | Whether the text can be edited. |
features | RichTextFeatures | – | What the extensions let the text contain: lists, tables, links, images, marks and the heading levels. They decide which controls apply. |
contentId | string | – | The editable text’s id: the Field’s control id, or a generated one. |
Strings
These are the default texts in @kvirn-ui/i18n.
For your whole app, pass messages to KvirnProvider. For one RichTextEditor, pass its messages prop.
richText.toolbar
The first part of the toolbar’s name, then the Field’s label. It is visually hidden.
| Language | Default text |
|---|---|
| Svenska | Formatering |
| Suomi | Muotoilu |
| Norsk bokmål | Formatering |
| Norsk nynorsk | Formatering |
| English | Formatting |
richText.blockType
The name of the picker that sets the type of the text.
| Language | Default text |
|---|---|
| Svenska | Texttyp |
| Suomi | Tekstityyppi |
| Norsk bokmål | Teksttype |
| Norsk nynorsk | Teksttype |
| English | Text type |
richText.bold
The name of the Bold control and the first line of its tooltip. Every control has a key like it.
| Language | Default text |
|---|---|
| Svenska | Fetstil |
| Suomi | Lihavointi |
| Norsk bokmål | Fet |
| Norsk nynorsk | Feit |
| English | Bold |
richText.link
The name of the Link button, which opens the link form.
| Language | Default text |
|---|---|
| Svenska | Länk |
| Suomi | Linkki |
| Norsk bokmål | Lenke |
| Norsk nynorsk | Lenkje |
| English | Link |
richText.linkUrlInvalid
The error in the link form when the web address can’t be used.
| Language | Default text |
|---|---|
| Svenska | Skriv webbadressen som https://www.exempel.se |
| Suomi | Kirjoita verkko-osoite muodossa https://www.esimerkki.fi |
| Norsk bokmål | Skriv nettadressen slik: https://www.eksempel.no |
| Norsk nynorsk | Skriv nettadressa slik: https://www.eksempel.no |
| English | Enter the web address like https://www.example.com |
richText.imageAlt
The label of the description field in the image form.
| Language | Default text |
|---|---|
| Svenska | Vad visar bilden? |
| Suomi | Mitä kuvassa näkyy? |
| Norsk bokmål | Hva viser bildet? |
| Norsk nynorsk | Kva viser biletet? |
| English | What does the image show? |
richText.imageAltMissing
The error when an image has no description and is not marked as decoration.
| Language | Default text |
|---|---|
| Svenska | Beskriv vad bilden visar, eller kryssa i att den bara är dekoration. |
| Suomi | Kuvaile, mitä kuvassa näkyy, tai valitse, että se on vain koriste. |
| Norsk bokmål | Beskriv hva bildet viser, eller huk av for at det bare er dekorasjon. |
| Norsk nynorsk | Beskriv kva biletet viser, eller kryss av for at det berre er dekorasjon. |
| English | Describe what the image shows, or tick that it’s only decoration. |
richText.imageUrlNotAllowed
The error when the image’s address is outside the allowed sources.
| Language | Default text |
|---|---|
| Svenska | Bilder från den adressen får inte användas här. Skriv en annan webbadress. |
| Suomi | Kuvia tästä osoitteesta ei voi käyttää täällä. Kirjoita toinen verkko-osoite. |
| Norsk bokmål | Bilder fra den adressen kan ikke brukes her. Skriv en annen nettadresse. |
| Norsk nynorsk | Bilete frå den adressa kan ikkje brukast her. Skriv ei anna nettadresse. |
| English | Images from that address aren’t allowed here. Enter a different web address. |
richText.imagePasteNotSupported
Announced when an image file or a data image is pasted or dropped.
| Language | Default text |
|---|---|
| Svenska | Bilder kan inte klistras in. Använd knappen Bild. |
| Suomi | Kuvia ei voi liittää. Käytä Kuva-painiketta. |
| Norsk bokmål | Bilder kan ikke limes inn. Bruk knappen Bilde. |
| Norsk nynorsk | Bilete kan ikkje limast inn. Bruk knappen Bilete. |
| English | Images can’t be pasted. Use the Image button. |
richText.imageSourceNotAllowed
Announced when a pasted image comes from an address outside the allowed sources.
| Language | Default text |
|---|---|
| Svenska | Den inklistrade bilden lades inte till, eftersom den kommer från en adress som inte är tillåten. |
| Suomi | Liitettyä kuvaa ei lisätty, koska se on osoitteesta, jota ei sallita. |
| Norsk bokmål | Det innlimte bildet ble ikke lagt til, fordi det kommer fra en adresse som ikke er tillatt. |
| Norsk nynorsk | Det innlima biletet vart ikkje lagt til, fordi det kjem frå ei adresse som ikkje er tillaten. |
| English | The pasted image wasn’t added, because it comes from an address that isn’t allowed. |
richText.linkAdded
Announced when a link is added.
| Language | Default text |
|---|---|
| Svenska | Länken är tillagd. |
| Suomi | Linkki lisätty. |
| Norsk bokmål | Lenken er lagt til. |
| Norsk nynorsk | Lenkja er lagd til. |
| English | Link added. |
richText.tableInserted
Announced when a table is inserted.
| Language | Default text |
|---|---|
| Svenska | Tabell med 3 kolumner och 3 rader tillagd. |
| Suomi | Taulukko lisätty: 3 saraketta ja 3 riviä. |
| Norsk bokmål | Tabell med 3 kolonner og 3 rader lagt til. |
| Norsk nynorsk | Tabell med 3 kolonnar og 3 rader lagd til. |
| English | Table with 3 columns and 3 rows added. |
richText.tableDeleted
Announced when a table is deleted, with how to undo it.
| Language | Default text |
|---|---|
| Svenska | Tabellen är borttagen. Ångra med Ctrl+Z. |
| Suomi | Taulukko poistettu. Kumoa painamalla Ctrl+Z. |
| Norsk bokmål | Tabellen er slettet. Angre med Ctrl+Z. |
| Norsk nynorsk | Tabellen er sletta. Angre med Ctrl+Z. |
| English | Table deleted. Undo with Ctrl+Z. |
richText.listLevel
Announced when a list item is nested or outdented, with its new level.
| Language | Default text |
|---|---|
| Svenska | Nivå 2 |
| Suomi | Taso 2 |
| Norsk bokmål | Nivå 2 |
| Norsk nynorsk | Nivå 2 |
| English | Level 2 |
richText.formatOn
Announced when a keyboard shortcut turns bold, italic or underline on. formatOff says it is off.
| Language | Default text |
|---|---|
| Svenska | Bold på |
| Suomi | Bold käytössä |
| Norsk bokmål | Bold på |
| Norsk nynorsk | Bold på |
| English | Bold on |
Known issues#
- With
image: falsea pasted image is dropped with no message: the paste guard is not installed without the Image extension. A text with no image support has nothing to refuse into, but the writer is not told. - No language marking inside the text. The editor can't mark a passage in another language (3.1.2 Language of Parts, AA), so a screen reader reads a mixed-language text in the page language.
- Screen reader support for a
contenteditablevaries across NVDA, JAWS and VoiceOver, and is the biggest risk. Test the editor with your users and their assistive technology. - A pasted link keeps its
target(Tiptap parses any declared attribute). Sanitize the output on the server. - The inactive selection (while focus is on a toolbar button) is the browser's own highlight.
- The link and image popovers anchor to their toolbar button, also when opened with Control+K, not to the caret.
- No upload. An image is inserted from an address with alt text.
- Tiptap's injected CSS is unlayered, so the theme restyles the few rules it must with
!important.
Information: Did you know?
If an issue here affects your service, list it in your accessibility statement with its workaround.
Testing#
The automated tests prove the keyboard behaviour, the names and states, that axe finds no violations in every story and theme, and, for the components they cover, that the stories hold up in forced colours, reduced motion, text spacing and a 320 pixel width. An Automated row passes on these tests alone. A Core or Release row passes only when an automated agent check and a person on the real assistive technology have both checked it. "agent-verified" means automated tests in the repository (with a virtual screen reader for the screen reader rows), not the real assistive technology.
| AT + browser + OS | Agent check | Human check | Result | Notes |
|---|---|---|---|---|
| Automated (re-runnable tests) | ||||
| axe, WCAG 2.2 A and AA, every story, 4 themes | pass | n/a | pass | rich-text-editor.stories.tsx, every story, 4 themes |
| Markup and ARIA (roles, names, ids, states) | pass | n/a | pass | rich-text-editor.test.tsx › the Field’s label names the editable text, a multi-line textbox; expectNoA11yViolations |
| Keyboard contract rows (Vitest browser) | pass | n/a | pass | 43 rows, each names a test (rich-text-toolbar.test.tsx › Tab goes to the toolbar (one stop), then the text, then the next field; Shift+Tab goes back) |
| Focus order and management | pass | n/a | pass | rich-text-editor.test.tsx asserts focus (toHaveFocus); first rule: Tab goes to the toolbar (one stop), then the text, then the next field; Shift+Tab goes back |
| Display modes (forced colours, 320px reflow, text spacing, reduced motion) | pass | n/a | pass | the four sweep projects (storybook-forced-colors, -reduced-motion, -reflow, -text-spacing), run in CI |
| Core (required for beta) | ||||
| NVDA + Chrome + Windows | pending | pending | pending | |
| VoiceOver + Safari + iOS | pending | pending | pending | |
| Release (before 1.0 and each minor) | ||||
| JAWS + Chrome + Windows | pending | pending | pending | |
| TalkBack + Chrome + Android | pending | pending | pending | |
| VoiceOver + Safari + macOS | pending | pending | pending |
What to check#
- Tab from the label: focus lands on the toolbar (one stop), then the text. Press Alt+F10 (Option+F10 on a Mac) to go from the text to the toolbar, and Escape to come back.
- In the toolbar, use the arrow keys, Home and End: each button is read with its name and, for toggles, pressed or not.
- In the text, press Control+B or Control+I (Command on a Mac): "Bold on" / "Bold off" is heard.
- Press Control+K (Command+K), add a web address and press Enter: the link is announced as added and focus is back in the text.
- In a list, Tab nests an item and says the level. On the first item and in a table's last cell Tab leaves the editor. In a table Tab moves between cells.
- Insert an image with no description and with a disallowed address: the error is read and focus stays in the form.
- Open "More" in the compact toolbar and choose Underline.
Information: Did you know?
A Core or Release row passes only with an agent check and a human check on the real assistive technology. Screen reader support for an editable text varies, so test with the assistive technology your staff use before you roll the editor out.