Skip to content

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

TypeScript

feat(core): TabList speaks the ARIA tabs pattern under role="tablist" (#5349)

Cindy Zhang022d453d0a94
diff --git a/.changeset/tablist-aria-role.md b/.changeset/tablist-aria-role.md
new file mode 100644
index 0000000000..6369cbcab4
--- /dev/null
+++ b/.changeset/tablist-aria-role.md
@@ -0,0 +1,13 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] TabList: a strip that switches panels in place can now say so with `role="tablist"`, and it speaks the WAI-ARIA tabs pattern — `role="tablist"` on the strip, `role="tab"` and `aria-selected` on the tabs, and `aria-controls` pointing at the panel each tab opens, from a new `panelId` prop on `Tab`. There is no new prop for the switch: `TabList` declares `role?: AriaRole` and reads it, the way `LayoutHeader`, `LayoutContent` and `LayoutPanel` already declare and document theirs. The keyboard behaviour the pattern asks for was already there: arrows move between tabs, Tab leaves the strip. Under the asserted role the strip takes only the horizontal arrows, leaving ArrowUp and ArrowDown to scroll the page.
+
+`role` already reached the DOM through `{...restProps}`, so a caller could pass `role="tablist"` and get a tablist whose children were still `<button>`s with `aria-current` — invalid markup, no `aria-selected`, and no warning. Reading the role turns that silent breakage into the correct behaviour; declaring it is what puts it in the type, the prop table and the docs.
+
+**Nothing changes for a caller who passes no `role`**: the strip is the `<nav>` landmark with `aria-current` it has always been. Any other role still passes through to the element untouched.
+
+Two development warnings come with the asserted role, and only with it. A tab with an `href` is a false statement inside a tablist, so the `href` is ignored and the warning says so. And a tab that controls nothing gets asked for a `panelId` — either that or an `aria-controls` you wrote yourself satisfies it, and a hand-written one is never overwritten. `aria-controls` is emitted only when you supply the id: pointing at a panel that does not exist is an invalid attribute value, which is worse than saying nothing. A menu or any other non-tab in a tablist strip is invalid markup, and warns too. The mirror case warns as well: a `panelId` on a strip that is not a tablist has no panel relationship to state, and is dropped.
+
+@cixzhang
diff --git a/apps/storybook/stories/TabList.stories.tsx b/apps/storybook/stories/TabList.stories.tsx
index 880bd87fd6..a6c001c1fc 100644
--- a/apps/storybook/stories/TabList.stories.tsx
+++ b/apps/storybook/stories/TabList.stories.tsx
@@ -413,3 +413,61 @@ export const OverflowVisible: Story = {
);
},
};
+
+/**
+ * `role="tablist"` asks for the WAI-ARIA tabs pattern: `role="tablist"` /
+ * `role="tab"`, `aria-selected`, and each tab pointing at the panel it
+ * controls. A screen reader announces "tab 2 of 3, selected" and can move to
+ * the panel it opens. Without it the strip stays a `<nav>` landmark marking
+ * the current tab with `aria-current`.
+ */
+export const TabsPattern: Story = {
+ render: () => {
+ const [value, setValue] = useState('overview');
+ const panels = {
+ overview: 'Everything at a glance.',
+ activity: 'What happened recently.',
+ members: 'Who has access.',
+ };
+ return (
+ <div style={{display: 'grid', gap: '12px', maxWidth: '400px'}}>
+ <TabList
+ value={value}
+ onChange={setValue}
+ role="tablist"
+ aria-label="Project views"
+ hasDivider>
+ <Tab
+ value="overview"
+ label="Overview"
+ id="tab-overview"
+ panelId="panel-overview"
+ />
+ <Tab
+ value="activity"
+ label="Activity"
+ id="tab-activity"
+ panelId="panel-activity"
+ />
+ <Tab
+ value="members"
+ label="Members"
+ id="tab-members"
+ panelId="panel-members"
+ />
+ </TabList>
+ {Object.entries(panels).map(([key, text]) => (
+ <div
+ key={key}
+ id={`panel-${key}`}
+ role="tabpanel"
+ aria-labelledby={`tab-${key}`}
+ tabIndex={0}
+ hidden={key !== value}>
+ {text}
+ </div>
+ ))}
+ </div>
+ );
+ },
+};
diff --git a/packages/core/src/TabList/Tab.doc.mjs b/packages/core/src/TabList/Tab.doc.mjs
index 920cda54f8..13243201e6 100644
--- a/packages/core/src/TabList/Tab.doc.mjs
+++ b/packages/core/src/TabList/Tab.doc.mjs
@@ -40,7 +40,13 @@ export const docs = {
name: 'href',
type: 'string',
description:
- 'URL to navigate to; when provided, the tab renders as an anchor element.',
+ 'URL to navigate to; when provided, the tab renders as an anchor element. Ignored in a TabList given an explicit role="tablist".',
+ },
+ {
+ name: 'panelId',
+ type: 'string',
+ description:
+ 'Id of the panel this tab controls, wired up as aria-controls where the TabList speaks the tabs pattern. Put the same id on the panel element. No effect under the navigation pattern, and a development warning says so.',
},
{
name: 'as',
@@ -138,6 +144,12 @@ export const docsZh = {
type: 'string',
description: '要导航到的 URL;提供时,标签渲染为锚点元素。',
},
+ {
+ name: 'panelId',
+ type: 'string',
+ description:
+ 'Id of the panel this tab controls, wired up as aria-controls where the TabList speaks the tabs pattern. Put the same id on the panel element. No effect under the navigation pattern, and a development warning says so.',
+ },
{
name: 'as',
type: 'LinkComponentType',
diff --git a/packages/core/src/TabList/Tab.tsx b/packages/core/src/TabList/Tab.tsx
index e1943508a1..dfa5fc593b 100644
--- a/packages/core/src/TabList/Tab.tsx
+++ b/packages/core/src/TabList/Tab.tsx
@@ -7,7 +7,8 @@
* @input Uses React, StyleX, TabListContext
* @output Exports Tab component and TabProps type
* @position Core tab item; renders as button or anchor in navigation with a
- * divider-overlay selected indicator
+ * divider-overlay selected indicator. Where the TabList speaks the tabs
+ * pattern it is a button with role="tab".
*
* SYNC: When modified, update:
* - /packages/core/src/TabList/TabList.doc.mjs
@@ -35,6 +36,7 @@ import {tabScope} from './tab.markers.stylex';
import {useLinkComponent} from '../Link/useLinkComponent';
import type {LinkComponentType} from '../Link/types';
import {mergeProps} from '../utils';
+import {useDevWarning} from '../hooks/useDevWarning';
import {EDGE_COMP_ATTR} from '../Layout/edgeCompensation.stylex';
import {themeProps} from '../utils/themeProps';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
@@ -64,8 +66,20 @@ export interface TabProps extends BaseProps<HTMLButtonElement> {
isLabelHidden?: boolean;
/**
* URL to navigate to. When provided, renders as an anchor element.
+ *
+ * Ignored in a TabList given an explicit `role="tablist"`: activating a tab
+ * there swaps a panel in place, so a tab that navigates would be a false
+ * statement.
*/
href?: string;
+ /**
+ * Id of the panel this tab controls, wired up as `aria-controls` where the
+ * TabList speaks the tabs pattern. Put the same id on the panel element.
+ *
+ * Has no effect under the navigation pattern, where there is no panel to
+ * associate — a development warning says so.
+ */
+ panelId?: string;
/**
* Icon element shown when tab is not selected.
*/
@@ -228,6 +242,7 @@ export function Tab({
label,
isLabelHidden = false,
href,
+ panelId,
icon,
selectedIcon,
endContent,
@@ -242,6 +257,9 @@ export function Tab({
const isSelected = tabListCtx.value === value;
const size: TabListSize = tabListCtx.size;
const isFill = tabListCtx.layout === 'fill';
+ const isTabsPattern = tabListCtx.pattern === 'tabs';
+ const isLink = href != null && !isTabsPattern;
+ const isTabRole = isTabsPattern && !isLink;
const displayIcon = isSelected && selectedIcon ? selectedIcon : icon;
const hasVisibleLabel = !isLabelHidden && label !== '';
@@ -249,6 +267,34 @@ export function Tab({
tabListCtx.onChange(value);
}, [tabListCtx, value]);
+ useDevWarning(
+ 'Tab',
+ 'href is ignored in a role="tablist" TabList — a tab swaps a panel in ' +
+ 'place rather than navigating. Drop the href, or drop the role for the ' +
+ 'navigation pattern.',
+ isTabRole && href != null,
+ );
+
+ // A consumer who wired aria-controls by hand already said which panel this
+ // is, so panelId is the sugar, not the only way in.
+ const controls = panelId ?? restProps['aria-controls'];
+
+ useDevWarning(
+ 'Tab',
+ 'a tab in a role="tablist" TabList controls nothing: pass panelId with ' +
+ 'the id of the panel it opens, so assistive technology can associate ' +
+ 'the two.',
+ isTabRole && controls == null,
+ );
+
+ useDevWarning(
+ 'Tab',
+ 'panelId does nothing outside a role="tablist" TabList — the navigation ' +
+ 'pattern has no panel to associate. Give the TabList role="tablist", ' +
+ 'or drop the panelId.',
+ !isTabsPattern && panelId != null,
+ );
+
const iconElement = displayIcon ? (
<span {...stylex.props(styles.icon, iconSizeStyles[size])}>
{displayIcon}
@@ -260,11 +306,25 @@ export function Tab({
...(isLabelHidden ? {'aria-label': label} : {}),
[EDGE_COMP_ATTR]: '',
'data-tab-value': value,
- // Generic `true` ("the current item within a set"), not `page`: the strip
- // switches views in place at least as often as it navigates, and claiming
- // "current page" when no page changed is a false statement to a screen
- // reader. Stays truthful for the `href` case too, just less specific.
- 'aria-current': isSelected ? ('true' as const) : undefined,
+ ...(isTabRole
+ ? {
+ role: 'tab' as const,
+ 'aria-selected': isSelected,
+ // Only when there is a panel to point at: an aria-controls whose
+ // target does not exist is an invalid attribute value, which is a
+ // worse state than saying nothing. The dev warning above asks for
+ // the id instead.
+ 'aria-controls': controls,
+ }
+ : {
+ // Generic `true` ("the current item within a set"), not `page`: the
+ // strip switches views in place at least as often as it navigates,
+ // and claiming "current page" when no page changed is a false
+ // statement to a screen reader. Stays truthful for the `href` case
+ // too, just less specific. A tab role states this with
+ // aria-selected instead.
+ 'aria-current': isSelected ? ('true' as const) : undefined,
+ }),
// Roving tabindex: the tab strip is a single Tab stop. The selected tab is
// the tabbable one; the rest are reachable via arrow keys (handled by
// TabList's onKeyDown). When no tab is selected, TabList's repair effect
@@ -321,7 +381,7 @@ export function Tab({
<span {...stylex.props(styles.endContentWrapper)}>{endContent}</span>
) : null;
- if (href != null) {
+ if (isLink) {
return (
<LinkComponent
ref={ref}
diff --git a/packages/core/src/TabList/TabList.doc.mjs b/packages/core/src/TabList/TabList.doc.mjs
index e9932aea57..cf7c8b9893 100644
--- a/packages/core/src/TabList/TabList.doc.mjs
+++ b/packages/core/src/TabList/TabList.doc.mjs
@@ -28,7 +28,7 @@ export const docs = {
{name: '--_tab-indicator-bottom', description: 'Vertical offset of the selected-tab indicator from the tab bottom edge. A host that draws its own bottom divider (Toolbar) sets this so the indicator sits on the divider instead of above it.', default: '-1px', private: true},
],
},
- description: 'Nav wrapper that provides TabListContext (value, onChange, size) to Tab and TabMenu children.',
+ description: 'Tab strip that provides TabListContext (value, onChange, size) to Tab and TabMenu children; a nav landmark, or the WAI-ARIA tabs pattern where role="tablist" asks for it.',
props: [
{
name: 'value',
@@ -60,6 +60,11 @@ export const docs = {
description: 'Whether to show a bottom border divider under the tab list.',
default: 'false',
},
+ {
+ name: 'role',
+ type: 'AriaRole',
+ description: "ARIA role for the strip. 'tablist' asks for the WAI-ARIA tabs pattern: role=\"tablist\" / role=\"tab\" and aria-selected, with each tab pointing at the panel it controls via its panelId; only tabs may live in a tablist strip, and an href on a tab is ignored there. Left unset, the strip is a nav landmark marking the current tab with aria-current. Any other value is passed through to the element unchanged.",
+ },
{
name: 'overflow',
type: "'auto' | 'scroll' | 'visible'",
@@ -69,7 +74,7 @@ export const docs = {
{
name: 'children',
type: 'ReactNode',
- description: 'Tab and TabMenu items to render inside the nav.',
+ description: 'Tab and TabMenu items to render inside the strip.',
slotElements: [
{
__element: 'Tab',
@@ -98,6 +103,7 @@ export const docs = {
{ guidance: true, description: 'Keep tab labels short and descriptive so users can quickly scan available sections.' },
{ guidance: true, description: 'Leave overflow handling on: a strip narrower than its tabs scrolls, and the selected tab is kept in view. Use TabMenu when you want a curated group of extra options rather than a scrolling strip.' },
{ guidance: true, description: 'When using hasDivider with action buttons alongside tabs, match the Button size to the TabList size (both md, both sm); the divided tab strip reserves space so tabs and same-size buttons align to a shared baseline above the rail.' },
+ { guidance: true, description: 'Reach for role="tablist" when the strip switches panels in place, and give each tab a panelId pointing at the panel it opens: that link is how a screen reader gets from a tab to its content. Leave it off for navigation between views.' },
{ guidance: false, description: 'Use tabs for sequential steps or workflows; use a stepper or wizard pattern instead.' },
{ guidance: false, description: 'Place more than 6–8 visible tabs before the overflow menu; prioritize the most important categories.' },
{ guidance: false, description: 'Confuse TabList with SegmentedControl or ToggleButton. TabList is for navigation between views. SegmentedControl and ToggleButton are input controls: SegmentedControl always has exactly one selected option, while ToggleButton can be toggled on or off.' },
@@ -119,6 +125,7 @@ export const docsZh = {
{ guidance: true, description: 'Keep tab labels short and descriptive so users can quickly scan available sections.' },
{ guidance: true, description: 'Leave overflow handling on: a strip narrower than its tabs scrolls, and the selected tab is kept in view. Use TabMenu when you want a curated group of extra options rather than a scrolling strip.' },
{ guidance: true, description: 'When using hasDivider with action buttons alongside tabs, match the Button size to the TabList size (both md, both sm); the divided tab strip reserves space so tabs and same-size buttons align to a shared baseline above the rail.' },
+ { guidance: true, description: 'Reach for role="tablist" when the strip switches panels in place, and give each tab a panelId pointing at the panel it opens: that link is how a screen reader gets from a tab to its content. Leave it off for navigation between views.' },
{ guidance: false, description: 'Use tabs for sequential steps or workflows; use a stepper or wizard pattern instead.' },
{ guidance: false, description: 'Place more than 6–8 visible tabs before the overflow menu; prioritize the most important categories.' },
{ guidance: false, description: 'Confuse TabList with SegmentedControl or ToggleButton. TabList is for navigation between views. SegmentedControl and ToggleButton are input controls: SegmentedControl always has exactly one selected option, while ToggleButton can be toggled on or off.' },
@@ -133,7 +140,7 @@ export const docsZh = {
/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */
export const docsDense = {
- description: 'Tab navigation w/ overflow menu support; semantic nav landmark w/ button or anchor tab items.',
+ description: 'Tab strip w/ overflow scrolling; nav landmark by default, WAI-ARIA tabs pattern under role="tablist".',
usage: {
description:
'TabList provides tab-style navigation for organizing content into categorized sections. Use it to let users switch between related views without leaving the page, with overflow items handled by a built-in "more" menu.',
@@ -141,6 +148,7 @@ export const docsDense = {
{ guidance: true, description: 'Keep tab labels short and descriptive so users can quickly scan available sections.' },
{ guidance: true, description: 'Leave overflow handling on: a strip narrower than its tabs scrolls, and the selected tab is kept in view. Use TabMenu when you want a curated group of extra options rather than a scrolling strip.' },
{ guidance: true, description: 'When using hasDivider with action buttons alongside tabs, match the Button size to the TabList size (both md, both sm); the divided tab strip reserves space so tabs and same-size buttons align to a shared baseline above the rail.' },
+ { guidance: true, description: 'Reach for role="tablist" when the strip switches panels in place, and give each tab a panelId pointing at the panel it opens: that link is how a screen reader gets from a tab to its content. Leave it off for navigation between views.' },
{ guidance: false, description: 'Use tabs for sequential steps or workflows; use a stepper or wizard pattern instead.' },
{ guidance: false, description: 'Place more than 6–8 visible tabs before the overflow menu; prioritize the most important categories.' },
{ guidance: false, description: 'Confuse TabList with SegmentedControl or ToggleButton. TabList is for navigation between views. SegmentedControl and ToggleButton are input controls: SegmentedControl always has exactly one selected option, while ToggleButton can be toggled on or off.' },
diff --git a/packages/core/src/TabList/TabList.test.tsx b/packages/core/src/TabList/TabList.test.tsx
index 0e7adbdd1a..c266f4958f 100644
--- a/packages/core/src/TabList/TabList.test.tsx
+++ b/packages/core/src/TabList/TabList.test.tsx
@@ -1310,3 +1310,212 @@ describe('TabList overflow (scroll)', () => {
expect(scrollBy.mock.calls[0][0].left).toBeCloseTo(-420);
});
});
+
+describe('TabList ARIA pattern — role="tablist"', () => {
+ function warnSpy() {
+ return vi.spyOn(console, 'warn').mockImplementation(() => {});
+ }
+
+ it('speaks the tabs pattern: a labelled tablist of tabs with aria-selected', () => {
+ render(
+ <TabList value="b" onChange={() => {}} role="tablist" aria-label="Views">
+ <Tab value="a" label="Alpha" panelId="panel-a" />
+ <Tab value="b" label="Beta" panelId="panel-b" />
+ </TabList>,
+ );
+
+ const tablist = screen.getByRole('tablist', {name: 'Views'});
+ const tabs = screen.getAllByRole('tab');
+ expect(tabs).toHaveLength(2);
+ expect(tabs.every(tab => tablist.contains(tab))).toBe(true);
+ expect(tabs[0]).toHaveAttribute('aria-selected', 'false');
+ expect(tabs[1]).toHaveAttribute('aria-selected', 'true');
+ expect(tabs[1]).toHaveAttribute('aria-controls', 'panel-b');
+ expect(tabs[1]).not.toHaveAttribute('aria-current');
+ });
+
+ it('lets the consumer name the tablist from another element', () => {
+ render(
+ <>
+ <h2 id="views-heading">Project views</h2>
+ <TabList
+ value="a"
+ onChange={() => {}}
+ role="tablist"
+ aria-labelledby="views-heading">
+ <Tab value="a" label="Alpha" panelId="panel-a" />
+ </TabList>
+ </>,
+ );
+
+ expect(screen.getByRole('tablist', {name: 'Project views'})).not.toBeNull();
+ });
+
+ it('renders no navigation landmark around the tabs', () => {
+ const {container} = render(
+ <TabList value="a" onChange={() => {}} role="tablist">
+ <Tab value="a" label="Alpha" panelId="panel-a" />
+ </TabList>,
+ );
+
+ expect(container.querySelector('nav')).toBeNull();
+ expect(screen.queryByRole('navigation')).toBeNull();
+ });
+
+ it('omits aria-controls when a tab has no panel, and says so', () => {
+ const warn = warnSpy();
+ render(
+ <TabList value="a" onChange={() => {}} role="tablist">
+ <Tab value="a" label="Alpha" />
+ </TabList>,
+ );
+
+ expect(screen.getByRole('tab')).not.toHaveAttribute('aria-controls');
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining(
+ 'Tab: a tab in a role="tablist" TabList controls nothing',
+ ),
+ );
+ warn.mockRestore();
+ });
+
+ it('leaves a hand-wired aria-controls alone, and does not ask for a panelId it already has', () => {
+ const warn = warnSpy();
+ render(
+ <TabList value="a" onChange={() => {}} role="tablist">
+ <Tab value="a" label="Alpha" aria-controls="panel-written-by-hand" />
+ </TabList>,
+ );
+
+ expect(screen.getByRole('tab')).toHaveAttribute(
+ 'aria-controls',
+ 'panel-written-by-hand',
+ );
+ expect(warn).not.toHaveBeenCalled();
+ warn.mockRestore();
+ });
+
+ it('ignores href: the tab is a button, and the caller is told', () => {
+ const warn = warnSpy();
+ render(
+ <TabList value="a" onChange={() => {}} role="tablist">
+ <Tab value="a" label="Alpha" panelId="panel-a" href="/alpha" />
+ </TabList>,
+ );
+
+ const tab = screen.getByRole('tab');
+ expect(tab.tagName).toBe('BUTTON');
+ expect(tab).not.toHaveAttribute('href');
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('Tab: href is ignored in a role="tablist"'),
+ );
+ warn.mockRestore();
+ });
+
+ it('warns about anything in the strip that is not a tab, however it got there', () => {
+ const warn = warnSpy();
+ const showMenu = true;
+ render(
+ <TabList value="a" onChange={() => {}} role="tablist">
+ <Tab value="a" label="Alpha" panelId="panel-a" />
+ {showMenu ? (
+ <div>
+ <TabMenu label="More" options={[{value: 'b', label: 'Beta'}]} />
+ </div>
+ ) : null}
+ </TabList>,
+ );
+
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('TabList: role="tablist" owns only tabs'),
+ );
+ warn.mockRestore();
+ });
+
+ it('says nothing when the strip holds only tabs with panels', () => {
+ const warn = warnSpy();
+ render(
+ <TabList value="a" onChange={() => {}} role="tablist">
+ <Tab value="a" label="Alpha" panelId="panel-a" />
+ <Tab value="b" label="Beta" panelId="panel-b" />
+ </TabList>,
+ );
+
+ expect(warn).not.toHaveBeenCalled();
+ warn.mockRestore();
+ });
+
+ it('leaves ArrowDown and ArrowUp to the page', async () => {
+ // A tablist reports itself as horizontal, so the vertical arrows are the
+ // page's to scroll with.
+ const user = userEvent.setup();
+ render(
+ <TabList value="a" onChange={() => {}} role="tablist">
+ <Tab value="a" label="Alpha" panelId="panel-a" />
+ <Tab value="b" label="Beta" panelId="panel-b" />
+ </TabList>,
+ );
+
+ const alpha = screen.getByRole('tab', {name: 'Alpha'});
+ alpha.focus();
+ await user.keyboard('{ArrowDown}');
+ expect(alpha).toHaveFocus();
+ });
+});
+
+describe('TabList ARIA pattern — no role', () => {
+ it('is the navigation landmark it has always been', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ render(
+ <TabList value="a" onChange={() => {}} aria-label="Views">
+ <Tab value="a" label="Alpha" />
+ <Tab value="b" label="Beta" />
+ </TabList>,
+ );
+
+ expect(screen.getByRole('navigation', {name: 'Views'})).toBeInTheDocument();
+ expect(screen.queryByRole('tablist')).toBeNull();
+ expect(screen.getByRole('button', {name: 'Alpha'})).toHaveAttribute(
+ 'aria-current',
+ 'true',
+ );
+ expect(warn).not.toHaveBeenCalled();
+ warn.mockRestore();
+ });
+
+ it('drops a panelId and says so: there is no panel relationship to state', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ render(
+ <TabList value="a" onChange={() => {}}>
+ <Tab value="a" label="Alpha" panelId="panel-a" />
+ </TabList>,
+ );
+
+ expect(screen.getByRole('button', {name: 'Alpha'})).not.toHaveAttribute(
+ 'aria-controls',
+ );
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining(
+ 'Tab: panelId does nothing outside a role="tablist" TabList',
+ ),
+ );
+ warn.mockRestore();
+ });
+});
+
+describe('TabList ARIA pattern — any other role', () => {
+ it('passes the role through and leaves the tabs on the navigation pattern', () => {
+ const {container} = render(
+ <TabList value="a" onChange={() => {}} role="toolbar">
+ <Tab value="a" label="Alpha" />
+ </TabList>,
+ );
+
+ expect(container.querySelector('nav')).toHaveAttribute('role', 'toolbar');
+ expect(screen.queryByRole('tablist')).toBeNull();
+ expect(screen.getByRole('button', {name: 'Alpha'})).toHaveAttribute(
+ 'aria-current',
+ 'true',
+ );
+ });
+});
diff --git a/packages/core/src/TabList/TabList.tsx b/packages/core/src/TabList/TabList.tsx
index aa2c984b35..a40fef5fed 100644
--- a/packages/core/src/TabList/TabList.tsx
+++ b/packages/core/src/TabList/TabList.tsx
@@ -7,8 +7,10 @@
* @input Uses React, StyleX, TabListContext, useListFocus, useKeyboardHint,
* useScrollOverflow, Icon
* @output Exports TabList component, TabListProps and TabListOverflow types
- * @position Nav wrapper; provides TabListContext to Tab and TabMenu children.
- * Owns roving-tabindex keyboard navigation (Arrow/Home/End) across the tab
+ * @position Tab strip wrapper; provides TabListContext to Tab and TabMenu
+ * children. A `<nav>` landmark by default; speaks the WAI-ARIA tabs pattern
+ * where the caller asks for it with `role="tablist"`. Owns
+ * roving-tabindex keyboard navigation (Arrow/Home/End) across the tab
* strip via the shared useListFocus hook so it is a single Tab stop, and
* owns horizontal scrolling when the tabs are wider than the strip.
*
@@ -24,6 +26,7 @@ import React, {
useEffect,
useMemo,
useRef,
+ type AriaRole,
type ReactNode,
} from 'react';
import * as stylex from '@stylexjs/stylex';
@@ -51,6 +54,7 @@ import {Icon} from '../Icon';
import {EDGE_COMP_ATTR} from '../Layout/edgeCompensation.stylex';
import {themeProps} from '../utils/themeProps';
import {observeResize, unobserveResize} from '../utils/sharedResizeObserver';
+import {devWarn} from '../utils/devWarning';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
import {useTranslator} from '../i18n';
@@ -108,6 +112,19 @@ export interface TabListProps extends Omit<BaseProps<HTMLElement>, 'onChange'> {
* @default false
*/
hasDivider?: boolean;
+ /**
+ * ARIA role for the strip.
+ *
+ * `"tablist"` asks for the WAI-ARIA tabs pattern: `role="tablist"` /
+ * `role="tab"` and `aria-selected`, with each tab pointing at the panel it
+ * controls via its `panelId`. Only tabs may live in a tablist strip, and a
+ * tab does not navigate — an `href` is ignored there.
+ *
+ * Left unset, the strip is a `<nav>` landmark marking the current tab with
+ * `aria-current`. Any other value is passed through to the element
+ * unchanged.
+ */
+ role?: AriaRole;
/**
* What happens when the tabs are wider than the strip.
*
@@ -332,6 +349,7 @@ export function TabList({
size: sizeProp,
layout = 'hug',
hasDivider = false,
+ role,
overflow = 'auto',
xstyle,
className,
@@ -341,6 +359,7 @@ export function TabList({
onFocus: onFocusProp,
onBlur: onBlurProp,
'aria-label': ariaLabelFromProps,
+ 'aria-labelledby': ariaLabelledBy,
'aria-orientation': _ariaOrientation,
[EDGE_COMP_ATTR]: _edgeCompAttr,
...restProps
@@ -350,12 +369,20 @@ export function TabList({
const size = useSize(sizeProp, 'md');
const hasScroll = overflow !== 'visible';
+ const stripRef = useRef<HTMLDivElement | null>(null);
+ // Only an asserted `role="tablist"` switches the pattern. Left unset the
+ // strip is the `<nav>` it has always been, and every other role passes
+ // through to the element untouched.
+ const isTabList = role === 'tablist';
+
// Roving-tabindex keyboard navigation across the tab strip via the shared
- // hook. `orientation: 'both'` accepts both arrow axes per the WAI-ARIA APG
- // allowance for tab strips (ArrowRight/ArrowDown advance, ArrowLeft/ArrowUp
- // retreat). We do not set `aria-orientation` on the `<nav>`: that attribute
- // is invalid on the navigation role and triggers an axe `aria-allowed-attr`
- // violation.
+ // hook. Under the navigation pattern `orientation: 'both'` accepts both
+ // arrow axes per the WAI-ARIA APG allowance for tab strips
+ // (ArrowRight/ArrowDown advance, ArrowLeft/ArrowUp retreat). A tablist
+ // reports itself as horizontal, so there the strip takes only the
+ // horizontal arrows and leaves ArrowUp and ArrowDown to scroll the page. We
+ // do not set `aria-orientation` on the `<nav>`: that attribute is invalid on
+ // the navigation role and triggers an axe `aria-allowed-attr` violation.
//
// `hasRovingTabIndex` makes the hook own the single tab stop: it stamps
// tabindex 0/-1, repairs the stop on mount and as stops mount/unmount or
@@ -366,7 +393,7 @@ export function TabList({
// the first enabled stop when none is tabbable.
const {listRef, handleKeyDown, handleFocus} = useListFocus<HTMLElement>({
itemSelector: TAB_STOP_SELECTOR,
- orientation: 'both',
+ orientation: isTabList ? 'horizontal' : 'both',
hasRovingTabIndex: true,
});
@@ -378,7 +405,6 @@ export function TabList({
} = useKeyboardHint();
const {scrollRef, overflowStart, overflowEnd} = useScrollOverflow();
- const stripRef = useRef<HTMLDivElement | null>(null);
const attachStrip = useCallback(
(el: HTMLDivElement | null) => {
@@ -488,8 +514,14 @@ export function TabList({
const scrollToEnd = useCallback(() => scrollByPage(1), [scrollByPage]);
const contextValue = useMemo(
- () => ({value, onChange, size, layout}),
- [value, onChange, size, layout],
+ () => ({
+ value,
+ onChange,
+ size,
+ layout,
+ pattern: isTabList ? ('tabs' as const) : ('nav' as const),
+ }),
+ [value, onChange, size, layout, isTabList],
);
const handleRootKeyDown = useCallback(
@@ -531,6 +563,35 @@ export function TabList({
[onBlurProp, onHintBlur],
);
+ // `role="tablist"` owns only tabs, so anything else in the strip is invalid
+ // markup. Dev-only, and only under the asserted role — nothing else in the
+ // component reads the rendered DOM.
+ const hasWarnedContentRef = useRef(false);
+ useEffect(() => {
+ const strip = stripRef.current;
+ if (
+ process.env.NODE_ENV === 'production' ||
+ !isTabList ||
+ !strip ||
+ hasWarnedContentRef.current
+ ) {
+ return;
+ }
+ const stranger = Array.from(strip.children).find(
+ child => child.getAttribute('role') !== 'tab',
+ );
+ if (stranger) {
+ hasWarnedContentRef.current = true;
+ devWarn(
+ 'TabList',
+ `role="tablist" owns only tabs, but the strip contains a <${stranger.tagName.toLowerCase()}> that is not one. ` +
+ 'Render menus and other controls outside the strip, or drop the role for the navigation pattern.',
+ );
+ }
+ // No dependency list: the check is on rendered DOM, which can change
+ // without any prop this component could watch.
+ });
+
const fadeStyle = !hasScroll
? null
: overflowStart && overflowEnd
@@ -541,12 +602,19 @@ export function TabList({
? styles.fadeEnd
: null;
+ // A tablist is not navigation, so the landmark element is only right under
+ // the navigation pattern. The role is fixed by a prop rather than by what
+ // the strip happens to hold, so this is settled once at the callsite.
+ const Wrapper = isTabList ? 'div' : 'nav';
+
return (
<TabListContext value={contextValue}>
- <nav
+ <Wrapper
ref={useMergedRefs(ref, listRef)}
{...restProps}
- aria-label={ariaLabel}
+ role={isTabList ? undefined : role}
+ aria-label={isTabList ? undefined : ariaLabel}
+ aria-labelledby={isTabList ? undefined : ariaLabelledBy}
onKeyDown={handleRootKeyDown}
onFocus={handleRootFocus}
onBlur={handleRootBlur}
@@ -564,6 +632,10 @@ export function TabList({
)}>
<div
ref={attachStrip}
+ role={isTabList ? 'tablist' : undefined}
+ aria-label={isTabList ? ariaLabel : undefined}
+ // The name belongs to whichever element carries the widget role.
+ aria-labelledby={isTabList ? ariaLabelledBy : undefined}
{...mergeProps(
themeProps('tab-strip'),
stylex.props(
@@ -623,7 +695,7 @@ export function TabList({
</button>
)}
{hintElement}
- </nav>
+ </Wrapper>
</TabListContext>
);
}
diff --git a/packages/core/src/TabList/TabListContext.ts b/packages/core/src/TabList/TabListContext.ts
index 0fb4959021..b2c9b955ae 100644
--- a/packages/core/src/TabList/TabListContext.ts
+++ b/packages/core/src/TabList/TabListContext.ts
@@ -5,7 +5,7 @@
/**
* @file TabListContext.ts
* @input React createContext, use
- * @output Exports TabListContext, useTabListContext
+ * @output Exports TabListContext, useTabListContext, TabListPattern
* @position Context provider; consumed by Tab.tsx, TabMenu.tsx
*
* SYNC: When modified, update /packages/core/src/TabList/TabList.doc.mjs
@@ -27,13 +27,24 @@ export type TabListSize = 'sm' | 'md' | 'lg';
export type TabListLayout = 'hug' | 'fill';
/**
- * Context for communicating value/onChange/size/layout from TabList to children.
+ * ARIA pattern the strip resolved to.
+ * - `'nav'`: a `<nav>` of links or buttons, current item marked with
+ * `aria-current`.
+ * - `'tabs'`: the WAI-ARIA tabs pattern — `role="tablist"` / `role="tab"`,
+ * `aria-selected`, and `aria-controls` for the panel each tab owns.
+ */
+export type TabListPattern = 'nav' | 'tabs';
+
+/**
+ * Context for communicating value/onChange/size/layout and the resolved ARIA
+ * pattern from TabList to children.
*/
export interface TabListContextValue {
value: string;
onChange: (value: string) => void;
size: TabListSize;
layout: TabListLayout;
+ pattern: TabListPattern;
}
export const TabListContext = createContext<TabListContextValue | null>(null);
diff --git a/packages/core/src/TabList/index.ts b/packages/core/src/TabList/index.ts
index ab394cf08e..19bd429b5b 100644
--- a/packages/core/src/TabList/index.ts
+++ b/packages/core/src/TabList/index.ts
@@ -21,4 +21,8 @@ export {TabMenu} from './TabMenu';
export type {TabMenuProps, TabMenuOption} from './TabMenu';
export {useTabListContext} from './TabListContext';
-export type {TabListSize, TabListLayout} from './TabListContext';
+export type {
+ TabListSize,
+ TabListLayout,
+ TabListPattern,
+} from './TabListContext';