An open source design system that's fully customizable and agent ready
TypeScript
fix(Typeahead): Escape in edit mode hides the list first, then restores the token and focuses it (#9608)
Cindy Zhang8d809ad012cd
diff --git a/.changeset/typeahead-escape-edit-focuses-token.md b/.changeset/typeahead-escape-edit-focuses-token.mdnew file mode 100644index 0000000000..d860f9643a--- /dev/null+++ b/.changeset/typeahead-escape-edit-focuses-token.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `Typeahead`: pressing Escape while editing the selected value now restores the value and moves focus to its token, instead of dropping focus to the page. With the list shown, the first Escape only hides the list.++@cixzhangdiff --git a/docs/specs/components/Typeahead/Typeahead.spec.md b/docs/specs/components/Typeahead/Typeahead.spec.mdindex cd0cc6c289..d1b45a9083 100644--- a/docs/specs/components/Typeahead/Typeahead.spec.md+++ b/docs/specs/components/Typeahead/Typeahead.spec.md@@ -97,18 +97,18 @@ BaseTypeahead and TypeaheadItem keep their own records.## Behavioral and layout contract-| ID | Invariant | Basis |-| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |-| FR1 | The current standalone presentation contains a Field and painted Input surface; the supported InputGroup path renders the same Input surface without a Field. The surface contains an editable input when unselected or editing, and a Selected token plus collapsed input when selected and not editing. | Current source, docs, and tests |-| FR2 | Input surface, Dropdown, Empty state, and Default item content carry the four Typeahead targets documented in `Typeahead.doc.mjs`. | Current source, docs, and tests |-| FR3 | Every result, whether default or caller-rendered, sits inside the same stable outer Result row that owns option semantics, highlight, selected styling, pointer interaction, and keyboard indexing. | Current source and tests |-| FR4 | `typeahead-item` reaches only the standard TypeaheadItem label/supporting-content branch inside a Result row. A custom `renderItem` branch or caller-provided `item.element` does not receive that target, and no branch gives the outer Result row a Typeahead target. | Current source and owner tests |-| FR5 | Result group heading and Selected result state are stable visible concepts but no Typeahead target reaches them (OQ1). The selected check uses a generic Icon, which exposes no Typeahead-specific selected-row selector. | Current source |-| FR6 | When present, Field, Selected token, Clear button, Spinner, and Icon-rendered start icon retain their Field, Token, Spinner, and Icon theming owners; arbitrary ReactNode start and item content stays caller-owned. | Current composition and owners |-| FR7 | A disabled Typeahead keeps the input's Tab stop with `aria-disabled` and `readOnly` (`spec:AST-085` FR1), opens and picks nothing, and drops search work in flight when it becomes disabled; with a `disabledMessage` it links the reason Tooltip through `aria-describedby`. Caller handlers other than focus and blur MUST NOT run while disabled (FR2). Implementation gap: a disabled input still runs caller click, pointer, and key handlers (`component:BaseTypeahead` FR9). | `spec:AST-085` FR1, FR2; current tests |-| FR8 | With a selected value and not editing, the Token paints over the collapsed input, which leaves the Tab order, and the Token's button, named by the field label and the value, is the Tab stop; clicking the Token enters edit mode, which searches the value's label and restores the input to the Tab order; blur without an action restores the Token; a composing Escape does not leave edit mode. With `hasClear`, the clear button calls `onChange(null)`, and clearing while editing empties the input. | Current tests |-| FR9 | The field has no root styling props: `control*` reaches the input surface and `container*` the Field box (`family:input-fields` FR10); DOM props and the ref reach the combobox input in both paths; a caller `onKeyDown` runs after built-in key handling, once per key, and also for keys on the clear button; a caller `aria-labelledby` follows the field's own name. The surface keeps one row with the end controls in flow at the inline end, and its height is the shared element size as a minimum. | `family:input-fields` FR10; current tests |-| FR10 | The result list follows `component:BaseTypeahead` FR12: a press on the field's input or its buttons, or in the list, keeps it open, and a press anywhere else closes it. | `component:BaseTypeahead` FR12 |+| ID | Invariant | Basis |+| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------- |+| FR1 | The current standalone presentation contains a Field and painted Input surface; the supported InputGroup path renders the same Input surface without a Field. The surface contains an editable input when unselected or editing, and a Selected token plus collapsed input when selected and not editing. | Current source, docs, and tests |+| FR2 | Input surface, Dropdown, Empty state, and Default item content carry the four Typeahead targets documented in `Typeahead.doc.mjs`. | Current source, docs, and tests |+| FR3 | Every result, whether default or caller-rendered, sits inside the same stable outer Result row that owns option semantics, highlight, selected styling, pointer interaction, and keyboard indexing. | Current source and tests |+| FR4 | `typeahead-item` reaches only the standard TypeaheadItem label/supporting-content branch inside a Result row. A custom `renderItem` branch or caller-provided `item.element` does not receive that target, and no branch gives the outer Result row a Typeahead target. | Current source and owner tests |+| FR5 | Result group heading and Selected result state are stable visible concepts but no Typeahead target reaches them (OQ1). The selected check uses a generic Icon, which exposes no Typeahead-specific selected-row selector. | Current source |+| FR6 | When present, Field, Selected token, Clear button, Spinner, and Icon-rendered start icon retain their Field, Token, Spinner, and Icon theming owners; arbitrary ReactNode start and item content stays caller-owned. | Current composition and owners |+| FR7 | A disabled Typeahead keeps the input's Tab stop with `aria-disabled` and `readOnly` (`spec:AST-085` FR1), opens and picks nothing, and drops search work in flight when it becomes disabled; with a `disabledMessage` it links the reason Tooltip through `aria-describedby`. Caller handlers other than focus and blur MUST NOT run while disabled (FR2). Implementation gap: a disabled input still runs caller click, pointer, and key handlers (`component:BaseTypeahead` FR9). | `spec:AST-085` FR1, FR2; current tests |+| FR8 | With a selected value and not editing, the Token paints over the collapsed input, which leaves the Tab order, and the Token's button, named by the field label and the value, is the Tab stop; clicking the Token enters edit mode, which searches the value's label and restores the input to the Tab order; blur without an action restores the Token; a composing Escape does not leave edit mode; a non-composing Escape in edit mode with the list hidden leaves edit mode: it restores the Token and moves focus to the Token's button, so focus never falls to the page body; Escape with the list shown hides the list first (`spec:AST-075` FR4). With `hasClear`, the clear button calls `onChange(null)`, and clearing while editing empties the input. | Current tests |+| FR9 | The field has no root styling props: `control*` reaches the input surface and `container*` the Field box (`family:input-fields` FR10); DOM props and the ref reach the combobox input in both paths; a caller `onKeyDown` runs after built-in key handling, once per key, and also for keys on the clear button; a caller `aria-labelledby` follows the field's own name. The surface keeps one row with the end controls in flow at the inline end, and its height is the shared element size as a minimum. | `family:input-fields` FR10; current tests |+| FR10 | The result list follows `component:BaseTypeahead` FR12: a press on the field's input or its buttons, or in the list, keeps it open, and a press anywhere else closes it. | `component:BaseTypeahead` FR12 |### Allowed variation@@ -264,7 +264,7 @@ normalize targets.| FR2 | `Typeahead.test.tsx` "exposes the empty state as a themeable target"; `TypeaheadItem.test.tsx`; `themingTargets.test.ts` | Empty search; default item | A missing empty-state target fails; a rendered class absent from the documented targets fails. Evidence gap: no test asserts the `typeahead`, `typeahead-dropdown`, or `typeahead-item` placement. | `audit:Typeahead/theming` || FR3, FR4, FR5 | `TypeaheadItem.test.tsx` "renders item.element raw in place of the label layout" | Default and caller content | `item.element` that keeps the default layout fails. Evidence gap: no test asserts the untargeted outer row, group heading, or selected state. | `audit:Typeahead/theming` || FR7 | `Typeahead.test.tsx` disabledMessage cases, including "keeps its tab stop when disabled without a reason" and "drops a search answer that arrives after the field became disabled"; `Typeahead.disabled.a11y.chromium.spec.ts` "Tab reaches the disabled field, which rings and stays read-only" | Disabled with and without a reason | A reason not linked from the input, a disabled input without a Tab stop, typing or selecting while disabled, or a search answer that lands after disabling fails. Evidence gap: no test asserts that caller handlers are skipped while disabled. | `audit:Typeahead/accessibility` |-| FR8, ORD1, AR2, AR3 | `Typeahead.test.tsx` edit-mode and collapsed-input tab-order cases; "calls onChange with null when clear button is clicked"; "does not show clear button when hasClear is false"; "names the token button, the Tab stop while a value shows, by the field label and the value", "names the token button with a caller aria-labelledby as the input is named" | Token, edit, blur, clear; Tab order | A Token that does not enter edit mode, an input left in the Tab order behind a Token, a composing Escape that leaves edit mode, a clear that does not send `null`, or a token button not named by the label and value fails. | `audit:Typeahead/behavior` |+| FR8, ORD1, AR2, AR3 | `Typeahead.test.tsx` edit-mode and collapsed-input tab-order cases; "hides the list on the first Escape, then restores the Token and focuses its button"; "does not exit edit mode on a composing Escape (IME)"; "calls onChange with null when clear button is clicked"; "does not show clear button when hasClear is false"; "names the token button, the Tab stop while a value shows, by the field label and the value", "names the token button with a caller aria-labelledby as the input is named" | Token, edit, blur, clear; Tab order | A Token that does not enter edit mode, an input left in the Tab order behind a Token, a composing Escape that leaves edit mode, a clear that does not send `null`, or a token button not named by the label and value fails. | `audit:Typeahead/behavior` || FR9, AR1 | `Typeahead.fr10.test.tsx` props-type case; `Typeahead.test.tsx` "forwards DOM props and ref to the combobox input while preserving edit and blur behavior", "forwards DOM props and ref to the input inside InputGroup, with control* on the surface", consumer key-handler cases, caller aria-labelledby cases, and end-controls cases; "exposes the resolved required state on the combobox (FormLayout FR5, AR2)", "marks the combobox invalid for an error status only (WCAG 4.1.2)", "keeps a caller's own aria-invalid and aria-required when the field's own state is off" | Standalone and grouped; key handlers; caller name | A root styling prop, a dropped DOM prop or ref, a caller key handler that runs first or twice, a lost caller name, a missing `aria-required` or error `aria-invalid`, or end controls out of flow fails. Evidence gap: no test asserts the minimum height. | `audit:Typeahead/layout` || FR10 | `component:BaseTypeahead` FR12's verification | — | — | — || PR1 | Covered by `component:BaseTypeahead`'s rows; no test asserts the absence of Typeahead listeners (evidence gap) | — | — | `audit:Typeahead/behavior` |diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsxindex 3cb0a601e3..6e08d51b89 100644--- a/packages/core/src/Typeahead/Typeahead.test.tsx+++ b/packages/core/src/Typeahead/Typeahead.test.tsx@@ -2130,6 +2130,46 @@ describe('Typeahead edit mode', () => {expect(onChange).not.toHaveBeenCalled();});+ // FR8: Escape with the list shown hides the list and edit mode stays; with+ // the list hidden it restores the Token and focuses its button, so focus+ // never falls to the page body.+ it('hides the list on the first Escape, then restores the Token and focuses its button', async () => {+ const user = userEvent.setup();+ function Controlled() {+ const [value, setValue] = useState<SearchableItem | null>(fruits[0]);+ return (+ <Typeahead+ label="Fruit"+ searchSource={fruitSource}+ value={value}+ onChange={setValue}+ />+ );+ }+ render(<Controlled />);+ const input = screen.getByRole<HTMLInputElement>('combobox');++ await user.click(screen.getByText(fruits[0].label, VISIBLE));+ await waitFor(() => {+ expect(input.value).toBe(fruits[0].label);+ expect(input).toHaveAttribute('aria-expanded', 'true');+ });++ await user.keyboard('{Escape}');+ expect(input).toHaveAttribute('aria-expanded', 'false');+ expect(input).toHaveFocus();+ expect(input).not.toHaveAttribute('tabindex', '-1');++ await user.keyboard('{Escape}');+ await waitFor(() => {+ expect(+ screen.getByRole('button', {name: new RegExp(fruits[0].label)}),+ ).toHaveFocus();+ });+ expect(input).toHaveAttribute('tabindex', '-1');+ expect(document.activeElement).not.toBe(document.body);+ });+it('does not exit edit mode on a composing Escape (IME)', async () => {const onChange = vi.fn();render(diff --git a/packages/core/src/Typeahead/Typeahead.tsx b/packages/core/src/Typeahead/Typeahead.tsxindex 0a13a40ffb..b85d5f9771 100644--- a/packages/core/src/Typeahead/Typeahead.tsx+++ b/packages/core/src/Typeahead/Typeahead.tsx@@ -538,26 +538,40 @@ export function Typeahead<T extends SearchableItem>({[editingValue, isEditing],);+ // Focus the token's button once it renders (the next cycle), so keyboard+ // users stay in the component after edit mode ends.+ const focusTokenNextFrame = useCallback(() => {+ requestAnimationFrame(() => {+ const tokenEl = tokenRef.current;+ if (tokenEl) {+ const button = tokenEl.querySelector('button');+ (button ?? tokenEl).focus();+ }+ });+ }, []);+// Handle selection from dropdown — clears edit modeconst handleChange = useCallback((item: T | null) => {setIsEditing(false);setEditingValue(null);onChange(item);- // After selection, focus the token so keyboard users stay in the component.- // Use requestAnimationFrame because the token renders on the next cycle.if (item) {- requestAnimationFrame(() => {- const tokenEl = tokenRef.current;- if (tokenEl) {- // Focus the internal button inside the token- const button = tokenEl.querySelector('button');- (button ?? tokenEl).focus();- }- });+ focusTokenNextFrame();}},- [onChange],+ [onChange, focusTokenNextFrame],+ );++ // Whether the base's list is shown: Escape then hides the list first, and+ // edit mode stays.+ const isListOpenRef = useRef(false);+ const handleOpenChange = useCallback(+ (isOpen: boolean) => {+ isListOpenRef.current = isOpen;+ onOpenChange?.(isOpen);+ },+ [onOpenChange],);// Handle clear (explicit X button on token). Edit mode copied the label into@@ -593,14 +607,14 @@ export function Typeahead<T extends SearchableItem>({if (isImeKeyEvent(e.nativeEvent)) {return;}- if (e.key === 'Escape' && editingValue) {+ if (e.key === 'Escape' && editingValue && !isListOpenRef.current) {e.preventDefault();setIsEditing(false);setEditingValue(null);- inputRef.current?.blur();+ focusTokenNextFrame();}},- [editingValue],+ [editingValue, focusTokenNextFrame],);// Click wrapper to focus input or enter edit mode@@ -738,7 +752,7 @@ export function Typeahead<T extends SearchableItem>({// aria-required / aria-invalid still applies.aria-invalid={status?.type === 'error' || rest['aria-invalid']}onChangeQuery={onChangeQuery}- onOpenChange={onOpenChange}+ onOpenChange={handleOpenChange}debounceMs={debounceMs}anchorRef={wrapperRef}onKeyDown={handleKeyDown}