An open source design system that's fully customizable and agent ready
TypeScript
fix(Typeahead, Tokenizer): the combobox exposes its required and invalid state (#9034)
Cindy Zhangf52dbbefb960
diff --git a/.changeset/combobox-aria-required.md b/.changeset/combobox-aria-required.mdnew file mode 100644index 0000000000..456bda4678--- /dev/null+++ b/.changeset/combobox-aria-required.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `Typeahead` and `Tokenizer` expose their state on the combobox (WCAG 2.2 SC 4.1.2; `component:FormLayout` FR5 and AR2). Before, the combobox had no `aria-required`, so under `FormLayout defaultOptionality="required"`, where the visible "Required" marker is hidden, a screen reader announced a required field as optional; and an error status showed its message with no `aria-invalid`. Now the combobox sets `aria-required` for the resolved required state and `aria-invalid` for an error status. A caller's own `aria-required` or `aria-invalid` still applies when the field's own state is off.++@cixzhang @duytbpdiff --git a/packages/core/src/FormLayout/FormLayout.spec.md b/packages/core/src/FormLayout/FormLayout.spec.mdindex b2d752f836..53a486374a 100644--- a/packages/core/src/FormLayout/FormLayout.spec.md+++ b/packages/core/src/FormLayout/FormLayout.spec.md@@ -44,7 +44,7 @@ system_specs: [spec:AST-038]| Behavior | Vertical stacks children; horizontal creates one fractional grid track per child in logical inline order; horizontal-labels pairs Field labels and controls, then collapses below a 481px viewport. || End-user impact | People encounter predictable field spacing and order, and assistive technology receives required-state information even when the form-wide visual convention leaves the common case unmarked. || Builder impact | Builders supply the fields and any semantic `<form>`, title, or footer; nested layouts replace the outer direction and optionality context for their descendants. |-| Compatibility/readiness | Released behavior recorded as current; no API, default, or runtime changes. One implementation gap is listed under Current-state impact. |+| Compatibility/readiness | Released behavior recorded as current; no API, default, or runtime changes. || Review checks | Reject lost root props, physical inline ordering, changed collapse boundaries, caller-overridable direction reflection, lost nested-context shadowing, or a visible optionality convention that disagrees with ARIA. || Governing rules | Established public FormLayout interface; `family:input-fields` outer-arrangement ownership; `architecture:public-component-api/INV5–INV9`; `architecture:component-theming-surface/INV2–INV6`. |@@ -61,14 +61,6 @@ This table is a review projection; the body below is authoritative.- Controlled/uncontrolled behavior: not applicable; FormLayout owns no form value or submission state.- Migration decision: none.-## Current-state impact--- **Required state lost for two controls (FR5, AR2).** Under- `defaultOptionality="required"` the visible "Required" marker is hidden,- but Typeahead and Tokenizer set no `aria-required`. Screen reader users- hear those fields as not required, while sighted users see the form-wide- convention.-## Ownership boundary**Owns**@@ -94,14 +86,14 @@ This table is a review projection; the body below is authoritative.## Behavioral and layout contract-| ID | Invariant | Basis |-| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |-| FR1 | `vertical` (the default) stacks children in a flex column with a `--spacing-4` gap. | Released source, tests, and stories |-| FR2 | `horizontal` places every direct child in one `1fr` grid column in the document's logical inline order, with a `--spacing-4` gap and no component-owned wrap rule. | Released source, tests, and stories |-| FR3 | `horizontal-labels` is a two-column grid (`auto 1fr`) with a `--spacing-3` row gap and `--spacing-4` column gap, items aligned to the start, so Field labels sit on the inline-start side of their controls; at a viewport width of 480px or below it becomes one flex column with a `--spacing-4` gap. OQ1 holds whether the collapsed label and control need a tighter pair gap. | Released source, Field composition, and tests |-| FR4 | FormLayout provides its direction and `defaultOptionality` to descendants in the same layer; a nested FormLayout replaces both for its own descendants, and content in a layer opened inside a FormLayout starts without them (`spec:AST-038` FR7, FR8). | Context source and tests |-| FR5 | `defaultOptionality` suppresses only the visible marker that restates the form default; descendant controls still expose the resolved `aria-required`, while native `required` stays tied to an explicit field `isRequired`. Unset keeps each field's own indicators. Implementation gap: under `defaultOptionality="required"`, Typeahead and Tokenizer set no `aria-required`, so those fields are announced as not required while the marker is hidden (Current-state impact). | Tests; `family:input-fields` ownership |-| FR6 | The root is a `div`. `ref`, DOM, data, ARIA, and event props, `xstyle`, class name, and inline style reach or compose on the root without replacing `data-direction` or the `form-layout` target. | `architecture:public-component-api/INV5–INV8`; source and tests |+| ID | Invariant | Basis |+| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |+| FR1 | `vertical` (the default) stacks children in a flex column with a `--spacing-4` gap. | Released source, tests, and stories |+| FR2 | `horizontal` places every direct child in one `1fr` grid column in the document's logical inline order, with a `--spacing-4` gap and no component-owned wrap rule. | Released source, tests, and stories |+| FR3 | `horizontal-labels` is a two-column grid (`auto 1fr`) with a `--spacing-3` row gap and `--spacing-4` column gap, items aligned to the start, so Field labels sit on the inline-start side of their controls; at a viewport width of 480px or below it becomes one flex column with a `--spacing-4` gap. OQ1 holds whether the collapsed label and control need a tighter pair gap. | Released source, Field composition, and tests |+| FR4 | FormLayout provides its direction and `defaultOptionality` to descendants in the same layer; a nested FormLayout replaces both for its own descendants, and content in a layer opened inside a FormLayout starts without them (`spec:AST-038` FR7, FR8). | Context source and tests |+| FR5 | `defaultOptionality` suppresses only the visible marker that restates the form default; descendant controls still expose the resolved `aria-required`, while native `required` stays tied to an explicit field `isRequired`. Unset keeps each field's own indicators. | Tests; `family:input-fields` ownership |+| FR6 | The root is a `div`. `ref`, DOM, data, ARIA, and event props, `xstyle`, class name, and inline style reach or compose on the root without replacing `data-direction` or the `form-layout` target. | `architecture:public-component-api/INV5–INV8`; source and tests |### Allowed variation@@ -134,7 +126,7 @@ This table is a review projection; the body below is authoritative.## Accessibility contract- **AR1 — Layout remains nonsemantic.** FormLayout renders a `<div>` and does not imply `<form>`, group, label, or submission semantics; callers provide those when their composition needs them.-- **AR2 — Required state remains perceivable.** A form-wide optionality convention may remove redundant visible markers, but descendant controls preserve the resolved required state for assistive technology. Implementation gap: Typeahead and Tokenizer do not (FR5).+- **AR2 — Required state remains perceivable.** A form-wide optionality convention may remove redundant visible markers, but descendant controls preserve the resolved required state for assistive technology.- **AR3 — Logical order is preserved.** Every direction retains DOM order and logical inline flow; FormLayout does not create a separate keyboard order.## Design relationships@@ -190,7 +182,7 @@ The root target reflects the closed `direction` axis. It owns the outer arrangem| -------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------- || FR1–FR3 | `FormLayout.test.tsx` direction snapshots; `FormLayout.stories.tsx` play checks; stable visual baseline `core-formlayout--vertical` | Vertical, horizontal, horizontal-labels wide and narrow | A changed style class set fails the snapshots; a narrow horizontal-labels control narrower than the layout, or a wide label not before its control, fails the play checks; a changed vertical layout comes back changed for review. The story play guard also runs the AuditMatrix play right-to-left at 320px and the default width, where mirrored horizontal columns are asserted. Gap: no right-to-left check asserts that a horizontal-labels label sits on the inline-start side of its control. | `audit:FormLayout/behavior` || FR4, ORD1 | `FormLayout.test.tsx` context and nesting tests; `Layer/layerScopedContext.test.tsx` | Default, explicit, nested; content in a fixed Layer and an inline Dialog | A lost default or value, lost shadowing by an inner layout's explicit values, or content inside a layer that still reads the outer `defaultOptionality` fails. Gap: no test covers an inner layout with unset props (which supplies its own defaults) or `direction` across a layer boundary. | `audit:FormLayout/behavior` |-| FR5, ORD3, AR2 | `FormLayout.test.tsx` optionality and `aria-required` tests | Required, optional, unset defaults; explicit exceptions | A redundant marker, a missing `aria-required`, or a native `required` from the default fails. FileInput and Slider tests cover a `required` default. Gap: no test covers Typeahead or Tokenizer under a `required` default, which do not expose it. | `audit:FormLayout/accessibility` |+| FR5, ORD3, AR2 | `FormLayout.test.tsx` optionality and `aria-required` tests | Required, optional, unset defaults; explicit exceptions | A redundant marker, a missing `aria-required`, or a native `required` from the default fails. FileInput, Slider, Typeahead, and Tokenizer tests cover a `required` default. | `audit:FormLayout/accessibility` || FR6, ORD2 | `FormLayout.test.tsx` ref, passthrough, and owned-metadata tests; `themingTargets.test.ts` | Ref, attributes, colliding `data-direction` | A ref on a non-`div`, a dropped `id` or `role`, or a replaced `data-direction` fails. Gap: no test covers event props or the styling-input merge order. | `audit:FormLayout/api` || AR1, AR3 | `FormLayout.test.tsx` div and passthrough tests; `FormLayout.stories.tsx` play checks | Plain root; caller `role` | A non-`div` root or a dropped caller `role` fails. Horizontal columns that do not mirror right-to-left fail the AuditMatrix play under the story play guard. Gap: no check fails if FormLayout adds a role of its own. | `audit:FormLayout/accessibility` || PR1 | Source review | Every direction | Gap: no automated check covers context identity or added resources. | `audit:FormLayout/behavior` |diff --git a/packages/core/src/Tokenizer/Tokenizer.test.tsx b/packages/core/src/Tokenizer/Tokenizer.test.tsxindex 22b1578c02..304940d546 100644--- a/packages/core/src/Tokenizer/Tokenizer.test.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.test.tsx@@ -28,6 +28,7 @@ import type {SearchSource, SearchableItem} from '../Typeahead/types';import {TestIcon} from '../__tests__/TestIcon';import {InternationalizationProvider} from '../i18n';import type * as TokenModule from '../Token';+import {FormLayout} from '../FormLayout/FormLayout';// Every Token render, in order, by label.//@@ -1600,6 +1601,86 @@ describe('Tokenizer', () => {});});+describe('Tokenizer required state (FormLayout FR5, AR2)', () => {+ it('exposes the resolved required state on the combobox', () => {+ const field = (props: {+ isRequired?: boolean;+ isOptional?: boolean;+ label: string;+ }) => (+ <Tokenizer+ {...props}+ searchSource={userSource}+ value={[]}+ onChange={() => {}}+ />+ );+ render(+ <>+ {field({label: 'Plain'})}+ {field({label: 'Explicit', isRequired: true})}+ <FormLayout defaultOptionality="required">+ {field({label: 'By default'})}+ {field({label: 'Opted out', isOptional: true})}+ </FormLayout>+ </>,+ );+ const required = (name: string) =>+ screen+ .getByRole('combobox', {name: new RegExp(`^${name}`)})+ .getAttribute('aria-required');+ expect(required('Plain')).toBeNull();+ expect(required('Explicit')).toBe('true');+ expect(required('By default')).toBe('true');+ expect(required('Opted out')).toBeNull();+ });+});++describe('Tokenizer invalid state', () => {+ it('marks the combobox invalid for an error status only (WCAG 4.1.2)', () => {+ const field = (+ label: string,+ status?: {type: 'error' | 'warning'; message: string},+ ) => (+ <Tokenizer+ label={label}+ status={status}+ searchSource={userSource}+ value={[]}+ onChange={() => {}}+ />+ );+ render(+ <>+ {field('None')}+ {field('Warned', {type: 'warning', message: 'Check this'})}+ {field('Failed', {type: 'error', message: 'Pick one'})}+ </>,+ );+ const invalid = (name: string) =>+ screen.getByRole('combobox', {name}).getAttribute('aria-invalid');+ expect(invalid('None')).toBeNull();+ expect(invalid('Warned')).toBeNull();+ expect(invalid('Failed')).toBe('true');+ });++ it("keeps a caller's own aria-invalid and aria-required when the field's own state is off", () => {+ render(+ <Tokenizer+ label="Caller"+ aria-invalid="true"+ aria-required="true"+ searchSource={userSource}+ value={[]}+ onChange={() => {}}+ />,+ );+ const combobox = screen.getByRole('combobox', {name: 'Caller'});+ expect(combobox).toHaveAttribute('aria-invalid', 'true');+ expect(combobox).toHaveAttribute('aria-required', 'true');+ });+});+describe('Tokenizer statusVariant forwarding', () => {it('defaults to attached (status renders with data-variant="attached")', () => {const {container} = render(diff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsxindex 9b02bd2b4a..8c914bb3b4 100644--- a/packages/core/src/Tokenizer/Tokenizer.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.tsx@@ -91,6 +91,7 @@ import {joinAriaIDs} from '../utils/inputAria';import {themeProps} from '../utils/themeProps';import {useTranslator} from '../i18n';import type {TokenizerBottomSheetProps} from './TokenizerBottomSheet';+import {useResolvedRequired} from '../hooks/useResolvedRequired';// Re-export status types for convenienceexport type {@@ -760,6 +761,7 @@ export function Tokenizer<T extends SearchableItem>({'aria-labelledby': ariaLabelledByProp,...restProps}: TokenizerWithPresentationProps<T>): React.JSX.Element {+ const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});const {rest, container} = useFieldInputStyling('Tokenizer', restProps, {containerXstyle,containerClassName,@@ -1421,6 +1423,14 @@ export function Tokenizer<T extends SearchableItem>({.join(' ') || undefined}onChangeQuery={onChangeQuery}+ // The resolved required state reaches the combobox, also when a+ // FormLayout default hides the visible marker (component:FormLayout+ // FR5, AR2).+ aria-required={isEffectivelyRequired || rest['aria-required']}+ // An error status is exposed on the combobox as on every other field+ // (WCAG 4.1.2; spec:AST-020 FR9). Without one, a caller's own+ // aria-required / aria-invalid still applies.+ aria-invalid={status?.type === 'error' || rest['aria-invalid']}__queryEntries={createEntries}debounceMs={debounceMs}onKeyDown={handleKeyDown}diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsxindex 5253c1dad0..aa5503e45c 100644--- a/packages/core/src/Typeahead/Typeahead.test.tsx+++ b/packages/core/src/Typeahead/Typeahead.test.tsx@@ -31,6 +31,7 @@ import {useState,type ProfilerOnRenderCallback,} from 'react';+import {FormLayout} from '../FormLayout/FormLayout';import {Typeahead} from './Typeahead';import {readFile} from 'node:fs/promises';import {resolve} from 'node:path';@@ -693,6 +694,84 @@ describe('Typeahead', () => {expect(screen.getByText(/Required/)).toBeInTheDocument();});+ it('exposes the resolved required state on the combobox (FormLayout FR5, AR2)', () => {+ const field = (props: {+ isRequired?: boolean;+ isOptional?: boolean;+ label: string;+ }) => (+ <Typeahead+ {...props}+ searchSource={fruitSource}+ value={null}+ onChange={() => {}}+ />+ );+ render(+ <>+ {field({label: 'Plain'})}+ {field({label: 'Explicit', isRequired: true})}+ <FormLayout defaultOptionality="required">+ {field({label: 'By default'})}+ {field({label: 'Opted out', isOptional: true})}+ </FormLayout>+ </>,+ );+ const required = (name: string) =>+ screen+ .getByRole('combobox', {name: new RegExp(`^${name}`)})+ .getAttribute('aria-required');+ expect(required('Plain')).toBeNull();+ expect(required('Explicit')).toBe('true');+ // The form default hides the visible marker, so assistive technology+ // must still hear the field as required.+ expect(required('By default')).toBe('true');+ expect(required('Opted out')).toBeNull();+ });++ it('marks the combobox invalid for an error status only (WCAG 4.1.2)', () => {+ const field = (+ label: string,+ status?: {type: 'error' | 'warning'; message: string},+ ) => (+ <Typeahead+ label={label}+ status={status}+ searchSource={fruitSource}+ value={null}+ onChange={() => {}}+ />+ );+ render(+ <>+ {field('None')}+ {field('Warned', {type: 'warning', message: 'Check this'})}+ {field('Failed', {type: 'error', message: 'Pick one'})}+ </>,+ );+ const invalid = (name: string) =>+ screen.getByRole('combobox', {name}).getAttribute('aria-invalid');+ expect(invalid('None')).toBeNull();+ expect(invalid('Warned')).toBeNull();+ expect(invalid('Failed')).toBe('true');+ });++ it("keeps a caller's own aria-invalid and aria-required when the field's own state is off", () => {+ render(+ <Typeahead+ label="Caller"+ aria-invalid="true"+ aria-required="true"+ searchSource={fruitSource}+ value={null}+ onChange={() => {}}+ />,+ );+ const combobox = screen.getByRole('combobox', {name: 'Caller'});+ expect(combobox).toHaveAttribute('aria-invalid', 'true');+ expect(combobox).toHaveAttribute('aria-required', 'true');+ });+it('renders error status message', () => {render(<Typeaheaddiff --git a/packages/core/src/Typeahead/Typeahead.tsx b/packages/core/src/Typeahead/Typeahead.tsxindex ada0c052e7..be29103a9d 100644--- a/packages/core/src/Typeahead/Typeahead.tsx+++ b/packages/core/src/Typeahead/Typeahead.tsx@@ -76,6 +76,7 @@ import {useTranslator} from '../i18n';import {useMergedRefs} from '../hooks/useMergedRefs';import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';+import {useResolvedRequired} from '../hooks/useResolvedRequired';export type {InputStatus as TypeaheadStatus,InputStatusType as TypeaheadStatusType,@@ -420,6 +421,7 @@ export function Typeahead<T extends SearchableItem>({'aria-labelledby': ariaLabelledByProp,...restProps}: TypeaheadProps<T>) {+ const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});const {rest, container} = useFieldInputStyling('Typeahead', restProps, {containerXstyle,containerClassName,@@ -695,6 +697,14 @@ export function Typeahead<T extends SearchableItem>({.join(' ') || undefined}ariaLabelledBy={inputLabelledBy}+ // The resolved required state reaches the combobox, also when a+ // FormLayout default hides the visible marker (component:FormLayout+ // FR5, AR2).+ aria-required={isEffectivelyRequired || rest['aria-required']}+ // An error status is exposed on the combobox as on every other field+ // (WCAG 4.1.2; spec:AST-020 FR9). Without one, a caller's own+ // aria-required / aria-invalid still applies.+ aria-invalid={status?.type === 'error' || rest['aria-invalid']}onChangeQuery={onChangeQuery}onOpenChange={onOpenChange}debounceMs={debounceMs}