An open source design system that's fully customizable and agent ready
TypeScript
fix(Selector, MultiSelector): a query change clears the highlight from the previous list (#8871)
Cindy Zhangdd61bd53b099
diff --git a/.changeset/selector-search-highlight.md b/.changeset/selector-search-highlight.mdnew file mode 100644index 0000000000..ee805a9d73--- /dev/null+++ b/.changeset/selector-search-highlight.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] In a searchable `Selector` or `MultiSelector`, typing now clears the highlight, so Enter never picks an option you did not highlight. Before, the highlight kept its old position, which could point at a different option of the filtered list or at nothing. ArrowDown then starts at the first row: the first enabled match in `Selector`, and Select all or the create row when shown in `MultiSelector`.++@cixzhangdiff --git a/docs/specs/components/MultiSelector/MultiSelector.spec.md b/docs/specs/components/MultiSelector/MultiSelector.spec.mdindex 3443686184..ac3f7166a6 100644--- a/docs/specs/components/MultiSelector/MultiSelector.spec.md+++ b/docs/specs/components/MultiSelector/MultiSelector.spec.md@@ -139,6 +139,7 @@ Complete prop syntax and examples remain in `MultiSelector.doc.mjs`.| FR13 | The field has no root styling props: `control*` reaches the bordered control box around the trigger and `container*` the Field box (`family:input-fields` FR10); a press on the control box outside the trigger opens it; a caller `onClick` runs after the built-in toggle and a caller `onKeyDown` after the built-in keyboard model, and is skipped for keys that model handles and cancels; a caller `aria-describedby` joins the field description and a caller `aria-labelledby` follows the field's own name. With `renderTrigger`, `container*` and `control*` have no effect and warn. The trigger height is the shared element size for its size and MUST grow with a set text size (`spec:AST-102` FR4). Implementation gap: the height is fixed. | `family:input-fields` FR10; `spec:AST-102` FR4; current tests || FR14 | Each toggle, select-all, or clear announces politely: the all-selected message when every option ends selected, the cleared message when none does, and otherwise the selection count. Once a person searches, the match count (or the empty-results message, or the create row's label when it is the only result) is announced politely; no search result is announced while `isLoading` (the FR2 gap). With `htmlName` the field submits one entry per selected value. | `spec:AST-086`; current tests || FR15 | With the built-in trigger, on close focus returns to the trigger only when focus would otherwise be lost (`family:overlay-dismissal` FR9); a close caused by moving focus elsewhere leaves focus there. A caller's control (`renderTrigger`) keeps FR8's focus return. | `family:overlay-dismissal` FR9; current tests |+| FR16 | With `hasSearch`, each change to the query clears the highlight, so `aria-activedescendant` never names a row of the previous list. ArrowDown then starts at the first row (Select all or the create row when shown, otherwise the first enabled match), Enter with nothing highlighted follows FR9, and Left and Right stay the search field's caret keys until a row is highlighted (FR10). | `MultiSelector.test.tsx`; `Selector.searchHighlight.test.tsx` |### Allowed variation@@ -329,6 +330,7 @@ empty-state content remains one shared tree.| FR13 | `MultiSelector.fr10.test.tsx` cases; `MultiSelector.test.tsx` caller aria-labelledby cases | Control box; caller handlers; renderTrigger | A root styling prop, `control*` off the control box, a caller handler before the built-in one, or a lost caller name or description fails. Evidence gap: no test asserts that a caller `onKeyDown` is skipped for a key the built-in model cancels, or the trigger height or its growth with text size (the FR13 gap). | `audit:MultiSelector/layout` || FR14, ORD1 | `MultiSelector.test.tsx` announcements, result-announcement, count-text, and form-participation cases; hasCreate announcement cases | Toggle, select-all, clear; search counts; loading; form | A missing or wrong announcement, a search-result announcement while loading, or a wrong form entry fails. Evidence gap: no test asserts the `onChange`-before-`changeAction` order. | `audit:MultiSelector/behavior` || FR15 | `MultiSelector.test.tsx` "with the built-in trigger, a light dismiss onto another field leaves focus there, and Escape returns it to the trigger" | Escape; light dismiss onto another field | A trigger that takes focus back from another field, or loses it on Escape, fails. | `audit:MultiSelector/behavior` |+| FR16 | `Selector.searchHighlight.test.tsx` MultiSelector suite; `MultiSelector.test.tsx` search Left/Right case | typing after arrowing, then ArrowDown, then Enter | A highlight kept from the previous list, or an Enter that picks a row the user did not highlight, fails. | `audit:MultiSelector/accessibility` || PR1 | Evidence gap: no test asserts the absence of listeners or the timer bounds | — | — | `audit:MultiSelector/behavior` || Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and targets | Missing, extra, prefixed, stale, or alias-backed mappings fail repository validation. | `audit:MultiSelector/theming` |diff --git a/docs/specs/components/Selector/Selector.spec.md b/docs/specs/components/Selector/Selector.spec.mdindex 0de950f651..ce377ecfa8 100644--- a/docs/specs/components/Selector/Selector.spec.md+++ b/docs/specs/components/Selector/Selector.spec.md@@ -161,6 +161,7 @@ These requirements describe shipped behavior on current `main`.| FR6 | While `isReadOnly` is true, the selected value remains focusable and form-submittable, while the selection surface, clear action, disclosure indicator, and every value-change path are unavailable. | Read-only interaction, form, and accessibility tests || FR7 | The listbox carries `data-astryx-menu-press` and follows `module:DropdownMenu/useMenuPress` FR1–FR3, FR5 and AR2: the option under a pointer's release is the one selected, the highlight follows a held pointer through `aria-activedescendant` while DOM focus stays on the combobox, a mouse released outside closes the list and a finger leaves it open, and the browser's stray click never selects. Trigger opening, arrow clamping and closed-trigger typeahead are unchanged. | `module:DropdownMenu/useMenuPress`; `Selector.test.tsx` press model suite || FR8 | Opening the closed list highlights the selected option when it is enabled. Otherwise ArrowUp highlights the last enabled option, and every other way of opening (ArrowDown, a press, Enter, Space) the first enabled option; with no enabled option nothing is highlighted. A disabled option is never highlighted on opening. A search list opened by a press, Enter or typing highlights nothing. | WAI-ARIA listbox and select-only combobox patterns; `Selector.openHighlight.test.tsx` |+| FR9 | In a search list, each change to the query clears the highlight, so `aria-activedescendant` never names an option of the previous list; ArrowDown then starts at the first enabled option, and Enter with nothing highlighted selects nothing. | WAI-ARIA combobox pattern; `Selector.searchHighlight.test.tsx` |### Allowed variation@@ -353,20 +354,21 @@ new theming target.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |-| FR1, AR2, AR3 | `Selector.test.tsx` selection, focus, and keyboard suites, including "leaves focus on the field a press moved it to" and "returns focus to the trigger when the press lands on nothing focusable" | closed/open, search/non-search, disabled option | Removing selection wiring, focus movement, or keyboard behavior fails the named interaction tests | `audit:Selector/behavior` |-| FR2 | placement and selected-item geometry tests; `SelectorKeyboardInset.a11y.chromium.spec.ts` | default, explicit, RTL, transformed entry, keyboard up | Using the wrong positioning model fails the expected position-area or margin | `audit:Selector/behavior` |-| FR3, AV1 | Focused `Selector.test.tsx` computed-display checks plus guarded Chromium Storybook matrix and stable visual stories | popover/bottom sheet, narrow/wide, start/end, LTR/RTL, selected/unselected, check/radio | Empty output reserves width, visible output collapses, logical placement flips incorrectly, or row content overflows | `audit:Selector/design-rendered` |-| FR4, AR1, AR2 | presentation tests plus `aria-haspopup` source review | pointer, compact coarse pointer, search/non-search | Wrong Popover/dialog roles or focus destinations fail tests; `aria-haspopup` values require source/a11y review | `audit:Selector/accessibility` |-| AR1, AV2 | `Selector.listbox.a11y.test.tsx` and `Listbox.a11y.chromium.spec.ts` against the shared Listbox contract; `SelectorListboxName.a11y.chromium.spec.ts` and `Selector.test.tsx` "names the listbox with the field label, not the trigger that shows the value" for the listbox name; `Selector.test.tsx` "Selector with hasSearch: the closed trigger names the selection" for the button trigger's name; `SelectorListboxName.a11y.chromium.spec.ts` "the closed searchable trigger is named by the label and the selected value" for the accessibility tree | popover/sheet, flat/grouped, selected/unselected, disabled, search, loading, custom RTL | A new or wider loss of role, listbox/option name, state, or ownership gates | `audit:Selector/accessibility` |-| FR5, FR6, AR1, AR2 (anchored), AR4 | `Selector.combobox.a11y.test.tsx` and `Selector.combobox.a11y.chromium.spec.ts` against the shared Combobox contract | closed, open with active option, read-only, busy, bottom-sheet open, search input with active option | The trigger or search input loses its role/name/state or popup kind, its open popup or active option relationship breaks, or read-only exposes a selection surface; the bottom-sheet trigger's `aria-controls` naming the inner listbox remains exact known debt | `audit:Selector/accessibility` |-| FR5 | loading, empty-state, and live-region tests | empty options, unmatched search, loading | Empty/no-results output appears or is announced while loading | `audit:Selector/behavior` |-| FR6, AR4 | read-only interaction, form, ARIA, and theme-state tests | search/non-search, clearable, open→read-only, disabled precedence | A value changes, popup or edit affordance remains, form value disappears, or read-only semantics are absent | `audit:Selector/accessibility` |-| FR7 | `Selector.test.tsx` press model suite | finger release over another option, finger/mouse release outside, listbox marker | The press option is selected, the listbox takes focus, a finger release outside closes the list, or the stray click selects | `audit:Selector/behavior` |-| FR8 | `Selector.openHighlight.test.tsx` | selected, none selected, disabled first and last options, selected option disabled, none enabled; ArrowDown, ArrowUp, Enter | An opening highlight on a disabled option, or off the enabled selected option, fails. | `audit:Selector/accessibility` |-| AR5 | `Selector.activeOption.test.tsx`: the ring after keyboard input, no ring after pointer input, the ring again when keyboard input follows a pointer highlight; the active option's indicator measured against the listbox in light and dark | keyboard-active option, pointer-active option | Removing the ring, or drawing it after pointer input, fails; an indicator under 3:1 against the listbox in either mode fails (the fill alone measures 1.09:1 light and 1.15:1 dark) | `audit:Selector/accessibility` |-| source-build contract | `Selector.source-build.test.mjs` | package source compiled by consumer Babel | Moving evaluated StyleX values outside the supported source form fails compilation | `audit:Selector/code-health` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |+| FR1, AR2, AR3 | `Selector.test.tsx` selection, focus, and keyboard suites, including "leaves focus on the field a press moved it to" and "returns focus to the trigger when the press lands on nothing focusable" | closed/open, search/non-search, disabled option | Removing selection wiring, focus movement, or keyboard behavior fails the named interaction tests | `audit:Selector/behavior` |+| FR2 | placement and selected-item geometry tests; `SelectorKeyboardInset.a11y.chromium.spec.ts` | default, explicit, RTL, transformed entry, keyboard up | Using the wrong positioning model fails the expected position-area or margin | `audit:Selector/behavior` |+| FR3, AV1 | Focused `Selector.test.tsx` computed-display checks plus guarded Chromium Storybook matrix and stable visual stories | popover/bottom sheet, narrow/wide, start/end, LTR/RTL, selected/unselected, check/radio | Empty output reserves width, visible output collapses, logical placement flips incorrectly, or row content overflows | `audit:Selector/design-rendered` |+| FR4, AR1, AR2 | presentation tests plus `aria-haspopup` source review | pointer, compact coarse pointer, search/non-search | Wrong Popover/dialog roles or focus destinations fail tests; `aria-haspopup` values require source/a11y review | `audit:Selector/accessibility` |+| AR1, AV2 | `Selector.listbox.a11y.test.tsx` and `Listbox.a11y.chromium.spec.ts` against the shared Listbox contract; `SelectorListboxName.a11y.chromium.spec.ts` and `Selector.test.tsx` "names the listbox with the field label, not the trigger that shows the value" for the listbox name; `Selector.test.tsx` "Selector with hasSearch: the closed trigger names the selection" for the button trigger's name; `SelectorListboxName.a11y.chromium.spec.ts` "the closed searchable trigger is named by the label and the selected value" for the accessibility tree | popover/sheet, flat/grouped, selected/unselected, disabled, search, loading, custom RTL | A new or wider loss of role, listbox/option name, state, or ownership gates | `audit:Selector/accessibility` |+| FR5, FR6, AR1, AR2 (anchored), AR4 | `Selector.combobox.a11y.test.tsx` and `Selector.combobox.a11y.chromium.spec.ts` against the shared Combobox contract | closed, open with active option, read-only, busy, bottom-sheet open, search input with active option | The trigger or search input loses its role/name/state or popup kind, its open popup or active option relationship breaks, or read-only exposes a selection surface; the bottom-sheet trigger's `aria-controls` naming the inner listbox remains exact known debt | `audit:Selector/accessibility` |+| FR5 | loading, empty-state, and live-region tests | empty options, unmatched search, loading | Empty/no-results output appears or is announced while loading | `audit:Selector/behavior` |+| FR6, AR4 | read-only interaction, form, ARIA, and theme-state tests | search/non-search, clearable, open→read-only, disabled precedence | A value changes, popup or edit affordance remains, form value disappears, or read-only semantics are absent | `audit:Selector/accessibility` |+| FR7 | `Selector.test.tsx` press model suite | finger release over another option, finger/mouse release outside, listbox marker | The press option is selected, the listbox takes focus, a finger release outside closes the list, or the stray click selects | `audit:Selector/behavior` |+| FR8 | `Selector.openHighlight.test.tsx` | selected, none selected, disabled first and last options, selected option disabled, none enabled; ArrowDown, ArrowUp, Enter | An opening highlight on a disabled option, or off the enabled selected option, fails. | `audit:Selector/accessibility` |+| FR9 | `Selector.searchHighlight.test.tsx` | typing after arrowing (ArrowDown to Cherry, then `ap`), typing then ArrowDown, a disabled only match, reopening after a search | A highlight that names an option of the previous list, an Enter that picks an option the user did not highlight, or an ArrowDown that lands on a disabled option fails. | `audit:Selector/accessibility` |+| AR5 | `Selector.activeOption.test.tsx`: the ring after keyboard input, no ring after pointer input, the ring again when keyboard input follows a pointer highlight; the active option's indicator measured against the listbox in light and dark | keyboard-active option, pointer-active option | Removing the ring, or drawing it after pointer input, fails; an indicator under 3:1 against the listbox in either mode fails (the fill alone measures 1.09:1 light and 1.15:1 dark) | `audit:Selector/accessibility` |+| source-build contract | `Selector.source-build.test.mjs` | package source compiled by consumer Babel | Moving evaluated StyleX values outside the supported source form fails compilation | `audit:Selector/code-health` |## Decision logdiff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsxindex 3bf93f4768..6bb43241e2 100644--- a/packages/core/src/MultiSelector/MultiSelector.tsx+++ b/packages/core/src/MultiSelector/MultiSelector.tsx@@ -1209,6 +1209,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({// Read by the live region above so it speaks what this element renders.const emptyStateRef = useRef<HTMLDivElement>(null);const triggerRef = useRef<HTMLElement>(null);+// A hover moves the highlight too, but the focus ring follows the shared// interaction modality (architecture:interaction-modality INV1): it is read// whenever a key or the pointer moves the highlight, so an action cell@@ -1848,6 +1849,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({onTriggerClick,onKeyDown: onComboboxKeyDown,onItemMouseEnter: onComboboxItemMouseEnter,+ setHighlightedIndex,} = useMultiCombobox({selectableItems: sortedItems,isDisabled: isDisabled || isEffectivelyReadOnly,@@ -1878,6 +1880,16 @@ export function MultiSelector<T extends MultiSelectorOptionType>({),});+ // A new query is a new list: the old highlight's index would name another+ // row, or one past the end, so it is cleared. With no row highlighted, Left+ // and Right stay the search field's caret keys. Adjusted during render+ // rather than in an effect.+ const [highlightedQuery, setHighlightedQuery] = useState(searchQuery);+ if (highlightedQuery !== searchQuery) {+ setHighlightedQuery(searchQuery);+ setHighlightedIndex(-1);+ }+const {isKeyboardHighlight, onKeyDown, onItemMouseEnter} =useKeyboardHighlight(readModality,diff --git a/packages/core/src/Selector/Selector.searchHighlight.test.tsx b/packages/core/src/Selector/Selector.searchHighlight.test.tsxnew file mode 100644index 0000000000..8955b643c4--- /dev/null+++ b/packages/core/src/Selector/Selector.searchHighlight.test.tsx@@ -0,0 +1,138 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Selector.searchHighlight.test.tsx+ * @input Uses Selector, MultiSelector, Testing Library+ * @output Tests that a searchable Selector or MultiSelector clears its+ * highlight as the query changes, so `aria-activedescendant` never names an+ * option of the previous list and Enter never picks one the user did not+ * highlight+ * @position Colocated behavior test for search in Selector and MultiSelector+ */++import {describe, it, expect, vi} from 'vitest';+import {render, screen} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {Selector} from './Selector';+import {MultiSelector} from '../MultiSelector';++const OPTIONS = [+ 'Apple',+ 'Apricot',+ {value: 'Avocado', disabled: true},+ 'Banana',+ 'Blueberry',+ 'Cherry',+];++const h = {hidden: true} as const;++/** The rendered option `aria-activedescendant` names, or null. */+function activeOption(search: HTMLElement): HTMLElement | null {+ const id = search.getAttribute('aria-activedescendant');+ return id == null ? null : document.getElementById(id);+}++describe('Selector: a query change clears the highlight', () => {+ function renderSearch(props: {value?: string} = {}) {+ const onChange = vi.fn();+ render(+ <Selector+ label="Fruit"+ options={OPTIONS}+ value={props.value}+ onChange={onChange}+ hasSearch+ />,+ );+ return onChange;+ }++ it('clears a highlight left from before the query, so Enter picks nothing unseen', async () => {+ const user = userEvent.setup();+ const onChange = renderSearch();+ await user.click(screen.getByRole('button', {name: /^Fruit\b/}));+ const search = screen.getByRole('combobox', h);+ // Apricot is index 1, inside the two-row list `b` leaves (Banana,+ // Blueberry), so a kept index would name Blueberry.+ await user.keyboard('{ArrowDown}{ArrowDown}');+ await user.type(search, 'b');+ expect(search.getAttribute('aria-activedescendant')).toBeNull();+ await user.keyboard('{Enter}');+ expect(onChange).not.toHaveBeenCalled();+ await user.keyboard('{ArrowDown}');+ expect(activeOption(search)?.textContent).toContain('Banana');+ await user.keyboard('{Enter}');+ expect(onChange).toHaveBeenCalledWith('Banana');+ });++ it('does not keep an index past the new list (ArrowDown to Cherry, then ap)', async () => {+ const user = userEvent.setup();+ renderSearch();+ await user.click(screen.getByRole('button', {name: /^Fruit\b/}));+ const search = screen.getByRole('combobox', h);+ await user.keyboard(+ '{ArrowDown}{ArrowDown}{ArrowDown}{ArrowDown}{ArrowDown}',+ );+ expect(activeOption(search)?.textContent).toContain('Cherry');+ await user.type(search, 'ap');+ expect(search.getAttribute('aria-activedescendant')).toBeNull();+ await user.keyboard('{ArrowDown}');+ expect(activeOption(search)?.textContent).toContain('Apple');+ });++ it('highlights nothing when the list reopens after a search', async () => {+ const user = userEvent.setup();+ const onChange = renderSearch({value: 'Cherry'});+ const trigger = screen.getByRole('button', {name: /Fruit/});+ await user.click(trigger);+ await user.type(screen.getByRole('combobox', h), 'b');+ await user.keyboard('{Escape}');+ await user.click(trigger);+ expect(activeOption(screen.getByRole('combobox', h))).toBeNull();+ await user.keyboard('{Enter}');+ expect(onChange).not.toHaveBeenCalled();+ });++ it('highlights nothing on ArrowDown when no match is enabled', async () => {+ const user = userEvent.setup();+ renderSearch();+ await user.click(screen.getByRole('button', {name: /^Fruit\b/}));+ const search = screen.getByRole('combobox', h);+ await user.type(search, 'a');+ expect(search.getAttribute('aria-activedescendant')).toBeNull();+ await user.type(search, 'vo');+ // Avocado is the only match and it is disabled: nothing is highlighted,+ // and no stale id is left behind.+ await user.keyboard('{ArrowDown}');+ expect(search.getAttribute('aria-activedescendant')).toBeNull();+ });+});++describe('MultiSelector: a query change clears the highlight', () => {+ it('clears a highlight left from before the query, so Enter picks nothing unseen', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <MultiSelector+ label="Fruit"+ options={OPTIONS}+ value={[]}+ onChange={onChange}+ hasSearch+ />,+ );+ await user.click(screen.getByRole('button', {name: /^Fruit\b/}));+ const search = screen.getByRole('combobox', h);+ // Apricot is index 1, inside the two-row list `b` leaves (Banana,+ // Blueberry), so a kept index would name Blueberry.+ await user.keyboard('{ArrowDown}{ArrowDown}');+ await user.type(search, 'b');+ expect(search.getAttribute('aria-activedescendant')).toBeNull();+ await user.keyboard('{Enter}');+ expect(onChange).not.toHaveBeenCalled();+ // ArrowDown then starts at the first match.+ await user.keyboard('{ArrowDown}');+ expect(activeOption(search)?.textContent).toContain('Banana');+ });+});diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsxindex c697f28e52..1e86696275 100644--- a/packages/core/src/Selector/Selector.tsx+++ b/packages/core/src/Selector/Selector.tsx@@ -1603,6 +1603,15 @@ export function Selector<T extends SelectorOptionType>(noteHighlightMove();}, [comboboxTriggerClick, noteHighlightMove]);+ // A new query is a new list: the old highlight's index would name another+ // option, or one past the end. Adjusted during render rather than in an+ // effect.+ const [highlightedQuery, setHighlightedQuery] = useState(searchQuery);+ if (highlightedQuery !== searchQuery) {+ setHighlightedQuery(searchQuery);+ setHighlightedIndex(-1);+ }+// Type-to-select, shared with the other collections (menus, listboxes).// Open, it walks the highlight — aria-activedescendant announces each match.// Closed, it commits the match like a native select, which changes the value