An open source design system that's fully customizable and agent ready
TypeScript
fix(ButtonGroup): one roving tab stop across the group's members (#5389)
Cindy Zhang917cc106f6b1
diff --git a/.changeset/button-group-roving-tabindex.md b/.changeset/button-group-roving-tabindex.mdnew file mode 100644index 0000000000..630ed307cb--- /dev/null+++ b/.changeset/button-group-roving-tabindex.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] ButtonGroup is a single tab stop. Its members now share one roving tab stop instead of taking one each, so a three-button group costs one Tab press rather than three. Arrow keys move between members along the orientation (flipped in RTL), Home/End jump to the ends, focus wraps, and disabled members are skipped. Two consequences worth knowing: a keyboard script or test that tabbed through a group member by member must use arrow keys now, and a member rendered as a link (`href`) joins the arrow order for the first time. (#5389)++@cixzhangdiff --git a/packages/core/src/ButtonGroup/ButtonGroup.doc.mjs b/packages/core/src/ButtonGroup/ButtonGroup.doc.mjsindex 50f2a65960..85ee61260b 100644--- a/packages/core/src/ButtonGroup/ButtonGroup.doc.mjs+++ b/packages/core/src/ButtonGroup/ButtonGroup.doc.mjs@@ -47,6 +47,7 @@ export const docs = {{guidance: false, description: "Don't use ButtonGroup for navigation. Use SegmentedControl or TabList for switching between views."},{guidance: false, description: "Don't nest ButtonGroups. If you need multiple groups, place them side by side with a gap."},{guidance: true, description: 'Name the group for what its buttons act on. The label is the group\u2019s accessible name and a screen reader reads it before each member.'},+ {guidance: true, description: 'Keep the group a single Tab stop. Arrow keys move between members along the orientation, Home/End jump to the ends, and disabled members are skipped — the WAI-ARIA APG roving tabindex technique: https://www.w3.org/WAI/ARIA/apg/practices/keyboard-interface/#kbd_roving_tabindex'},{guidance: false, description: "Don't disable the group to show that an action is in flight. A disabled member drops focus, so a keyboard user loses their place; leave the group enabled and show progress on the button that started the work."},],anatomy: [@@ -87,6 +88,7 @@ export const docsZh = {{guidance: false, description: '不要使用 ButtonGroup 进行导航,使用 SegmentedControl 或 TabList 切换视图。'},{guidance: false, description: '不要嵌套 ButtonGroup。如需多个组,请并排放置并留有间隔。'},{guidance: true, description: '按钮组的标签应说明这些按钮作用于什么。该标签是按钮组的无障碍名称,屏幕阅读器会在每个成员之前朗读它。'},+ {guidance: true, description: '按钮组是单个 Tab 停靠点。方向键沿排列方向在成员间移动焦点,Home/End 跳到首尾,禁用成员会被跳过——即 WAI-ARIA APG 的 roving tabindex 技术。'},{guidance: false, description: '不要用禁用整个按钮组来表示操作进行中。禁用的成员会失去焦点,键盘用户会丢失位置;请保持按钮组可用,并在发起操作的按钮上显示进度。'},],anatomy: [@@ -110,6 +112,7 @@ export const docsDense = {{guidance: false, description: "Don't use for navigation. Use SegmentedControl or TabList."},{guidance: false, description: "Don't nest ButtonGroups."},{guidance: true, description: 'Label the group for what its buttons act on; it is the accessible name.'},+ {guidance: true, description: 'Single Tab stop; arrows move between members, Home/End to ends, disabled skipped (APG roving tabindex).'},{guidance: false, description: "Don't disable the group for an in-flight action; a disabled member drops focus."},],},diff --git a/packages/core/src/ButtonGroup/ButtonGroup.test.tsx b/packages/core/src/ButtonGroup/ButtonGroup.test.tsxindex 4889720177..db807d683a 100644--- a/packages/core/src/ButtonGroup/ButtonGroup.test.tsx+++ b/packages/core/src/ButtonGroup/ButtonGroup.test.tsx@@ -12,6 +12,7 @@*/import {describe, it, expect} from 'vitest';+import type {ReactNode} from 'react';import {render, screen, fireEvent} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {transformSync} from '@babel/core';@@ -764,6 +765,25 @@ describe('ButtonGroup', () => {).toHaveFocus();});+ it('leaves a link member in the arrow order', async () => {+ const user = userEvent.setup();+ render(+ <ButtonGroup label="Docs actions">+ <Button label="Save" />+ <Button label="Docs" href="https://example.com" />+ <Button label="Print" />+ </ButtonGroup>,+ );++ screen.getByRole('button', {name: 'Save'}).focus();++ await user.keyboard('{ArrowRight}');+ expect(screen.getByRole('link', {name: 'Docs'})).toHaveFocus();++ await user.keyboard('{ArrowRight}');+ expect(screen.getByRole('button', {name: 'Print'})).toHaveFocus();+ });+it('still moves between its own members when the group sits inside a popover', async () => {const user = userEvent.setup();// A group rendered inside a Popover, ContextMenu, HoverCard or Toast has@@ -796,4 +816,190 @@ describe('ButtonGroup', () => {expect(button('Copy')).toHaveFocus();});});++ // ===========================================================================+ // Roving tabindex+ //+ // The group is a single tab stop: exactly one enabled member carries+ // tabindex="0", the rest carry -1, and the stop moves with arrow navigation.+ // Entering and leaving is asserted through the real tab order as well as the+ // attribute, because the attribute alone says nothing about a member the+ // itemSelector missed — such a member stays natively tabbable and quietly+ // adds a second stop.+ // ===========================================================================+ describe('roving tabindex', () => {+ const tabIndexOf = (name: string) =>+ screen.getByRole('button', {name}).getAttribute('tabindex');++ const bracketed = (group: ReactNode) => (+ <>+ <button type="button">before</button>+ {group}+ <button type="button">after</button>+ </>+ );++ const clipboard = (+ <ButtonGroup label="Actions">+ <Button label="Copy" />+ <Button label="Cut" />+ <Button label="Paste" />+ </ButtonGroup>+ );++ it('gives the group one tab stop, on the first member', () => {+ render(clipboard);++ expect(tabIndexOf('Copy')).toBe('0');+ expect(tabIndexOf('Cut')).toBe('-1');+ expect(tabIndexOf('Paste')).toBe('-1');+ });++ it('takes one Tab to enter and one to leave', async () => {+ const user = userEvent.setup();+ render(bracketed(clipboard));++ await user.tab();+ expect(screen.getByRole('button', {name: 'before'})).toHaveFocus();++ await user.tab();+ expect(screen.getByRole('button', {name: 'Copy'})).toHaveFocus();++ await user.tab();+ expect(screen.getByRole('button', {name: 'after'})).toHaveFocus();+ });++ it('moves the tab stop with arrow navigation', async () => {+ const user = userEvent.setup();+ render(clipboard);++ screen.getByRole('button', {name: 'Copy'}).focus();+ await user.keyboard('{ArrowRight}');++ expect(tabIndexOf('Copy')).toBe('-1');+ expect(tabIndexOf('Cut')).toBe('0');+ });++ it('never parks the tab stop on a disabled member', () => {+ render(+ <ButtonGroup label="Actions">+ <Button label="Copy" isDisabled />+ <Button label="Cut" />+ <Button label="Paste" />+ </ButtonGroup>,+ );++ expect(tabIndexOf('Copy')).toBe('-1');+ expect(tabIndexOf('Cut')).toBe('0');+ });++ it('repairs the tab stop when the member holding it unmounts', () => {+ const {rerender} = render(+ <ButtonGroup label="Actions">+ <Button label="Copy" />+ <Button label="Cut" />+ </ButtonGroup>,+ );+ expect(tabIndexOf('Copy')).toBe('0');++ rerender(+ <ButtonGroup label="Actions">+ <Button label="Cut" />+ </ButtonGroup>,+ );++ expect(tabIndexOf('Cut')).toBe('0');+ });++ it('repairs the tab stop when the member holding it becomes disabled', () => {+ const {rerender} = render(+ <ButtonGroup label="Actions">+ <Button label="Copy" />+ <Button label="Cut" />+ </ButtonGroup>,+ );+ expect(tabIndexOf('Copy')).toBe('0');++ rerender(+ <ButtonGroup label="Actions">+ <Button label="Copy" isDisabled />+ <Button label="Cut" />+ </ButtonGroup>,+ );++ expect(tabIndexOf('Copy')).toBe('-1');+ expect(tabIndexOf('Cut')).toBe('0');+ });++ it('counts a link member as the tab stop', async () => {+ const user = userEvent.setup();+ render(+ bracketed(+ <ButtonGroup label="Docs actions">+ <Button label="Docs" href="https://example.com" />+ <Button label="Print" />+ </ButtonGroup>,+ ),+ );++ expect(+ screen.getByRole('link', {name: 'Docs'}).getAttribute('tabindex'),+ ).toBe('0');+ expect(tabIndexOf('Print')).toBe('-1');++ await user.tab();+ await user.tab();+ expect(screen.getByRole('link', {name: 'Docs'})).toHaveFocus();++ await user.tab();+ expect(screen.getByRole('button', {name: 'after'})).toHaveFocus();+ });++ it('contributes no tab stop when the whole group is disabled', async () => {+ const user = userEvent.setup();+ render(+ bracketed(+ <ButtonGroup label="Actions" isDisabled>+ <Button label="Copy" />+ <Button label="Cut" />+ </ButtonGroup>,+ ),+ );++ await user.tab();+ expect(screen.getByRole('button', {name: 'before'})).toHaveFocus();++ await user.tab();+ expect(screen.getByRole('button', {name: 'after'})).toHaveFocus();+ });++ it('leaves the tab stop on its own members when a member owns an open menu', async () => {+ const user = userEvent.setup();+ render(+ <ButtonGroup label="Approve action">+ <Button label="Allow once" />+ <DropdownMenu+ hasChevron={false}+ button={{label: 'Allow options', isIconOnly: true}}+ items={[{label: 'Allow for 30 minutes'}, {label: 'Always allow'}]}+ />+ </ButtonGroup>,+ );++ const trigger = screen.getByRole('button', {name: /Allow options/});+ expect(tabIndexOf('Allow once')).toBe('0');+ expect(trigger.getAttribute('tabindex')).toBe('-1');++ await user.click(trigger);++ // The menu's own items are a different list level (the boundary), so the+ // group must not stamp them or hand them its tab stop.+ const item = screen.getByRole('menuitem', {+ name: 'Allow for 30 minutes',+ hidden: true,+ });+ expect(item.getAttribute('tabindex')).not.toBe('0');+ expect(tabIndexOf('Allow once')).toBe('0');+ });+ });});diff --git a/packages/core/src/ButtonGroup/ButtonGroup.tsx b/packages/core/src/ButtonGroup/ButtonGroup.tsxindex 6bea9d6b83..631d0fefce 100644--- a/packages/core/src/ButtonGroup/ButtonGroup.tsx+++ b/packages/core/src/ButtonGroup/ButtonGroup.tsx@@ -131,6 +131,10 @@ const elevationStyles = stylex.create({* Children automatically detect the group via context and apply position-aware* styles in pure CSS.*+ * The group is a single tab stop: arrow keys move between members along the+ * orientation, Home/End jump to the ends, focus wraps, and disabled members are+ * skipped (the APG roving tabindex technique, via `useListFocus`).+ ** Members that render their own layer — a Button with a `tooltip`, or a* DropdownMenu — compose correctly, including as the trailing member.*@@ -167,12 +171,16 @@ export function ButtonGroup({ref,'data-testid': testId,onKeyDown,+ onFocus,...props}: ButtonGroupProps): ReactNode {const size = useSize(sizeProp, 'md');- const {listRef, handleKeyDown} = useListFocus<HTMLDivElement>({- itemSelector: 'button, [tabindex="0"]',+ const {listRef, handleKeyDown, handleFocus} = useListFocus<HTMLDivElement>({+ // Roving rewrites `tabindex` on every item, so the selector cannot key off+ // a value: `[tabindex="0"]` would drop each member the moment it is+ // stamped -1. `a[href]` catches a Button rendered with `href`.+ itemSelector: 'button, a[href], [tabindex]',// A member's layer renders inline inside the group (useLayer does not// portal it), so a key pressed in an open DropdownMenu bubbles here. The// boundary is the group's own root or any layer, whichever is nearer to@@ -181,6 +189,7 @@ export function ButtonGroup({// instead would swallow every arrow key it owns.boundarySelector: '[role="group"], [popover]',orientation,+ hasRovingTabIndex: true,});const contextValue = useMemo(@@ -208,6 +217,7 @@ export function ButtonGroup({role="group"aria-label={label}onKeyDown={composeEventHandlers(onKeyDown, handleKeyDown)}+ onFocus={composeEventHandlers(onFocus, handleFocus)}aria-disabled={isDisabled || undefined}data-testid={testId}>{children}