An open source design system that's fully customizable and agent ready
TypeScript
fix(MultiSelector): a disabled trigger keeps its tab stop (#7852)
Cindy Zhangb2c4f180a17f
diff --git a/.changeset/multiselector-focusable-disabled.md b/.changeset/multiselector-focusable-disabled.mdnew file mode 100644index 0000000000..9f989ece75--- /dev/null+++ b/.changeset/multiselector-focusable-disabled.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A disabled `MultiSelector` 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/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 13e122a342..2f8aa9bb46 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1401,6 +1401,16 @@ jobs:--project chromium \--output empty-state-announcement-output+ # A disabled MultiSelector trigger keeps focus when it is disabled while+ # focused. jsdom never moves focus off a newly disabled element, so only+ # a real engine shows the loss this guards against.+ - name: Run MultiSelector disabled-focus contract+ run: |+ pnpm exec playwright test \+ packages/core/src/MultiSelector/MultiSelector.disabledFocus.a11y.chromium.spec.ts \+ --project chromium \+ --output multiselector-disabled-focus-output+# Table merges a consumer min-width with its column floors through CSS# max(). jsdom keeps any string, so only a real engine shows whether the# emitted declaration parses; an invalid one drops the floors entirely.diff --git a/packages/core/src/MultiSelector/MultiSelector.disabledFocus.a11y.chromium.spec.ts b/packages/core/src/MultiSelector/MultiSelector.disabledFocus.a11y.chromium.spec.tsnew file mode 100644index 0000000000..f643f4dcc8--- /dev/null+++ b/packages/core/src/MultiSelector/MultiSelector.disabledFocus.a11y.chromium.spec.ts@@ -0,0 +1,71 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file MultiSelector.disabledFocus.a11y.chromium.spec.ts+ * @input The `Core/MultiSelector` Default story in a built Storybook.+ * @output Real-engine proof of `spec:AST-085` FR4: a trigger disabled while it+ * holds keyboard focus keeps focus and reports itself disabled.+ * @position Run with `pnpm test:a11y-contract`; a DOM emulator does not move+ * focus off an element that becomes disabled, so it cannot show the loss.+ */++import {expect, test} from '@playwright/test';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => {+ await storybook?.close();+});++test('a focused trigger keeps focus when it becomes disabled', async ({+ page,+}) => {+ const storyId = 'core-multiselector--default';+ await page.goto(+ `${storybook.origin}/iframe.html?id=${storyId}&viewMode=story`,+ );+ const trigger = page.getByRole('combobox', {name: 'Columns'});+ await trigger.focus();+ await expect(trigger).toBeFocused();++ await page.evaluate(id => {+ const channel = (+ window as unknown as {+ __STORYBOOK_ADDONS_CHANNEL__?: {+ emit: (event: string, payload: unknown) => void;+ };+ }+ ).__STORYBOOK_ADDONS_CHANNEL__;+ if (channel == null) {+ throw new Error('Storybook channel is unavailable');+ }+ channel.emit('updateStoryArgs', {+ storyId: id,+ updatedArgs: {isDisabled: true},+ });+ }, storyId);++ // Wait for the disabled re-render in either form, so focus is checked+ // after it lands.+ await expect+ .poll(async () =>+ trigger.evaluate(+ el =>+ el.hasAttribute('disabled') ||+ el.getAttribute('aria-disabled') === 'true',+ ),+ )+ .toBe(true);+ await expect(trigger).toBeFocused();+});diff --git a/packages/core/src/MultiSelector/MultiSelector.doc.mjs b/packages/core/src/MultiSelector/MultiSelector.doc.mjsindex a2c6827cfb..a49be6bc39 100644--- a/packages/core/src/MultiSelector/MultiSelector.doc.mjs+++ b/packages/core/src/MultiSelector/MultiSelector.doc.mjs@@ -304,7 +304,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 MultiSelector 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 MultiSelector in Tooltip.',},{name: 'isLabelHidden',@@ -511,7 +511,7 @@ export const docs = {{guidance: false,description:- 'Wrap a disabled MultiSelector 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 MultiSelector in Tooltip to explain why it is disabled. Use the disabledMessage prop, which attaches the reason to the trigger itself.',},],},@@ -552,7 +552,7 @@ export const docsZh = {htmlName:'用于表单提交的 HTML name 属性。为每个已选值渲染一个隐藏输入,类似原生多选。',disabledMessage:- '解释选择器被禁用的原因。与 isDisabled 一起使用时,悬停/键盘聚焦时显示工具提示,并通过 aria-disabled 保持触发器可聚焦(仍无法激活)。请使用此属性,而不是用 Tooltip 包裹被禁用的选择器。',+ '解释选择器被禁用的原因。与 isDisabled 一起使用时,悬停/键盘聚焦时显示工具提示,触发器与所有被禁用的选择器一样通过 aria-disabled 保持可聚焦(仍无法激活)。请使用此属性,而不是用 Tooltip 包裹被禁用的选择器。',isLabelHidden: '视觉上隐藏标签同时保持其可访问性。',description: '标签下方显示的辅助文本。',isOptional: '将字段标记为可选。',@@ -619,7 +619,7 @@ export const docsZh = {{guidance: false,description:- 'Wrap a disabled MultiSelector 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 MultiSelector in Tooltip to explain why it is disabled. Use the disabledMessage prop, which attaches the reason to the trigger itself.',},],},@@ -674,7 +674,7 @@ export const docsDense = {{guidance: false,description:- 'Wrap a disabled MultiSelector 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 MultiSelector in Tooltip to explain why it is disabled. Use the disabledMessage prop, which attaches the reason to the trigger itself.',},],},diff --git a/packages/core/src/MultiSelector/MultiSelector.focusableDisabled.test.tsx b/packages/core/src/MultiSelector/MultiSelector.focusableDisabled.test.tsxnew file mode 100644index 0000000000..22ebe3677b--- /dev/null+++ b/packages/core/src/MultiSelector/MultiSelector.focusableDisabled.test.tsx@@ -0,0 +1,121 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file MultiSelector.focusableDisabled.test.tsx+ * @input Uses vitest, @testing-library/react, StyleX, MultiSelector+ * @output Conformance tests for spec:AST-085 FR1–FR3 and FR6 on MultiSelector;+ * FR4 needs a real engine (MultiSelector.disabledFocus.a11y.chromium.spec.ts)+ * @position Testing; validates the disabled trigger of MultiSelector.tsx+ */++import {describe, it, expect, vi} from 'vitest';+import {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 {MultiSelector} from './MultiSelector';++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>+ <MultiSelector+ 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('MultiSelector 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([]);+ });++ // 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/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsxindex c2016dde39..e4fb8dffb3 100644--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx@@ -35,7 +35,7 @@ import {generateThemeCSS} from '../theme/generateThemeRules';import {selectorPresentationStyles} from '../Selector/selectorPresentation.stylex';import {groupStyles} from '../InputGroup/groupStyles';import {InputGroup, InputGroupText} from '../InputGroup';-import {focusVars} from '../theme/tokens.stylex';+import {colorVars, focusVars} from '../theme/tokens.stylex';function generateThemeTestCSS(theme: Parameters<typeof generateThemeCSS>[0]) {const {prose, component} = generateThemeCSS(theme);@@ -210,6 +210,45 @@ describe('MultiSelector', () => {);});+ it('shows no disabled focus ring after a pointer pick (spec:AST-085 FR6)', async () => {+ const field = (isDisabled: boolean) => (+ <MultiSelector+ label="Fruit"+ options={defaultOptions}+ value={[]}+ 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 dialog = await screen.findByRole('dialog', {name: 'Fruit'});+ fireEvent.pointerDown(dialog, {pointerType: 'touch'});+ fireEvent.click(dialog, {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('renders with label', () => {render(<MultiSelector@@ -515,7 +554,9 @@ describe('MultiSelector', () => {isDisabled/>,);- expect(screen.getByRole('combobox')).toBeDisabled();+ const trigger = screen.getByRole('combobox');+ expect(trigger).not.toHaveAttribute('disabled');+ expect(trigger).toHaveAttribute('aria-disabled', 'true');});it('has correct ARIA attributes', () => {@@ -1602,7 +1643,7 @@ describe('MultiSelector', () => {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(<MultiSelectorlabel="Fruit"@@ -1612,7 +1653,7 @@ describe('MultiSelector', () => {isDisabled/>,);- expect(screen.getByRole('combobox')).toHaveAttribute('tabIndex', '-1');+ expect(screen.getByRole('combobox')).toHaveAttribute('tabIndex', '0');});it('opens the listbox with ArrowDown from a focused trigger', async () => {@@ -2076,7 +2117,7 @@ describe('MultiSelector', () => {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(<MultiSelectorlabel="Fruit"@@ -2087,8 +2128,9 @@ describe('MultiSelector', () => {/>,);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/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsxindex 9fbe560e0c..9f1e827fbe 100644--- a/packages/core/src/MultiSelector/MultiSelector.tsx+++ b/packages/core/src/MultiSelector/MultiSelector.tsx@@ -271,6 +271,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: {@@ -688,8 +703,8 @@ export interface MultiSelectorProps<* The selected values stay visible, focusable, and included in form* submission, and retain their 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;@@ -701,8 +716,8 @@ export interface MultiSelectorProps<* 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* ```@@ -2409,8 +2424,18 @@ export function MultiSelector<T extends MultiSelectorOptionType>({});}+ // 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,id: triggerId,// A caller's description is kept alongside the field's own.'aria-describedby':@@ -2423,13 +2448,20 @@ export function MultiSelector<T extends MultiSelectorOptionType>({// Newly forwarded handlers compose component first: the built-in toggle// and keyboard model always run. `onFocus` keeps its existing caller-first// order.- onKeyDown: composeEventHandlers(onKeyDown, onKeyDownProp),+ onKeyDown: isDisabled+ ? onKeyDown+ : composeEventHandlers(onKeyDown, onKeyDownProp),onFocus: event => {onFocus?.(event);surface.onTriggerFocus(event);},- onClick: composeEventHandlers(handleTriggerButtonClick, onClick),- tabIndex: isDisabled && !showsDisabledMessage ? -1 : 0,+ onClick: isDisabled+ ? event => {+ event.preventDefault();+ event.stopPropagation();+ }+ : composeEventHandlers(handleTriggerButtonClick, onClick),+ tabIndex: 0,...stylex.props(styles.trigger,isEffectivelyReadOnly && styles.triggerReadOnly,@@ -2496,14 +2528,9 @@ export function MultiSelector<T extends MultiSelectorOptionType>({<>{renderTrigger(triggerProps)}{htmlName != null &&+ !isDisabled &&value.map(v => (- <input- key={v}- type="hidden"- name={htmlName}- value={v}- disabled={isDisabled}- />+ <input key={v} type="hidden" name={htmlName} value={v} />))}{selectionSurface}</>@@ -2541,6 +2568,10 @@ export function MultiSelector<T extends MultiSelectorOptionType>({surface.isTriggerFocusRingSuppressed &&selectorPresentationStyles.pointerRestoredFocus,isDisabled && inputWrapperStyles.disabled,+ variant === 'input' &&+ isDisabled &&+ !surface.isTriggerFocusRingSuppressed &&+ styles.triggerDisabledFocus,isEffectivelyReadOnly && styles.triggerReadOnly,variant !== 'input' && isDisabled && styles.triggerGhostDisabled,variant !== 'input' &&@@ -2598,26 +2629,19 @@ export function MultiSelector<T extends MultiSelectorOptionType>({? activeDescendantId: 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 useMultiCombobox.- 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+ // useMultiCombobox block every way of opening it.+ aria-disabled={isDisabled ? 'true' : undefined}><span {...stylex.props(styles.triggerContent)}>{renderTriggerContent()}</span></button>+ {/* A disabled selector submits no value (`spec:AST-085` FR3). */}{htmlName != null &&+ !isDisabled &&value.map(v => (- <input- key={v}- type="hidden"- name={htmlName}- value={v}- // Disabled native controls are excluded from form submission;- // mirror that for the hidden carriers.- disabled={isDisabled}- />+ <input key={v} type="hidden" name={htmlName} value={v} />))}{isBusy && <Spinner size="sm" />}{hasClear &&