An open source design system that's fully customizable and agent ready
TypeScript
fix(Typeahead): the value token's button is named by the field label and the value (#9049)
Cindy Zhangb2e79c45d8f5
diff --git a/.changeset/typeahead-token-tab-stop-named.md b/.changeset/typeahead-token-tab-stop-named.mdnew file mode 100644index 0000000000..e1f26221d4--- /dev/null+++ b/.changeset/typeahead-token-tab-stop-named.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[fix] With a value, a `Typeahead`'s Tab stop is the value's token button (WCAG 2.2 SC 2.4.6 and 4.1.2). It was named by the value alone ("Apple"), so screen reader users could not tell which field it belonged to. It is now named by the field label and the value ("Fruit Apple"), and described by the field's description and status.++A clickable `Token` passed `aria-labelledby` and `aria-describedby` to its root, a generic element where they named nothing. It now passes them to its inner button, the element that owns its action. Every other structure keeps them on its root.++@cixzhang @duytbpdiff --git a/packages/core/src/Token/Token.spec.md b/packages/core/src/Token/Token.spec.mdindex 5ef81f6532..8a3bc535b7 100644--- a/packages/core/src/Token/Token.spec.md+++ b/packages/core/src/Token/Token.spec.md@@ -130,7 +130,7 @@ Consumer migration instructions belong in consumer docs and release notes.| FR7 | The label never wraps: the root is capped at its container's inline size and clips overflow. In the static and link structures the Label ends in an ellipsis; in the clickable and link-and-remove structures the inner control clips the Label without an ellipsis. `isLabelHidden` keeps the Label in the DOM with a visually hidden clip treatment. | Current source and tests || FR8 | `color` defaults to `default`, painting `--color-neutral` with primary text; every other built-in tone paints its tinted background with its matching colored text. The `token` target reflects the resolved `color` and `size` for every value, including a theme-added color, which receives no component fill or text color until a theme paints it. | Current source and tests || FR9 | Clickable and link structures paint the shared hover overlay under a hover-capable pointer and the shared pressed overlay for mouse and touch presses; the static structure paints neither. | Current source |-| FR10 | `ref` reaches the root element of every structure. Supported DOM, ARIA, data, and event props reach the root; `data-testid` reaches the root; `xstyle`, `className`, and `style` merge in that order after component styles. | Current source and tests |+| FR10 | `ref` reaches the root element of every structure. Supported DOM, ARIA, data, and event props reach the root, except that in the clickable structure `aria-labelledby` and `aria-describedby` reach the inner button, the element that owns the token's action (`architecture:public-component-api` INV5); `data-testid` reaches the root; `xstyle`, `className`, and `style` merge in that order after component styles. | Current source and tests |### Allowed variation@@ -142,15 +142,15 @@ Consumer migration instructions belong in consumer docs and release notes.### Representative states-| State | Required invariant | Allowed variation |-| ------------------ | ------------------------------------------------------------------------------------- | --------------------------- |-| Static | `span` root; Token adds no focusable element except a Remove button. | Tone, size, slots. |-| Clickable | One inner button named by the label; container click calls `onClick`. | End content. |-| Link | Root is the link; focus outline on the link itself. | Router link component. |-| Link and remove | Container holds a link and a sibling Remove button; surface click activates the link. | Modified and middle clicks. |-| Removable | Remove button named "Remove {label}" with a 24 by 24 CSS pixel target. | Locale wording. |-| Disabled clickable | Buttons focusable with `aria-disabled="true"`; no callback fires; half opacity. | Tone. |-| Hidden label | Label text visually hidden; the root's `aria-label` equals the label. | Structure. |+| State | Required invariant | Allowed variation |+| ------------------ | ------------------------------------------------------------------------------------------------------- | --------------------------- |+| Static | `span` root; Token adds no focusable element except a Remove button. | Tone, size, slots. |+| Clickable | One inner button named by the label, or by a caller `aria-labelledby`; container click calls `onClick`. | End content. |+| Link | Root is the link; focus outline on the link itself. | Router link component. |+| Link and remove | Container holds a link and a sibling Remove button; surface click activates the link. | Modified and middle clicks. |+| Removable | Remove button named "Remove {label}" with a 24 by 24 CSS pixel target. | Locale wording. |+| Disabled clickable | Buttons focusable with `aria-disabled="true"`; no callback fires; half opacity. | Tone. |+| Hidden label | Label text visually hidden; the root's `aria-label` equals the label. | Structure. |### Transformation and precedence order@@ -178,7 +178,8 @@ Consumer migration instructions belong in consumer docs and release notes.separate focusable controls in DOM order; neither is nested in the other, sothe HTML interactive-content rule holds.- **AR2 — Names.** In the clickable and link-and-remove structures the inner- button or link takes its name from the Label. In the link structure the link+ button or link takes its name from the Label, or, in the clickable structure,+ from a caller `aria-labelledby` (FR10). In the link structure the linkis the root and takes its name from all of its content, including End content(a label "Inbox" with a count reads "Inbox 12"). TheRemove button is named by the translated "Remove {label}" string.@@ -234,18 +235,18 @@ token's text color.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------ | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- |-| FR2, FR10 | `Token.test.tsx` render, ref, and pass-through suites | Static, clickable, and link roots; caller props | A wrong root element, a detached ref, or a dropped caller prop fails DOM assertions. Gap: no test covers the ref on the link-and-remove container. | `audit:Token/behavior` |-| FR1, FR7 | `Token.stories.tsx` size, icon, and end-content fixtures in a browser | Sizes, icon and end content | Gap: the size and overflow unit tests assert presence only, and no story renders a long label; slot order and block size are visible only in the rendered fixtures, and the ellipsis has no check. | `audit:Token/layout` |-| FR3, FR4, FR6, AR1 | `Token.test.tsx` link, clickable, and link-with-remove suites | Link, clickable, link and remove, modified and middle clicks | Nesting the Remove button, firing the token action from Remove, or losing delegation fails. Gap: no test asserts that `onClick` is dropped with `href`. | `audit:Token/behavior` |-| FR5, AR5 | `Token.test.tsx` disabled tests | Disabled clickable with remove; disabled static; disabled link with and without remove | A native `disabled`, a lost tab stop, a disabled link with a destination, an unreflected disabled state, or a fired callback fails. | `audit:Token/a11y` |-| AR2, AR3, AR7 | `Token.test.tsx` accessibility suite | Remove name, hidden label, description | A missing remove name, lost hidden label, or missing description fails. Gap: no test asserts the link structure's content-derived name. | `audit:Token/a11y` |-| AR6 | `TokenRemoveTarget.a11y.chromium.spec.ts` | Pre-set filter tokens (default size), LTR and RTL | A remove target that misses its X edge or swallows a label press fails in real Chromium. Gap: the `sm` clipping is not covered. | `audit:Token/a11y` |-| FR8 | `Token.test.tsx` custom-color test; `extensibleAxes.test.ts`; `themingTargets.test.ts` | Theme-added color; map wiring | Dropping the `color` reflection fails. Gap: no test asserts `data-size` or any tone's paint; those are visible only in `Token.stories.tsx`. | `audit:Token/theming` |-| FR9, AR4 | `Token.stories.tsx` clickable and link fixtures in a browser | Hover, press, keyboard focus on the token | Gap: no automated check covers overlays or indicators, and no story renders a clickable or link token with Remove, so the double indicator on Remove has no fixture. | `audit:Token/design` |-| PR1 | Source review | Every structure | Gap: no automated check fails if Token adds a per-token listener, observer, or timer. | `audit:Token/behavior` |-| AR2, AR3, AR5, AR7 | Accessibility-tree evidence (`spec:AST-009` FR3) | Every structure; hidden label; description; disabled | Gap: no accessibility-tree check proves the computed names, the hidden-label name, the description, or the disabled state; the unit tests assert DOM attributes only. | `audit:Token/a11y` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------ | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- |+| FR2, FR10 | `Token.test.tsx` render, ref, and pass-through suites | Static, clickable, and link roots; caller props; caller naming on a clickable and a disabled link token | A wrong root element, a detached ref, a dropped caller prop, or a clickable token's `aria-labelledby` left on its root fails DOM assertions. Gap: no test covers the ref on the link-and-remove container. | `audit:Token/behavior` |+| FR1, FR7 | `Token.stories.tsx` size, icon, and end-content fixtures in a browser | Sizes, icon and end content | Gap: the size and overflow unit tests assert presence only, and no story renders a long label; slot order and block size are visible only in the rendered fixtures, and the ellipsis has no check. | `audit:Token/layout` |+| FR3, FR4, FR6, AR1 | `Token.test.tsx` link, clickable, and link-with-remove suites | Link, clickable, link and remove, modified and middle clicks | Nesting the Remove button, firing the token action from Remove, or losing delegation fails. Gap: no test asserts that `onClick` is dropped with `href`. | `audit:Token/behavior` |+| FR5, AR5 | `Token.test.tsx` disabled tests | Disabled clickable with remove; disabled static; disabled link with and without remove | A native `disabled`, a lost tab stop, a disabled link with a destination, an unreflected disabled state, or a fired callback fails. | `audit:Token/a11y` |+| AR2, AR3, AR7 | `Token.test.tsx` accessibility suite | Remove name, hidden label, description | A missing remove name, lost hidden label, or missing description fails. Gap: no test asserts the link structure's content-derived name. | `audit:Token/a11y` |+| AR6 | `TokenRemoveTarget.a11y.chromium.spec.ts` | Pre-set filter tokens (default size), LTR and RTL | A remove target that misses its X edge or swallows a label press fails in real Chromium. Gap: the `sm` clipping is not covered. | `audit:Token/a11y` |+| FR8 | `Token.test.tsx` custom-color test; `extensibleAxes.test.ts`; `themingTargets.test.ts` | Theme-added color; map wiring | Dropping the `color` reflection fails. Gap: no test asserts `data-size` or any tone's paint; those are visible only in `Token.stories.tsx`. | `audit:Token/theming` |+| FR9, AR4 | `Token.stories.tsx` clickable and link fixtures in a browser | Hover, press, keyboard focus on the token | Gap: no automated check covers overlays or indicators, and no story renders a clickable or link token with Remove, so the double indicator on Remove has no fixture. | `audit:Token/design` |+| PR1 | Source review | Every structure | Gap: no automated check fails if Token adds a per-token listener, observer, or timer. | `audit:Token/behavior` |+| AR2, AR3, AR5, AR7 | Accessibility-tree evidence (`spec:AST-009` FR3) | Every structure; hidden label; description; disabled | Gap: no accessibility-tree check proves the computed names, the hidden-label name, the description, or the disabled state; the unit tests assert DOM attributes only. | `audit:Token/a11y` |## Decision logdiff --git a/packages/core/src/Token/Token.test.tsx b/packages/core/src/Token/Token.test.tsxindex 48c8bf8084..81422e4dca 100644--- a/packages/core/src/Token/Token.test.tsx+++ b/packages/core/src/Token/Token.test.tsx@@ -256,6 +256,43 @@ describe('Token accessibility', () => {).toBeInTheDocument();});+ it('keeps aria-labelledby and aria-describedby on a disabled link token', () => {+ render(+ <>+ <span id="dl-label">Docs section</span>+ <span id="dl-hint">Unavailable offline</span>+ <Token+ label="Docs"+ href="/docs"+ isDisabled+ aria-labelledby="dl-label"+ aria-describedby="dl-hint"+ />+ </>,+ );+ const link = screen.getByRole('link', {name: 'Docs section'});+ expect(link).toHaveAccessibleDescription('Unavailable offline');+ });++ it("passes aria-labelledby and aria-describedby to a clickable token's button (public-component-api INV5)", () => {+ render(+ <>+ <span id="field-label">Fruit</span>+ <span id="field-hint">Pick one</span>+ <Token+ label="Apple"+ onClick={() => {}}+ aria-labelledby="field-label"+ aria-describedby="field-hint"+ data-testid="token"+ />+ </>,+ );+ const button = screen.getByRole('button', {name: 'Fruit'});+ expect(button).toHaveAccessibleDescription('Pick one');+ expect(screen.getByTestId('token')).not.toHaveAttribute('aria-labelledby');+ });+it('reflects the disabled state on the token target in every structure (theming-surface INV6)', () => {render(<>diff --git a/packages/core/src/Token/Token.tsx b/packages/core/src/Token/Token.tsxindex 4f288a9495..d89c1e3188 100644--- a/packages/core/src/Token/Token.tsx+++ b/packages/core/src/Token/Token.tsx@@ -299,6 +299,8 @@ export function Token({className,style,'data-testid': testId,+ 'aria-labelledby': ariaLabelledBy,+ 'aria-describedby': ariaDescribedBy,ref,...rest}: TokenProps) {@@ -342,6 +344,14 @@ export function Token({</>);+ // Naming inputs reach the element that owns the token's action: the inner+ // button of a clickable token, otherwise the root+ // (architecture:public-component-api INV5).+ const labellingProps = {+ 'aria-labelledby': ariaLabelledBy,+ 'aria-describedby': ariaDescribedBy,+ };+const sharedProps = {'data-testid': testId,...(isLabelHidden ? {'aria-label': label} : {}),@@ -380,6 +390,7 @@ export function Token({style,)}{...rest}+ {...labellingProps}{...disabledInteractionProps(rest.onKeyDown)}{...sharedProps}>{content}@@ -413,6 +424,7 @@ export function Token({style,)}{...rest}+ {...labellingProps}{...(isDisabled ? {'aria-disabled': true} : {})}{...sharedProps}>{content}@@ -466,6 +478,7 @@ export function Token({style,)}{...rest}+ {...labellingProps}{...sharedProps}/>);@@ -509,6 +522,7 @@ export function Token({<buttontype="button"onClick={effectiveOnClick}+ {...labellingProps}aria-disabled={isDisabled || undefined}{...(isDisabled ? disabledInteractionProps() : null)}{...stylex.props(styles.invisibleButton)}>@@ -546,6 +560,7 @@ export function Token({style,)}{...rest}+ {...labellingProps}{...sharedProps}>{content}</span>diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsxindex aa5503e45c..918bdebc55 100644--- a/packages/core/src/Typeahead/Typeahead.test.tsx+++ b/packages/core/src/Typeahead/Typeahead.test.tsx@@ -94,6 +94,9 @@ const fruits: SearchableItem[] = [{id: '5', label: 'Elderberry'},];+// The token's value also sits in a hidden span its button is labelled by.+const VISIBLE = {selector: ':not([hidden])'};+const fruitSource: SearchSource = {search: (query: string) =>fruits.filter(f => f.label.toLowerCase().includes(query.toLowerCase())),@@ -694,6 +697,43 @@ describe('Typeahead', () => {expect(screen.getByText(/Required/)).toBeInTheDocument();});+ it('names the token button, the Tab stop while a value shows, by the field label and the value', async () => {+ const user = userEvent.setup();+ render(+ <Typeahead+ label="Fruit"+ description="Pick your favorite fruit"+ status={{type: 'error', message: 'Pick a ripe one'}}+ searchSource={fruitSource}+ value={{id: 'apple', label: 'Apple'}}+ onChange={() => {}}+ />,+ );+ await user.tab();+ const tabStop = document.activeElement as HTMLElement;+ expect(tabStop).toHaveAccessibleName('Fruit Apple');+ expect(tabStop).toHaveAccessibleDescription(/Pick your favorite fruit/);+ expect(tabStop).toHaveAccessibleDescription(/Pick a ripe one/);+ });++ it('names the token button with a caller aria-labelledby as the input is named', async () => {+ const user = userEvent.setup();+ render(+ <>+ <span id="section-title">Lunch</span>+ <Typeahead+ label="Fruit"+ aria-labelledby="section-title"+ searchSource={fruitSource}+ value={{id: 'apple', label: 'Apple'}}+ onChange={() => {}}+ />+ </>,+ );+ await user.tab();+ expect(document.activeElement).toHaveAccessibleName('Fruit Lunch Apple');+ });+it('exposes the resolved required state on the combobox (FormLayout FR5, AR2)', () => {const field = (props: {isRequired?: boolean;@@ -794,7 +834,7 @@ describe('Typeahead', () => {onChange={() => {}}/>,);- expect(screen.getByText(fruits[0].label)).toBeInTheDocument();+ expect(screen.getByText(fruits[0].label, VISIBLE)).toBeInTheDocument();});it('shows clear button when hasClear and value is selected', () => {@@ -1695,10 +1735,10 @@ describe('Typeahead edit mode', () => {// iOS raises the software keyboard only for a focus made while the browser// still dispatches the person's tap, so the focus must not wait for a frame.it.each([- ['the token', () => screen.getByText(fruits[0].label)],+ ['the token', () => screen.getByText(fruits[0].label, VISIBLE)],['the field around it',- () => screen.getByText(fruits[0].label).closest('div')!,+ () => screen.getByText(fruits[0].label, VISIBLE).closest('div')!,],])('focuses the input with the label selected inside the tap on %s',@@ -1758,7 +1798,7 @@ describe('Typeahead edit mode', () => {);const input = screen.getByRole<HTMLInputElement>('combobox');- fireEvent.click(screen.getByText(fruits[3].label));+ fireEvent.click(screen.getByText(fruits[3].label, VISIBLE));expect(input).toHaveFocus();expect(input.value).toBe(fruits[3].label);@@ -1785,7 +1825,7 @@ describe('Typeahead edit mode', () => {screen.getByRole('combobox');// Click the token text to enter edit mode- const tokenText = screen.getByText(fruits[0].label);+ const tokenText = screen.getByText(fruits[0].label, VISIBLE);const tokenContainer = tokenText.closest('div')!;fireEvent.click(tokenContainer);@@ -1812,7 +1852,7 @@ describe('Typeahead edit mode', () => {const input = screen.getByRole<HTMLInputElement>('combobox');// Enter edit mode: the token gives way to the label as editable text- fireEvent.click(screen.getByText(fruits[0].label).closest('div')!);+ fireEvent.click(screen.getByText(fruits[0].label, VISIBLE).closest('div')!);await waitFor(() => expect(input.value).toBe(fruits[0].label));fireEvent.click(screen.getByRole('button', {name: 'Clear selection'}));@@ -1851,7 +1891,9 @@ describe('Typeahead edit mode', () => {render(<Controlled />);const input = screen.getByRole<HTMLInputElement>('combobox');- fireEvent.click(screen.getByText(fruits[0].label).closest('div')!);+ fireEvent.click(+ screen.getByText(fruits[0].label, VISIBLE).closest('div')!,+ );await waitFor(() => expect(input.value).toBe(fruits[0].label));leaveEditMode(input);@@ -1895,7 +1937,7 @@ describe('Typeahead edit mode', () => {const input = screen.getByRole('combobox');// Enter edit mode- const tokenText = screen.getByText(fruits[0].label);+ const tokenText = screen.getByText(fruits[0].label, VISIBLE);fireEvent.click(tokenText.closest('div')!);// Blur without selecting anything@@ -1918,7 +1960,7 @@ describe('Typeahead edit mode', () => {// Enter edit mode by clicking the token; the input uncollapses and// rejoins the Tab order (tabindex is cleared).- const tokenText = screen.getByText(fruits[0].label);+ const tokenText = screen.getByText(fruits[0].label, VISIBLE);fireEvent.click(tokenText.closest('div')!);await act(async () => {await new Promise(r => requestAnimationFrame(r));@@ -1969,7 +2011,9 @@ describe('Typeahead collapsed input tab order', () => {);// Focus the token's internal button, then Tab away — focus must not land// on the visually hidden combobox input.- const tokenButton = screen.getByRole('button', {name: fruits[0].label});+ const tokenButton = screen.getByRole('button', {+ name: new RegExp(`${fruits[0].label}$`),+ });tokenButton.focus();await user.tab();expect(screen.getByRole('combobox')).not.toHaveFocus();@@ -1997,7 +2041,7 @@ describe('Typeahead collapsed input tab order', () => {/>,);// Entering edit mode removes the token and uncollapses the input- const tokenText = screen.getByText(fruits[0].label);+ const tokenText = screen.getByText(fruits[0].label, VISIBLE);fireEvent.click(tokenText.closest('div')!);expect(screen.getByRole('combobox')).not.toHaveAttribute('tabindex');});diff --git a/packages/core/src/Typeahead/Typeahead.tsx b/packages/core/src/Typeahead/Typeahead.tsxindex be29103a9d..c8de37c11d 100644--- a/packages/core/src/Typeahead/Typeahead.tsx+++ b/packages/core/src/Typeahead/Typeahead.tsx@@ -433,6 +433,7 @@ export function Typeahead<T extends SearchableItem>({const inputId = idProp ?? generatedInputId;const inputLabelId = useId();const fieldLabelId = useId();+ const tokenValueId = useId();const descriptionId = useId();const statusMessageId = useId();const inputGroup = useInputGroup();@@ -665,14 +666,33 @@ export function Typeahead<T extends SearchableItem>({<BusyIndicatorLaneProvider value={busyLane}><div {...stylex.props(styles.contentLane)}>{showToken && (- <Token- ref={tokenRef}- label={value.label}- size={size}- onClick={handleEnterEditMode}- isDisabled={isDisabled}- xstyle={styles.tokenOverlay}- />+ <>+ {/* The token's button is the field's Tab stop while a value+ shows, so it is named as the input is (the field label,+ with a caller aria-labelledby) plus the value, and+ described like the input (input-fields FR10; WCAG 2.4.6,+ 4.1.2). */}+ <span id={tokenValueId} hidden>+ {value.label}+ </span>+ <Token+ ref={tokenRef}+ label={value.label}+ size={size}+ onClick={handleEnterEditMode}+ isDisabled={isDisabled}+ aria-labelledby={joinAriaIDs(+ inputLabelledBy ?? fieldLabelId,+ tokenValueId,+ )}+ aria-describedby={+ [ariaDescribedByProp, ariaDescribedBy]+ .filter(Boolean)+ .join(' ') || undefined+ }+ xstyle={styles.tokenOverlay}+ />+ </>)}<TrailingKeyDownContext value={onKeyDown}><BaseTypeahead@@ -755,7 +775,8 @@ export function Typeahead<T extends SearchableItem>({isLabelHidden={isLabelHidden}description={description}inputID={inputId}- labelID={ariaLabelledByProp != null ? fieldLabelId : undefined}+ // Always set: the value token's name references the field label.+ labelID={fieldLabelId}descriptionID={description ? descriptionId : undefined}isOptional={isOptional}isRequired={isRequired}