An open source design system that's fully customizable and agent ready
TypeScript
fix(CodeBlock): the code viewport is a Tab stop only while its content overflows (#7424)
Cindy Zhanga4ed399053f6
diff --git a/.changeset/codeblock-overflow-tab-stop.md b/.changeset/codeblock-overflow-tab-stop.mdnew file mode 100644index 0000000000..4613df7874--- /dev/null+++ b/.changeset/codeblock-overflow-tab-stop.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `CodeBlock`'s code viewport is a keyboard Tab stop only while its content actually overflows, through the shared scroll capability: a short snippet no longer adds an unexplained stop to the page's Tab order, a wide or capped block still does, and a viewport that stops overflowing keeps focus where it is. Role and accessible name are unchanged.++@cixzhangdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 38e8921d07..45704aff63 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1346,6 +1346,16 @@ jobs:--project chromium \--output table-min-width-output+ # A CodeBlock viewport is a Tab stop only while its code overflows; jsdom+ # has no layout, so only a real engine shows the stop appear with a wide+ # or capped block and stay away from a short one.+ - name: Run CodeBlock overflow tab-stop contract+ run: |+ pnpm exec playwright test \+ packages/core/src/CodeBlock/__tests__/CodeBlockOverflowStop.a11y.chromium.spec.ts \+ --project chromium \+ --output codeblock-overflow-stop-output+# A DropdownMenu header and footer sit beside the menu, outside its# role="menu" element, and join one Tab sequence with it. Focus order,# the popover's focus trap, the keyboard-only ring and a finger tap on adiff --git a/apps/storybook/stories/CodeBlock.stories.tsx b/apps/storybook/stories/CodeBlock.stories.tsxindex eb0cf68eb7..3c26236828 100644--- a/apps/storybook/stories/CodeBlock.stories.tsx+++ b/apps/storybook/stories/CodeBlock.stories.tsx@@ -97,6 +97,18 @@ export const WithHighlightedLines: Story = {},};+/**+ * The code viewport is a keyboard stop only while its content overflows.+ * This story starts fitting; the browser contract widens the code and caps+ * the height to prove each state, and shrinks it again to prove focus stays.+ */+export const OverflowStop: Story = {+ args: {+ language: 'tsx',+ code: 'const fits = true;',+ },+};+export const JSON: Story = {args: {code: `{diff --git a/packages/core/src/CodeBlock/CodeBlock.spec.md b/packages/core/src/CodeBlock/CodeBlock.spec.mdindex 68a8f0ab45..8712c5581e 100644--- a/packages/core/src/CodeBlock/CodeBlock.spec.md+++ b/packages/core/src/CodeBlock/CodeBlock.spec.md@@ -39,15 +39,15 @@ system_specs: [spec:AST-025]## 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. |-| Behavior | CodeBlock renders a read-only multi-line code surface, applies syntax highlighting when available, preserves the source string for copy, and exposes optional line, header, copy, theme, and disclosure behavior without editing the content. |-| End-user impact | Readers can inspect and copy code, understand optional line emphasis, and operate long or collapsible examples with keyboard and assistive technology. |-| Builder impact | Builders choose the released display axes without an additional migration or opt-in; the diff layer is one more opt-in axis, and five defaulted syntax-theme slots mean no syntax theme has to change for it. |-| Compatibility/readiness | The released `CodeBlock` API and defaults remain stable; FR9 (the diff layer) is current and an implementation gap until its implementation ships; Markdown's default path for `diff` fences changes with it (`component:Markdown` FR29). The current implementation still gives every code viewport a keyboard stop even when it does not overflow, contrary to `spec:AST-025/FR12`; that retained implementation gap is not accepted here. |-| 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, or viewport focusability that ignores effective overflow. |-| 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). |+| 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. |+| Behavior | CodeBlock renders a read-only multi-line code surface, applies syntax highlighting when available, preserves the source string for copy, and exposes optional line, header, copy, theme, and disclosure behavior without editing the content. |+| End-user impact | Readers can inspect and copy code, understand optional line emphasis, and operate long or collapsible examples with keyboard and assistive technology. |+| Builder impact | Builders choose the released display axes without an additional migration or opt-in; the diff layer is one more opt-in axis, and five defaulted syntax-theme slots mean no syntax theme has to change for it. |+| Compatibility/readiness | The released `CodeBlock` API and defaults remain stable; FR9 (the diff layer) is current and an implementation gap until its implementation ships; Markdown's default path for `diff` fences changes with it (`component:Markdown` FR29). |+| 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, or viewport focusability that ignores effective overflow. |+| 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). |This table is a review projection; the body below is authoritative only after owner approval.@@ -102,7 +102,7 @@ Consumer migration instructions belong in consumer docs and release notes.| 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; implementation gap |+| 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; implementation gap |### Allowed variation@@ -201,7 +201,7 @@ A per-line typed wash (an added/removed flavour of `highlightLines`) is not deci## Open questions-None. The retained `spec:AST-025/FR12` integration gap has a current owner and required outcome; it is implementation work, not an unresolved product decision.+None.## Content boundarydiff --git a/packages/core/src/CodeBlock/CodeBlock.test.tsx b/packages/core/src/CodeBlock/CodeBlock.test.tsxindex 4afc8fd647..8152701d07 100644--- a/packages/core/src/CodeBlock/CodeBlock.test.tsx+++ b/packages/core/src/CodeBlock/CodeBlock.test.tsx@@ -81,17 +81,19 @@ describe('CodeBlock', () => {expect(root).toHaveStyle({opacity: '0.75'});});- it('makes the scroll container keyboard-focusable', () => {+ it('names the code viewport and gives it a tab stop only while it overflows', () => {+ // jsdom has no layout, so the viewport fits: a fitting viewport is not a+ // tab stop (AST-025 FR12); the overflowing states are browser evidence.render(<CodeBlock code="const x = 1;" language="javascript" />);const region = screen.getByRole('group');- expect(region).toHaveAttribute('tabindex', '0');+ expect(region).not.toHaveAttribute('tabindex');expect(region).toHaveAttribute('aria-label', 'javascript');+ expect(region).toHaveAttribute('data-scroll-axis', 'both');});it('labels the scroll region "Code" when no language label is shown', () => {render(<CodeBlock code="hello" hasLanguageLabel={false} />);const region = screen.getByRole('group');- expect(region).toHaveAttribute('tabindex', '0');expect(region).toHaveAttribute('aria-label', 'Code');});@@ -371,9 +373,9 @@ describe('CodeBlock', () => {fireEvent.click(header);expect(header).toHaveAttribute('aria-expanded', 'false');- // Collapsed: the wrapper is inert, so the keyboard-focusable scroll- // container (tabIndex=0) inside it drops out of the tab order and the- // accessibility tree instead of remaining an invisible tab stop.+ // Collapsed: the wrapper is inert, so the scroll container inside it+ // drops out of the tab order and the accessibility tree instead of+ // remaining an invisible tab stop while it overflows.expect(region).toHaveAttribute('inert');const scrollContainer = screen.getByRole('group');expect(scrollContainer.closest('[inert]')).toBe(region);@@ -399,12 +401,12 @@ describe('CodeBlock', () => {expect(region).toHaveAttribute('inert');fireEvent.click(header);expect(header).toHaveAttribute('aria-expanded', 'true');- // Expanded again: inert is removed and the scroll container is a- // keyboard-focusable group once more.+ // Expanded again: inert is removed and the scroll container is a named+ // group once more (its tab stop follows overflow, see the browser spec).expect(region).not.toHaveAttribute('inert');const scrollContainer = screen.getByRole('group');expect(scrollContainer.closest('[inert]')).toBeNull();- expect(scrollContainer).toHaveAttribute('tabindex', '0');+ expect(scrollContainer).toHaveAttribute('data-scroll-axis', 'both');});it('applies a per-instance syntax theme via the syntaxTheme prop', () => {diff --git a/packages/core/src/CodeBlock/CodeBlock.tsx b/packages/core/src/CodeBlock/CodeBlock.tsxindex 24963203aa..49fabbc72b 100644--- a/packages/core/src/CodeBlock/CodeBlock.tsx+++ b/packages/core/src/CodeBlock/CodeBlock.tsx@@ -34,6 +34,7 @@ import {} from '../theme/tokens.stylex';import {mergeProps} from '../utils';import {useClipboard} from '../hooks/useClipboard';+import {useScrollableArea} from '../hooks/useScrollableArea';import {Icon} from '../Icon';import {IconButton} from '../IconButton';import {@@ -117,6 +118,13 @@ const styles = stylex.create({backgroundColor: 'var(--color-syntax-background)',overflow: 'hidden',},+ // The viewport is a flex item of the column root. Its implied min-height+ // would be its content while it fits (the shared capability keeps it+ // `overflow: clip` then), so a root sized from outside could never make it+ // shrink and scroll; 0 lets the root's bound reach it.+ viewport: {+ minHeight: 0,+ },headerRow: {display: 'flex',alignItems: 'center',@@ -160,10 +168,6 @@ const styles = stylex.create({margin: 0,lineHeight: typeScaleVars['--text-supporting-leading'],},- scrollContainer: {- overflowX: 'auto',- overflowY: 'auto',- },codeWrapper: {display: 'flex',minWidth: 'fit-content',@@ -800,7 +804,19 @@ export function CodeBlock({// this is always a resolvable reference — aria-controls can be unconditional.const regionId = useId();- const scrollContainerRef = useRef<HTMLDivElement>(null);+ // The code viewport enters the Tab order only while its content actually+ // overflows (AST-025 FR12–FR13): the shared scroll capability measures+ // both axes, keeps focus where it is when overflow goes away, and owns the+ // overflow declarations. role="group" (not "region") so several code+ // blocks on a page don't create duplicate same-named landmarks.+ const {getViewportProps, getContentProps} = useScrollableArea({+ axis: 'both',+ keyboardAccess: {+ owner: 'viewport',+ role: 'group',+ label: languageLabel ?? t('@astryx.codeBlock.code'),+ },+ });const scrollStyle: CSSProperties | undefined =maxHeight != null? {@@ -895,21 +911,16 @@ export function CodeBlock({const codeBody = (<div- ref={scrollContainerRef}- // The scroll container is keyboard-focusable so keyboard users can- // scroll long or wide code that overflows the viewport. Uses- // role="group" (not "region") so multiple code blocks on a page don't- // create duplicate same-named landmarks (axe: landmark-unique).- tabIndex={0}- role="group"- aria-label={languageLabel ?? t('@astryx.codeBlock.code')}- {...mergeProps(stylex.props(styles.scrollContainer), {+ {...getViewportProps<HTMLDivElement>({+ ...stylex.props(styles.viewport),style: scrollStyle,})}><div- {...stylex.props(- styles.codeWrapper,- showHeader && !hasLineNumbers && styles.codeWrapperCompact,+ {...getContentProps<HTMLDivElement>(+ stylex.props(+ styles.codeWrapper,+ showHeader && !hasLineNumbers && styles.codeWrapperCompact,+ ),)}>{useSpans ? (<SpanCodeContent@@ -958,7 +969,7 @@ export function CodeBlock({// While collapsed, the region is only hidden visually (0fr grid// row); inert also removes it from the tab order and accessibility// tree so keyboard users cannot Tab into the invisible scroll- // container (tabIndex=0). aria-controls pointing at an inert+ // container (a tab stop while it overflows). aria-controls pointing at an inert// element remains a valid, resolvable reference.inert={isCollapsed ? true : undefined}{...stylex.props(diff --git a/packages/core/src/CodeBlock/__tests__/CodeBlockOverflowStop.a11y.chromium.spec.ts b/packages/core/src/CodeBlock/__tests__/CodeBlockOverflowStop.a11y.chromium.spec.tsnew file mode 100644index 0000000000..29c2f6a1ed--- /dev/null+++ b/packages/core/src/CodeBlock/__tests__/CodeBlockOverflowStop.a11y.chromium.spec.ts@@ -0,0 +1,125 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CodeBlockOverflowStop.a11y.chromium.spec.ts+ * @input Built CodeBlock story and real Chromium layout+ * @output Browser evidence that the code viewport is a Tab stop only while it overflows+ * @position CodeBlock FR8 / AST-025 FR12–FR13 proof over the shared scroll capability+ */++import {expect, test, type Page} from '@playwright/test';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++const STORY = 'core-codeblock--overflow-stop';+const WIDE = 'const wide = "' + 'x'.repeat(400) + '";';+const TALL = Array.from({length: 40}, (_, i) => `const line${i} = ${i};`).join(+ '\n',+);++async function mount(page: Page) {+ await page.setViewportSize({width: 600, height: 500});+ await page.goto(`${storybook.origin}/iframe.html?id=${STORY}&viewMode=story`);+ await expect(page.getByRole('group', {name: 'tsx'})).toBeVisible();+}++async function setArgs(page: Page, args: Record<string, unknown>) {+ await page.evaluate(+ async ({storyId, updatedArgs}) =>+ new Promise<void>(resolve => {+ const channel = (+ window as unknown as {+ __STORYBOOK_ADDONS_CHANNEL__: {+ emit: (event: string, payload: unknown) => void;+ once: (event: string, handler: () => void) => void;+ };+ }+ ).__STORYBOOK_ADDONS_CHANNEL__;+ channel.once('storyRendered', () => resolve());+ channel.emit('updateStoryArgs', {storyId, updatedArgs});+ setTimeout(resolve, 1500);+ }),+ {storyId: STORY, updatedArgs: args},+ );+}++function viewport(page: Page) {+ return page.getByRole('group', {name: 'tsx'});+}++test('a fitting viewport is not a Tab stop', async ({page}) => {+ await mount(page);+ await expect(viewport(page)).not.toHaveAttribute('tabindex', /.*/);+ // Tab from the document start lands on the copy button, never the viewport.+ await page.keyboard.press('Tab');+ const active = await page.evaluate(() =>+ document.activeElement?.getAttribute('role'),+ );+ expect(active).not.toBe('group');+});++test('inline overflow adds the stop; block overflow adds it too', async ({+ page,+}) => {+ await mount(page);+ await setArgs(page, {code: WIDE});+ await expect(viewport(page)).toHaveAttribute('tabindex', '0');+ await expect(viewport(page)).toHaveAttribute(+ 'data-scrollable-inline',+ 'true',+ );++ await setArgs(page, {code: TALL, maxHeight: 160});+ await expect(viewport(page)).toHaveAttribute('tabindex', '0');+ await expect(viewport(page)).toHaveAttribute('data-scrollable-block', 'true');+});++test('losing overflow removes the stop without moving focus', async ({+ page,+}) => {+ await mount(page);+ await setArgs(page, {code: WIDE});+ await expect(viewport(page)).toHaveAttribute('tabindex', '0');+ await viewport(page).focus();+ await expect(viewport(page)).toBeFocused();++ await setArgs(page, {code: 'const fits = true;'});+ // Focus stays on the element that had it; the stop is gone for the next Tab.+ await expect(viewport(page)).toBeFocused();+ await expect(viewport(page)).toHaveAttribute('tabindex', '-1');+ // Leaving and coming back by keyboard skips it: it is out of the Tab order.+ await page.keyboard.press('Shift+Tab');+ await page.keyboard.press('Tab');+ await expect(viewport(page)).not.toBeFocused();+ await expect(viewport(page)).not.toHaveAttribute('tabindex', '0');+});++test('a root height set from outside bounds the viewport, which then scrolls', async ({+ page,+}) => {+ await mount(page);+ // The IDE template's pattern: the block fills a parent of fixed height.+ await setArgs(page, {code: TALL, style: {height: 160}});+ const vp = viewport(page);+ await expect(vp).toHaveAttribute('tabindex', '0');+ await expect(vp).toHaveAttribute('data-scrollable-block', 'true');+ const box = await vp.boundingBox();+ expect(box?.height ?? 0).toBeLessThan(160);+ const scrollable = await vp.evaluate(+ node => node.scrollHeight > node.clientHeight + 1,+ );+ expect(scrollable).toBe(true);+});diff --git a/packages/core/src/Markdown/plugins/semanticFence.test.tsx b/packages/core/src/Markdown/plugins/semanticFence.test.tsxindex acfb3bfb5f..235fe13827 100644--- a/packages/core/src/Markdown/plugins/semanticFence.test.tsx+++ b/packages/core/src/Markdown/plugins/semanticFence.test.tsx@@ -412,9 +412,10 @@ describe('createMarkdownFenceTransform', () => {expect(createNode).not.toHaveBeenCalled();expect(document.querySelector('pre')).toHaveTextContent('plain source');expect(screen.getByRole('button', {name: 'Copy code'})).toBeInTheDocument();+ // CodeBlock's named viewport; its tab stop follows overflow (none in jsdom).expect(screen.getByRole('group', {name: 'text'})).toHaveAttribute(- 'tabindex',- '0',+ 'data-scroll-axis',+ 'both',);rerender(