An open source design system that's fully customizable and agent ready
TypeScript
fix(Typeahead, Tokenizer): a disabled field keeps its tab stop (#9275)
Cindy Zhang1408785fd629
diff --git a/.changeset/typeahead-disabled-keeps-tab-stop.md b/.changeset/typeahead-disabled-keeps-tab-stop.mdnew file mode 100644index 0000000000..a60bdf2cc9--- /dev/null+++ b/.changeset/typeahead-disabled-keeps-tab-stop.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Typeahead, Tokenizer, PowerSearch: a disabled field keeps its tab stop. Before, a field disabled without a `disabledMessage` rendered a natively disabled input, so Tab skipped it and screen-reader users moving by focus never reached it. Now the input is announced as disabled (`aria-disabled`), stays read-only, opens and picks nothing, and shows a focus ring under keyboard focus. A search still in flight when the field becomes disabled is dropped: it opens, announces, and spins nothing. A Tokenizer or PowerSearch with `tokenOverflowBehavior="unfocusedLayer"` and no `disabledMessage` keeps its natively disabled input for now.++@cixzhangdiff --git a/packages/core/src/Field/inputDisabledFocus.ts b/packages/core/src/Field/inputDisabledFocus.tsindex 0e20014007..7f6229ab63 100644--- a/packages/core/src/Field/inputDisabledFocus.ts+++ b/packages/core/src/Field/inputDisabledFocus.ts@@ -4,7 +4,7 @@* @file inputDisabledFocus.ts* @input Uses StyleX and theme tokens* @output inputDisabledFocusStyles (internal; not re-exported from Field/index.ts)- * @position Field wrapper style shared by TextInput and TextArea+ * @position Field wrapper style shared by the text-entry fields*/import * as stylex from '@stylexjs/stylex';@@ -25,4 +25,18 @@ export const inputDisabledFocusStyles = stylex.create({':has(> [aria-disabled="true"]:focus-visible)': `inset 0px 0px 0px 2px ${colorVars['--color-accent-muted']}`,},},+ // The same ring for a field whose input sits deeper than the wrapper's+ // direct children (Typeahead, Tokenizer). Keyed on the input itself, so a+ // focused token or status button keeps only its own outline.+ nestedRing: {+ borderColor: {+ default: colorVars['--color-border-emphasized'],+ ':has(input[aria-disabled="true"]:focus-visible)':+ colorVars['--color-accent'],+ },+ boxShadow: {+ default: 'none',+ ':has(input[aria-disabled="true"]:focus-visible)': `inset 0px 0px 0px 2px ${colorVars['--color-accent-muted']}`,+ },+ },});diff --git a/packages/core/src/PowerSearch/PowerSearch.test.tsx b/packages/core/src/PowerSearch/PowerSearch.test.tsxindex 07440bc3b4..b10ce0a355 100644--- a/packages/core/src/PowerSearch/PowerSearch.test.tsx+++ b/packages/core/src/PowerSearch/PowerSearch.test.tsx@@ -437,7 +437,7 @@ describe('PowerSearch', () => {expect((input as HTMLInputElement).value).toBe('');});- it('keeps the input natively disabled when disabled without a reason', () => {+ it("keeps the input's tab stop when disabled without a reason", () => {render(<PowerSearchconfig={config}@@ -446,7 +446,9 @@ describe('PowerSearch', () => {isDisabled/>,);- expect(screen.getByRole('combobox')).toBeDisabled();+ const input = screen.getByRole('combobox');+ expect(input).not.toBeDisabled();+ expect(input).toHaveAttribute('aria-disabled', 'true');});});diff --git a/packages/core/src/Tokenizer/Tokenizer.doc.mjs b/packages/core/src/Tokenizer/Tokenizer.doc.mjsindex 94d6bbd23f..b7e698cf90 100644--- a/packages/core/src/Tokenizer/Tokenizer.doc.mjs+++ b/packages/core/src/Tokenizer/Tokenizer.doc.mjs@@ -91,7 +91,8 @@ export const docs = {{name: 'isDisabled',type: 'boolean',- description: 'Disables the input and all token interactions.',+ description:+ 'Disables the input and all token interactions. The input keeps its tab stop: it is announced as disabled (aria-disabled), is read-only, and opens and picks nothing. With tokenOverflowBehavior="unfocusedLayer" and no disabledMessage, the input is natively disabled and out of the tab order.',default: 'false',},{@@ -104,7 +105,7 @@ export const docs = {name: 'disabledMessage',type: 'string',description:- 'Explains why the tokenizer is disabled. With isDisabled, shows a tooltip on hover/keyboard focus and keeps the input focusable via aria-disabled (input stays blocked). Use this instead of wrapping a disabled Tokenizer in Tooltip. Disabled controls swallow the hover events an external Tooltip needs.',+ 'Explains why the tokenizer is disabled. With isDisabled, shows a tooltip on hover/keyboard focus and keeps the input focusable via aria-disabled (input stays blocked). Use this instead of wrapping a disabled Tokenizer in Tooltip, so the reason is attached to the field itself.',},{name: 'status',@@ -474,7 +475,7 @@ export const docsZh = {name: 'disabledMessage',type: 'string',description:- 'Explains why the tokenizer is disabled. With isDisabled, shows a tooltip on hover/keyboard focus and keeps the input focusable via aria-disabled (input stays blocked). Use this instead of wrapping a disabled Tokenizer in Tooltip. Disabled controls swallow the hover events an external Tooltip needs.',+ 'Explains why the tokenizer is disabled. With isDisabled, shows a tooltip on hover/keyboard focus and keeps the input focusable via aria-disabled (input stays blocked). Use this instead of wrapping a disabled Tokenizer in Tooltip, so the reason is attached to the field itself.',},{name: 'status',diff --git a/packages/core/src/Tokenizer/Tokenizer.test.tsx b/packages/core/src/Tokenizer/Tokenizer.test.tsxindex 2cb81e9189..e9f93b749c 100644--- a/packages/core/src/Tokenizer/Tokenizer.test.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.test.tsx@@ -406,7 +406,11 @@ describe('Tokenizer', () => {isDisabled/>,);- expect(screen.getByRole('combobox')).toBeDisabled();+ // The input keeps its tab stop (spec:AST-085 FR1).+ expect(screen.getByRole('combobox')).toHaveAttribute(+ 'aria-disabled',+ 'true',+ );// Remove button should not be present when disabledexpect(screen.queryByRole('button', {name: 'Remove Alice'}),@@ -1390,17 +1394,30 @@ describe('Tokenizer', () => {expect(onChange).not.toHaveBeenCalled();});- it('keeps the input natively disabled when disabled without a reason', () => {+ it("keeps the input's tab stop when disabled without a reason", async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();render(- <Tokenizer- label="Members"- searchSource={userSource}- value={[]}- onChange={() => {}}- isDisabled- />,+ <>+ <button type="button">Before</button>+ <Tokenizer+ label="Members"+ searchSource={userSource}+ value={[]}+ onChange={onChange}+ isDisabled+ />+ </>,);- expect(screen.getByRole('combobox')).toBeDisabled();+ const input = screen.getByRole('combobox');+ expect(input).not.toBeDisabled();+ expect(input).toHaveAttribute('aria-disabled', 'true');+ screen.getByRole('button', {name: 'Before'}).focus();+ await user.tab();+ expect(input).toHaveFocus();+ await user.keyboard('Ali{Enter}');+ expect(input).toHaveValue('');+ expect(onChange).not.toHaveBeenCalled();});});describe('announcements', () => {diff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsxindex a65023e35b..06a26f9e75 100644--- a/packages/core/src/Tokenizer/Tokenizer.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.tsx@@ -51,6 +51,7 @@ import {type FieldInputBaseProps,useFieldInputStyling,} from '../Field/fieldParts';+import {inputDisabledFocusStyles} from '../Field/inputDisabledFocus';import {useMergedRefs} from '../hooks/useMergedRefs';import {TokenizerClearAllMessageContext} from './TokenizerClearAllMessageContext';import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';@@ -264,7 +265,13 @@ export interface TokenizerProps<T extends SearchableItem> extends Omit<* @default 'No results found'*/emptySearchText?: ReactNode;- /** Whether the input is disabled. @default false */+ /**+ * Whether the input is disabled. The disabled input keeps its tab stop: it+ * is announced as disabled (`aria-disabled`), is read-only, and opens and+ * picks nothing. With `tokenOverflowBehavior="unfocusedLayer"` and no+ * `disabledMessage`, the input is natively disabled and out of the tab order.+ * @default false+ */isDisabled?: boolean;/*** Explains why the tokenizer is disabled. When set together with@@ -273,8 +280,8 @@ export interface TokenizerProps<T extends SearchableItem> extends Omit<* reason is discoverable by keyboard and assistive technology. Input stays* blocked.*- * Use this instead of wrapping a disabled tokenizer in `Tooltip` — disabled- * controls don't emit the pointer events an external tooltip needs.+ * Use this instead of wrapping a disabled tokenizer in `Tooltip`, so the+ * reason is attached to the field itself.*/disabledMessage?: string;/** Show clear button (clears all tokens). @default false */@@ -1378,6 +1385,7 @@ export function Tokenizer<T extends SearchableItem>({isTruncated ? truncatedSizeStyles[size] : sizeStyle,isTruncated && styles.truncatedWrapper,isDisabled && inputWrapperStyles.disabled,+ isDisabled && inputDisabledFocusStyles.nestedRing,status && inputStatusBorderStyles[status.type],status && !isDisabled && inputStatusHoverShadowStyles[status.type],status && inputStatusFocusWithinStyles[status.type],@@ -1432,7 +1440,12 @@ export function Tokenizer<T extends SearchableItem>({minQueryLength={minQueryLength}emptySearchText={emptySearchText}isDisabled={isDisabled}- isFocusableDisabled={showsDisabledMessage}+ // A disabled field keeps its tab stop (spec:AST-085 FR1), except in+ // unfocusedLayer mode, where the input lives in a layer a disabled+ // field never opens; how that field takes focus is undecided.+ isFocusableDisabled={+ showsDisabledMessage || (isDisabled && !isLayerMode)+ }hasAutoFocus={hasAutoFocus}inputId={inputId}ariaLabelledBy={fieldLabelledBy}diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsxindex a3549449c4..fe7737469b 100644--- a/packages/core/src/Typeahead/BaseTypeahead.tsx+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx@@ -154,10 +154,10 @@ export interface BaseTypeaheadProps<T extends SearchableItem> extends Omit<isDisabled?: boolean;/**- * When disabled with a reason, keeps the input focusable via `aria-disabled`- * (instead of the native `disabled` attribute) and `readOnly` so an- * associated disabled-reason tooltip stays discoverable by keyboard and- * assistive technology. Query and text mutation, opening the list, and a+ * When disabled, keeps the input focusable via `aria-disabled` (instead of+ * the native `disabled` attribute) and `readOnly`, so the field keeps its+ * tab stop and any disabled-reason tooltip stays discoverable by keyboard+ * and assistive technology (`spec:AST-085` FR1). Query and text mutation, opening the list, and a* pick by Enter or a press are blocked, also from a list that was open* before this state applied; Escape or Tab still closes it. Consumers* (Typeahead) own the tooltip and wrapper.@@ -752,6 +752,17 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({}loadingRef.current = false;}+ // A field that becomes disabled stops showing a search as busy in the same+ // render, and the dropped query shows no outcome, so no empty state; the+ // layout effect below drops the work itself.+ const [disabledOfState, setDisabledOfState] = useState(isDisabled);+ if (disabledOfState !== isDisabled) {+ setDisabledOfState(isDisabled);+ if (isDisabled && isLoading) {+ setIsLoading(false);+ setHasSearched(false);+ }+ }// When the search source is replaced, any in-flight load from the previous// source is abandoned (generation bumped above). Notify the wrapper's busy lane@@ -799,6 +810,23 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({const isDisabledRef = useRef(isDisabled);useIsomorphicLayoutEffect(() => {isDisabledRef.current = isDisabled;+ if (!isDisabled) {+ return;+ }+ // Search work scheduled or in flight when the field became disabled is+ // dropped: a later answer lists, announces and spins nothing+ // (spec:AST-085 FR2). Bumping the generation fails its checks.+ searchGenRef.current++;+ if (searchTimeoutRef.current) {+ clearTimeout(searchTimeoutRef.current);+ searchTimeoutRef.current = null;+ }+ prevSearchSourceRef.current.cancel?.();+ // The busy state itself cleared in the render that disabled the field.+ if (loadingRef.current) {+ loadingRef.current = false;+ onLoadingChangeRef.current?.(false);+ }}, [isDisabled]);const showLayer = useCallback(() => {if (isDisabledRef.current) {diff --git a/packages/core/src/Typeahead/Typeahead.disabled.a11y.chromium.spec.ts b/packages/core/src/Typeahead/Typeahead.disabled.a11y.chromium.spec.tsnew file mode 100644index 0000000000..caf0b6dcfb--- /dev/null+++ b/packages/core/src/Typeahead/Typeahead.disabled.a11y.chromium.spec.ts@@ -0,0 +1,62 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope core/Typeahead core/Tokenizer core/Field ^apps/storybook/stories/Typeahead ^apps/storybook/stories/Tokenizer++/**+ * @file Typeahead.disabled.a11y.chromium.spec.ts+ * @input Checked-in Disabled Storybook fixtures and real Chromium+ * @output Tab-stop, aria-disabled, read-only and focus-ring evidence+ * @position Browser regression for spec:AST-085 FR1, FR2 and FR6 on the+ * text-entry search fields+ */++import {expect, test} from '@playwright/test';+import {+ serveStorybook,+ DEFAULT_STORYBOOK_DIR,+ 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 () => storybook?.close());++for (const story of ['core-typeahead--disabled', 'core-tokenizer--disabled']) {+ test(`${story}: Tab reaches the disabled field, which rings and stays read-only`, async ({+ page,+ }, testInfo) => {+ await page.goto(+ `${storybook.origin}/iframe.html?id=${story}&viewMode=story`,+ );+ const input = page.getByRole('combobox');+ await input.waitFor();+ await expect(input).not.toBeDisabled();+ await expect(input).toHaveAttribute('aria-disabled', 'true');++ await page.keyboard.press('Tab');+ await expect(input).toBeFocused();+ // The nearest wrapper with a box shadow draws the field's ring.+ const ring = await input.evaluate(element => {+ for (let node = element.parentElement; node; node = node.parentElement) {+ const shadow = getComputedStyle(node).boxShadow;+ if (shadow !== 'none') {+ return shadow;+ }+ }+ return 'none';+ });+ expect(ring).toContain('inset');+ await testInfo.attach('focused', {+ body: await page.screenshot({path: testInfo.outputPath('focused.png')}),+ contentType: 'image/png',+ });++ await page.keyboard.type('a');+ await page.keyboard.press('ArrowDown');+ await expect(input).toHaveValue('');+ await expect(input).toHaveAttribute('aria-expanded', 'false');+ });+}diff --git a/packages/core/src/Typeahead/Typeahead.doc.mjs b/packages/core/src/Typeahead/Typeahead.doc.mjsindex 7931bcb2ab..a72d0bdd2a 100644--- a/packages/core/src/Typeahead/Typeahead.doc.mjs+++ b/packages/core/src/Typeahead/Typeahead.doc.mjs@@ -154,14 +154,15 @@ export const docs = {{name: 'isDisabled',type: 'boolean',- description: 'Disables the input.',+ description:+ 'Disables the input. The field keeps its tab stop: it is announced as disabled (aria-disabled), is read-only, and opens and picks nothing.',default: 'false',},{name: 'disabledMessage',type: 'string',description:- 'Explains why the input is disabled. With isDisabled, shows a tooltip on hover/keyboard focus and keeps the field focusable via aria-disabled (activation stays blocked). Use this instead of wrapping a disabled Typeahead in Tooltip. Disabled controls swallow the hover events an external Tooltip needs.',+ 'Explains why the input is disabled. With isDisabled, shows a tooltip on hover/keyboard focus, and the reason describes the field (activation stays blocked). Use this instead of wrapping a disabled Typeahead in Tooltip, so the reason is attached to the field itself.',},{name: 'maxMenuItems',diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsxindex fb31fcbf5c..b4d7f6b9cc 100644--- a/packages/core/src/Typeahead/Typeahead.test.tsx+++ b/packages/core/src/Typeahead/Typeahead.test.tsx@@ -21,7 +21,9 @@ import {} from 'vitest';import {render, screen, fireEvent, waitFor, act} from '@testing-library/react';import userEvent from '@testing-library/user-event';+import * as stylex from '@stylexjs/stylex';import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';+import {colorVars} from '../theme/tokens.stylex';import {createRef,Profiler,@@ -86,6 +88,21 @@ afterEach(() => {});// Test data+// The disabled focus ring a nested input's wrapper carries, by its StyleX class.+const NESTED_RING = stylex+ .props(+ stylex.create({+ ring: {+ boxShadow: {+ default: null,+ ':has(input[aria-disabled="true"]:focus-visible)': `inset 0px 0px 0px 2px ${colorVars['--color-accent-muted']}`,+ },+ },+ }).ring,+ )+ .className!.split(' ')+ .pop()!;+const fruits: SearchableItem[] = [{id: '1', label: 'Apple'},{id: '2', label: 'Banana'},@@ -2471,19 +2488,76 @@ describe('Typeahead disabledMessage', () => {);});- it('remains natively disabled when disabled without a reason', () => {+ it('keeps its tab stop when disabled without a reason', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();render(- <Typeahead- label="Assignee"- searchSource={fruitSource}- value={null}- onChange={() => {}}- isDisabled- />,+ <>+ <button type="button">Before</button>+ <Typeahead+ label="Assignee"+ searchSource={fruitSource}+ value={null}+ onChange={onChange}+ hasEntriesOnFocus+ isDisabled+ />+ </>,);const input = screen.getByRole('combobox');- expect(input).toBeDisabled();- expect(input).not.toHaveAttribute('aria-disabled');+ expect(input).not.toBeDisabled();+ expect(input).toHaveAttribute('aria-disabled', 'true');+ expect(input).toHaveAttribute('readonly');++ screen.getByRole('button', {name: 'Before'}).focus();+ await user.tab();+ expect(input).toHaveFocus();+ await user.keyboard('Apple{Enter}');+ expect(input).toHaveValue('');+ expect(input).toHaveAttribute('aria-expanded', 'false');+ expect(onChange).not.toHaveBeenCalled();+ // jsdom cannot match :focus-visible: the field's wrapper carries the+ // disabled focus ring's class (spec:AST-085 FR6).+ expect(input.closest(`.${NESTED_RING}`)).not.toBeNull();+ });++ it('drops a search answer that arrives after the field became disabled', async () => {+ let settle: (items: SearchableItem[]) => void = () => {};+ const searchSource: SearchSource = {+ search: async () =>+ new Promise<SearchableItem[]>(resolve => {+ settle = resolve;+ }),+ bootstrap: () => [],+ };+ const props = {+ label: 'Assignee',+ searchSource,+ value: null,+ onChange: () => {},+ debounceMs: 0,+ };+ const {rerender} = render(<Typeahead {...props} />);+ const input = screen.getByRole('combobox');+ fireEvent.change(input, {target: {value: 'Ap'}});+ await waitFor(() => {+ expect(getBusySpinner()).toBeInTheDocument();+ });++ rerender(<Typeahead {...props} isDisabled />);+ expect(queryBusySpinner()).not.toBeInTheDocument();+ await act(async () => {+ settle(fruits.slice(0, 1));+ await Promise.resolve();+ });++ expect(input).toHaveAttribute('aria-expanded', 'false');+ expect(+ document.querySelector('[data-astryx-live-region="polite"]')+ ?.textContent ?? '',+ ).toBe('');+ // The dropped query has no outcome: no empty state either.+ expect(screen.queryByText('No results found')).not.toBeInTheDocument();});});diff --git a/packages/core/src/Typeahead/Typeahead.tsx b/packages/core/src/Typeahead/Typeahead.tsxindex 42a3d37985..ff677eb1cd 100644--- a/packages/core/src/Typeahead/Typeahead.tsx+++ b/packages/core/src/Typeahead/Typeahead.tsx@@ -68,6 +68,7 @@ import {type FieldInputBaseProps,useFieldInputStyling,} from '../Field/fieldParts';+import {inputDisabledFocusStyles} from '../Field/inputDisabledFocus';import type {SizeValue} from '../utils/types';import type {SearchableItem, SearchSource} from './types';import {themeProps} from '../utils/themeProps';@@ -166,17 +167,21 @@ export interface TypeaheadProps<T extends SearchableItem> extends Omit<* @default 'No results found'*/emptySearchText?: ReactNode;- /** Whether the input is disabled. @default false */+ /**+ * Whether the input is disabled. A disabled field keeps its tab stop: it is+ * announced as disabled (`aria-disabled`), is read-only, and opens and+ * picks nothing.+ * @default false+ */isDisabled?: boolean;/*** Explains why the input is disabled. When set together with `isDisabled`,* the input shows a tooltip with this text on hover and keyboard focus, and- * the field stays focusable (via `aria-disabled`) so the reason is- * discoverable by keyboard and assistive technology. Editing and selection- * stay blocked.+ * the reason describes the field for assistive technology. Editing and+ * selection stay blocked.*- * Use this instead of wrapping a disabled input in `Tooltip` — disabled- * controls don't emit the pointer events an external tooltip needs.+ * Use this instead of wrapping a disabled input in `Tooltip`, so the reason+ * is attached to the field itself.** @example* ```@@ -444,10 +449,9 @@ export function Typeahead<T extends SearchableItem>({const inputRef = useRef<HTMLInputElement>(null);const tokenRef = useRef<HTMLElement>(null);- // Disabled-reason tooltip. Disabled controls swallow pointer events, so the- // tooltip listeners attach to the input wrapper (which already exists) and- // the input stays perceivable via aria-disabled + readOnly instead of the- // disabled attribute. Editing and selection stay blocked by the isDisabled+ // Disabled-reason tooltip. The tooltip listeners attach to the input wrapper+ // (which already exists); a disabled input stays perceivable via+ // aria-disabled + readOnly instead of the disabled attribute. Editing and selection stay blocked by the isDisabled// guards (handleWrapperClick, handleEnterEditMode, and BaseTypeahead's own// focus/change guards).const showsDisabledMessage = isDisabled && !!disabledMessage;@@ -649,6 +653,7 @@ export function Typeahead<T extends SearchableItem>({status && !isDisabled && inputStatusHoverShadowStyles[status.type],status && inputStatusFocusWithinStyles[status.type],isDisabled && inputWrapperStyles.disabled,+ isDisabled && inputDisabledFocusStyles.nestedRing,inputGroup && groupStyles.inGroup,controlXstyle,),@@ -709,7 +714,8 @@ export function Typeahead<T extends SearchableItem>({emptySearchText={emptySearchText}isDisabled={isDisabled}hasAutoFocus={hasAutoFocus}- isFocusableDisabled={showsDisabledMessage}+ // A disabled field keeps its tab stop (spec:AST-085 FR1).+ isFocusableDisabled={isDisabled}inputId={inputId}ariaDescribedBy={[ariaDescribedByProp, ariaDescribedBy]