An open source design system that's fully customizable and agent ready
TypeScript
fix(Selector): the highlight follows its option by value when the options change (#10818)
Cindy Zhangaeb654c336dd
diff --git a/.changeset/selector-highlight-follows-value.md b/.changeset/selector-highlight-follows-value.mdnew file mode 100644index 0000000000..cac534d9fb--- /dev/null+++ b/.changeset/selector-highlight-follows-value.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Selector: when the options move or reload while the list is open, the highlight stays on its option instead of naming whatever option now sits at its old position. If its option leaves, the highlight moves to the next remaining enabled option after it, or the previous one when none remains after it, and with none left nothing is highlighted.++@cixzhangdiff --git a/docs/specs/components/Selector/Selector.spec.md b/docs/specs/components/Selector/Selector.spec.mdindex ce377ecfa8..2ccdd3fa49 100644--- a/docs/specs/components/Selector/Selector.spec.md+++ b/docs/specs/components/Selector/Selector.spec.md@@ -151,17 +151,18 @@ and examples remain in `Selector.doc.mjs`.These requirements describe shipped behavior on current `main`.-| ID | Shipped invariant | Evidence |-| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |-| FR1 | Selecting an enabled option updates the one selected value, closes the active presentation, and returns the trigger to its stable closed state. | Consumer docs and selection interaction tests |-| FR2 | Without explicit placement, a non-search popover aligns the selected row over the trigger and clamps it to the viewport, above any software keyboard (`spec:AST-059` FR9); a keyboard that goes down while it is open does not move its top. Search popovers and explicit placement use normal Layer positioning. | Consumer docs, implementation, and geometry tests |-| FR3 | An option whose resolved selection indicator draws no content reserves no mark-column space. Visible selected or themed replacement indicators remain in layout at `indicatorPosition`; the resulting state-dependent label position or available width is intentional, and row content keeps its existing overflow behavior. | `itemMarkColumn`, focused indicator tests, and Chromium evidence stories |-| FR4 | `popover` uses an anchored Popover. `bottom-sheet` uses a modal BottomSheet. `adaptive` resolves to the modal bottom sheet on compact coarse-pointer screens and Popover otherwise. | Presentation controller and adaptive-presentation tests |-| FR5 | While `isLoading` is true, the trigger exposes busy state and the listbox suppresses empty and no-results output. | Loading, empty-state, and announcement tests |-| 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` |+| ID | Shipped invariant | Evidence |+| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |+| FR1 | Selecting an enabled option updates the one selected value, closes the active presentation, and returns the trigger to its stable closed state. | Consumer docs and selection interaction tests |+| FR2 | Without explicit placement, a non-search popover aligns the selected row over the trigger and clamps it to the viewport, above any software keyboard (`spec:AST-059` FR9); a keyboard that goes down while it is open does not move its top. Search popovers and explicit placement use normal Layer positioning. | Consumer docs, implementation, and geometry tests |+| FR3 | An option whose resolved selection indicator draws no content reserves no mark-column space. Visible selected or themed replacement indicators remain in layout at `indicatorPosition`; the resulting state-dependent label position or available width is intentional, and row content keeps its existing overflow behavior. | `itemMarkColumn`, focused indicator tests, and Chromium evidence stories |+| FR4 | `popover` uses an anchored Popover. `bottom-sheet` uses a modal BottomSheet. `adaptive` resolves to the modal bottom sheet on compact coarse-pointer screens and Popover otherwise. | Presentation controller and adaptive-presentation tests |+| FR5 | While `isLoading` is true, the trigger exposes busy state and the listbox suppresses empty and no-results output. | Loading, empty-state, and announcement tests |+| 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` |+| FR10 | The highlight follows its option by value: when options move or reload, the highlighted option stays highlighted while it remains in the list; if it leaves, the highlight moves to the next remaining option after it in list order, or the previous remaining option when none remains after it. A disabled option is never highlighted this way, and with no enabled option left nothing is highlighted. | WAI-ARIA listbox pattern; `Selector.highlightFollowsValue.test.tsx` |### Allowed variation@@ -354,21 +355,22 @@ 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` |-| 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` |+| 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` |+| FR10 | `Selector.highlightFollowsValue.test.tsx` | options reordered while open; options reloaded as new objects; the highlighted option removed (the next one follows); the last option removed (the previous one follows); a disabled option in the way; no old option left | A highlight that names a different option after the options change, lands on a disabled option, or survives with no old option left 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/Selector/Selector.activeOption.test.tsx b/packages/core/src/Selector/Selector.activeOption.test.tsxindex f77b972c02..f39272fe46 100644--- a/packages/core/src/Selector/Selector.activeOption.test.tsx+++ b/packages/core/src/Selector/Selector.activeOption.test.tsx@@ -131,6 +131,101 @@ describe('Selector active option indicator', () => {expect(hasRing(row)).toBe(true);});+ it('keeps the fill alone when the options move after the mouse took the highlight', async () => {+ const user = userEvent.setup();+ const {rerender} = render(+ <Selector+ label="Fruit"+ options={OPTIONS}+ value="Apple"+ onChange={() => {}}+ />,+ );+ const field = screen.getByRole('combobox', {name: 'Fruit'});+ field.focus();+ await user.keyboard('{ArrowDown}');+ await user.keyboard('{ArrowDown}');+ await user.hover(option('Cherry'));+ expect(hasRing(activeOption(field))).toBe(false);++ rerender(+ <Selector+ label="Fruit"+ options={[OPTIONS[2], OPTIONS[0], OPTIONS[1]]}+ value="Apple"+ onChange={() => {}}+ />,+ );+ const row = activeOption(field);+ expect(row).toHaveTextContent('Cherry');+ expect(hasRing(row)).toBe(false);+ });++ it('keeps the ring on a keyboard highlight that the options move onto a still mouse’s old row', async () => {+ const user = userEvent.setup();+ const {rerender} = render(+ <Selector+ label="Fruit"+ options={OPTIONS}+ value="Apple"+ onChange={() => {}}+ />,+ );+ const field = screen.getByRole('combobox', {name: 'Fruit'});+ field.focus();+ await user.keyboard('{ArrowDown}');+ await user.keyboard('{ArrowDown}');+ // The browser reports the row under a still pointer as entered while the+ // keyboard move holds the highlight.+ fireEvent.mouseEnter(option('Cherry'));+ expect(activeOption(field)).toHaveTextContent('Banana');++ rerender(+ <Selector+ label="Fruit"+ options={[OPTIONS[0], OPTIONS[2], OPTIONS[1]]}+ value="Apple"+ onChange={() => {}}+ />,+ );+ const row = activeOption(field);+ expect(row).toHaveTextContent('Banana');+ expect(hasRing(row)).toBe(true);+ });++ it('keeps the ring when the follow lands the keyboard highlight on a still mouse’s option', async () => {+ const user = userEvent.setup();+ const {rerender} = render(+ <Selector+ label="Fruit"+ options={OPTIONS}+ value="Apple"+ onChange={() => {}}+ />,+ );+ const field = screen.getByRole('combobox', {name: 'Fruit'});+ field.focus();+ await user.keyboard('{ArrowDown}');+ await user.keyboard('{ArrowDown}');+ // The row under a still pointer is reported as entered while the keyboard+ // move holds the highlight.+ fireEvent.mouseEnter(option('Cherry'));+ expect(activeOption(field)).toHaveTextContent('Banana');++ // Banana leaves; the highlight follows to Cherry, the next option.+ rerender(+ <Selector+ label="Fruit"+ options={[OPTIONS[0], OPTIONS[2]]}+ value="Apple"+ onChange={() => {}}+ />,+ );+ const row = activeOption(field);+ expect(row).toHaveTextContent('Cherry');+ expect(hasRing(row)).toBe(true);+ });+// WCAG 2.2 1.4.11: a state indicator needs 3:1 against the listbox it sits// on. The overlay fill alone measures about 1.09:1 (light) and 1.15:1// (dark).diff --git a/packages/core/src/Selector/Selector.highlightFollowsValue.test.tsx b/packages/core/src/Selector/Selector.highlightFollowsValue.test.tsxnew file mode 100644index 0000000000..ac68dbefe4--- /dev/null+++ b/packages/core/src/Selector/Selector.highlightFollowsValue.test.tsx@@ -0,0 +1,146 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Selector.highlightFollowsValue.test.tsx+ * @input Uses Selector, Testing Library+ * @output Tests that an open Selector's highlight follows its option by value+ * when the options move or reload: it stays on its option, moves to the+ * next remaining enabled option after it (the previous one when it was+ * last) when its option leaves, and clears when none remains+ * @position Colocated behavior test for Selector's highlight+ */++import {describe, it, expect} from 'vitest';+import {render, screen, fireEvent} from '@testing-library/react';+import {Selector} from './Selector';+import type {SelectorOptionType} from './types';++function activeOptionText(control: HTMLElement): string | null {+ const id = control.getAttribute('aria-activedescendant');+ if (id == null || id === '') {+ return null;+ }+ return document.getElementById(id)?.textContent ?? null;+}++function SelectorWith({options}: {options: SelectorOptionType[]}) {+ return (+ <Selector label="Level" options={options} value="" onChange={() => {}} />+ );+}++/** Opens the list and moves the highlight down `steps` times. */+function openAndHighlight(steps: number): HTMLElement {+ const trigger = screen.getByRole('combobox');+ trigger.focus();+ fireEvent.keyDown(trigger, {key: 'ArrowDown'});+ for (let step = 0; step < steps; step++) {+ fireEvent.keyDown(trigger, {key: 'ArrowDown'});+ }+ return trigger;+}++describe('Selector: the highlight follows its option by value', () => {+ it('stays on its option when the options move', () => {+ const {rerender} = render(+ <SelectorWith options={['Easy', 'Hard', 'Expert']} />,+ );+ const trigger = openAndHighlight(1);+ expect(activeOptionText(trigger)).toBe('Hard');++ rerender(<SelectorWith options={['Expert', 'Easy', 'Hard']} />);+ expect(activeOptionText(trigger)).toBe('Hard');+ });++ it('stays on its option when the options reload as new objects', () => {+ const {rerender} = render(+ <SelectorWith+ options={[{value: 'Easy'}, {value: 'Hard'}, {value: 'Expert'}]}+ />,+ );+ const trigger = openAndHighlight(1);+ rerender(+ <SelectorWith+ options={[{value: 'Novice'}, {value: 'Hard'}, {value: 'Expert'}]}+ />,+ );+ expect(activeOptionText(trigger)).toBe('Hard');+ });++ it('moves to the next remaining option after its option when that option leaves', () => {+ const {rerender} = render(+ <SelectorWith options={['Easy', 'Hard', 'Expert', 'Master']} />,+ );+ const trigger = openAndHighlight(1);+ expect(activeOptionText(trigger)).toBe('Hard');++ rerender(<SelectorWith options={['Master', 'Easy', 'Expert']} />);+ expect(activeOptionText(trigger)).toBe('Expert');+ });++ it('moves to the previous remaining option when the option that left was last', () => {+ const {rerender} = render(+ <SelectorWith options={['Easy', 'Hard', 'Expert']} />,+ );+ const trigger = openAndHighlight(2);+ expect(activeOptionText(trigger)).toBe('Expert');++ rerender(<SelectorWith options={['Easy', 'Hard']} />);+ expect(activeOptionText(trigger)).toBe('Hard');+ });++ it('skips a disabled option when it moves the highlight', () => {+ const {rerender} = render(+ <SelectorWith options={['Easy', 'Hard', 'Expert', 'Master']} />,+ );+ const trigger = openAndHighlight(1);++ rerender(+ <SelectorWith+ options={['Easy', {value: 'Expert', disabled: true}, 'Master']}+ />,+ );+ expect(activeOptionText(trigger)).toBe('Master');+ });++ it('highlights nothing when none of its options remains', () => {+ const {rerender} = render(+ <SelectorWith options={['Easy', 'Hard', 'Expert']} />,+ );+ const trigger = openAndHighlight(1);++ rerender(<SelectorWith options={['Novice', 'Master']} />);+ expect(activeOptionText(trigger)).toBeNull();+ });++ it('moves to the previous remaining option when every option after it left', () => {+ const {rerender} = render(+ <SelectorWith options={['Easy', 'Hard', 'Expert']} />,+ );+ const trigger = openAndHighlight(1);+ expect(activeOptionText(trigger)).toBe('Hard');++ rerender(<SelectorWith options={['Easy']} />);+ expect(activeOptionText(trigger)).toBe('Easy');+ });++ it('does not throw when the highlight already sits past the end of the list', () => {+ const FIVE = ['Apple', 'Banana', 'Cherry', 'Date', 'Elder'];+ const {rerender} = render(<SelectorWith options={FIVE} />);+ const trigger = openAndHighlight(1);+ expect(activeOptionText(trigger)).toBe('Banana');+ // A row under a still pointer is reported as entered while the keyboard+ // move holds the highlight; the hover applies on the next pointer move.+ const elder = screen+ .getAllByRole('option', {hidden: true})+ .find(row => row.textContent === 'Elder');+ expect(elder).toBeDefined();+ fireEvent.mouseEnter(elder as HTMLElement);++ rerender(<SelectorWith options={FIVE.slice(0, 3)} />);+ fireEvent.pointerMove(document);+ expect(() =>+ rerender(<SelectorWith options={FIVE.slice(0, 2)} />),+ ).not.toThrow();+ });+});diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsxindex 1e86696275..6a3223258a 100644--- a/packages/core/src/Selector/Selector.tsx+++ b/packages/core/src/Selector/Selector.tsx@@ -1095,6 +1095,58 @@ function filterOptionsByQuery(return items.filter(item => optionMatchesQuery(item, query));}+/**+ * New option objects with the same values and enabled states give the same+ * signature, so they do not move the highlight.+ */+function optionSignature(+ items: ReadonlyArray<{value: string; disabled?: boolean}>,+): string {+ return items+ .map(item => `${item.disabled === true ? '-' : '+'}${item.value}`)+ .join('\u0000');+}++/**+ * The index in `next` of the option highlighted at `index` in `previous`.+ * When that option is gone or disabled, the highlight moves to the next+ * remaining enabled option. With none after it, it moves to the previous+ * one. -1 means none remains.+ */+function followHighlight(+ previous: ReadonlyArray<{value: string; disabled?: boolean}>,+ next: ReadonlyArray<{value: string; disabled?: boolean}>,+ index: number,+): number {+ const enabledIndexOf = (value: string | undefined) =>+ value == null+ ? -1+ : next.findIndex(item => item.value === value && item.disabled !== true);+ const stayed = enabledIndexOf(previous[index]?.value);+ if (stayed >= 0) {+ return stayed;+ }+ for (let after = index + 1; after < previous.length; after++) {+ const found = enabledIndexOf(previous[after]?.value);+ if (found >= 0) {+ return found;+ }+ }+ // The highlight can sit past the end of the list it was set in: a hover+ // applied after the list shrank. Start from the list's own last option.+ for (+ let before = Math.min(index, previous.length) - 1;+ before >= 0;+ before--+ ) {+ const found = enabledIndexOf(previous[before]?.value);+ if (found >= 0) {+ return found;+ }+ }+ return -1;+}+/*** A selector/dropdown component for choosing from a list of options.*@@ -1612,6 +1664,41 @@ export function Selector<T extends SelectorOptionType>(setHighlightedIndex(-1);}+ // The highlight follows its option by value when the options move or+ // reload, so it never names whatever option now sits at its old index.+ // Adjusted during render, as the query reset above.+ const highlightSignature = optionSignature(filteredItems);+ const [highlightedList, setHighlightedList] = useState({+ signature: highlightSignature,+ items: filteredItems,+ });+ if (highlightedList.signature !== highlightSignature) {+ setHighlightedList({signature: highlightSignature, items: filteredItems});+ if (highlightedQuery === searchQuery && highlightedIndex >= 0) {+ const followed = followHighlight(+ highlightedList.items,+ filteredItems,+ highlightedIndex,+ );+ setHighlightedIndex(followed);+ // The hovered row moves with its option too, so the ring keeps showing+ // only a highlight that keyboard input set.+ if (hoveredIndex != null) {+ if (hoveredIndex === highlightedIndex) {+ setHoveredIndex(followed >= 0 ? followed : null);+ } else {+ const hoveredValue = highlightedList.items[hoveredIndex]?.value;+ const moved = filteredItems.findIndex(+ item => item.value === hoveredValue,+ );+ // A follow that lands the keyboard highlight on the hovered option+ // keeps it a keyboard highlight.+ setHoveredIndex(moved >= 0 && moved !== followed ? moved : null);+ }+ }+ }+ }+// 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