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
import { CodeBlock } from '@kvirn-ui/react'
import { useCodeBlockTexts } from './texts.ts'
export function DefaultCodeBlock() {
const { texts } = useCodeBlockTexts()
return (
<CodeBlock.Root>
<CodeBlock.Label>{texts.installLabel}</CodeBlock.Label>
<CodeBlock.Code>pnpm add @kvirn-ui/react @kvirn-ui/theme</CodeBlock.Code>
<CodeBlock.Copy />
</CodeBlock.Root>
)
}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.jsonimport { CodeBlock } from '@kvirn-ui/react'
import { useCodeBlockTexts } from './texts.ts'
export function LongLine() {
const { texts } = useCodeBlockTexts()
return (
<CodeBlock.Root>
<CodeBlock.Label>{texts.requestLabel}</CodeBlock.Label>
<CodeBlock.Code>
<code>
curl --request POST https://api.example.org/e-services/parking-permits/applications
--header "Content-Type: application/json" --data @application.json
</code>
</CodeBlock.Code>
<CodeBlock.Copy />
</CodeBlock.Root>
)
}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
import { CodeBlock } from '@kvirn-ui/react'
import { useCodeBlockTexts } from './texts.ts'
export function NamedCopy() {
const { texts } = useCodeBlockTexts()
return (
<CodeBlock.Root>
<CodeBlock.Label>{texts.installLabel}</CodeBlock.Label>
<CodeBlock.Code>pnpm add @kvirn-ui/react @kvirn-ui/theme</CodeBlock.Code>
<CodeBlock.Copy>{texts.copyCommand}</CodeBlock.Copy>
</CodeBlock.Root>
)
}Props in this example:
childrenon CodeBlock.Copy
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
import { CodeBlock } from '@kvirn-ui/react'
import { useCodeBlockTexts } from './texts.ts'
const command = 'curl https://api.example.org/e-services/status'
export function WithoutPrompt() {
const { texts } = useCodeBlockTexts()
return (
<CodeBlock.Root>
<CodeBlock.Label>{texts.statusLabel}</CodeBlock.Label>
<CodeBlock.Code>{`$ ${command}`}</CodeBlock.Code>
{/* The reader sees the prompt. Copy writes only the command. */}
<CodeBlock.Copy text={command} />
</CodeBlock.Root>
)
}Props in this example:
texton 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
import { CodeBlock, Stack } from '@kvirn-ui/react'
import { useCodeBlockTexts } from './texts.ts'
export function SeveralBlocks() {
const { texts } = useCodeBlockTexts()
return (
<Stack className="kv-stack--gap-4">
<CodeBlock.Root>
<CodeBlock.Label>{texts.installLabel}</CodeBlock.Label>
<CodeBlock.Code>pnpm add @kvirn-ui/react @kvirn-ui/theme</CodeBlock.Code>
<CodeBlock.Copy
messages={{
label: texts.copyCommand,
copied: texts.installCopied,
failed: texts.installFailed,
}}
/>
</CodeBlock.Root>
<CodeBlock.Root>
<CodeBlock.Label>{texts.requestLabel}</CodeBlock.Label>
<CodeBlock.Code>
curl --request POST https://api.example.org/e-services/parking-permits/applications
</CodeBlock.Code>
<CodeBlock.Copy
messages={{
label: texts.copyRequest,
copied: texts.requestCopied,
failed: texts.requestFailed,
}}
/>
</CodeBlock.Root>
</Stack>
)
}Props in this example:
messageson CodeBlock.Copy
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).
| Part | Element / role | ARIA | Notes |
|---|---|---|---|
| CodeBlock.Root | <div> → generic, or group | role="group" and aria-labelledby while a Label is mounted | class="kv-code-block". Without a Label it is a plain <div>. Also exported as CodeBlockRoot |
| CodeBlock.Label | <p> → paragraph | id, set by the Root | class="kv-code-block-label". It names the group. Also exported as CodeBlockLabel |
| CodeBlock.Code | <pre> → generic | none | class="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> → button | as CopyButton | class="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 part | attributes | passed through | One 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
KvirnProviderwithuseLocale().localePropson 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 part | none | Root 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.
| Key | Where | What happens |
|---|---|---|
| Tab | CodeBlock | Moves 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+Tab | CodeBlock | Moves focus back off the Copy button Test: code-block.test.tsx › keyboard › Shift+Tab moves focus off the Copy button |
| Enter | Copy | Copies 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).
| When | What it says | Message key | Politeness |
|---|---|---|---|
| Copy succeeded | copyButton.copied | Polite | |
| Copy was refused | copyButton.failed | Assertive |
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 attribute | Values | Meaning |
|---|---|---|
kv-code-block | always | The part class. The default theme draws the surface. |
role="group", aria-labelledby | while a Label is mounted | The 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 attribute | Values | Meaning |
|---|---|---|
kv-code-block-label | always | The part class. |
id | set by the Root | Names 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 attribute | Values | Meaning |
|---|---|---|
kv-code-block-code | always | The 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.
| Prop | Type | Default | Description |
|---|---|---|---|
text | string | (() => string) | the Code's text | The text to copy. By default the text content of CodeBlock.Code. |
textRef | RefObject<Element | null> | the Code element | The 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. |
children | ReactNode | the message copyButton.label | Your own label, which replaces the message, so its language is yours to set. |
status | boolean | true | false removes the words shown after the button, so you draw your own from data-status. The result is announced either way. |
messages | Partial<{ label, copied, failed }> | – | Per-instance overrides of the three messages. See Strings. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-button kv-code-block-copy | always | The class of Button, and the part class. |
data-status | idle, copied or failed | As CopyButton: the result of the last copy, a hook for your own cue. |
useCodeBlock
Takes no options.
Result
| Prop | Type | Default | Description |
|---|---|---|---|
rootProps | CodeBlockRootProps | – | Spread on the Root: the class, and role="group" with aria-labelledby while a Label is mounted. |
labelProps | CodeBlockLabelProps | – | Spread on the Label: the class and the id that names the group. |
codeProps | CodeBlockCodeProps | – | Spread on the Code, which also gets context.codeRef as its ref. |
context | CodeBlockContextValue | – | What the parts share: labelId, codeRef and registerLabel. |
hasLabel | boolean | – | 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.
| Language | Default text |
|---|---|
| Svenska | Kopiera |
| Suomi | Kopioi |
| Norsk bokmål | Kopier |
| Norsk nynorsk | Kopier |
| English | Copy |
copyButton.copied
Announced politely after the code was copied.
| Language | Default text |
|---|---|
| Svenska | Kopierat |
| Suomi | Kopioitu |
| Norsk bokmål | Kopiert |
| Norsk nynorsk | Kopiert |
| English | Copied |
copyButton.failed
Announced assertively when the browser refused. The code is selected.
| Language | Default text |
|---|---|
| Svenska | Det gick inte att kopiera. Markera texten och kopiera den själv. |
| Suomi | Kopiointi epäonnistui. Valitse teksti ja kopioi se itse. |
| Norsk bokmål | Kunne ikke kopiere. Marker teksten og kopier den selv. |
| Norsk nynorsk | Kunne ikkje kopiere. Marker teksten og kopier han sjølv. |
| English | Could 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 + 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 | code-block.stories.tsx, every story, 4 themes |
| Markup and ARIA (roles, names, ids, states) | pass | n/a | pass | code-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) | pass | n/a | pass | 3 rows, each names a test in code-block.test.tsx |
| Focus order and management | pass | n/a | pass | code-block.test.tsx: Enter on Copy writes the code and keeps focus |
| 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#
- 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.