Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(CodeBlock, Carousel): the code viewport and the scroller draw the shared focus ring (#8875)

Cindy Zhangf81f09df30b5
diff --git a/.changeset/codeblock-carousel-focus-ring.md b/.changeset/codeblock-carousel-focus-ring.md
new file mode 100644
index 0000000000..0740f8224c
--- /dev/null
+++ b/.changeset/codeblock-carousel-focus-ring.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `CodeBlock` and `Carousel`: the code viewport (while the code overflows) and the carousel scroller draw the theme's focus ring instead of the browser's default, and a theme's `--focus-outline-*` tokens reach them. Both rings sit inside their component's clipped box, so they show whole. The Carousel ring is painted by the carousel itself rather than the scroller, so the scroller's edge-fade mask no longer fades it, at rest or mid-scroll. The Carousel ring is drawn by an internal shared overlay.
+
+@cixzhang
diff --git a/docs/architecture/interaction-modality.md b/docs/architecture/interaction-modality.md
index 4ddfafdd2b..30b3d1aed6 100644
--- a/docs/architecture/interaction-modality.md
+++ b/docs/architecture/interaction-modality.md
@@ -133,7 +133,11 @@ work.
- **INV1 — Last input owns programmatic focus visibility.** Programmatic focus
preserves the current modality. After pointer input it does not show the shared
- focus indicator; after keyboard input it does.
+ focus indicator; after keyboard input it does. A wrapper whose content would
+ cover a ring it draws, such as a masked scroller that is its own stacking
+ context, draws the shared ring as the focus-owner overlay
+ (`focusWithinOwnerOverlay` in `privateAttributes/focusOwner.stylex.ts`), keyed
+ on the owner attribute as INV3 says.
- **INV2 — Modality and focus ownership stay separate.** Shared modality decides
visibility. Each component family decides the semantic focus owner and the
element that paints on its behalf.
diff --git a/packages/core/src/Carousel/Carousel.focusRing.test.tsx b/packages/core/src/Carousel/Carousel.focusRing.test.tsx
new file mode 100644
index 0000000000..b536f90a11
--- /dev/null
+++ b/packages/core/src/Carousel/Carousel.focusRing.test.tsx
@@ -0,0 +1,53 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Carousel.focusRing.test.tsx
+ * @input Uses Carousel, focusOutlineStyles and the focus-owner module
+ * @output Tests that the Carousel root paints its scroller's shared focus ring
+ * @position Colocated test; the painted ring is checked in
+ * CarouselFocusRing.a11y.chromium.spec.ts
+ *
+ * jsdom does not match `:focus-visible` or paint, so this pins the
+ * composition the root's overlay ring needs: the scroller is a direct child
+ * marked as the focus owner, it paints no ring of its own, because its
+ * edge-fade mask would erase it, and the root carries the owner overlay.
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import {describe, it, expect} from 'vitest';
+import {render, screen} from '@testing-library/react';
+import {Carousel} from './Carousel';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+import {
+ focusOwnerProps,
+ focusWithinOwnerOverlay,
+} from '../privateAttributes/focusOwner.stylex';
+
+const atoms = (className: string | undefined) =>
+ (className ?? '').split(' ').filter(c => c !== '' && !c.includes('__'));
+
+describe("Carousel: the root paints the scroller's shared focus ring", () => {
+ it('marks the scroller as the focus owner, with no ring of its own, under a root that carries the owner overlay', () => {
+ render(
+ <Carousel aria-label="Photos">
+ <div>One</div>
+ <div>Two</div>
+ </Carousel>,
+ );
+ const root = screen.getByRole('region', {name: 'Photos'});
+ const scroller = root.querySelector('.astryx-carousel-scroller');
+ expect(scroller).not.toBeNull();
+ expect(scroller!.parentElement).toBe(root);
+ for (const attribute of Object.keys(focusOwnerProps)) {
+ expect(scroller!.hasAttribute(attribute)).toBe(true);
+ }
+ for (const c of atoms(
+ stylex.props(focusOutlineStyles.suppressed).className,
+ )) {
+ expect(scroller!.className.split(' ')).toContain(c);
+ }
+ for (const c of atoms(stylex.props(focusWithinOwnerOverlay).className)) {
+ expect(root.className.split(' ')).toContain(c);
+ }
+ });
+});
diff --git a/packages/core/src/Carousel/Carousel.tsx b/packages/core/src/Carousel/Carousel.tsx
index 8ba62b7c49..f096e04aa9 100644
--- a/packages/core/src/Carousel/Carousel.tsx
+++ b/packages/core/src/Carousel/Carousel.tsx
@@ -41,7 +41,13 @@ import {
radiusVars,
durationVars,
easeVars,
+ focusVars,
} from '../theme/tokens.stylex';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+import {
+ focusOwnerProps,
+ focusWithinOwnerOverlay,
+} from '../privateAttributes/focusOwner.stylex';
import {Button} from '../Button';
import {Icon} from '../Icon';
import {useLayer} from '../Layer';
@@ -591,7 +597,13 @@ export function Carousel({
{...htmlProps}
{...mergeProps(
themeProps('carousel'),
- stylex.props(styles.root, xstyle),
+ stylex.props(
+ styles.root,
+ // The scroller is the focus owner. Its edge-fade mask would cover a
+ // ring the root draws itself.
+ focusWithinOwnerOverlay,
+ xstyle,
+ ),
className,
style,
)}
@@ -608,6 +620,7 @@ export function Carousel({
aria-label={ariaLabel}
tabIndex={hasOverflow ? 0 : -1}
onWheel={handleWheel}
+ {...focusOwnerProps}
{...mergeProps(
themeProps('carousel-scroller', {
gap,
@@ -617,6 +630,8 @@ export function Carousel({
}),
stylex.props(
styles.scroller,
+ // A tab stop whose shared ring the root paints.
+ focusOutlineStyles.suppressed,
gapStyles[gap],
padding != null && paddingStyles[padding],
hasSnap && styles.snap,
diff --git a/packages/core/src/Carousel/__tests__/CarouselFocusRing.a11y.chromium.spec.ts b/packages/core/src/Carousel/__tests__/CarouselFocusRing.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..8a4c4db6bb
--- /dev/null
+++ b/packages/core/src/Carousel/__tests__/CarouselFocusRing.a11y.chromium.spec.ts
@@ -0,0 +1,243 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope ^(packages/core/src/(Carousel|CodeBlock)/|packages/core/src/utils/focusOutline|apps/storybook/stories/(Carousel|CodeBlock)\.stories)
+
+/**
+ * @file CarouselFocusRing.a11y.chromium.spec.ts
+ * @input Built Carousel and CodeBlock stories and real Chromium keyboard input
+ * @output Evidence that the Carousel scroller's and the CodeBlock viewport's
+ * keyboard rings paint whole: no mask erases the Carousel ring, at rest or
+ * mid-scroll, and no clipping ancestor cuts either ring
+ * @position Real-engine proof for the focus rings; jsdom cannot match
+ * :focus-visible or paint
+ */
+
+import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';
+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();
+});
+
+interface RingPaint {
+ readonly focusVisible: boolean;
+ /** The element that paints the ring: the focused one or an ancestor. */
+ readonly painter: string;
+ readonly outlineStyle: string;
+ readonly outlineWidth: number;
+ /** A mask on the painter or between it and the page erases the ring. */
+ readonly masked: ReadonlyArray<string>;
+ /** Pixels of the ring each clipping ancestor cuts off, by side. */
+ readonly clipped: ReadonlyArray<string>;
+}
+
+async function tabTo(page: Page, selector: string, maxTabs = 20) {
+ for (let i = 0; i < maxTabs; i++) {
+ await page.keyboard.press('Tab');
+ if (
+ await page.evaluate(
+ sel => document.activeElement?.matches(sel) ?? false,
+ selector,
+ )
+ ) {
+ return;
+ }
+ }
+ throw new Error(`Tab never reached ${selector}`);
+}
+
+/** Find which element paints the focused element's ring, and measure it. */
+async function measureRing(page: Page): Promise<RingPaint> {
+ return page.evaluate(() => {
+ const focused = document.activeElement as HTMLElement;
+ let painter: HTMLElement | null = focused;
+ while (
+ painter != null &&
+ getComputedStyle(painter).outlineStyle === 'none'
+ ) {
+ painter = painter.parentElement;
+ }
+ if (painter == null) {
+ return {
+ focusVisible: focused.matches(':focus-visible'),
+ painter: 'none',
+ outlineStyle: 'none',
+ outlineWidth: 0,
+ masked: [],
+ clipped: [],
+ };
+ }
+ const style = getComputedStyle(painter);
+ const width = parseFloat(style.outlineWidth) || 0;
+ const offset = parseFloat(style.outlineOffset) || 0;
+ const box = painter.getBoundingClientRect();
+ const reach = width + offset;
+ const ring = {
+ top: box.top - reach,
+ right: box.right + reach,
+ bottom: box.bottom + reach,
+ left: box.left - reach,
+ };
+ const masked: string[] = [];
+ const clipped: string[] = [];
+ for (
+ let node: HTMLElement | null = painter;
+ node != null && node !== document.body;
+ node = node.parentElement
+ ) {
+ const nodeStyle = getComputedStyle(node);
+ const mask =
+ nodeStyle.maskImage || nodeStyle.getPropertyValue('-webkit-mask-image');
+ if (mask && mask !== 'none') {
+ masked.push(node.className.split(' ')[0] || node.tagName);
+ }
+ if (
+ node === painter ||
+ (nodeStyle.overflowX === 'visible' && nodeStyle.overflowY === 'visible')
+ ) {
+ continue;
+ }
+ const rect = node.getBoundingClientRect();
+ const margin =
+ nodeStyle.overflowX === 'clip'
+ ? parseFloat(nodeStyle.overflowClipMargin) || 0
+ : 0;
+ const clip = {
+ top: rect.top + parseFloat(nodeStyle.borderTopWidth) - margin,
+ right: rect.right - parseFloat(nodeStyle.borderRightWidth) + margin,
+ bottom: rect.bottom - parseFloat(nodeStyle.borderBottomWidth) + margin,
+ left: rect.left + parseFloat(nodeStyle.borderLeftWidth) - margin,
+ };
+ const cut = {
+ top: clip.top - ring.top,
+ right: ring.right - clip.right,
+ bottom: ring.bottom - clip.bottom,
+ left: clip.left - ring.left,
+ };
+ for (const [side, px] of Object.entries(cut)) {
+ if (px > 0.5) {
+ clipped.push(
+ `${node.tagName.toLowerCase()}.${side}=${px.toFixed(1)}px`,
+ );
+ }
+ }
+ }
+ return {
+ focusVisible: focused.matches(':focus-visible'),
+ painter: painter === focused ? 'self' : painter.className.split(' ')[0],
+ outlineStyle: style.outlineStyle,
+ outlineWidth: width,
+ masked,
+ clipped,
+ };
+ });
+}
+
+function expectWholeRing(paint: RingPaint, label: string) {
+ expect(paint.focusVisible, label).toBe(true);
+ expect(paint.outlineStyle, label).toBe('solid');
+ expect(paint.outlineWidth, label).toBeGreaterThan(0);
+ expect(paint.masked, label).toEqual([]);
+ expect(paint.clipped, label).toEqual([]);
+}
+
+/** The painted color at one viewport point, read from a real screenshot. */
+async function pixel(page: Page, x: number, y: number) {
+ const shot = await page.screenshot({clip: {x, y, width: 1, height: 1}});
+ return page.evaluate(async base64 => {
+ const blob = await (await fetch(`data:image/png;base64,${base64}`)).blob();
+ const bitmap = await createImageBitmap(blob);
+ const canvas = new OffscreenCanvas(1, 1);
+ const context = canvas.getContext('2d')!;
+ context.drawImage(bitmap, 0, 0);
+ const [r, g, b] = context.getImageData(0, 0, 1, 1).data;
+ return [r, g, b] as const;
+ }, shot.toString('base64'));
+}
+
+/**
+ * The ring the Carousel root's overlay paints, checked in pixels: the
+ * midpoint of each edge, one pixel inside the root, shows the ring's color.
+ */
+async function expectRingPaintsEveryEdge(page: Page, label: string) {
+ const root = page.locator('#storybook-root .astryx-carousel').first();
+ const ring = await root.evaluate(el => {
+ const after = getComputedStyle(el, '::after');
+ const probe = document.createElement('span');
+ probe.style.color = after.outlineColor;
+ document.body.append(probe);
+ const [r, g, b] = getComputedStyle(probe)
+ .color.match(/[\d.]+/g)!
+ .slice(0, 3)
+ .map(Number);
+ probe.remove();
+ return {style: after.outlineStyle, color: [r, g, b]};
+ });
+ expect(ring.style, label).toBe('solid');
+ const box = (await root.boundingBox())!;
+ const edges = {
+ top: [box.x + box.width / 2, box.y + 1],
+ bottom: [box.x + box.width / 2, box.y + box.height - 2],
+ // Above the vertically centred scroll buttons, which sit over the edges.
+ start: [box.x + 1, box.y + box.height / 4],
+ end: [box.x + box.width - 2, box.y + box.height / 4],
+ } as const;
+ for (const [edge, [x, y]] of Object.entries(edges)) {
+ const painted = await pixel(page, Math.floor(x), Math.floor(y));
+ const distance = Math.hypot(
+ painted[0] - ring.color[0],
+ painted[1] - ring.color[1],
+ painted[2] - ring.color[2],
+ );
+ expect(distance, `${label}: ${edge} edge`).toBeLessThan(40);
+ }
+}
+
+test.describe('Carousel and CodeBlock focus rings (Chromium)', () => {
+ for (const story of ['core-carousel--default', 'core-carousel--cards']) {
+ test(`${story}: an overflowing Carousel paints its ring on every edge, at rest and mid-scroll`, async ({
+ page,
+ }) => {
+ await page.setViewportSize({width: 640, height: 600});
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${story}&viewMode=story`,
+ );
+ const scroller = page.locator(
+ '#storybook-root .astryx-carousel-scroller',
+ );
+ await expect(scroller).toBeVisible();
+ await tabTo(page, '#storybook-root .astryx-carousel-scroller');
+ await expectRingPaintsEveryEdge(page, 'at rest');
+
+ await scroller.evaluate(el => {
+ el.style.scrollBehavior = 'auto';
+ el.scrollLeft = (el.scrollWidth - el.clientWidth) / 2;
+ });
+ await page.waitForTimeout(100);
+ await expectRingPaintsEveryEdge(page, 'mid-scroll');
+ });
+ }
+
+ test('an overflowing CodeBlock paints the whole ring around its viewport', async ({
+ page,
+ }) => {
+ await page.setViewportSize({width: 480, height: 800});
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-codeblock--diff-long-lines&viewMode=story`,
+ );
+ await expect(
+ page.locator('#storybook-root pre, #storybook-root code').first(),
+ ).toBeVisible();
+ await tabTo(page, '#storybook-root [tabindex="0"]');
+ expectWholeRing(await measureRing(page), 'viewport');
+ });
+});
diff --git a/packages/core/src/CodeBlock/CodeBlock.focusRing.test.tsx b/packages/core/src/CodeBlock/CodeBlock.focusRing.test.tsx
new file mode 100644
index 0000000000..e5a9cb02e0
--- /dev/null
+++ b/packages/core/src/CodeBlock/CodeBlock.focusRing.test.tsx
@@ -0,0 +1,21 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CodeBlock.focusRing.test.tsx
+ * @input Uses CodeBlock and the inset focus-ring test helper
+ * @output Tests that the code viewport draws the shared focus ring, inset so
+ * the root's clip does not cut it
+ * @position Colocated test; the ring's geometry is checked in a real browser
+ */
+
+import {describe, it} from 'vitest';
+import {render, screen} from '@testing-library/react';
+import {CodeBlock} from './CodeBlock';
+import {expectInsetSharedFocusRing} from '../__tests__/insetFocusRing';
+
+describe('CodeBlock: the code viewport draws the shared focus ring', () => {
+ it('inset inside the clipped root', () => {
+ render(<CodeBlock code="const a = 1;" language="ts" />);
+ expectInsetSharedFocusRing(screen.getByRole('group', {hidden: true}));
+ });
+});
diff --git a/packages/core/src/CodeBlock/CodeBlock.tsx b/packages/core/src/CodeBlock/CodeBlock.tsx
index 18dd72a99e..ad6651adae 100644
--- a/packages/core/src/CodeBlock/CodeBlock.tsx
+++ b/packages/core/src/CodeBlock/CodeBlock.tsx
@@ -32,6 +32,7 @@ import {
borderVars,
durationVars,
easeVars,
+ focusVars,
} from '../theme/tokens.stylex';
import {isRenderable, mergeProps, rtlStyles} from '../utils';
import {useClipboard} from '../hooks/useClipboard';
@@ -142,6 +143,14 @@ const styles = stylex.create({
viewport: {
minHeight: 0,
},
+ // The root clips (overflow: hidden, for its corners), so the viewport's
+ // keyboard ring sits inside its own box instead of around it.
+ viewportFocusRingInset: {
+ outlineOffset: {
+ default: null,
+ ':focus-visible': `calc(-1 * ${focusVars['--focus-outline-width']})`,
+ },
+ },
// With no header, Copy sits in its own inline-end column beside the code
// viewport rather than over it, so no line, scrolled or wrapped, runs under
// the button. The column is as wide as its content; the single row still
@@ -1242,7 +1251,12 @@ export function CodeBlock({
const codeBody = (
<div
{...getViewportProps<HTMLDivElement>({
- ...stylex.props(styles.viewport),
+ // A tab stop while the code overflows: the shared ring, which a theme
+ // restyles through the focus-outline tokens.
+ ...focusOutlineProps.focusVisible(
+ styles.viewport,
+ styles.viewportFocusRingInset,
+ ),
style: scrollStyle,
})}>
<div
diff --git a/packages/core/src/__tests__/insetFocusRing.ts b/packages/core/src/__tests__/insetFocusRing.ts
new file mode 100644
index 0000000000..ac3307c657
--- /dev/null
+++ b/packages/core/src/__tests__/insetFocusRing.ts
@@ -0,0 +1,55 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file insetFocusRing.ts
+ * @input Uses StyleX, focusOutlineStyles, focusVars
+ * @output Test helpers asserting an element composes the shared focus ring,
+ * either as is or inset by its own width (for a tab stop that sits flush
+ * against a clipping ancestor)
+ * @position Shared test utility for focus-ring composition checks
+ *
+ * jsdom does not match `:focus-visible`, so these pin the composition: the
+ * element carries the atomic classes the ring compiles to. The geometry is
+ * checked in a real browser.
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import {expect} from 'vitest';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+import {focusVars} from '../theme/tokens.stylex';
+
+const inset = stylex.create({
+ ring: {
+ outlineOffset: {
+ default: null,
+ ':focus-visible': `calc(-1 * ${focusVars['--focus-outline-width']})`,
+ },
+ },
+});
+
+// Debug class names name their source file; only the atoms matter.
+const atoms = (className: string | undefined) =>
+ (className ?? '').split(' ').filter(c => c !== '' && !c.includes('__'));
+
+const sharedRing = atoms(
+ stylex.props(focusOutlineStyles.focusVisible).className,
+);
+const insetRing = atoms(
+ stylex.props(focusOutlineStyles.focusVisible, inset.ring).className,
+);
+
+/** The element draws the shared ring at the token offset. */
+export function expectSharedFocusRing(el: Element): void {
+ const classes = el.className.split(' ');
+ for (const c of sharedRing) {
+ expect(classes).toContain(c);
+ }
+}
+
+/** The element draws the shared ring inset by the ring's own width. */
+export function expectInsetSharedFocusRing(el: Element): void {
+ const classes = el.className.split(' ');
+ for (const c of insetRing) {
+ expect(classes).toContain(c);
+ }
+}
diff --git a/packages/core/src/privateAttributes/focusOwner.stylex.ts b/packages/core/src/privateAttributes/focusOwner.stylex.ts
index d9a9195415..11f112b805 100644
--- a/packages/core/src/privateAttributes/focusOwner.stylex.ts
+++ b/packages/core/src/privateAttributes/focusOwner.stylex.ts
@@ -45,7 +45,43 @@ const styles = stylex.create({
focusVars['--focus-outline-offset'],
},
},
+ // The same ring, drawn as an overlay pseudo-element above the wrapper's
+ // content and inset by the ring's width, for a marked control whose own
+ // painting would cover a ring on the wrapper: a scroller with an edge-fade
+ // mask is its own stacking context. The wrapper must be positioned and must
+ // not use ::after.
+ focusWithinOwnerOverlay: {
+ '::after': {
+ content: '""',
+ position: 'absolute',
+ inset: 0,
+ pointerEvents: 'none',
+ borderRadius: 'inherit',
+ outlineWidth: {
+ default: null,
+ ':has(> [data-astryx-focus-owner]:focus-visible)':
+ focusVars['--focus-outline-width'],
+ },
+ outlineStyle: {
+ default: 'none',
+ ':has(> [data-astryx-focus-owner]:focus-visible)':
+ focusVars['--focus-outline-style'],
+ },
+ outlineColor: {
+ default: null,
+ ':has(> [data-astryx-focus-owner]:focus-visible)':
+ focusVars['--focus-outline-color'],
+ },
+ outlineOffset: {
+ default: null,
+ ':has(> [data-astryx-focus-owner]:focus-visible)': `calc(-1 * ${focusVars['--focus-outline-width']})`,
+ },
+ },
+ },
});
/** The wrapper's focus ring. */
export const focusWithinOwner = styles.focusWithinOwner;
+
+/** The wrapper's focus ring, drawn above the wrapper's content. */
+export const focusWithinOwnerOverlay = styles.focusWithinOwnerOverlay;