An open source design system that's fully customizable and agent ready
TypeScript
fix(core): single tab stop per CheckboxList option (#4364)
Baraa Hamodi21c607530548
diff --git a/.changeset/a11y-checkbox-list-tabstop.md b/.changeset/a11y-checkbox-list-tabstop.mdnew file mode 100644index 0000000000..f9014b0239--- /dev/null+++ b/.changeset/a11y-checkbox-list-tabstop.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] CheckboxList: each option is a single tab stop — the checkbox is the option's only focusable control (WCAG 4.1.2). The row is now an enlarged click/tap target that delegates surface clicks to the checkbox via a new `interactiveRef` prop on Item/ListItem (the useClickableContainer pattern), replacing the internal invisible row button. `interactiveRef` is mutually exclusive with `onClick`/`href`.+@bhamodidiff --git a/packages/core/src/CheckboxList/CheckboxList.test.tsx b/packages/core/src/CheckboxList/CheckboxList.test.tsxindex 8fbfa3ec95..5d92ed2400 100644--- a/packages/core/src/CheckboxList/CheckboxList.test.tsx+++ b/packages/core/src/CheckboxList/CheckboxList.test.tsx@@ -154,14 +154,105 @@ describe('CheckboxList', () => {</CheckboxList>,);- // Click the interactive row (invisible-button pattern), which is where the- // composed onClick lives — not the inner checkbox.- await user.click(screen.getByRole('button', {name: 'Option B'}));+ // The row is a pointer-only click surface (no invisible row button — the+ // checkbox is the option's only tab stop). Click the row's label area,+ // where the composed onClick fires — not the inner checkbox.+ expect(+ screen.queryByRole('button', {name: 'Option B'}),+ ).not.toBeInTheDocument();+ // The text also exists in the checkbox's visually hidden <label>; target+ // the row's label <span> to click the row surface.+ await user.click(screen.getByText('Option B', {selector: 'span'}));expect(handleClick).toHaveBeenCalledTimes(1);expect(handleChange).toHaveBeenCalledWith(['a', 'b']);});+ describe('single tab stop per option (WCAG 4.1.2 / APG checkbox pattern)', () => {+ it('renders exactly one focusable control per option — the checkbox, no row button', () => {+ render(+ <CheckboxList label="Preferences" value={['a']} onChange={() => {}}>+ <CheckboxListItem label="Option A" value="a" />+ <CheckboxListItem label="Option B" value="b" />+ </CheckboxList>,+ );+ // No invisible whole-row button duplicating the checkbox's action.+ expect(screen.queryByRole('button')).not.toBeInTheDocument();+ for (const item of screen.getAllByRole('listitem')) {+ const focusables = item.querySelectorAll(+ 'button, a[href], input, select, textarea, [tabindex]:not([tabindex="-1"])',+ );+ expect(focusables).toHaveLength(1);+ expect(focusables[0]).toBe(within(item).getByRole('checkbox'));+ }+ });++ it('Tab moves directly from one option checkbox to the next', async () => {+ const user = userEvent.setup();+ render(+ <CheckboxList label="Preferences" value={[]} onChange={() => {}}>+ <CheckboxListItem label="Option A" value="a" />+ <CheckboxListItem label="Option B" value="b" />+ </CheckboxList>,+ );+ await user.tab();+ expect(screen.getByRole('checkbox', {name: 'Option A'})).toHaveFocus();+ await user.tab();+ expect(screen.getByRole('checkbox', {name: 'Option B'})).toHaveFocus();+ // No further tab stop inside the list (the row itself is not focusable).+ await user.tab();+ expect(document.body).toHaveFocus();+ });++ it('clicking the row surface (outside the checkbox) still toggles', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <CheckboxList label="Preferences" value={['a']} onChange={handleChange}>+ <CheckboxListItem label="Option A" value="a" />+ <CheckboxListItem label="Option B" value="b" />+ </CheckboxList>,+ );+ // The text also exists in the checkbox's visually hidden <label>;+ // target the row's label <span> to click the row surface.+ await user.click(screen.getByText('Option B', {selector: 'span'}));+ expect(handleChange).toHaveBeenCalledTimes(1);+ expect(handleChange).toHaveBeenCalledWith(['a', 'b']);+ });++ it('toggles with Space on the focused checkbox, which reports checked state', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <CheckboxList label="Preferences" value={['a']} onChange={handleChange}>+ <CheckboxListItem label="Option A" value="a" />+ <CheckboxListItem label="Option B" value="b" />+ </CheckboxList>,+ );+ await user.tab();+ // The focused control is the checkbox itself, so its accessible name+ // and checked state are what assistive tech announces on focus.+ const checkboxA = screen.getByRole('checkbox', {name: 'Option A'});+ expect(checkboxA).toHaveFocus();+ expect(checkboxA).toBeChecked();+ await user.keyboard(' ');+ expect(handleChange).toHaveBeenCalledTimes(1);+ expect(handleChange).toHaveBeenCalledWith([]);+ });++ it('the row itself is not focusable', () => {+ render(+ <CheckboxList label="Preferences" value={[]} onChange={() => {}}>+ <CheckboxListItem label="Option A" value="a" />+ </CheckboxList>,+ );+ const item = screen.getByRole('listitem');+ expect(item).not.toHaveAttribute('tabindex');+ item.focus();+ expect(item).not.toHaveFocus();+ });+ });+it('disables all checkboxes when group isDisabled is true', () => {render(<CheckboxListdiff --git a/packages/core/src/CheckboxList/CheckboxListItem.tsx b/packages/core/src/CheckboxList/CheckboxListItem.tsxindex f76366274b..738715b085 100644--- a/packages/core/src/CheckboxList/CheckboxListItem.tsx+++ b/packages/core/src/CheckboxList/CheckboxListItem.tsx@@ -16,12 +16,11 @@* - /packages/cli/templates/blocks/components/CheckboxList/ (showcase blocks)*/-import {use, type MouseEvent, type ReactNode} from 'react';+import {use, useRef, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';import {colorVars} from '../theme/tokens.stylex';import type {BaseProps} from '../BaseProps';-import {composeEventHandlers} from '../utils';import {useDevWarning} from '../hooks/useDevWarning';import {CheckboxInput} from '../CheckboxInput/CheckboxInput';import {ListItem} from '../List/ListItem';@@ -212,6 +211,14 @@ export function CheckboxListItem({// Whether this item is interactive (has a toggle handler)const isInteractive = !effectiveReadOnly && (ctx != null || onCheck != null);+ // The checkbox is the row's single keyboard control and action. The row is+ // an enlarged click/tap target that delegates surface clicks to it via+ // ListItem's `interactiveRef` (useClickableContainer), so each option is+ // exactly one tab stop. Delegate whenever the row should respond to clicks:+ // a toggleable item, or one carrying a consumer `onClick`.+ const checkboxRef = useRef<HTMLInputElement | null>(null);+ const hasRowInteraction = isInteractive || onClickProp != null;+const handleToggle = () => {if (effectiveDisabled || effectiveReadOnly || isBusy) {return;@@ -244,14 +251,12 @@ export function CheckboxListItem({description={description}endContent={endContent}isDisabled={effectiveDisabled}- onClick={- isInteractive || onClickProp- ? composeEventHandlers<MouseEvent>(- onClickProp as ((event: MouseEvent) => void) | undefined,- isInteractive ? handleToggle : undefined,- )- : undefined- }+ // Delegate row clicks to the checkbox instead of wiring onClick (which+ // would add an invisible row button = a second tab stop). The checkbox+ // stays the option's sole focusable control (WCAG 4.1.2 / APG checkbox+ // pattern). A consumer onClick rides on the checkbox itself (below), so+ // it still fires for both direct and delegated (row-surface) clicks.+ interactiveRef={hasRowInteraction ? checkboxRef : undefined}aria-busy={isBusy || undefined}xstyle={[@@ -266,10 +271,12 @@ export function CheckboxListItem({style={style}startContent={<CheckboxInput+ ref={checkboxRef}label={checkboxLabel}isLabelHiddenvalue={resolvedChecked}onChange={() => handleToggle()}+ onClick={onClickProp}isDisabled={effectiveDisabled}isReadOnly={effectiveReadOnly}isLoading={isBusy}diff --git a/packages/core/src/Item/Item.doc.mjs b/packages/core/src/Item/Item.doc.mjsindex 5d6e9fc938..5f20477893 100644--- a/packages/core/src/Item/Item.doc.mjs+++ b/packages/core/src/Item/Item.doc.mjs@@ -37,6 +37,7 @@ export const docs = {{name: 'labelLines', type: 'number', description: 'Max lines before label truncates with ellipsis.'},{name: 'descriptionLines', type: 'number', description: 'Max lines before description truncates with ellipsis.'},{name: 'onClick', type: '(event: MouseEvent) => void', description: 'Click handler. Makes the item clickable with button semantics.'},+ {name: 'interactiveRef', type: 'RefObject<HTMLElement | null>', description: 'Ref to a nested control (e.g. a checkbox in startContent) that owns the item\'s keyboard access and action. The row becomes an enlarged click/tap target that delegates surface clicks to it (useClickableContainer) and renders no invisible button/anchor, so the row adds no second tab stop (WCAG 4.1.2). Mutually exclusive with onClick/href — those are ignored when set.'},{name: 'href', type: 'string', description: 'Link URL. Makes the item a link via an invisible anchor element.'},{name: 'target', type: "'_blank' | '_self'", description: 'Link target. Only used with href. target="_blank" automatically adds noopener noreferrer.'},{name: 'rel', type: 'string', description: 'Link relationship tokens. noopener noreferrer are merged automatically for target="_blank".'},@@ -90,6 +91,8 @@ export const docsZh = {labelLines: '标签截断前的最大行数。',descriptionLines: '描述截断前的最大行数。',onClick: '点击处理函数。使项目可点击,具有按钮语义。',+ interactiveRef:+ '指向嵌套控件(如 startContent 中的复选框)的 ref,该控件承载项目的键盘访问和操作。行成为更大的点击/触摸目标,将表面点击委托给该控件(useClickableContainer),且不渲染不可见按钮/锚点,因此行不会增加第二个 Tab 停留点(WCAG 4.1.2)。与 onClick/href 互斥——设置后二者将被忽略。',href: '链接 URL。通过不可见锚点元素使项目成为链接。',target: '链接目标。仅与 href 一起使用。target="_blank" 会自动添加 noopener noreferrer。',rel: '链接关系标记。target="_blank" 会自动合并 noopener noreferrer。',@@ -157,6 +160,8 @@ export const docsDense = {labelLines: 'Max label lines before truncation.',descriptionLines: 'Max description lines before truncation.',onClick: 'Click handler; enables button semantics.',+ interactiveRef:+ 'Ref to a nested control that owns the item\'s keyboard access/action; row delegates surface clicks to it (useClickableContainer), no invisible button/anchor, no second tab stop (WCAG 4.1.2). Mutually exclusive with onClick/href.',href: 'Link URL; enables anchor semantics.',target:'Link target, only with href. target="_blank" auto-adds noopener noreferrer.',diff --git a/packages/core/src/Item/Item.test.tsx b/packages/core/src/Item/Item.test.tsxindex 389fcb0e2c..36df1c048e 100644--- a/packages/core/src/Item/Item.test.tsx+++ b/packages/core/src/Item/Item.test.tsx@@ -9,11 +9,35 @@* SYNC: When Item component changes, update tests to match new behavior*/+import {useRef} from 'react';import {describe, it, expect, vi} from 'vitest';import {render, screen} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {Item} from './Item';+/**+ * Item in delegation mode: `interactiveRef` points at a nested control that+ * owns the row's keyboard access and action. The row is an enlarged tap target+ * that forwards surface clicks to that control (useClickableContainer).+ */+function DelegatingItem({onToggle}: {onToggle?: () => void}) {+ const ref = useRef<HTMLInputElement>(null);+ return (+ <Item+ label="Row"+ interactiveRef={ref}+ startContent={+ <input+ ref={ref}+ type="checkbox"+ aria-label="Pick row"+ onChange={onToggle}+ />+ }+ />+ );+}+describe('Item', () => {// ===========================================================================// Basic rendering@@ -190,6 +214,70 @@ describe('Item', () => {expect(buttons).toHaveLength(1);});+ // ===========================================================================+ // Interactive — interactiveRef (delegation to a nested control)+ // ===========================================================================++ it('renders no invisible button in interactiveRef (delegation) mode', () => {+ const {container} = render(<DelegatingItem />);+ // The nested control provides keyboard access — the row must not add a+ // second focusable control for the same action (WCAG 4.1.2).+ expect(container.querySelector('button')).not.toBeInTheDocument();+ });++ it('keeps the nested control as the only tab stop in interactiveRef mode', async () => {+ const user = userEvent.setup();+ render(<DelegatingItem />);+ await user.tab();+ expect(screen.getByRole('checkbox')).toHaveFocus();+ // Next tab leaves the item entirely — the row itself is not focusable.+ await user.tab();+ expect(screen.getByRole('checkbox')).not.toHaveFocus();+ expect(document.body).toHaveFocus();+ });++ it('delegates a row-surface click to the interactive control', async () => {+ const user = userEvent.setup();+ const onToggle = vi.fn();+ render(<DelegatingItem onToggle={onToggle} />);+ // Clicking the label (row surface) is forwarded to the checkbox.+ await user.click(screen.getByText('Row'));+ expect(onToggle).toHaveBeenCalledTimes(1);+ });++ it('does not double-fire when the interactive control itself is clicked', async () => {+ const user = userEvent.setup();+ const onToggle = vi.fn();+ render(<DelegatingItem onToggle={onToggle} />);+ await user.click(screen.getByRole('checkbox'));+ // The row must not re-forward the control's own click back to it.+ expect(onToggle).toHaveBeenCalledTimes(1);+ });++ it('ignores onClick when interactiveRef is set (delegation wins, single tab stop)', async () => {+ const user = userEvent.setup();+ const onClick = vi.fn();+ function ItemWithBoth() {+ const ref = useRef<HTMLInputElement>(null);+ return (+ <Item+ label="Row"+ onClick={onClick}+ interactiveRef={ref}+ startContent={+ <input ref={ref} type="checkbox" aria-label="Pick row" />+ }+ />+ );+ }+ const {container} = render(<ItemWithBoth />);+ // No invisible button (onClick is ignored in delegation mode)...+ expect(container.querySelector('button')).not.toBeInTheDocument();+ // ...and the checkbox is still the sole tab stop.+ await user.tab();+ expect(screen.getByRole('checkbox')).toHaveFocus();+ });+// ===========================================================================// Interactive — href (invisible anchor pattern)// ===========================================================================diff --git a/packages/core/src/Item/Item.tsx b/packages/core/src/Item/Item.tsxindex 4817c041df..554c83ba66 100644--- a/packages/core/src/Item/Item.tsx+++ b/packages/core/src/Item/Item.tsx@@ -4,7 +4,7 @@/*** @file Item.tsx- * @input Uses React, ReactNode, StyleXStyles, theme tokens+ * @input Uses React, ReactNode, StyleXStyles, theme tokens, useClickableContainer* @output Exports Item component, ItemProps type* @position Core layout primitive; consumed by index.ts, tested by Item.test.tsx*@@ -16,7 +16,7 @@* - /packages/cli/templates/blocks/components/Item/ (showcase blocks)*/-import type {ReactNode} from 'react';+import {useRef, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import {colorVars,@@ -27,9 +27,11 @@ import {typeScaleVars,} from '../theme/tokens.stylex';import type {BaseProps} from '../BaseProps';-import {mergeProps} from '../utils';+import {mergeProps, mergeRefs} from '../utils';import {computeTargetAndRel} from '../Link/computeTargetAndRel';import {useLinkComponent} from '../Link/useLinkComponent';+import {useClickableContainer} from '../hooks/useClickableContainer';+import {useDevWarning} from '../hooks/useDevWarning';import {themeProps} from '../utils/themeProps';// =============================================================================@@ -108,6 +110,20 @@ export interface ItemProps extends BaseProps<HTMLElement> {*/onClick?: (event: React.MouseEvent) => void;+ /**+ * Ref to a nested control inside the item (e.g. a checkbox in+ * `startContent`) that already provides the item's keyboard access and+ * action. When set, the item becomes an enlarged click/tap target that+ * delegates surface clicks to that control via the `useClickableContainer`+ * pattern: it renders no invisible button/anchor, so the row adds no second+ * tab stop (WCAG 4.1.2 — one focusable control per option). Clicks on the+ * control itself, and on any other nested interactive element, are left to+ * that element. Mutually exclusive with `onClick`/`href` — when+ * `interactiveRef` is set those are ignored (the nested control is the sole+ * action).+ */+ interactiveRef?: React.RefObject<HTMLElement | null>;+/*** Link URL. Makes the item a link via an invisible anchor element.*/@@ -349,6 +365,7 @@ export function Item({labelLines,descriptionLines,onClick,+ interactiveRef,href,target: targetFromProps,rel: relFromProps,@@ -363,7 +380,29 @@ export function Item({...restProps}: ItemProps) {const LinkComponent = useLinkComponent();- const isInteractive = onClick != null || href != null;++ // Delegation mode: the row is an enlarged click/tap target for a nested+ // control (e.g. a checkbox) that owns the keyboard access and action. The+ // control is the row's only tab stop; the row proxies surface clicks to it.+ const isDelegate = interactiveRef != null;+ const containerRef = useRef<HTMLElement | null>(null);+ // Only onClick is needed: onMouseUp handles middle-click href navigation,+ // which delegation mode never has (href is ignored here).+ const {onClick: delegatedOnClick} = useClickableContainer({+ containerRef,+ interactiveRef: interactiveRef ?? undefined,+ disabled: isDisabled,+ });++ useDevWarning(+ 'Item',+ '`interactiveRef` is mutually exclusive with `onClick`/`href`. In ' ++ 'delegation mode the row only forwards clicks to the referenced control, ' ++ 'so `onClick`/`href` are ignored. Drop one of them.',+ isDelegate && (onClick != null || href != null),+ );++ const isInteractive = onClick != null || href != null || isDelegate;const {target, rel} = computeTargetAndRel(targetFromProps, relFromProps);// When a semantic role is provided (e.g. "menuitem"), a parent component// handles keyboard access. Skip the invisible button/anchor and put@@ -441,7 +480,10 @@ export function Item({<span {...stylex.props(styles.startContent)}>{startContent}</span>)}- {hasParentRole ? (+ {hasParentRole || isDelegate ? (+ // Delegation mode (and parent-role mode) put the label in a plain span:+ // keyboard access lives on the nested control, so no invisible+ // button/anchor is rendered and the row adds no second tab stop.<span{...stylex.props(styles.content,@@ -497,7 +539,9 @@ export function Item({return (<Component- ref={ref as React.Ref<never>}+ ref={+ (isDelegate ? mergeRefs(ref, containerRef) : ref) as React.Ref<never>+ }{...restProps}aria-selected={(allowsAriaSelected && isSelected) || undefined}// aria-selected is invalid on roles that don't permit it (listitem, a@@ -527,11 +571,13 @@ export function Item({)}role={role}onClick={- hasParentRole- ? onClick- : isInteractive- ? handleContainerClick- : undefined+ isDelegate+ ? delegatedOnClick+ : hasParentRole+ ? onClick+ : isInteractive+ ? handleContainerClick+ : undefined}>{innerContent}</Component>diff --git a/packages/core/src/List/ListItem.doc.mjs b/packages/core/src/List/ListItem.doc.mjsindex 922a909a2b..1312442179 100644--- a/packages/core/src/List/ListItem.doc.mjs+++ b/packages/core/src/List/ListItem.doc.mjs@@ -59,6 +59,11 @@ export const docs = {type: '(e: MouseEvent) => void',description: 'Click handler; enables the invisible button pattern.',},+ {+ name: 'interactiveRef',+ type: 'RefObject<HTMLElement | null>',+ description: 'Ref to a nested control (e.g. a checkbox in startContent) that owns the item\'s keyboard access and action. The row becomes an enlarged click/tap target that delegates surface clicks to it (useClickableContainer) and renders no invisible button/anchor, so the row adds no second tab stop (WCAG 4.1.2). Mutually exclusive with onClick/href — those are ignored when set.',+ },{name: 'href',type: 'string',@@ -121,6 +126,11 @@ export const docsZh = {type: '(e: MouseEvent) => void',description: '点击处理函数;启用隐形按钮模式。',},+ {+ name: 'interactiveRef',+ type: 'RefObject<HTMLElement | null>',+ description: '指向嵌套控件(如 startContent 中的复选框)的 ref,该控件承载项目的键盘访问和操作。行成为更大的点击/触摸目标,将表面点击委托给该控件(useClickableContainer),且不渲染不可见按钮/锚点,因此行不会增加第二个 Tab 停留点(WCAG 4.1.2)。与 onClick/href 互斥——设置后二者将被忽略。',+ },{name: 'href',type: 'string',@@ -162,6 +172,8 @@ export const docsDense = {startContent: 'Content before label area (e.g. icon, avatar).',endContent: 'Content after label area (e.g. badge, chevron).',onClick: 'Click handler; enables invisible button pattern.',+ interactiveRef:+ 'Ref to a nested control that owns the item\'s keyboard access/action; row delegates surface clicks to it (useClickableContainer), no invisible button/anchor, no second tab stop (WCAG 4.1.2). Mutually exclusive with onClick/href.',href: 'Link URL; enables invisible anchor pattern.',target: 'Link target attribute, only when href provided. target="_blank" auto-adds noopener noreferrer.',rel: 'Link relationship tokens. noopener noreferrer are merged for target="_blank".',diff --git a/packages/core/src/List/ListItem.tsx b/packages/core/src/List/ListItem.tsxindex 3764f4edb3..17e7625288 100644--- a/packages/core/src/List/ListItem.tsx+++ b/packages/core/src/List/ListItem.tsx@@ -75,6 +75,17 @@ export interface ListItemProps extends BaseProps<HTMLLIElement> {*/onClick?: (e: React.MouseEvent) => void;+ /**+ * Ref to a nested control inside the item (e.g. a checkbox in+ * `startContent`) that already provides the item's keyboard access and+ * action. When set, the item becomes an enlarged click/tap target that+ * delegates surface clicks to that control via the `useClickableContainer`+ * pattern: it renders no invisible button/anchor, so the row adds no second+ * tab stop (WCAG 4.1.2 — one focusable control per option). Mutually+ * exclusive with `onClick`/`href` — when set those are ignored.+ */+ interactiveRef?: React.RefObject<HTMLElement | null>;+/*** URL for link items. Renders an invisible anchor element.* Automatically enables hover/press styles when provided.@@ -199,6 +210,7 @@ export function ListItem({startContent,endContent,onClick,+ interactiveRef,href,target,rel,@@ -239,6 +251,7 @@ export function ListItem({description={description}endContent={endContent}onClick={onClick}+ interactiveRef={interactiveRef}href={href}target={target as '_blank' | '_self'}rel={rel}