An open source design system that's fully customizable and agent ready
schema_version: 3 template_version: 7 kind: component id: component:CodeBlock authority: current archive_reason: null superseded_by: null approved_by: cixzhang approved_at: 2026-10-12 owners: [cixzhang] review_triggers: [public-api, behavior, layout, theming, accessibility, testing] verified_by: [ packages/core/src/CodeBlock/CodeBlock.test.tsx, packages/core/src/CodeBlock/CodeBlock.startLineNumber.test.tsx, packages/core/src/CodeBlock/highlightRanges.test.ts, packages/core/src/CodeBlock/tokenizer.test.ts, packages/core/src/theme/themingTargets.test.ts, packages/core/src/docPropLiterals.test.ts, packages/core/src/docPropReferences.test.ts, apps/storybook/stories/CodeBlock.stories.tsx, apps/storybook/rtl-audit/targets.json, ] modules: [] families: [] design_specs: [] architecture: [ architecture:public-component-api, architecture:component-theming-surface, architecture:component-test-sufficiency, architecture:theme-tokens, architecture:icon-resolution-and-component-slots, ] contributing: []
system_specs: [spec:AST-025]
CodeBlock component contract
Contract at a glance
| Area | Contract |
|---|---|
| Public contract | CodeBlock and CodeBlockProps are exported from @astryxdesign/core/CodeBlock; code is required, and the remaining released props configure language, header, line presentation, copy, wrapping, sizing, syntax theme, and collapse behavior; isDiff (FR9) adds the diff layer as a caller choice over any language; endContent (FR10) places caller controls beside Copy; language takes a built-in identifier or a language value, each less common language is its own module at @astryxdesign/core/CodeBlock/languages/<path>, and createCodeLanguage makes a custom one from a tokenize function (FR13); tokenizer is deprecated. |
| Behavior | CodeBlock renders a read-only code surface, applies syntax highlighting when available, preserves the source string for copy, and exposes optional line, header, copy, caller-control, theme, and disclosure behavior without editing the content; no control covers the code, and a one-line block with no header (no title, language label hidden) reads as one row (FR11). The copy glyph resolves through the code-block-copy component icon slot with the copied state (FR15). |
| End-user impact | Readers can inspect and copy code, understand optional line emphasis, and operate long or collapsible examples with keyboard and assistive technology. Readers of a block with no header never have code under a control, at the cost of the controls' column width, and a one-line command whose label is hidden reads as one row with its controls beside it; product actions sit beside Copy instead of outside the block. Readers of C, C++, SQL, Rust, Kotlin, Swift, and Go snippets see them highlighted instead of plain (FR12), and so do readers of GraphQL, Java, Thrift, Objective-C, TOML, PowerShell, Ruby, Lua, and Dockerfile snippets wherever the product passes that language's module (FR13). |
| Builder impact | Builders choose the released display axes without an additional migration or opt-in; the diff layer is one more opt-in axis, endContent (FR10) is one optional slot for their own controls, a less common language is one import passed as language (FR13), and five defaulted syntax-theme slots mean no syntax theme has to change for it. |
| Compatibility/readiness | The released CodeBlock API remains stable except that tokenizer is deprecated in favour of a custom language value (FR13), and its defaults hold except for the visible headerless layout (FR11) and the newly built-in languages (FR12) in Compatibility below; FR10 (endContent, additive) and FR11 are current and await implementation; FR12 (built-in languages), FR13 (language values, additive apart from the tokenizer deprecation), and PR4 (their budget) are current and await implementation; FR9 (the diff layer) is current and shipped; Markdown's default path for diff fences follows it (component:Markdown FR29). FR15 (the copy icon slot, additive) is current and awaits implementation. |
| Review checks | Reject lost code text, copy of a transformed string, an unnamed copy or disclosure control, stale disclosure state/wiring, dropped root props/ref, a theme target off its painter, viewport focusability that ignores effective overflow, a control painted over the code, or caller controls that toggle the disclosure. |
| Governing rules | architecture:public-component-api/INV1,INV5–INV9; architecture:component-theming-surface/INV3–INV7,INV12; architecture:component-test-sufficiency/INV1–INV7,INV10–INV11; spec:AST-025/FR12–FR13; architecture:theme-tokens (syntax vocabulary and the diff slot defaults); architecture:icon-resolution-and-component-slots/INV2,INV4–INV8 (the copy icon slot). |
This table is a review projection; the body below is authoritative only after owner approval.
Intent
Present read-only, standalone or multi-line code with optional syntax, navigation aids, copy behavior, bounded scrolling, and collapsible disclosure while preserving the caller's source string.
Compatibility and migration
- Released default preserved: yes, except the visible headerless layout (FR11) and the newly built-in languages (FR12), below
- Compatibility class: compatible;
tokenizeris deprecated, not removed, so no prop, export, type, default, target, or ref migration is required yet - Controlled/uncontrolled behavior: collapse state remains component-owned, starts expanded when applicable, and returns to expanded when its control disappears
- Visible default change (FR11), not breaking: a block with no header shows its controls in their own column beside the code instead of over it, so its code ends that much earlier, a block sized to its content (
fit-content) grows by the column's width, and a one-line block reads as one row. A block with a title or a visible language label keeps its header at every line count. Markdown fences with no language take it through the default code path (component:Markdown). No prop, type, or target migration follows from it. - Visible default change (FR12), not breaking: blocks and Markdown fences in the newly built-in languages are highlighted instead of plain, and the exported
tokenize,tokenizeAsync, andtokenizeStreamingfunctions, with the RichText code blocks and editors that call them, return tokens for those identifiers; text, copy output, labels, and a customtokenizerare unchanged, and the built-in tokenizer grows within the PR4 budget. Markdown fences reach these identifiers by their leading word characters (component:MarkdownFR29): acppfence highlights as C++, while ac++fence reads asc. - Additive API (FR13):
languagealso accepts a language module, each module has its own subpath under@astryxdesign/core/CodeBlock/languages/, and the exportedtokenize,tokenizeAsync, andtokenizeStreamingaccept a module wherever they accept a language identifier; nothing changes until a product imports a module and passes it. - Additive API (FR14), current state, not owner-reviewed:
startLineNumbersets the first line's number in the source file; its default of 1 keeps the released gutter andhighlightLinesmeaning - Deprecation (FR13): the released
tokenizerprop is deprecated and still works exactly as released; a staged codemod rewritestokenizer={fn}beside a staticlanguage="x"other thanplaintexttolanguage={createCodeLanguage({name: 'x', identifiers: ['x'], tokenize: fn})}, which keepsdata-language="x"and thexlabel, and reports every use it cannot prove (a dynamic or missing language,plaintext, a spread); the prop is removed only at a minor release. - Additive theme surface (FR15): a theme may map the copy glyph through
componentIcons['code-block-copy']; with no entry, the glyph is unchanged. - Migration decision: deprecate
tokenizerin favour of a custom language value; no change is required until its removal
Consumer migration instructions belong in consumer docs and release notes.
Ownership boundary
Owns
Read-only multi-line code presentation, built-in and custom token rendering, line numbers and emphasis, header/title/language presentation, copy behavior and feedback, optional wrapping and bounded scrolling, optional collapse behavior, syntax-theme composition, root prop/ref composition, and the documented CodeBlock theme targets.
The language value: what a
CodeLanguagecarries, the per-language modules under@astryxdesign/core/CodeBlock/languages/<path>,createCodeLanguage, and how each Astryx surface that colours code with CodeBlock's tokenizer accepts one, including LabDiffViewer'slanguageandcodeLanguages(FR13).
Does not own / non-goals
- Inline code inside prose — owned by
component:Code. - The meaning, localization, or bidirectional ordering of caller-supplied code and language identifiers — owned by the product callsite and platform text engine.
- Shared effective-scroll measurement and focus policy — owned by
spec:AST-025; CodeBlock integrates that capability rather than defining a parallel detector. - Editing, selection models, validation, execution, or persistence of code — owned by another component or the product callsite.
Public concepts
| Concept | Closed values or states | Meaning | Availability | Default | Owner | Stability | Invalid-value behavior |
|---|---|---|---|---|---|---|---|
| code content | caller-supplied string | Supplies the exact read-only source that is displayed and copied. | Every render | required | product callsite | stable | rejected by the public type |
| language | built-in identifier (FR12), language value (FR13: an Astryx module or a custom language), or plaintext/unknown | Selects tokenization and the optional visible/accessible language label. | Every render | plaintext |
component:CodeBlock | stable | an identifier with no built-in grammar renders without tokens unless the deprecated custom tokenizer paints it |
| line presentation | numbers off/on; highlights absent or one-indexed line set; wrapped/unwrapped | Adds navigation and emphasis without changing the copied source string. | Code body | off/absent | component:CodeBlock | stable | out-of-range highlights have no rendered line |
| diff layer | off; on — each line classified by its first character: + added, - removed, header (@@; a --- /+++ pair directly before an @@), else context |
Tints added and removed rows and quiets header rows from the syntax theme while the rest of every line keeps the base language's syntax paint; the glyph stays in display and copy. | Code body, any language |
off | product callsite | stable | rejected by the public type (boolean) |
| header | absent; title; language label; title and language label | Gives the snippet context and houses the caller controls and copy when it exists. | Derived from title and label choices | derived | component:CodeBlock | stable | empty visible content still requires AT naming |
| copy | hidden; available; transient copied feedback; transient failure feedback | Copies the exact code string, then invokes onCopy only after a successful clipboard write; a failed write shows the failure feedback instead (FR2). |
Every render when enabled | available | component:CodeBlock | stable | failed clipboard writes do not invoke onCopy |
copy failure callback (onCopyError) |
absent; (error: unknown) => void |
Receives the clipboard rejection once per failed write, so the product can log or recover; the control shows and announces the failure itself (FR2). Owner decision, Nov 6 2026 (Cindy). | Every render when copy is enabled | absent | component:CodeBlock | stable | TypeScript rejects other values; a successful write never calls it |
caller controls (endContent) |
absent; caller-rendered nodes | Places product actions beside Copy, before it in reading order, in the header or the corner cluster; never creates the header. | Every render | absent | product callsite | stable | any React node; CodeBlock does not inspect it |
| corner cluster | absent; caller controls and copy, in that order | Holds the controls of a block with no header in their own inline-end column beside the code, centred on the first line. | Blocks with no header and any control | derived | component:CodeBlock | stable | an empty cluster takes no column |
| syntax rendering | auto; CSS ranges; spans; deprecated custom tokenizer; optional per-instance syntax theme | Selects a supported paint path without changing the text or public code semantics. | Every render | auto |
component:CodeBlock | stable | unsupported range capability falls back to spans |
| collapse | unavailable; expanded; collapsed | Turns an eligible visible header into a disclosure when the line threshold is met. | Long blocks with a header and collapse enabled | unavailable | component:CodeBlock | stable | missing-header or below-threshold blocks remain expanded and ordinary |
| container geometry | card/section; small/medium; fit-content/custom width; unbounded/bounded height | Selects presentation and overflow geometry while preserving the read-only code task. | Every render | card/md | component:CodeBlock | stable | values follow their documented CSS/type behavior |
Behavioral and layout contract
| ID | Candidate invariant | Basis | Draft review state |
|---|---|---|---|
| FR1 | CodeBlock MUST display the caller's code string as read-only code. Built-in or custom tokenization MAY change syntax paint but MUST NOT change displayed or copied source text. | released types, source, tests, consumer docs; established public interface | verify |
| FR2 | A successful copy MUST write the exact code string, invoke onCopy once, expose localized copied feedback, and preserve the copy control's discoverable purpose. A failed write MUST NOT report success: it shows a cross icon in place of the copy icon and names and announces the control as the localized "Failed to copy value to clipboard." for as long as the copied feedback would show, and calls onCopyError once with the rejection; the error detail is not exposed (Owner decision, Nov 6 2026 (Cindy)). |
shipped source/tests; architecture:component-test-sufficiency/INV2–INV6; WCAG name/status obligations |
verify |
| FR3 | A title or visible non-plaintext language label MUST create the visible header, at every line count. Hiding the language label MUST NOT remove copy behavior. Headerless copy remains available when enabled. endContent never creates the header. |
released types, source, tests, consumer docs; established public interface; proposal for endContent |
verify |
| FR4 | Line numbers, highlighted lines, wrapping, width, container presentation, size, and maximum height MUST affect only their documented presentation axes. Numeric maxHeight={0} MUST remain a valid zero-pixel bound rather than being discarded. |
released public type/docs; architecture:public-component-api/INV3,INV9; objective JavaScript nullish semantics |
verified by focused regression |
| FR5 | Collapse MUST become available only when enabled, a visible header exists, and the line threshold is met. The control MUST expose expanded state and a resolvable controlled region; collapsed content remains mounted but inert, and losing the control expands the region before hiding the control. | shipped docs/source/tests; WAI-ARIA disclosure pattern and HTML inert semantics |
verify |
| FR6 | The root and documented header/title/copy targets MUST remain on their visible painters, reflect the documented visual axes, and continue emitting the approved deprecated aliases until their authorized removal window. | architecture:component-theming-surface/INV3–INV7,INV12; source/docs/tests |
verify |
| FR7 | Supported DOM, data, ARIA, class, style, and xstyle inputs MUST compose on the documented root, and the public ref MUST reach that root. |
architecture:public-component-api/INV5,INV6,INV8; shipped source |
verify |
| FR8 | The code viewport MUST enter sequential keyboard navigation only while at least one applicable axis effectively overflows; losing overflow MUST NOT move current focus. It retains an appropriate role and accessible name while focusable. | spec:AST-025/FR12–FR13 |
settled by current authority |
| FR9 | With the diff layer on (isDiff), CodeBlock MUST classify each line by its first character — + added, - removed, @@ header, anything else context — except that a --- line (three minus signs and a space, the unified-diff file header form) directly followed by a +++ line and then an @@ line is a file header (both lines), wherever it occurs; every other ---/+++ line, ---i; included, is removed or added. CodeBlock MUST set the glyph column aside and tokenize the REST of every line (context, added, and removed alike) with the base language's syntax highlighting. Added, removed, and header lines MUST paint as whole rows — the line-number gutter cell included — from the syntax-theme slots --color-syntax-added, --color-syntax-removed, and --color-syntax-diff-header, whose defaults architecture:theme-tokens owns; header rows take the syntax theme's punctuation colour as text (--color-text-secondary in the default theme) and never change paint; context rows keep ordinary paint. On an added or removed row, the line number and the glyph take the row's marker slot — --color-syntax-added-marker / --color-syntax-removed-marker — so the margin reads the change in colour; every run of code text, painted by a token or not, keeps its syntax-theme colour. In the Astryx default syntax theme the marker slots default to the theme's tinted-text tokens and the header paint to the muted background (architecture:theme-tokens owns the values); a syntax theme that does not set them inherits its own colours — the marker slots and the header text its line-number colour (its punctuation slot), the header paint none at all (the header row sits on the theme's own syntax background) — so number, glyph, and header text stay legible on that theme's background in every page mode, and the glyph's shape carries the meaning where its colour does not. The glyph (+, -, the leading space of a context line, or nothing for a context or header line without one — the marker column is then empty and the whole line is code) MUST render in its own fixed-width marker column — secondary colour on context rows and the row's marker slot on added and removed rows, separated from the code by a token gap (--spacing-2, a proportion themes may vary like the rest), excluded from selection for layout yet present in the copied text — so the code column starts at the same inline offset on every line and the content's own indentation is never shifted; the gutter order is line number, marker, code, mirrored in RTL with the code's direction unchanged. The header (language label, copy, disclosure) and the viewport's name stay as for any other code: with the layer over plaintext the visible language label and the viewport name are diff, and over a language they name both (tsx diff). Markdown's fence mapping onto the layer is component:Markdown FR29. Row paint MUST compose with line numbers without moving text; on a highlighted added, removed, or header line the highlight REPLACES the row paint rather than stacking on it, so text keeps its single-paint contrast; and row paint MUST span the full line width — the scrolled overflow of a long line included, in wrapped and unwrapped mode — not only the visible viewport. Contrast floor: in the Astryx default syntax theme, every default token colour and the row's marker slot (line number and glyph) on a painted row MUST measure ≥ 4.5:1 against the default tints composited over the code block's own --color-syntax-background on the default card surface. In a syntax theme that overrides a diff slot, a token that already measures under 4.5:1 on that theme's own syntax background MUST NOT drop further on the slot, and every other token MUST clear 4.5:1 on it. Two known shortfalls, tracked separately: the shipped syntax presets do not yet meet the floor on the default tints with the layer on, and shipped page themes whose own text tokens fall under it on the tints keep that shortfall, tracked for a fix in those themes, until each sets its tokens or the diff slots. |
this record DEC-1 | current; owner-approved 2026-10-12 |
| FR10 | endContent MUST render the caller's nodes beside Copy and before it in reading order: in the header when one exists, otherwise in the corner cluster (FR11); without Copy it keeps that place. It MUST sit outside the disclosure control, and pointer or keyboard activation inside it MUST NOT toggle collapse. CodeBlock MUST NOT name, restyle, or announce its content; the caller owns each control's name, state, and action. |
proposal; the end-content slot of the Dialog and Drawer headers | verify |
| FR11 | With no header, the corner cluster MUST occupy its own inline-end column beside the code viewport, as wide as its content and never over the viewport, so that no line, at rest, scrolled, wrapped, or in either direction, is painted under a control; the cluster MUST be centred on the first line of code. A headerless block whose code is one line — counted after removing one trailing newline — therefore reads as one row: code, then the controls, with even space above and below; the single-line mode a caller gets by leaving out the title and passing hasLanguageLabel={false}. When the code gains lines, the block grows downward and the controls keep their place. A visible language label or a title keeps the header at every line count (FR3). The column paints from the code-block root, so no theme target is added. |
the Code Body and Copy Button design relationships; proposal | verify |
| FR12 | Without the deprecated tokenizer, given a built-in identifier, CodeBlock MUST paint syntax for these built-in identifiers and their aliases: typescript/ts, javascript/js, tsx, jsx; json; html, xml, svg; css, scss, less; python/py; bash, sh, zsh, shell; php; hack; yaml/yml; markdown/md; c, h; cpp, c++, cc, cxx, hpp, hh; sql; rust/rs; kotlin, kt, kts; swift; go/golang. Each built-in paints the comment, string, number, and keyword tokens its language has from the syntax theme. Any other identifier renders as plain code with its label unless the deprecated tokenizer paints it; an identifier string never resolves to a language value. |
proposal | verify |
| FR13 | Each less common language MUST be its own module, one per subpath, each exporting one language value: graphql (graphql, gql), java (java), thrift (thrift), objectiveC (objective-c, objc, m, mm), toml (toml), powershell (powershell, ps1, pwsh), ruby (ruby, rb), lua (lua), and dockerfile (dockerfile, docker), at @astryxdesign/core/CodeBlock/languages/<path>, where <path> is the export's name in kebab case (languages/graphql exports graphql, languages/objective-c exports objectiveC). A language value is a CodeLanguage carrying everything needed to render that language: read-only name (the identifier its label shows, such as graphql: code text shown verbatim like a built-in identifier, never translated prose, so it needs no catalog entry), identifiers, fileExtensions, and fileNames (for example graphql, or Dockerfile), all required, and its grammar, which stays internal. language MUST accept a language value as well as an identifier string: given one, CodeBlock paints the code with that language, labels it with its name, and reflects its first identifier wherever it reflects the language, such as data-language on its theme targets (FR6), in the same render as a built-in would; a string selects only a built-in grammar (FR12). There is no provider, registry, or grouped export: each module is imported and passed on its own, and only modules a bundle imports reach it. A custom language is the same kind of value: createCodeLanguage({name, identifiers, fileExtensions, fileNames, tokenize}), exported from @astryxdesign/core/CodeBlock, makes one from a caller's tokenize(code, language) function returning {type, start, end} tokens, which runs synchronously; fileExtensions and fileNames default to none. It is passed and listed exactly like an Astryx module, and Astryx modules keep their grammar internal. In a codeLanguages list, a listed value takes precedence over a built-in with the same identifier, and a later entry over an earlier one. The released tokenizer prop is deprecated and still works exactly as released, taking precedence over the language's grammar; it is removed only at a minor release, and a codemod rewrites a block whose language is a static string literal other than plaintext to a custom language passed as language, whose first identifier is that string, and reports every other use it cannot rewrite. The exported tokenize, tokenizeAsync, and tokenizeStreaming MUST accept a language value wherever they accept a language identifier. A surface that sees only a fence's language word takes modules through its own prop: Markdown's codeLanguages (component:Markdown FR30) and RichText's (spec:AST-061). Lab's DiffViewer takes a language value as its language the same way; without one it infers a file's language from the file's extension or name among the built-ins and the values in its own codeLanguages, and an unmatched file stays plain. It tokenizes each hunk's old and new side as continuous text with whichever grammar applies, and its line-number gutters and change marks are unaffected. Modules are opaque values: CodeBlock exposes no grammar format. The module is the portable form of a language (spec:AST-082/FR3): a platform CodeBlock takes the same kind of value for its language. A language value's brand is read through a registered key, and its type carries one optional phantom member typed never, so the package's language values and a swizzled copy's match (spec:AST-110 FR3); the member is never present at runtime and the value stays opaque. |
proposal | verify |
| FR14 | Current state, not owner-reviewed. startLineNumber (default 1) MUST set the number of the first line in the source file. The gutter MUST show file coordinates (startLineNumber + index), so an excerpt reads with its real line numbers. A value below 1 MUST clamp to 1. highlightLines MUST use the same file coordinates, and an out-of-range entry MUST render no highlight. The offset MUST NOT change the displayed or copied source text (FR1). |
released public type and JSDoc; shipped API | verify |
| FR15 | The copy control's glyph MUST resolve through the code-block-copy component icon slot, passing {copied}, which is true while the copied feedback (FR2) shows. With no theme entry, the glyph is copy, check while copied, and a cross while a failed write shows (FR2), when {copied} is false. When the slot resolves to no icon (a theme value of null, a slot function that returns null, or a request with icon: null), only the glyph is hidden: the control keeps its size, name, tooltip, and copy behavior, and shows no glyph at rest or while copied. A request size changes only the glyph, never the control. |
proposal; architecture:icon-resolution-and-component-slots/INV2,INV4–INV8 |
verify |
Allowed variation
- AV1 — Syntax paint. Built-in token colors, custom token types, CSS Highlight API use, span fallback, and syntax themes may vary paint without changing the source string or code task. Diff row tints are three syntax-theme slots like any other syntax paint: a syntax theme may harmonize them with its palette, and a theme that sets none keeps the defaults.
- AV2 — Theme paint. Current CodeBlock targets may vary their accepted visual properties without changing text, control semantics, or ownership.
- AV3 — Code content. The product supplies arbitrary code text and the matching language identifier; CodeBlock does not interpret the program's meaning.
Representative states
| State | Required invariant | Allowed variation |
|---|---|---|
| plaintext/headerless | Exact source text; localized code viewport name; corner cluster beside the code, never over it. | Caller code and container geometry. |
| one-line row | With no header (no title, hasLanguageLabel={false}): one row: code, then the controls, centred with even space; more lines grow downward and the controls stay put. |
Code and caller controls. |
| titled highlighted code | Header context, optional line numbers/highlights, exact copy string. | Language, title, size, and theme paint. |
| wrapped or height-bounded | Content remains readable and copy preserves the source; keyboard focus follows effective overflow. | Width, height, line count, and writing mode. |
| collapsible expanded/collapsed | Named disclosure, correct expanded state, resolvable controlled region, inert only while collapsed. | Title/language content and theme paint. |
| custom syntax path | Tokens may change paint but not source text or copy output. | Token types, rendering mode, and syntax theme. |
Transformation and precedence order
- ORD1 — Source. Caller code string → line partition → built-in or custom tokenization → range/span paint; copy always consumes the original code string.
- ORD2 — Header. Title and eligible language label determine header presence (FR3); caller controls and then copy are placed in that header when present and in the corner cluster beside the code when absent.
- ORD3 — Styling. Root theme target and reflected visual axes → base/container/size/dynamic styles → consumer
xstyle, class, and inline-style composition.
Performance and resources
- PR1 — Tokenization. Short code may tokenize synchronously; long built-in code yields through the async tokenizer and cancels stale work when code or language changes.
- PR2 — Highlight lifetime. Range-mode highlighting removes ranges and visibility listeners when its rendered token set changes or unmounts.
- PR3 — Large line sets. Large blocks may chunk line rendering and use content visibility, without losing source order or line identity.
- PR4 — Language budget. The built-in tokenizer, every FR12 grammar included, stays within 4,608 bytes minified and gzipped, and each FR13 module adds at most 512 bytes minified and gzipped to a bundle that imports it, and nothing to one that does not; nothing loads at run time, so short code paints in its first render (PR1) and no block waits on the network.
Accessibility contract
- AR1 — Named controls. Every rendered copy and disclosure control has a non-empty accessible name, including when title text is empty or whitespace-only.
- AR2 — Disclosure. The collapsible header exposes expanded state and its controlled region, toggles with pointer, Enter, and Space, and makes collapsed descendants inert without removing the controlled region.
- AR3 — Copy feedback. Copy success updates the control name and emits one localized polite announcement; a failed write emits one localized assertive announcement, because it is an error (
spec:AST-086FR5); the visible purpose remains available through the tooltip. - AR4 — Scroll access. A named viewport enters the tab order only for effective overflow and retains native Arrow/Page access, per
spec:AST-025/FR12–FR13.
Design relationships
| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
|---|---|---|---|---|
| Header Bar | Provides supporting file/language context and houses the optional disclosure, caller controls, and copy. | observed shipped representation | supporting context | FR3, FR5, FR10, AR1–AR3 |
| Header Title | Groups the visible title, language label, and disclosure indicator inside the header. | observed shipped representation | supporting context | FR3, FR5, AR1–AR2 |
| Line Numbers | Support code navigation without becoming part of copied source. | observed shipped representation | supporting metadata | FR1, FR4 |
| Code Body | Keeps code text dominant, readable, scrollable or wrappable, and syntax-themed. | observed shipped representation | primary content | FR1, FR4, FR8 |
| Highlighted Lines | Add optional emphasis without replacing or mutating the source string. | observed shipped representation | supporting emphasis | FR1, FR4 |
| Copy Button | Exposes the code-copy action and transient success feedback without toggling the disclosure; with no header it sits with the caller controls in the corner cluster beside the code, never over it. | objective interaction semantics | secondary action | FR2, FR11, FR15, AR1–AR3 |
Exact CodeBlock proportions and syntax colors are not contract requirements; they remain within the syntax-paint and theme-paint variation allowed above.
Theming anatomy
{
"Header Bar": {"target": "code-block-header"},
"Header Title": {"target": "code-block-title"},
"Line Numbers": {"inherits": "code-block"},
"Code Body": {"target": "code-block"},
"Highlighted Lines": {"inherits": "code-block"},
"Copy Button": {"target": "code-block-copy-button"}
}
Family and system relationships
architecture:public-component-apiowns export reachability, accepted root props, styling composition, ref reachability, released defaults, and consumer documentation.architecture:component-theming-surfaceowns target qualification, target placement, visual-axis reflection, anatomy disposition, and deprecated target-alias compatibility.architecture:component-test-sufficiencyowns rational evidence partitions and mutation-sensitive proof for the component's established public interfaces and objective standards.spec:AST-025owns effective overflow measurement, scroll focus, naming, chaining, and focus stability. CodeBlock owns its viewport/content structure and integrates that shared behavior.
Verification map
| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
|---|---|---|---|---|
| FR1, PR1–PR3 | tokenizer.test.ts; highlightRanges.test.ts; CodeBlock focused tests and built Storybook |
short/long, built-in/custom, ranges/spans, empty lines | Text changes, stale tokens paint, ranges leak, source order changes, or long work stops yielding/canceling. | audit:CodeBlock/behavior |
| FR12, FR13, PR4 | tokenizer.test.ts (one representative snippet per built-in family and alias, and per module: the comment, string, number, and keyword tokens each language has; an unknown identifier yields no tokens, and a module's identifier passed as a string yields none); CodeBlock, Markdown, RichText, and Lab DiffViewer tests (a module passed as language, or listed in codeLanguages, paints and labels; DiffViewer infers a listed module from a file's extension or name; the same identifier or file without it stays plain; a custom language from createCodeLanguage paints, labels, and infers like a module; a listed value beats a built-in with the same identifier; the deprecated tokenizer still wins over a built-in identifier and a language value and still works as released; a language value reflects its first identifier as data-language; the codemod rewrites static non-plaintext uses, keeps their data-language and label, and reports the rest; server rendering paints in the first render); a size check over the minified, gzipped tokenizer and each module, and a bundle check that an unimported module adds nothing |
every FR12 identifier and alias, every FR13 module passed as language and in codeLanguages, a diffed file named by a module's extension or file name, a module identifier as a plain string, a custom language passed and listed, a custom language reusing a built-in identifier, the deprecated tokenizer alone, with a built-in identifier, and with a language value, an unknown identifier, an empty string |
A listed identifier renders without tokens, an alias paints differently from its family, a string resolves to a module, a module fails to paint or label on any of the four surfaces, a diffed file infers a module that was not listed, a custom language behaves differently from a module, a listed value loses to a built-in, the deprecated tokenizer stops working or loses to a language value, a language value reflects anything but its first identifier, the codemod rewrites a use it cannot prove or drops one silently, source text changes, the tokenizer exceeds 4,608 bytes, a module adds more than 512 bytes, or an unimported module reaches the bundle. |
audit:CodeBlock/behavior |
| FR2, AR1, AR3 | CodeBlock.test.tsx; component-scoped accessibility audit; the failed-write suite (a rejected writeText: cross icon, failure name, tooltip and announcement, onCopyError once with the rejection and no onCopy, the same 2 s reset, a later success clears it) |
copy success, rapid repeat, localized feedback, empty title | Exact source is not copied, callback fires on failure, announcement is absent/duplicated, or a control is unnamed. | audit:CodeBlock/a11y |
| FR3–FR5, AR2 | CodeBlock.test.tsx; CodeBlock.stories.tsx; exact-head browser evidence |
headerless, titled, zero max height, line options, collapse/control removal | Header/copy placement changes, zero is dropped, disclosure state/wiring/keyboard behavior breaks, or inert outlives its control. | audit:CodeBlock/behavior |
| FR6 | themingTargets.test.ts; consumer docs; source review |
root, header, title, copy; current and deprecated names | A target leaves its painter, an axis stops reflecting, or a deprecated alias disappears before authorization. | audit:CodeBlock/theming |
| FR7 | focused root-prop/ref tests; strict lint/typecheck; consumer-doc validation | ref plus supported root/style/data/ARIA inputs | The ref misses the root, accepted props disappear, or styling inputs replace rather than compose. | audit:CodeBlock/api |
| FR8, AR4 | spec:AST-025 integration evidence plus real-browser fit/overflow/focus transitions |
fitting, inline overflow, block overflow, losing overflow | A fitting viewport adds a stop, overflow is unreachable, naming disappears, or focus moves when overflow ends. | audit:CodeBlock/a11y |
| FR9 | tokenizer.test.ts (diff line classes; file-header pair rule; base-language tokens past the glyph); CodeBlock.test.tsx (row attributes, marker column, copy string incl. glyphs, highlightLines, header kept with the diff / tsx diff label and viewport name); syntax-theme tests (five slot defaults and overrides; a preset without marker or header slots takes punctuation text and no header paint); exact-head browser evidence incl. every default syntax token colour and the row marker slot (line number and glyph) measured ≥ 4.5:1 on painted rows in light and dark against the code block's own --color-syntax-background on the default card surface (the two known shortfalls in FR9 excepted) (on the light page background the surface is translucent and a plain row's default keyword already sits under the floor — a pre-existing shortfall that affects every CodeBlock there, tracked separately), and equal code-column x-offsets for context, added, and removed lines |
added/removed/header/context over tsx and over plaintext; a removed line starting with --; ---i; / +++i; right before an @@ (removed/added, not header); a --- /+++ pair with no @@ after it (removed/added); a --- /+++ /@@ file header after an earlier hunk (header); the layer over plaintext (label and viewport name diff) and over tsx (tsx diff); a context line with no leading space; a line longer than the viewport, scrolled (tint to the full scroll width) and wrapped; with highlightLines on an added line and on a header line (highlight paint only, text measured on it); with line numbers (gutter cell tinted, number in the row's marker slot); plain and token-painted text on a changed row keeping their syntax colours; light and dark (contrast measured on each); a custom syntax theme overriding the slots; indented code under all three line kinds; RTL (gutter mirrored, code direction unchanged) |
A glyph removed from display or copy, a changed line's code starting at a different offset than its neighbours, a header row painted as a change or hidden, a header's text or paint taken from the page theme under a defined syntax theme, a ---prefixed removed line painted as a header, syntax paint lost past the glyph, a tint from anywhere but the three row slots, a gutter cell left untinted, a line number or glyph left in the ordinary colour on a changed row, code text recoloured by the row, a tint that stops at the viewport edge of a scrolled line, the header, collapse control, or viewport name lost on a diff, a ---i; line painted as a header, or a default token or marker on a painted row under 4.5:1 on the default surface, or an override on which a token that clears 4.5:1 on the theme's own background falls under it or an already-short token drops further |
audit:CodeBlock/a11y |
| FR10 | CodeBlock.test.tsx (before Copy in the header and in the corner cluster, outside the disclosure control, pointer and Enter/Space inside it do not toggle, no header created, kept in place without Copy); exact-head browser evidence |
header and headerless, with and without Copy, collapsible, LTR and RTL | A caller control toggles collapse, sits inside the disclosure or after Copy, creates a header, or is renamed or restyled by CodeBlock. | audit:CodeBlock/behavior |
| FR11 | real-browser geometry evidence over built stories | a long first line at rest, scrolled to its end, and wrapped; a one-line headerless block with and without caller controls; a one-line block with a visible label (keeps its header); one line growing to several; both sizes; LTR and RTL; light and dark | Any control box overlaps the code viewport, the cluster leaves the first line's centre, a one-line headerless block's space above and below differs, a block with a visible label or title loses its header, or the controls move when lines are added. | audit:CodeBlock/behavior |
| FR14 | Current state, not owner-reviewed. CodeBlock.startLineNumber.test.tsx (gutter from 1 by default; file coordinates from startLineNumber; highlightLines in file coordinates; a value below 1 clamps to 1; out-of-range highlights render nothing; copy stays exact) |
default; a three-line excerpt starting at line 40; a value of 0; a highlight inside the excerpt (42) and entries outside it (1, 2, 39, 43, 100) | The gutter starts at 1 when startLineNumber is set, a highlight lands on the excerpt index instead of the file line, a value below 1 shows a number below 1, or copy includes gutter numbers. |
audit:CodeBlock/behavior |
| FR15 | CodeBlock.test.tsx copy icon slot suite; a slot inventory test that each declared slot is rendered by its component and listed in its consumer docs; theme-build parity between a built and a runtime theme |
no entry, a mapped name, a slot function in both states, a function that returns undefined for one state, null, a size request, an unknown name |
The glyph ignores the slot or its state, null removes the control, its name, or its copy action, a size request resizes the button, an unknown name loses the fallback, or the consumer docs do not list the slot. |
audit:CodeBlock/theming |
| RTL | rtl:audit -- --filter CodeBlock D2 target plus exact-head browser evidence |
title, caller controls, and copy order, and the corner cluster at the inline end, in LTR/RTL | Logical order fails to mirror or physical placement leaks. | audit:CodeBlock/rtl |
| Consumer metadata | CLI component CodeBlock --json; docs typecheck; prop/target validation; package-export checks |
released props/defaults/ref and current/deprecated targets | A released prop/default/ref/target disappears from consumer discovery or docs name an unsupported value. | audit:CodeBlock/docs |
Decision log
DEC-1 — Diff is a line layer over any language, tinted by three defaulted syntax-theme slots
Decider: cixzhang, 2026-10-12
A reader of a changelog, migration note, or review comment sees what was added and what was removed at a glance, and still reads the code as code: with the diff layer on, the leading +/- column is set aside and the rest of every line keeps the base language's syntax highlighting, so a tsx diff looks like tsx with two kinds of tinted rows. The tints are syntax paint, so they live in the syntax theme as --color-syntax-added, --color-syntax-removed, and --color-syntax-diff-header, with the margin colours beside them as --color-syntax-added-marker and --color-syntax-removed-marker, all with defaults architecture:theme-tokens owns; the gutter cell, line number, and glyph share the row's hue because a reader scanning the margin should find the change there, while the code — every token and every plain run — keeps the syntax theme's colours so a property or identifier reads the same on a changed row as on a context row; a theme may override them to sit with its own palette. No single default strength keeps every shipped preset's passing tokens above the floor on the tints while the tint stays visible — a dark preset under a light page theme receives a pale tint — so the floor binds the default theme and overriding themes, and the presets' shortfall is known and tracked separately. Hunk and file headers stay visible as quiet rows in the syntax theme's own secondary (punctuation) colour — on the muted band in the default theme, on the theme's own background in a defined theme — the treatment the common diff renderers give them — because a fence is the author's exact text: paint never changes it (FR1) and copy round-trips it; an author who wants no headers leaves them out of the fence. A --- line (with its space) is a file header only directly before a +++ line and an @@ line, so a removed line that starts with -- — ---i; right before the next hunk included — is not misread, and a multi-file diff keeps every file header; the one shape the rule cannot tell apart is a removed -- line directly followed by an added ++ line and a hunk header, which reads as a file header and is accepted. A Markdown fence selects the layer by its info string on the default path only, so a custom renderer's contract stays unchanged. The +/- glyph sits in its own marker column with a token gap before the code, so a reader's eye finds the change at the margin and the code's indentation reads exactly as written. On a tinted row the glyph and the line number take the row's marker slot, because the glyph is the cue a reader without colour depends on and it reads with the code it marks; in the default theme the marker slots default to the theme's own tinted-text tokens, which are made to sit on tinted surfaces, and a syntax theme that does not set them keeps its own colours — its line-number colour for the markers and the header text, and no header paint — rather than borrowing the page theme's tokens, which could sit on the wrong polarity under a dark preset on a light page. Rejected: deriving the marker colours from the theme's string and tag tokens (a theme whose tag is green would mark removed rows green); recolouring the code itself to the row hue, all of it or only the runs no token paints (it changes what a property or identifier looks like between rows). A light tint of plain code toward the row hue is not adopted. Text keeps its syntax colours — the semantic text colours fall under the floor on their tints — and the glyphs stay in the text so the change reads without colour and copies exactly. The Markdown fence mapping is Markdown's own fact (its FR29); this record owns only the layer.
A per-line typed wash (an added/removed flavour of highlightLines) is not decided here: the layer answers the need with the diff text itself. On a highlighted changed line the highlight replaces the tint because two translucent paints would compound into a colour no theme chose and push tokens under the floor. Rejected: hiding header lines (paint would change the displayed text and break copy; authors omit headers by omitting them from the fence); diff as a standalone language (every line falls to plaintext, so the code stops reading as code); tinting from the semantic tokens alone with no syntax slots (a custom syntax theme could not harmonize the rows with its palette); colouring the changed text with --color-success/--color-error (below the 4.5:1 text minimum on the tinted rows); per-language diff-<lang> identifiers in the component API (they multiply the language list; the fence convention maps to the prop instead); a separate Diff component (a fence is a CodeBlock and Markdown already routes fences there).
DEC-2 — Product actions are one caller-rendered slot beside Copy
Decider: cixzhang, 2026-10-24
A product that gives a snippet a second verb, such as running a command in a terminal, needs that control in the same place a reader already finds Copy, and the system needs that without learning the product's verbs. endContent is that place: the caller renders its own controls and owns their names, states, and actions, and CodeBlock only positions them, before Copy in reading order, so Copy stays the last control at the inline end in every block. The name follows the header end-content slot of Dialog and Drawer, which carries the same meaning there. Caller controls never create a header, because a header exists to carry the snippet's context, and a block without context keeps its controls in the corner cluster. Rejected: a declared list of {label, icon, onClick} actions (CodeBlock would render controls it does not own); a prop per product verb.
DEC-3 — Controls take their own column, so a headerless one-line block is one row
Decider: cixzhang, 2026-10-24
A control painted over code hides the reader's text, so a headerless block's controls sit in their own inline-end column beside the code viewport, as wide as the controls themselves; the column runs the block's full height because a scroll box clips its lines as one rectangle. Centring the column on the first line makes a headerless one-line block read as one row with even space and keeps the controls still while a block grows line by line, so a streamed block never moves its controls. Single-line mode is the existing choice to hide the language label: a caller that shows the label keeps the header and its context at every line count, and one that hides it gets the row. The column has no width cap; the caller supplies a few icon controls, and the code viewport takes the rest. Rejected: folding a visible label into a one-line row (the label is context the caller chose to show, and a streamed block would move its code when the label returned to a header); reserving space on the first line only (a scrolled line still runs under the control).
DEC-4 — A native language set chosen by use; every other language is its own module, passed as the language
Decider: cixzhang, 2026-10-25
A reader sees a short snippet highlighted in its first render (PR1), with no product setup, for the languages people write most: the native set is the 11 families CodeBlock already knows plus C and C++, SQL, Rust, Kotlin, Swift, and Go, which together cover about 97% of fences that name a language in a large engineering Markdown corpus, inside a 4,608-byte budget every consumer pays. Every other language is opt in one language at a time: a product imports that language's module and passes it where the language goes, as language on CodeBlock or Lab's DiffViewer, or in codeLanguages on the surfaces that only see a fence's word or a file's name, so the value that names the language also carries what renders it, and a bundle holds only the languages it imports. A language the product writes itself is the same kind of value, made from its own tokenize function, so one concept covers every language and the separate tokenizer prop is deprecated; Astryx modules stay opaque so their grammar format stays internal. Rejected: a context provider (what renders a block would depend on where it sits, not on its props); language packs or grouped exports (a product would opt into languages it never shows); every family built in (every consumer pays for the long tail); a global registry (state shared across React roots and requests); loading grammars on demand (a block would paint plain, then recolour, and wait on the network).
Open questions
None.
Content boundary
This file does not duplicate consumer prop tables/examples, syntax-token definitions, current audit scores, implementation steps, or shared scrolling/theming rules. It links to their owners.