Skip to
Keyboard shortcuts

Use the up and down arrow keys to move between items. Press Alt+Shift+K to open this list again.

Alpha version out now. The API may still change.

CodeBlock

A code sample or a command with a label and a copy button. A labelled sample of code, such as a command to run, with a button that copies it. The code wraps instead of scrolling sideways, and nothing is coloured to carry meaning.

Package
@kvirn-ui/react
Testing
Automated. Core 0 of 2, Release 0 of 3

When to use it#

  • Use it for a command, a request or a short sample that the reader will copy and run.
  • Give it a label that says what it is: “Install”, “Send an application”. The label names the block for screen reader users (people using software that reads the screen aloud).
  • For one short text such as a case number, use a CopyButton next to it.
  • Not for running text: use a paragraph.

Example#

Install

pnpm add @kvirn-ui/react @kvirn-ui/theme

Use cases#

A long command that wraps

A request or a path can be longer than the screen. The code wraps at any character instead of scrolling sideways, so it fits a screen 320 CSS pixels wide (the width of a page zoomed to 400%). Copy still copies the whole text.

Send an application

curl --request POST https://api.example.org/e-services/parking-permits/applications --header "Content-Type: application/json" --data @application.json

Information: Did you know?

A line can break in the middle of a path or a hyphenated word. Where a break would mislead, say the exact text in the paragraph before the block.

A copy button that says what it copies

Give Copy visible words of your own, such as “Copy command”, instead of “Copy”. What you write inside Copy is its visible text and also its name, so the two match. These words are not translated for you: take them from your own translations.

Install

pnpm add @kvirn-ui/react @kvirn-ui/theme

Props in this example:

A command copied without its prompt

A command is easier to read with the prompt sign in front, but the prompt isn’t part of what to run. Give Copy the text to write, and it copies that instead of what is shown.

Check that the service is running

$ curl https://api.example.org/e-services/status

Props in this example:

  • text on CodeBlock.Copy

Information: Did you know?

If the browser refuses to copy, the whole code is selected, prompt included, so the reader can copy it by hand. Use a prompt only where readers expect one.

Several blocks, each saying what was copied

With more than one block on a page, “Copy” and “Copied” alone don’t say which block they mean. Set the button’s words and both results for each block in messages. The words shown after the button are the same words a screen reader announces.

Install

pnpm add @kvirn-ui/react @kvirn-ui/theme

Send an application

curl --request POST https://api.example.org/e-services/parking-permits/applications

Props in this example:

Accessibility#

What it does for you#

  • APG pattern: none. A code block is static text, so there is no APG pattern. Its one control is a CopyButton (see the CopyButton page).
  • Deviations: none
  • Native elements used: <pre> for the code, <p> for the label, <button> for Copy.

A CodeBlock shows a code sample or a reference with a copy button. The code wraps, so there is no scroller to reach and no 2D scrolling (1.4.10 Reflow, AA). There is no syntax highlighting, so no colour carries meaning (1.4.1 Use of Color, A).

PartElement / roleARIANotes
CodeBlock.Root<div> → generic, or grouprole="group" and aria-labelledby while a Label is mountedclass="kv-code-block". Without a Label it is a plain <div>. Also exported as CodeBlockRoot
CodeBlock.Label<p> → paragraphid, set by the Rootclass="kv-code-block-label". It names the group. Also exported as CodeBlockLabel
CodeBlock.Code<pre> → genericnoneclass="kv-code-block-code". Never a Tab stop, no tabindex, no overflow. Put <code> inside it if you want. Also exported as CodeBlockCode
CodeBlock.Copy<button> → buttonas CopyButtonclass="kv-button kv-code-block-copy". Copies the Code's text. On failure it selects the Code. Also exported as CodeBlockCopy. It inherits the CopyButton's span.kv-copy-status after the button (status={false} removes it); there is no separate Status part
every partattributespassed throughOne element per part, always the same: no as. className joins the part's class, the ref gets the element

useCodeBlock() gives rootProps, labelProps, codeProps and the values the parts share.

What you need to do#

  • Give the block a Label that says what it is ("Install", "Example request") so the group has a name (1.3.1 Info and Relationships, 2.4.6 Headings and Labels). A block without one is a plain div.
  • Code or a label that is not in the page's language goes in a nested KvirnProvider with useLocale().localeProps on your own element (3.1.2 Language of Parts). Code is mostly language-neutral, but a comment or a message in it is not.
  • A long line wraps at any character, so say the exact text in prose when a break would mislead (a path, a hyphenated token).
  • No syntax highlighting: don't convey meaning by colour in the code (1.4.1 Use of Color).

Warning: Don't forget

Give every block a label. Without one, a screen reader user hears no name for the block (1.3.1 Info and Relationships, 2.4.6 Headings and Labels).

Visual and modes#

Headless: CodeBlock ships no CSS. With @kvirn-ui/theme/theme.css:

  • Focus indicator: Copy's, because it is a Button. The Code is never focused.
  • Target size: Copy is a Button (2.5.8 Target Size (Minimum), AA).
  • Contrast: the code is text on the page surface, and the default theme checks that pair for the minimum contrast (1.4.3 Contrast (Minimum), AA).
  • Forced colours: the code keeps a visible edge in the system's text colour. The status words and icon use the system's text colour too.
  • Reduced motion: nothing moves.
  • Layout: a wrapping row. The Label and the Code take a full row each. Copy and its status share the last row, and the failure text wraps below Copy on a narrow screen. The icons don't flip in right-to-left languages.
  • Reflow and text spacing: the code wraps and never scrolls, so there is no sideways scrolling at 320 CSS pixels and nothing is clipped at 400% zoom or with wider text spacing (1.4.10 Reflow, 1.4.12 Text Spacing). The reflow sweep checks every story at 320 CSS pixels for horizontal overflow, and the text-spacing sweep checks that no box clips text once the wider spacing is applied. Zoom to 400% is checked by eye.

Focus management#

  • Initial focus: not moved.
  • Trap: no.
  • Restore to: not applicable. After a copy or a failure, focus stays on Copy.
  • Never obscured by: CodeBlock renders no overlay.

Allowed elements#

No part takes as.

Part`as`Why
every partnoneRoot is a group named by the Label (an element would not change that), Label a <p> (never a heading), Code a <pre> (1.3.1 Info and Relationships, A; 4.1.2 Name, Role, Value, A)

WCAG success criteria#

  • 1.3.1 Info and Relationships (A): the group is named by the Label.
  • 1.4.10 Reflow (AA) and 1.4.12 Text Spacing (AA): the code wraps and there is no scroll region.
  • 2.1.1 Keyboard (A) and 2.4.3 Focus Order (A): the one Tab stop is Copy, after the Code in the page's order.
  • 1.4.3 Contrast (Minimum) (AA): the code is text on the page surface, a pair the theme's contrast check measures.
  • 2.5.3 Label in Name (A): Copy is a CopyButton, so its name is its visible text and the result never replaces it. A label of your own should keep its visible words in the name.
  • 1.4.1 Use of Color (A), 3.3.1 Error Identification (A) and 4.1.3 Status Messages (AA): through CopyButton, which writes the result as words after the button and announces it.

Keyboard#

Focus
native
Selection follows focus
n/a
Arrows wrap
n/a
Shortcuts
none

The Code is text and not a Tab stop. The Copy button is a native <button>. The CopyButton page describes Enter, Space and what happens when copying fails.

KeyWhereWhat happens
TabCodeBlockMoves focus to the Copy button. The Code and the Label are skipped
Test: code-block.test.tsx › keyboard › Tab moves focus to the Copy button and skips the code
Shift+TabCodeBlockMoves focus back off the Copy button
Test: code-block.test.tsx › keyboard › Shift+Tab moves focus off the Copy button
EnterCopyCopies the code, announces the result, focus stays on the button
Test: code-block.test.tsx › copy › Enter on Copy writes the code and keeps focus

Space, Escape, arrow keys and Home / End are not handled by the CodeBlock. The Copy button handles Space natively.

Announcements#

CodeBlock tells screen reader users about these changes without moving focus. Each message waits until the screen reader is quiet (polite) or interrupts it (assertive).

WhenWhat it saysMessage keyPoliteness
Copy succeededcopyButton.copiedPolite
Copy was refusedcopyButton.failedAssertive

The text in all five languages

Change the text#

For your whole app, pass messages to KvirnProvider. For one CodeBlock, pass its messages prop.

<KvirnProvider messages={{ copyButton: { copied: '…' } }}>

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.

API reference#

import { CodeBlock, useCodeBlock } from '@kvirn-ui/react'

CodeBlock.Root

Renders <div class="kv-code-block">. It is a group named by the Label while one is mounted, and a plain div without one.

Class or attributeValuesMeaning
kv-code-blockalwaysThe part class. The default theme draws the surface.
role="group", aria-labelledbywhile a Label is mountedThe group is named by the Label. Without a Label the Root is a plain div.

CodeBlock.Label

Renders <p class="kv-code-block-label">: what the code is, never a heading.

Class or attributeValuesMeaning
kv-code-block-labelalwaysThe part class.
idset by the RootNames the group. A Label is a p, never a heading.

CodeBlock.Code

Renders <pre class="kv-code-block-code">. It has no tabindex, so it is never a Tab stop. The default theme wraps its text instead of scrolling. Put a <code> inside it if you like.

Class or attributeValuesMeaning
kv-code-block-codealwaysThe part class. The default theme sets the mono type and wraps the text.

CodeBlock.Copy

Renders A CopyButton for the Code: it copies the Code’s text and selects the Code when copying fails. It takes the other props of a CopyButton.

PropTypeDefaultDescription
textstring | (() => string)the Code's textThe text to copy. By default the text content of CodeBlock.Code.
textRefRefObject<Element | null>the Code elementThe element selected when the browser refuses to write.
onCopied(text: string) => void–Called with the text after it was written to the clipboard.
onCopyError(text: string) => void–Called when the text could not be written, after the failure is announced.
childrenReactNodethe message copyButton.labelYour own label, which replaces the message, so its language is yours to set.
statusbooleantruefalse removes the words shown after the button, so you draw your own from data-status. The result is announced either way.
messagesPartial<{ label, copied, failed }>–Per-instance overrides of the three messages. See Strings.
Class or attributeValuesMeaning
kv-button kv-code-block-copyalwaysThe class of Button, and the part class.
data-statusidle, copied or failedAs CopyButton: the result of the last copy, a hook for your own cue.

useCodeBlock

Takes no options.

Result

PropTypeDefaultDescription
rootPropsCodeBlockRootProps–Spread on the Root: the class, and role="group" with aria-labelledby while a Label is mounted.
labelPropsCodeBlockLabelProps–Spread on the Label: the class and the id that names the group.
codePropsCodeBlockCodeProps–Spread on the Code, which also gets context.codeRef as its ref.
contextCodeBlockContextValue–What the parts share: labelId, codeRef and registerLabel.
hasLabelboolean–True while a Label is mounted.

Strings

These are the default texts in @kvirn-ui/i18n.

For your whole app, pass messages to KvirnProvider. For one CodeBlock.Copy, pass its messages prop.

CodeBlock has no strings of its own: the Label is your text. Copy uses the messages of CopyButton.

copyButton.label

The visible text and the accessible name of Copy.

LanguageDefault text
SvenskaKopiera
SuomiKopioi
Norsk bokmålKopier
Norsk nynorskKopier
EnglishCopy

copyButton.copied

Announced politely after the code was copied.

LanguageDefault text
SvenskaKopierat
SuomiKopioitu
Norsk bokmålKopiert
Norsk nynorskKopiert
EnglishCopied

copyButton.failed

Announced assertively when the browser refused. The code is selected.

LanguageDefault text
SvenskaDet gick inte att kopiera. Markera texten och kopiera den själv.
SuomiKopiointi epäonnistui. Valitse teksti ja kopioi se itse.
Norsk bokmålKunne ikke kopiere. Marker teksten og kopier den selv.
Norsk nynorskKunne ikkje kopiere. Marker teksten og kopier han sjølv.
EnglishCould not copy. Select the text and copy it yourself.

Known issues#

  • WebKit is not automated. Keyboard rows run in Vitest browser mode on Chromium. WebKit is not covered by the automated tests, so check Safari with your own users and assistive technology.
  • No syntax highlighting (it would be a dependency, and colour must not carry meaning).
  • The group gets its name after scripts run. The Label names the group once the page's scripts run, not in the HTML the server sends. Before that the block is a plain div, with the label text just before the code in reading order. It matters to your accessibility statement only if your site promises to work without JavaScript.

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 + OSAgent checkHuman checkResultNotes
Automated (re-runnable tests)
axe, WCAG 2.2 A and AA, every story, 4 themespassn/apasscode-block.stories.tsx, every story, 4 themes
Markup and ARIA (roles, names, ids, states)passn/apasscode-block.test.tsx (axe and role, name and state): Root is a div, Label a p and Code a pre, with the part classes
Keyboard contract rows (Vitest browser)passn/apass3 rows, each names a test in code-block.test.tsx
Focus order and managementpassn/apasscode-block.test.tsx: Enter on Copy writes the code and keeps focus
Display modes (forced colours, 320px reflow, text spacing, reduced motion)passn/apassthe four sweep projects (storybook-forced-colors, -reduced-motion, -reflow, -text-spacing), run in CI
Core (required for beta)
NVDA + Chrome + Windowspendingpendingpending
VoiceOver + Safari + iOSpendingpendingpending
Release (before 1.0 and each minor)
JAWS + Chrome + Windowspendingpendingpending
TalkBack + Chrome + Androidpendingpendingpending
VoiceOver + Safari + macOSpendingpendingpending

What to check#

  • Press Tab: focus goes straight to Copy, skipping the label and the code.
  • Move to the block with a screen reader: it reads a labelled group with its label. Copy reads "Copy, button".
  • Press Enter, then Space on Copy: "Copied" is announced once each time, and focus stays on Copy.
  • Over plain HTTP or with clipboard access blocked, Copy announces the failure and selects the code.
  • At 320 CSS px or 400% zoom, the code wraps and nothing scrolls sideways.