Components · Data Display
CodeBlock
Several lines of code or a log on a framed code surface, with an optional header for the file name and a copy action.
import { CodeBlock } from "@botiverse/raft-ui";Several lines of code or a log, on a framed code surface that scrolls sideways instead of wrapping. An optional header names the file and holds actions such as Copy. You render the code inside, plain or highlighted.
When to use
Anatomy
CodeBlock: the frame. Required.CodeBlockHeader: the optional top bar, with a hairline under it.CodeBlockTitle: the file name, in Space Mono.CodeBlockActions: the actions at its right end.
CodeBlockBody: the code panel. Render the code in aCodeBlockPrewith itscodeinside it. Required.CodeBlockPre: the code'spre, keyboard-reachable while it scrolls (Accessibility).CodeBlockAction: a 32px icon button withradius-chip(34px withradius-controlwith a mouse), like every control embedded in a frame. You provide its icon and what it does.
Variants
Behavior
- Long lines scroll sideways inside the body. The code doesn't wrap.
- After a copy, the copy icon turns into a check, then back after a moment, as in CopyableCode.
Content
- Put the file name in the title, with its extension:
raft.config.ts. - Leave the header out when there is no file name.
Accessibility
- Give every
CodeBlockActionanaria-label, such as "Copy code": it is icon-only. - Announce a completed copy, for example with
aria-liveon the button, so the change of icon isn't the only signal. - Keep the code in
preandcode, so it is read as code and keeps its whitespace. - Render the code in
CodeBlockPre. A long line scrolls inside it, and while it does it is a region the keyboard can reach (tabindex="0",role="region"), named by itsaria-label("Code" by default; name it after the language, "ts code"): Safari doesn't let the keyboard reach a scroller that can't take focus, and aprewith no role can't carry a name. Code that fits adds no Tab stop. It measures again whenever thepreresizes or its code changes (highlighting that arrives late, code that streams in), so a line that grows long gets the Tab stop. It shows the inset ink ring on keyboard focus.
Rules
- Set code in Space Mono,
text-mono-code. - Put the block on
layer-code, with aline-hairlineborder andradius-container. - Put the actions 6px from the block's corner, 4px apart. Without a header they sit in a column of their own beside the code, as wide as the actions, so no line runs under them however many there are, and the block is at least tall enough to keep 6px under them. In a header they are centered in its 40px and 6px from its end (Shape).
API
CodeBlock, CodeBlockAction, CodeBlockActions, CodeBlockBody, CodeBlockHeader, CodeBlockPre, CodeBlockTitle
Framed code surface. Compose a header and a body inside it.
Also takes the attributes of its element.
Related
Changes
- 0.2.0 · AddedAdded stable
CodeBlock*and semanticMarkdown*compound primitives.