An open source design system that's fully customizable and agent ready
TypeScript
fix(Selector): a disabled Selector trigger keeps its tab stop (#7844)
Cindy Zhangef184a721479
diff --git a/.changeset/selector-focusable-disabled.md b/.changeset/selector-focusable-disabled.mdnew file mode 100644index 0000000000..9f71b56c26--- /dev/null+++ b/.changeset/selector-focusable-disabled.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A disabled `Selector` keeps its place in the tab order, so keyboard and screen-reader users can reach it and hear that it is unavailable (WCAG 2.2 SC 2.1.1 Keyboard and 4.1.2 Name, Role, Value; `spec:AST-085` FR1–FR4). Before, its trigger rendered the native `disabled` attribute and `tabIndex={-1}`, so Tab skipped it and a focused trigger lost focus when disabled; now it exposes `aria-disabled="true"`, keeps focus, still opens nothing, and submits no form value. Like a natively disabled button, it runs no caller event handler other than focus and blur, and a press on it reaches no handler. A focused disabled trigger shows a keyboard focus ring, dimmed with the rest of the control (SC 2.4.7 Focus Visible; `spec:AST-085` FR6).++@cixzhangdiff --git a/packages/core/src/PowerSearch/PowerSearchFilterEditor.test.tsx b/packages/core/src/PowerSearch/PowerSearchFilterEditor.test.tsxindex 826c0a1740..1237f1f946 100644--- a/packages/core/src/PowerSearch/PowerSearchFilterEditor.test.tsx+++ b/packages/core/src/PowerSearch/PowerSearchFilterEditor.test.tsx@@ -370,7 +370,8 @@ describe('PowerSearchFilterEditor', () => {expect(screen.queryByRole('button', {name: 'Delete'})).toBeNull();const [fieldTrigger, operatorTrigger] = selectorTriggers();- expect(fieldTrigger).toBeDisabled();- expect(operatorTrigger).toBeDisabled();+ // Disabled triggers stay focusable (spec:AST-085 FR1).+ expect(fieldTrigger).toHaveAttribute('aria-disabled', 'true');+ expect(operatorTrigger).toHaveAttribute('aria-disabled', 'true');});});diff --git a/packages/core/src/Selector/Selector.doc.mjs b/packages/core/src/Selector/Selector.doc.mjsindex 24d71c660f..185648d100 100644--- a/packages/core/src/Selector/Selector.doc.mjs+++ b/packages/core/src/Selector/Selector.doc.mjs@@ -273,7 +273,7 @@ export const docs = {name: 'disabledMessage',type: 'string',description:- 'Explains why the selector is disabled. With isDisabled, shows a tooltip on hover/keyboard focus and keeps the trigger focusable via aria-disabled (activation stays blocked). Use this instead of wrapping a disabled Selector in Tooltip. Disabled controls swallow the hover events an external Tooltip needs.',+ 'Explains why the selector is disabled. With isDisabled, shows the reason as a tooltip on hover and keyboard focus of the trigger, which stays focusable (aria-disabled) like every disabled selector; activation stays blocked. Use this instead of wrapping a disabled Selector in Tooltip.',},{name: 'isLabelHidden',@@ -475,7 +475,7 @@ export const docs = {{guidance: false,description:- 'Wrap a disabled Selector in Tooltip to explain why it is disabled; disabled triggers swallow the hover events the wrapper needs. Use the disabledMessage prop instead.',+ 'Wrap a disabled Selector in Tooltip to explain why it is disabled. Use the disabledMessage prop, which attaches the reason to the trigger itself.',},],anatomy,@@ -536,7 +536,7 @@ export const docsZh = {{guidance: false,description:- 'Wrap a disabled Selector in Tooltip to explain why it is disabled; disabled triggers swallow the hover events the wrapper needs. Use the disabledMessage prop instead.',+ 'Wrap a disabled Selector in Tooltip to explain why it is disabled. Use the disabledMessage prop, which attaches the reason to the trigger itself.',},],anatomy,@@ -607,7 +607,7 @@ export const docsDense = {{guidance: false,description:- 'Wrap a disabled Selector in Tooltip to explain why it is disabled; disabled triggers swallow the hover events the wrapper needs. Use the disabledMessage prop instead.',+ 'Wrap a disabled Selector in Tooltip to explain why it is disabled. Use the disabledMessage prop, which attaches the reason to the trigger itself.',},],anatomy,diff --git a/packages/core/src/Selector/Selector.focusableDisabled.test.tsx b/packages/core/src/Selector/Selector.focusableDisabled.test.tsxnew file mode 100644index 0000000000..cf73b63fb9--- /dev/null+++ b/packages/core/src/Selector/Selector.focusableDisabled.test.tsx@@ -0,0 +1,127 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Selector.focusableDisabled.test.tsx+ * @input Uses vitest, @testing-library/react, StyleX, Selector+ * @output Conformance tests for spec:AST-085 FR1–FR4 and FR6 on Selector+ * @position Testing; validates the disabled trigger of Selector.tsx+ */++import {describe, it, expect, vi} from 'vitest';+import {act, render, screen} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import * as stylex from '@stylexjs/stylex';+import {colorVars} from '../theme/tokens.stylex';+import {Selector} from './Selector';++type Handler = () => void;+function Harness(props: {+ isDisabled: boolean;+ variant?: 'input' | 'secondary' | 'ghost';+ onClick?: Handler;+ onKeyDown?: Handler;+ onMouseDown?: Handler;+ onDoubleClick?: Handler;+}) {+ return (+ <form aria-label="Form">+ <button type="button">Before</button>+ <Selector+ label="Fruit"+ htmlName="fruit"+ options={['Apple', 'Banana']}+ value="Banana"+ onChange={() => {}}+ {...props}+ />+ <button type="button">After</button>+ </form>+ );+}++const trigger = () => screen.getByRole('combobox', {name: 'Fruit'});++describe('Selector disabled (spec:AST-085)', () => {+ it('FR1: renders no native disabled and keeps its tab stop', async () => {+ const user = userEvent.setup();+ const {container} = render(<Harness isDisabled />);+ expect(container.querySelector('[disabled]')).toBeNull();+ expect(trigger()).toHaveAttribute('aria-disabled', 'true');+ await user.click(screen.getByRole('button', {name: 'Before'}));+ await user.tab();+ expect(trigger()).toHaveFocus();+ await user.tab();+ expect(screen.getByRole('button', {name: 'After'})).toHaveFocus();+ });++ it('FR2: no press or key opens it or reaches a caller or ancestor handler', async () => {+ const user = userEvent.setup();+ const handlers = {+ onClick: vi.fn(),+ onKeyDown: vi.fn(),+ onMouseDown: vi.fn(),+ onDoubleClick: vi.fn(),+ };+ const onAncestorClick = vi.fn();+ render(+ <div onClick={onAncestorClick}>+ <Harness isDisabled {...handlers} />+ </div>,+ );+ await user.dblClick(trigger());+ trigger().focus();+ for (const key of ['{Enter}', ' ', '{ArrowDown}', 'b']) {+ await user.keyboard(key);+ }+ expect(trigger()).toHaveAttribute('aria-expanded', 'false');+ expect(screen.queryByRole('listbox')).toBeNull();+ for (const handler of [...Object.values(handlers), onAncestorClick]) {+ expect(handler).not.toHaveBeenCalled();+ }+ });++ it('FR3: submits no value while disabled', () => {+ const {rerender} = render(<Harness isDisabled={false} />);+ const form = () =>+ screen.getByRole<HTMLFormElement>('form', {name: 'Form'});+ expect(new FormData(form()).getAll('fruit')).toEqual(['Banana']);+ rerender(<Harness isDisabled />);+ expect(new FormData(form()).getAll('fruit')).toEqual([]);+ });++ it('FR4: keeps focus when it becomes disabled while focused', () => {+ const {rerender} = render(<Harness isDisabled={false} />);+ act(() => trigger().focus());+ rerender(<Harness isDisabled />);+ expect(trigger()).toHaveFocus();+ });++ // jsdom cannot match `:focus-visible`: compare the ring's StyleX class hash.+ const RING = stylex+ .props(+ stylex.create({+ ring: {+ boxShadow: {+ default: null,+ ':has(> [aria-disabled="true"]:focus-visible)': `inset 0px 0px 0px 2px ${colorVars['--color-accent-muted']}`,+ },+ },+ }).ring,+ )+ .className!.split(' ')+ .pop()!;++ it.each([+ ['input', true],+ ['secondary', false],+ ['ghost', false],+ ] as const)(+ 'FR6: a disabled %s trigger carries its own ring: %s',+ (variant, ring) => {+ render(<Harness isDisabled variant={variant} />);+ const wrapper = trigger().parentElement!;+ expect(wrapper.classList.contains(RING)).toBe(ring);+ expect(getComputedStyle(wrapper).cursor).toBe('default');+ },+ );+});diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsxindex 8a92adaa3f..7b40a39ede 100644--- a/packages/core/src/Selector/Selector.test.tsx+++ b/packages/core/src/Selector/Selector.test.tsx@@ -36,7 +36,7 @@ import {InternationalizationProvider} from '../i18n';import {defineTheme} from '../theme/defineTheme';import {Theme} from '../theme/Theme';import {generateThemeCSS} from '../theme/generateThemeRules';-import {spacingVars} from '../theme/tokens.stylex';+import {colorVars, spacingVars} from '../theme/tokens.stylex';import {selectorPresentationStyles} from './selectorPresentation.stylex';import {groupStyles} from '../InputGroup/groupStyles';@@ -303,6 +303,45 @@ describe('Selector', () => {);});+ it('shows no disabled focus ring after a pointer pick (spec:AST-085 FR6)', async () => {+ const field = (isDisabled: boolean) => (+ <Selector+ label="Fruit"+ options={OPTIONS}+ onChange={() => {}}+ presentation="bottom-sheet"+ isDisabled={isDisabled}+ />+ );+ const {rerender} = render(field(false));+ const trigger = screen.getByRole('combobox');+ fireEvent.pointerDown(trigger, {pointerType: 'touch'});+ fireEvent.click(trigger, {detail: 1});+ const option = await screen.findByRole('option', {name: /Banana/});+ fireEvent.pointerDown(option, {pointerType: 'touch'});+ fireEvent.click(option, {detail: 1});+ rerender(field(true));++ const ring = stylex+ .props(+ stylex.create({+ ring: {+ boxShadow: {+ default: null,+ ':has(> [aria-disabled="true"]:focus-visible)': `inset 0px 0px 0px 2px ${colorVars['--color-accent-muted']}`,+ },+ },+ }).ring,+ )+ .className!.split(' ')+ .pop()!;+ const wrapper = screen.getByRole('combobox').parentElement!;+ expect(wrapper).toHaveClass(+ stylex.props(selectorPresentationStyles.pointerRestoredFocus).className!,+ );+ expect(wrapper).not.toHaveClass(ring);+ });+it('uses content-hugging height without extra bottom content padding', () => {const source = readFileSync('packages/core/src/Selector/SelectorBottomSheet.tsx',@@ -1821,9 +1860,11 @@ describe('Selector', () => {expect(screen.getByRole('combobox')).toHaveFocus();});- it('trigger is not focusable when disabled', () => {+ it('trigger keeps its tab stop when disabled (spec:AST-085 FR1)', () => {render(<Selector label="Fruit" options={OPTIONS} isDisabled />);- expect(screen.getByRole('combobox')).toHaveAttribute('tabIndex', '-1');+ const trigger = screen.getByRole('combobox');+ expect(trigger).toHaveAttribute('tabIndex', '0');+ expect(trigger).toHaveAttribute('aria-disabled', 'true');});it('opens the listbox with ArrowDown from a focused trigger', async () => {@@ -2715,11 +2756,12 @@ describe('Selector', () => {expect(onChange).not.toHaveBeenCalled();});- it('remains non-focusable when disabled without a reason', () => {+ it('stays focusable when disabled without a reason (spec:AST-085 FR1)', () => {render(<Selector label="Fruit" options={OPTIONS} isDisabled />);const trigger = screen.getByRole('combobox');- expect(trigger).toBeDisabled();- expect(trigger).toHaveAttribute('tabIndex', '-1');+ expect(trigger).not.toHaveAttribute('disabled');+ expect(trigger).toHaveAttribute('aria-disabled', 'true');+ expect(trigger).toHaveAttribute('tabIndex', '0');});});describe('isReadOnly', () => {diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsxindex 487e0f149c..81e4a1aeb2 100644--- a/packages/core/src/Selector/Selector.tsx+++ b/packages/core/src/Selector/Selector.tsx@@ -291,6 +291,21 @@ const styles = stylex.create({'[data-astryx-press="on"]': 'scale(0.98)',},},+ // A disabled input-variant trigger keeps its tab stop (`spec:AST-085` FR1),+ // and the shared disabled wrapper style drops the field focus ring, so the+ // trigger shows keyboard focus here instead (FR6). It keys on the trigger+ // itself, a direct child, so a focused status button keeps its own outline.+ triggerDisabledFocus: {+ borderColor: {+ default: colorVars['--color-border-emphasized'],+ ':has(> [aria-disabled="true"]:focus-visible)':+ colorVars['--color-accent'],+ },+ boxShadow: {+ default: 'none',+ ':has(> [aria-disabled="true"]:focus-visible)': `inset 0px 0px 0px 2px ${colorVars['--color-accent-muted']}`,+ },+ },triggerGhostDisabled: {backgroundImage: 'none',transform: {@@ -627,8 +642,8 @@ interface SelectorPropsBase<* The selected value stays visible, focusable, and included in form* submission, and retains its combobox identity with `aria-readonly`. The* selection surface and editing affordances are removed.- * Unlike `isDisabled`, a read-only selector is not dimmed and stays in the- * tab order. `isDisabled` takes precedence when both are set.+ * Unlike `isDisabled`, a read-only selector is not dimmed and keeps its+ * value in form submission. `isDisabled` takes precedence when both are set.* @default false*/isReadOnly?: boolean;@@ -640,8 +655,8 @@ interface SelectorPropsBase<* so the reason is discoverable by keyboard and assistive technology.* Activation stays blocked.*- * Use this instead of wrapping a disabled selector in `Tooltip` — disabled- * controls don't emit the pointer events an external tooltip needs.+ * Use this instead of wrapping a disabled selector in `Tooltip`, so the+ * reason is attached to the trigger itself.** @example* ```@@ -1872,8 +1887,24 @@ export function Selector<T extends SelectorOptionType>(});}+ // A disabled trigger stays focusable but, like a natively disabled button,+ // runs no caller event handler other than focus and blur, and a press on it+ // reaches no handler at all (`spec:AST-085` FR2).+ const callerProps = isDisabled+ ? Object.fromEntries(+ Object.entries(rest).filter(+ ([key]) => !/^on[A-Z]/.test(key) || /^on(Focus|Blur)/.test(key),+ ),+ )+ : rest;const triggerSharedProps: React.HTMLAttributes<HTMLElement> = {- ...rest,+ ...callerProps,+ onClick: isDisabled+ ? event => {+ event.preventDefault();+ event.stopPropagation();+ }+ : rest.onClick,id: triggerId,// A caller's description is kept alongside the field's own.'aria-describedby':@@ -1887,12 +1918,14 @@ export function Selector<T extends SelectorOptionType>(// it leaves uncancelled. A caller `onClick` arrives through `rest` and// runs on the trigger before the press bubbles to the control box's// toggle, as it always has.- onKeyDown: composeEventHandlers(handleTriggerKeyDown, onKeyDownProp),+ onKeyDown: isDisabled+ ? handleTriggerKeyDown+ : composeEventHandlers(handleTriggerKeyDown, onKeyDownProp),onFocus: event => {onFocus?.(event);surface.onTriggerFocus(event);},- tabIndex: isDisabled && !showsDisabledMessage ? -1 : 0,+ tabIndex: 0,...stylex.props(styles.trigger,isEffectivelyReadOnly && styles.triggerReadOnly,@@ -1932,6 +1965,10 @@ export function Selector<T extends SelectorOptionType>(surface.isTriggerFocusRingSuppressed &&selectorPresentationStyles.pointerRestoredFocus,isDisabled && inputWrapperStyles.disabled,+ variant === 'input' &&+ isDisabled &&+ !surface.isTriggerFocusRingSuppressed &&+ styles.triggerDisabledFocus,isEffectivelyReadOnly && styles.triggerReadOnly,variant !== 'input' && isDisabled && styles.triggerGhostDisabled,variant !== 'input' &&@@ -1991,22 +2028,15 @@ export function Selector<T extends SelectorOptionType>(? getItemId(highlightedIndex): undefined}- // With a disabledMessage the trigger keeps focusability via- // aria-disabled so the reason is focus-discoverable; activation is- // still blocked by the isDisabled guards in useCombobox.- disabled={isDisabled && !showsDisabledMessage}- aria-disabled={showsDisabledMessage ? 'true' : undefined}>+ // A disabled trigger keeps its tab stop and says so through+ // aria-disabled (`spec:AST-085` FR1); the isDisabled guards in+ // useCombobox block every way of opening it.+ aria-disabled={isDisabled ? 'true' : undefined}>{valueContent}</button>- {htmlName != null && (- <input- type="hidden"- name={htmlName}- value={value ?? ''}- // Disabled native controls are excluded from form submission;- // mirror that for the hidden carrier.- disabled={isDisabled}- />+ {/* A disabled selector submits no value (`spec:AST-085` FR3). */}+ {htmlName != null && !isDisabled && (+ <input type="hidden" name={htmlName} value={value ?? ''} />)}{isBusy && <Spinner size="sm" />}{hasClear && value != null && !isDisabled && !isEffectivelyReadOnly && (