Skip to content

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

TypeScript

feat(tablist): roving tabindex + arrow-key navigation on the tab strip (navigation-1, interim) (#3434)

Cindy Zhang00b992d99e83
diff --git a/.changeset/tablist-roving-keyboard.md b/.changeset/tablist-roving-keyboard.md
new file mode 100644
index 0000000000..637f196502
--- /dev/null
+++ b/.changeset/tablist-roving-keyboard.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] TabList is now a single tab stop with arrow-key navigation between tabs (roving tabindex) — Arrow keys move focus, Home/End jump to the ends, disabled tabs are skipped, and focus wraps. This does not change the semantic roles (still `<nav>`/`aria-current`); the full tablist/tab/tabpanel conversion is tracked separately in #3335. Reference (#3343).
+
+@cixzhang
diff --git a/packages/core/src/TabList/Tab.tsx b/packages/core/src/TabList/Tab.tsx
index 6a35bdcc19..dcf4f118c8 100644
--- a/packages/core/src/TabList/Tab.tsx
+++ b/packages/core/src/TabList/Tab.tsx
@@ -259,7 +259,13 @@ export function Tab({
...restProps,
...(isLabelHidden ? {'aria-label': label} : {}),
[EDGE_COMP_ATTR]: '',
+ 'data-tab-value': value,
'aria-current': isSelected ? ('page' 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
+ // makes the first stop tabbable.
+ tabIndex: isSelected ? 0 : -1,
...mergeProps(
themeProps('tab', {
selected: isSelected ? 'selected' : null,
diff --git a/packages/core/src/TabList/TabList.doc.mjs b/packages/core/src/TabList/TabList.doc.mjs
index fd252fbf24..5edd9f30c8 100644
--- a/packages/core/src/TabList/TabList.doc.mjs
+++ b/packages/core/src/TabList/TabList.doc.mjs
@@ -55,6 +55,12 @@ export const docs = {
description: 'Whether to show a bottom border divider under the tab list.',
default: 'false',
},
+ {
+ name: 'orientation',
+ type: "'horizontal' | 'vertical'",
+ description: "Orientation of the tab strip, controlling which arrow keys move focus between tabs and the reported aria-orientation. 'horizontal': ArrowLeft/ArrowRight. 'vertical': ArrowUp/ArrowDown. Both axes' arrows are accepted regardless.",
+ default: "'horizontal'",
+ },
{
name: 'children',
type: 'ReactNode',
diff --git a/packages/core/src/TabList/TabList.test.tsx b/packages/core/src/TabList/TabList.test.tsx
index 661447d7f8..5de621dce6 100644
--- a/packages/core/src/TabList/TabList.test.tsx
+++ b/packages/core/src/TabList/TabList.test.tsx
@@ -280,6 +280,173 @@ describe('TabList', () => {
});
});
+describe('TabList keyboard navigation (roving tabindex)', () => {
+ it('exposes the tab strip as a single Tab stop (only selected tab is tabbable)', () => {
+ render(
+ <TabList value="settings" onChange={() => {}}>
+ <Tab value="home" label="Home" />
+ <Tab value="settings" label="Settings" />
+ <Tab value="profile" label="Profile" />
+ </TabList>,
+ );
+
+ expect(screen.getByRole('button', {name: 'Home'})).toHaveAttribute(
+ 'tabindex',
+ '-1',
+ );
+ expect(screen.getByRole('button', {name: 'Settings'})).toHaveAttribute(
+ 'tabindex',
+ '0',
+ );
+ expect(screen.getByRole('button', {name: 'Profile'})).toHaveAttribute(
+ 'tabindex',
+ '-1',
+ );
+ });
+
+ it('makes the first tab tabbable when the selected value matches no tab', () => {
+ render(
+ <TabList value="__none__" onChange={() => {}}>
+ <Tab value="home" label="Home" />
+ <Tab value="settings" label="Settings" />
+ </TabList>,
+ );
+
+ expect(screen.getByRole('button', {name: 'Home'})).toHaveAttribute(
+ 'tabindex',
+ '0',
+ );
+ expect(screen.getByRole('button', {name: 'Settings'})).toHaveAttribute(
+ 'tabindex',
+ '-1',
+ );
+ });
+
+ it('moves focus with ArrowRight and ArrowLeft', async () => {
+ const user = userEvent.setup();
+ render(
+ <TabList value="home" onChange={() => {}}>
+ <Tab value="home" label="Home" />
+ <Tab value="settings" label="Settings" />
+ <Tab value="profile" label="Profile" />
+ </TabList>,
+ );
+
+ const home = screen.getByRole('button', {name: 'Home'});
+ const settings = screen.getByRole('button', {name: 'Settings'});
+ const profile = screen.getByRole('button', {name: 'Profile'});
+
+ home.focus();
+ expect(home).toHaveFocus();
+
+ await user.keyboard('{ArrowRight}');
+ expect(settings).toHaveFocus();
+
+ await user.keyboard('{ArrowRight}');
+ expect(profile).toHaveFocus();
+
+ await user.keyboard('{ArrowLeft}');
+ expect(settings).toHaveFocus();
+ });
+
+ it('supports ArrowDown and ArrowUp as forward/backward as well', async () => {
+ const user = userEvent.setup();
+ render(
+ <TabList value="home" onChange={() => {}}>
+ <Tab value="home" label="Home" />
+ <Tab value="settings" label="Settings" />
+ </TabList>,
+ );
+
+ const home = screen.getByRole('button', {name: 'Home'});
+ const settings = screen.getByRole('button', {name: 'Settings'});
+
+ home.focus();
+ await user.keyboard('{ArrowDown}');
+ expect(settings).toHaveFocus();
+
+ await user.keyboard('{ArrowUp}');
+ expect(home).toHaveFocus();
+ });
+
+ it('jumps to first and last tab with Home and End', async () => {
+ const user = userEvent.setup();
+ render(
+ <TabList value="settings" onChange={() => {}}>
+ <Tab value="home" label="Home" />
+ <Tab value="settings" label="Settings" />
+ <Tab value="profile" label="Profile" />
+ </TabList>,
+ );
+
+ const home = screen.getByRole('button', {name: 'Home'});
+ const settings = screen.getByRole('button', {name: 'Settings'});
+ const profile = screen.getByRole('button', {name: 'Profile'});
+
+ settings.focus();
+
+ await user.keyboard('{End}');
+ expect(profile).toHaveFocus();
+
+ await user.keyboard('{Home}');
+ expect(home).toHaveFocus();
+ });
+
+ it('wraps around at the ends', async () => {
+ const user = userEvent.setup();
+ render(
+ <TabList value="home" onChange={() => {}}>
+ <Tab value="home" label="Home" />
+ <Tab value="settings" label="Settings" />
+ <Tab value="profile" label="Profile" />
+ </TabList>,
+ );
+
+ const home = screen.getByRole('button', {name: 'Home'});
+ const profile = screen.getByRole('button', {name: 'Profile'});
+
+ home.focus();
+ await user.keyboard('{ArrowLeft}');
+ expect(profile).toHaveFocus();
+
+ await user.keyboard('{ArrowRight}');
+ expect(home).toHaveFocus();
+ });
+
+ it('skips disabled tabs during arrow navigation', async () => {
+ const user = userEvent.setup();
+ render(
+ <TabList value="home" onChange={() => {}}>
+ <Tab value="home" label="Home" />
+ <Tab value="settings" label="Settings" aria-disabled="true" />
+ <Tab value="profile" label="Profile" />
+ </TabList>,
+ );
+
+ const home = screen.getByRole('button', {name: 'Home'});
+ const profile = screen.getByRole('button', {name: 'Profile'});
+
+ home.focus();
+ await user.keyboard('{ArrowRight}');
+ expect(profile).toHaveFocus();
+ });
+
+ it('does not intercept unrelated keys', async () => {
+ const user = userEvent.setup();
+ render(
+ <TabList value="home" onChange={() => {}}>
+ <Tab value="home" label="Home" />
+ <Tab value="settings" label="Settings" />
+ </TabList>,
+ );
+
+ const home = screen.getByRole('button', {name: 'Home'});
+ home.focus();
+ await user.keyboard('a');
+ expect(home).toHaveFocus();
+ });
+});
+
describe('Tab polymorphic link', () => {
it('renders custom component when href and as are provided', () => {
render(
diff --git a/packages/core/src/TabList/TabList.tsx b/packages/core/src/TabList/TabList.tsx
index 4e097d3d12..2b9efca57c 100644
--- a/packages/core/src/TabList/TabList.tsx
+++ b/packages/core/src/TabList/TabList.tsx
@@ -6,7 +6,9 @@
* @file TabList.tsx
* @input Uses React, StyleX, TabListContext
* @output Exports TabList component and TabListProps type
- * @position Nav wrapper; provides TabListContext to Tab and TabMenu children
+ * @position Nav wrapper; provides TabListContext to Tab and TabMenu children.
+ * Owns roving-tabindex keyboard navigation (Arrow/Home/End) across the tab
+ * strip so it is a single Tab stop.
*
* SYNC: When modified, update:
* - /packages/core/src/TabList/TabList.doc.mjs
@@ -15,21 +17,33 @@
* - /packages/cli/templates/blocks/components/TabList/ (showcase blocks)
*/
-import React, {useMemo, type ReactNode} from 'react';
+import React, {useCallback, useMemo, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {borderVars, colorVars, spacingVars} from '../theme/tokens.stylex';
import type {BaseProps} from '../BaseProps';
import {TabListContext} from './TabListContext';
-import type {TabListSize} from './TabListContext';
+import type {TabListOrientation, TabListSize} from './TabListContext';
import {useSize} from '../SizeContext/SizeContext';
-import {mergeProps} from '../utils';
+import {mergeProps, mergeRefs} from '../utils';
+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import {EDGE_COMP_ATTR} from '../Layout/edgeCompensation.stylex';
import {themeProps} from '../utils/themeProps';
-export interface TabListProps extends Omit<
- BaseProps<HTMLElement>,
- 'onChange'
-> {
+/**
+ * Selector matching the focusable stops in the tab strip: every Tab
+ * (`[data-tab-value]`) and every TabMenu trigger (`[data-tab-menu]`),
+ * in DOM order. Disabled stops are filtered out by the handler.
+ */
+const TAB_STOP_SELECTOR = '[data-tab-value],[data-tab-menu]';
+
+function isDisabledStop(el: HTMLElement): boolean {
+ return (
+ el.getAttribute('aria-disabled') === 'true' ||
+ (el instanceof HTMLButtonElement && el.disabled)
+ );
+}
+
+export interface TabListProps extends Omit<BaseProps<HTMLElement>, 'onChange'> {
ref?: React.Ref<HTMLElement>;
/**
* The currently selected tab value.
@@ -57,6 +71,15 @@ export interface TabListProps extends Omit<
* @default false
*/
hasDivider?: boolean;
+ /**
+ * Orientation of the tab strip, controlling which arrow keys move
+ * focus between tabs.
+ * - `'horizontal'` (default): ArrowLeft / ArrowRight (ArrowUp / ArrowDown
+ * also work per the WAI-ARIA APG).
+ * - `'vertical'`: ArrowUp / ArrowDown (ArrowLeft / ArrowRight also work).
+ * @default 'horizontal'
+ */
+ orientation?: TabListOrientation;
/**
* Tab and TabMenu children.
*/
@@ -104,6 +127,7 @@ export function TabList({
size: sizeProp,
layout = 'hug',
hasDivider = false,
+ orientation = 'horizontal',
xstyle,
className,
style,
@@ -111,17 +135,87 @@ export function TabList({
...restProps
}: TabListProps) {
const size = useSize(sizeProp, 'md');
+ const navRef = useRef<HTMLElement>(null);
const contextValue = useMemo(
() => ({value, onChange, size, layout}),
[value, onChange, size, layout],
);
+ // Roving tabindex: the tab strip is a single Tab stop. Individual Tabs set
+ // tabIndex={0} on the selected tab and -1 on the rest (see Tab.tsx). If the
+ // selected value doesn't correspond to any focusable stop (e.g. selection
+ // lives in a collapsed TabMenu that renders no matching stop, or there is no
+ // selection at all), no stop would be tabbable — this effect repairs that by
+ // making the first stop tabbable. Same pattern as the SegmentedControl fix.
+ useIsomorphicLayoutEffect(() => {
+ const nav = navRef.current;
+ if (nav == null) {
+ return;
+ }
+ const stops = Array.from(
+ nav.querySelectorAll<HTMLElement>(TAB_STOP_SELECTOR),
+ );
+ if (stops.length === 0) {
+ return;
+ }
+ const hasTabbable = stops.some(el => el.tabIndex === 0);
+ if (!hasTabbable) {
+ const firstEnabled = stops.find(el => !isDisabledStop(el)) ?? stops[0];
+ firstEnabled.tabIndex = 0;
+ }
+ });
+
+ const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLElement>) => {
+ const nav = navRef.current;
+ if (nav == null) {
+ return;
+ }
+
+ // Accept both axes' arrows per the WAI-ARIA APG so keyboard users don't
+ // have to know the orientation: forward keys advance, backward keys
+ // retreat. Orientation only affects the reported aria-orientation.
+ const isForward = e.key === 'ArrowRight' || e.key === 'ArrowDown';
+ const isBackward = e.key === 'ArrowLeft' || e.key === 'ArrowUp';
+
+ if (!isForward && !isBackward && e.key !== 'Home' && e.key !== 'End') {
+ return;
+ }
+
+ const stops = Array.from(
+ nav.querySelectorAll<HTMLElement>(TAB_STOP_SELECTOR),
+ ).filter(el => !isDisabledStop(el));
+ if (stops.length === 0) {
+ return;
+ }
+
+ const currentIndex = stops.findIndex(el => el === document.activeElement);
+ let nextIndex: number;
+
+ if (e.key === 'Home') {
+ nextIndex = 0;
+ } else if (e.key === 'End') {
+ nextIndex = stops.length - 1;
+ } else if (isForward) {
+ nextIndex = currentIndex === -1 ? 0 : (currentIndex + 1) % stops.length;
+ } else {
+ nextIndex =
+ currentIndex === -1
+ ? stops.length - 1
+ : (currentIndex - 1 + stops.length) % stops.length;
+ }
+
+ e.preventDefault();
+ stops[nextIndex].focus();
+ }, []);
+
return (
<TabListContext value={contextValue}>
<nav
- ref={ref}
+ ref={mergeRefs(ref, navRef)}
aria-label="Tabs"
+ aria-orientation={orientation}
+ onKeyDown={handleKeyDown}
{...{[EDGE_COMP_ATTR]: ''}}
{...restProps}
{...mergeProps(
diff --git a/packages/core/src/TabList/TabListContext.ts b/packages/core/src/TabList/TabListContext.ts
index 76adce856b..50d5228c7c 100644
--- a/packages/core/src/TabList/TabListContext.ts
+++ b/packages/core/src/TabList/TabListContext.ts
@@ -26,6 +26,12 @@ export type TabListSize = 'sm' | 'md' | 'lg';
*/
export type TabListLayout = 'hug' | 'fill';
+/**
+ * Orientation of the tab strip. Controls which arrow keys move focus
+ * between tabs and the reported `aria-orientation`.
+ */
+export type TabListOrientation = 'horizontal' | 'vertical';
+
/**
* Context for communicating value/onChange/size/layout from TabList to children.
*/
@@ -36,9 +42,7 @@ export interface TabListContextValue {
layout: TabListLayout;
}
-export const TabListContext = createContext<TabListContextValue | null>(
- null,
-);
+export const TabListContext = createContext<TabListContextValue | null>(null);
TabListContext.displayName = 'TabListContext';
/**
diff --git a/packages/core/src/TabList/TabMenu.tsx b/packages/core/src/TabList/TabMenu.tsx
index 19b7e41187..9232037934 100644
--- a/packages/core/src/TabList/TabMenu.tsx
+++ b/packages/core/src/TabList/TabMenu.tsx
@@ -309,6 +309,8 @@ export function TabMenu({
aria-haspopup="menu"
aria-expanded={popover.isOpen}
aria-controls={menuId}
+ data-tab-menu=""
+ tabIndex={hasSelectedOption ? 0 : -1}
onClick={handleToggle}
{...mergeProps(
themeProps('tab-menu'),
@@ -393,9 +395,7 @@ export function TabMenu({
})}
{option.label}
</span>
- {isSelected && (
- <Icon icon="check" size="sm" color="accent" />
- )}
+ {isSelected && <Icon icon="check" size="sm" color="accent" />}
</div>
);
})}