Skip to content

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

TypeScript

fix(Table): the scroll wrapper and tree toggles draw the shared focus ring (#8873)

Cindy Zhang7cb107c5bd2e
diff --git a/.changeset/table-focus-ring.md b/.changeset/table-focus-ring.md
new file mode 100644
index 0000000000..b34882f94c
--- /dev/null
+++ b/.changeset/table-focus-ring.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `Table`: three of its keyboard tab stops draw the theme's focus ring instead of the browser's default: the scroll wrapper once the table scrolls inline, and the tree plugin's row expander and expand-all toggle. A theme's `--focus-outline-*` tokens now reach them. The scroll wrapper's ring sits inside its box, clear of a bordered Card's border, so a Card no longer cuts off its edges (a Card's rounded corners still trim the ring's square corners); at `density="compact"` the tree toggles' ring sits inside the toggle, so the row does not clip it. The row-expansion, grouped-rows and filter buttons are unchanged.
+
+@cixzhang
diff --git a/.github/a11y-baseline.json b/.github/a11y-baseline.json
index d2295bf73d..b2146fda44 100644
--- a/.github/a11y-baseline.json
+++ b/.github/a11y-baseline.json
@@ -333,6 +333,11 @@
"impact": "serious",
"helpUrl": "https://dequeuniversity.com/rules/axe/4.12/aria-conditional-attr?application=playwright"
},
+ {
+ "key": "core/tabletree::core-tabletree--compact-density::aria-conditional-attr",
+ "impact": "serious",
+ "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/aria-conditional-attr?application=playwright"
+ },
{
"key": "Text::Color Variants::color-contrast",
"impact": "serious",
diff --git a/apps/storybook/stories/TableTree.stories.tsx b/apps/storybook/stories/TableTree.stories.tsx
index 05ac816d22..3b985ccb75 100644
--- a/apps/storybook/stories/TableTree.stories.tsx
+++ b/apps/storybook/stories/TableTree.stories.tsx
@@ -190,6 +190,31 @@ export const Default: Story = {
},
};
+/**
+ * The tree at `density="compact"`, whose rows are shorter than the toggle's
+ * ring would be outside it; the toggles' keyboard ring sits inside them.
+ */
+export const CompactDensity: Story = {
+ render: () => {
+ const {visibleData, treeConfig} = useTableTreeState<OrgRow>({
+ data: orgChart,
+ idKey: 'id',
+ defaultExpandedIds: ['eng'],
+ });
+ const tree = useTableTreeData({...treeConfig, hasExpandAllControl: true});
+
+ return (
+ <Table
+ data={visibleData}
+ columns={columns}
+ idKey="id"
+ density="compact"
+ plugins={{tree}}
+ />
+ );
+ },
+};
+
/**
* `expandAll` / `collapseAll` from the state hook, driving a deep hierarchy.
* Indentation is `calc(level * token)` — there is no depth cap.
diff --git a/packages/core/src/Table/Table.focusRing.test.tsx b/packages/core/src/Table/Table.focusRing.test.tsx
new file mode 100644
index 0000000000..7766006d45
--- /dev/null
+++ b/packages/core/src/Table/Table.focusRing.test.tsx
@@ -0,0 +1,104 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Table.focusRing.test.tsx
+ * @input Uses Table, useTableTreeState, useTableTreeData, focusOutlineStyles
+ * @output Tests that Table's own tab stops (the scroll wrapper, the tree
+ * expander, the expand-all toggle) draw the shared focus ring
+ * @position Colocated test; the ring's geometry is checked in a real browser
+ *
+ * jsdom does not match `:focus-visible`, so these pin the composition: each
+ * tab stop carries the classes `focusOutlineStyles.focusVisible` compiles to.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {render, screen, within} from '@testing-library/react';
+import * as stylex from '@stylexjs/stylex';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+import {borderVars, focusVars} from '../theme/tokens.stylex';
+import {Table} from './Table';
+import type {TableColumn} from './types';
+import {useTableTreeData} from './plugins/tree/useTableTreeData';
+import {useTableTreeState} from './plugins/tree/useTableTreeState';
+
+const sharedFocusRingClasses = stylex
+ .props(focusOutlineStyles.focusVisible)
+ .className!.split(' ');
+
+// The scroll wrapper keeps the shared ring but sits it inside its own box,
+// because it bleeds to a clipping container's edges.
+const inset = stylex.create({
+ ring: {
+ outlineOffset: {
+ default: null,
+ ':focus-visible': `calc(-1 * (${focusVars['--focus-outline-width']} + ${borderVars['--border-width']}))`,
+ },
+ },
+});
+const insetFocusRingClasses = stylex
+ .props(focusOutlineStyles.focusVisible, inset.ring)
+ .className!.split(' ')
+ // Debug class names name their source file; only the atoms matter.
+ .filter(c => !c.includes('__'));
+
+function expectSharedFocusRing(el: Element) {
+ const classes = el.className.split(' ');
+ for (const c of sharedFocusRingClasses) {
+ expect(classes).toContain(c);
+ }
+}
+
+interface FileRow extends Record<string, unknown> {
+ id: string;
+ name: string;
+ children?: FileRow[];
+}
+
+const files: FileRow[] = [
+ {
+ id: 'src',
+ name: 'src',
+ children: [{id: 'utils', name: 'utils.ts'}],
+ },
+ {id: 'readme', name: 'README.md'},
+];
+
+const columns: TableColumn<FileRow>[] = [{key: 'name', header: 'Name'}];
+
+function TreeTable() {
+ const {visibleData, treeConfig} = useTableTreeState<FileRow>({
+ data: files,
+ idKey: 'id',
+ });
+ const tree = useTableTreeData({...treeConfig, hasExpandAllControl: true});
+ return (
+ <Table data={visibleData} columns={columns} idKey="id" plugins={{tree}} />
+ );
+}
+
+describe('Table: its own tab stops draw the shared focus ring', () => {
+ it('the scroll wrapper, inset', () => {
+ const {container} = render(
+ <Table data={[{id: '1', name: 'One'}]} columns={columns} idKey="id" />,
+ );
+ const wrapper = container.querySelector('.astryx-table-scroll-wrapper');
+ expect(wrapper).not.toBeNull();
+ const classes = wrapper!.className.split(' ');
+ for (const c of insetFocusRingClasses) {
+ expect(classes).toContain(c);
+ }
+ });
+
+ it('the tree row expander', () => {
+ render(<TreeTable />);
+ expectSharedFocusRing(screen.getByRole('button', {name: /expand row/i}));
+ });
+
+ it('the expand-all toggle', () => {
+ render(<TreeTable />);
+ const headerRow = screen.getAllByRole('row')[0];
+ expectSharedFocusRing(
+ within(headerRow).getByRole('button', {name: /expand all/i}),
+ );
+ });
+});
diff --git a/packages/core/src/Table/Table.tsx b/packages/core/src/Table/Table.tsx
index ff8ace56d7..8a757f05d8 100644
--- a/packages/core/src/Table/Table.tsx
+++ b/packages/core/src/Table/Table.tsx
@@ -19,7 +19,8 @@
import {use, useMemo, type ReactElement, type Ref} from 'react';
import * as stylex from '@stylexjs/stylex';
-import {colorVars} from '../theme/tokens.stylex';
+import {borderVars, colorVars, focusVars} from '../theme/tokens.stylex';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {BaseTable} from './BaseTable';
import {TableContext} from './TableContext';
import {useBaseTablePlugins} from './useBaseTablePlugins';
@@ -140,6 +141,15 @@ const scrollWrapperStyles = stylex.create({
':last-child': 'calc(-1 * var(--container-padding-block-end, 0px))',
},
},
+ // The wrapper bleeds to its container's edges, under a Card's border, and
+ // the Card clips there, so its keyboard ring sits inside its own box, clear
+ // of that border too.
+ focusRingInset: {
+ outlineOffset: {
+ default: null,
+ ':focus-visible': `calc(-1 * (${focusVars['--focus-outline-width']} + ${borderVars['--border-width']}))`,
+ },
+ },
});
/**
@@ -200,6 +210,10 @@ function TableScrollWrapper({
stylex.props(
scrollWrapperStyles.base,
scrollWrapperStyles.containerBleed,
+ // A tab stop once the table scrolls inline: the shared ring, which a
+ // theme restyles through the focus-outline tokens.
+ focusOutlineStyles.focusVisible,
+ scrollWrapperStyles.focusRingInset,
...(pluginStyles ?? []),
),
),
diff --git a/packages/core/src/Table/__tests__/TableFocusRing.a11y.chromium.spec.ts b/packages/core/src/Table/__tests__/TableFocusRing.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..54ac090747
--- /dev/null
+++ b/packages/core/src/Table/__tests__/TableFocusRing.a11y.chromium.spec.ts
@@ -0,0 +1,149 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope ^(packages/core/src/Table/|packages/core/src/utils/focusOutline|apps/storybook/stories/Table(Tree)?\.stories)
+
+/**
+ * @file TableFocusRing.a11y.chromium.spec.ts
+ * @input Built Table and TableTree stories and real Chromium keyboard input
+ * @output Evidence that Table's own tab stops (the scroll wrapper in a Card,
+ * the tree expander and expand-all toggle at compact density) paint the
+ * shared focus ring, and that no clipping ancestor cuts it off
+ * @position Real-engine proof for the focus ring; 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 RingFit {
+ readonly focusVisible: boolean;
+ readonly outlineStyle: string;
+ readonly outlineWidth: number;
+ /** Pixels of the ring each clipping ancestor cuts off, by side. */
+ readonly clipped: ReadonlyArray<string>;
+}
+
+/** Tab until `selector` holds focus, then measure its ring against every clip. */
+async function tabToAndMeasure(
+ page: Page,
+ selector: string,
+ maxTabs = 20,
+): Promise<RingFit> {
+ for (let i = 0; i < maxTabs; i++) {
+ await page.keyboard.press('Tab');
+ const reached = await page.evaluate(
+ sel => document.activeElement?.matches(sel) ?? false,
+ selector,
+ );
+ if (reached) {
+ break;
+ }
+ }
+ return page.evaluate(sel => {
+ const el = document.activeElement as HTMLElement | null;
+ if (el == null || !el.matches(sel)) {
+ throw new Error(`Tab never reached ${sel}`);
+ }
+ const style = getComputedStyle(el);
+ const width = parseFloat(style.outlineWidth) || 0;
+ const offset = parseFloat(style.outlineOffset) || 0;
+ const box = el.getBoundingClientRect();
+ const reach = width + offset;
+ const ring = {
+ top: box.top - reach,
+ right: box.right + reach,
+ bottom: box.bottom + reach,
+ left: box.left - reach,
+ };
+ const clipped: string[] = [];
+ for (
+ let node = el.parentElement;
+ node != null && node !== document.body;
+ node = node.parentElement
+ ) {
+ const ancestor = getComputedStyle(node);
+ if (
+ ancestor.overflowX === 'visible' &&
+ ancestor.overflowY === 'visible'
+ ) {
+ continue;
+ }
+ const rect = node.getBoundingClientRect();
+ // Content is clipped at the padding box, inside the borders.
+ const clip = {
+ top: rect.top + parseFloat(ancestor.borderTopWidth),
+ right: rect.right - parseFloat(ancestor.borderRightWidth),
+ bottom: rect.bottom - parseFloat(ancestor.borderBottomWidth),
+ left: rect.left + parseFloat(ancestor.borderLeftWidth),
+ };
+ 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)) {
+ // Sub-pixel layout rounding is not a visible cut.
+ if (px > 0.5) {
+ clipped.push(
+ `${node.tagName.toLowerCase()}.${side}=${px.toFixed(1)}px`,
+ );
+ }
+ }
+ }
+ return {
+ focusVisible: el.matches(':focus-visible'),
+ outlineStyle: style.outlineStyle,
+ outlineWidth: width,
+ clipped,
+ };
+ }, selector);
+}
+
+async function mount(page: Page, story: string) {
+ await page.goto(`${storybook.origin}/iframe.html?id=${story}&viewMode=story`);
+ await expect(page.locator('#storybook-root table')).toBeVisible();
+}
+
+test.describe('Table focus ring (Chromium)', () => {
+ test('the scroll wrapper of a table in a bordered Card paints the whole shared ring', async ({
+ page,
+ }) => {
+ await page.setViewportSize({width: 480, height: 800});
+ await mount(page, 'core-table--responsive-scroll-in-card');
+ const fit = await tabToAndMeasure(page, '#storybook-root [tabindex="0"]');
+ expect(fit.focusVisible).toBe(true);
+ expect(fit.outlineStyle).toBe('solid');
+ expect(fit.outlineWidth).toBeGreaterThan(0);
+ expect(fit.clipped).toEqual([]);
+ });
+
+ test('the tree expander and expand-all toggle at compact density paint the whole shared ring', async ({
+ page,
+ }) => {
+ await mount(page, 'core-tabletree--compact-density');
+ for (const selector of [
+ '#storybook-root thead button',
+ '#storybook-root tbody tr[aria-expanded] button',
+ ]) {
+ const fit = await tabToAndMeasure(page, selector);
+ expect(fit.focusVisible, selector).toBe(true);
+ expect(fit.outlineStyle, selector).toBe('solid');
+ expect(fit.outlineWidth, selector).toBeGreaterThan(0);
+ expect(fit.clipped, selector).toEqual([]);
+ }
+ });
+});
diff --git a/packages/core/src/Table/plugins/tree/useTableTreeData.tsx b/packages/core/src/Table/plugins/tree/useTableTreeData.tsx
index 91c1e8b056..a7e5d81d56 100644
--- a/packages/core/src/Table/plugins/tree/useTableTreeData.tsx
+++ b/packages/core/src/Table/plugins/tree/useTableTreeData.tsx
@@ -39,7 +39,13 @@ import {
type ReactNode,
} from 'react';
import * as stylex from '@stylexjs/stylex';
-import {colorVars, radiusVars, spacingVars} from '../../../theme/tokens.stylex';
+import {
+ colorVars,
+ focusVars,
+ radiusVars,
+ spacingVars,
+} from '../../../theme/tokens.stylex';
+import {focusOutlineProps} from '../../../utils/focusOutline.stylex';
import {Icon} from '../../../Icon';
import {mergeRefs} from '../../../utils';
import {
@@ -60,6 +66,7 @@ import english from '../../../i18n/generated-english/Table/plugins/tree/useTable
import {createSharedContext} from '../../../utils/sharedContext';
registerEnglishFallback(english);
+import {TableContext} from '../../TableContext';
// =============================================================================
// Types
@@ -262,6 +269,14 @@ const treeStyles = stylex.create({
indent: (paddingInlineStart: string) => ({
paddingInlineStart,
}),
+ // A compact row is shorter than the ring around the 24px toggle, and the
+ // cell clips its overflow, so there the ring sits inside the toggle.
+ expanderFocusInset: {
+ outlineOffset: {
+ default: null,
+ ':focus-visible': `calc(-1 * ${focusVars['--focus-outline-width']})`,
+ },
+ },
expanderButton: {
display: 'inline-flex',
alignItems: 'center',
@@ -350,6 +365,7 @@ function TreeExpander({
rowLabel?: string;
}) {
const t = useComponentTranslator();
+ const isCompact = use(TableContext)?.density === 'compact';
const normalizedRowLabel = rowLabel?.trim();
const ariaLabel = normalizedRowLabel
? isExpanded
@@ -362,7 +378,10 @@ function TreeExpander({
return (
<button
type="button"
- {...stylex.props(treeStyles.expanderButton)}
+ {...focusOutlineProps.focusVisible(
+ treeStyles.expanderButton,
+ isCompact && treeStyles.expanderFocusInset,
+ )}
onClick={e => {
e.stopPropagation();
onToggle();
@@ -403,11 +422,15 @@ function TreeExpandAllToggle({
onCollapseAll: () => void;
}) {
const t = useComponentTranslator();
+ const isCompact = use(TableContext)?.density === 'compact';
const allExpanded = isAllExpanded === true;
return (
<button
type="button"
- {...stylex.props(treeStyles.expanderButton)}
+ {...focusOutlineProps.focusVisible(
+ treeStyles.expanderButton,
+ isCompact && treeStyles.expanderFocusInset,
+ )}
onClick={e => {
e.stopPropagation();
if (allExpanded) {