An open source design system that's fully customizable and agent ready
TypeScript
fix(MultiSelector): opening the closed list never highlights a disabled option (#10820)
Cindy Zhang2e6162c9ac85
diff --git a/.changeset/multiselector-open-skips-disabled.md b/.changeset/multiselector-open-skips-disabled.mdnew file mode 100644index 0000000000..ac6be518e4--- /dev/null+++ b/.changeset/multiselector-open-skips-disabled.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] MultiSelector: opening the closed list never highlights a disabled option. ArrowDown, Enter, Space and a press highlight the first enabled option in the order the list opens in, and ArrowUp the last, so Enter no longer lands on an option it cannot toggle. A list with search still highlights nothing when a press or Enter opens it.++@cixzhangdiff --git a/docs/specs/components/MultiSelector/MultiSelector.spec.md b/docs/specs/components/MultiSelector/MultiSelector.spec.mdindex ac3f7166a6..a727ecacbc 100644--- a/docs/specs/components/MultiSelector/MultiSelector.spec.md+++ b/docs/specs/components/MultiSelector/MultiSelector.spec.md@@ -140,6 +140,7 @@ Complete prop syntax and examples remain in `MultiSelector.doc.mjs`.| 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` |+| FR18 | Opening the closed list never highlights a disabled option: ArrowUp highlights the last enabled option, and every other way of opening (ArrowDown, a press, Enter, Space) the first enabled option, in the order the list opens in, with selected options first; with no enabled option nothing is highlighted. Typing on a closed list opens on the typed match. A search list opened by a press, Enter or typing highlights nothing. | `component:Selector` FR8; `MultiSelector.openHighlight.test.tsx` |### Allowed variation@@ -315,24 +316,25 @@ empty-state content remains one shared tree.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- |-| FR1, FR2 | `MultiSelector.test.tsx` render, labels, count, sections, list-structure, search-affordance, select-all, and empty-state cases; "keeps a standalone secondary trigger out of the group geometry" | Standalone and grouped; search; sections; select-all; empty | A missing Field, trigger part, search row, option, divider, heading, or empty state fails; the no-options cases assert the current FR2 gap pending conformance. Evidence gap: no test asserts that the InputGroup path omits the Field. | `audit:MultiSelector/anatomy` |-| FR3, FR6 | `MultiSelector.test.tsx` theme-target cases (empty state, clear icon, indicator icon, disabled state, option row, popup); `themingTargets.test.ts` | Every local target; shared clear glyph | A missing or moved target, or a clear glyph with a component alias, fails. Evidence gap: no test asserts the `multi-selector-search` or section-heading targets. | `audit:MultiSelector/theming` |-| FR4 | `MultiSelector.test.tsx` "routes the clear glyph through the shared clear button" and statusVariant cases | Shared clear and status | A clear or status that leaves its shared owner fails. Evidence gap: no test asserts the CheckboxInput, Divider, Text, and BottomSheet delegation beyond rendering. | `audit:MultiSelector/theming` |-| FR5 | `MultiSelector.test.tsx` "uses a bottom sheet and stays open while toggling options", "uses a bottom sheet for adaptive presentation on compact touch", "moves keyboard focus into a bottom-sheet listbox" | Popover and sheet | A sheet that closes on a toggle or lacks the listbox fails. Evidence gap: no test asserts that both presentations host one panel tree. | `audit:MultiSelector/behavior` |-| FR7 | `MultiSelector.test.tsx` isReadOnly cases; "a read-only selector advertises no panel on the caller's control" | Read-only with loading; pointer, keyboard, typeahead | A read-only field that opens or changes fails. Evidence gap: no test asserts read-only form submission or `aria-readonly`. | `audit:MultiSelector/behavior` |-| FR8 | `MultiSelector.test.tsx` trigger render prop, read-only, and focus-return cases; `MultiSelector.fr10.test.tsx` renderTrigger cases | Caller control closed and open; handle; disabled; focus return | A caller control that does not open the panel, name the listbox, or get focus back, or a handle that opens a disabled selector, fails. | `audit:MultiSelector/behavior` |-| FR9 | `MultiSelector.test.tsx` hasCreate cases; `CreateRow.a11y.chromium.spec.ts` | Create offered, committed, skipped, absent while loading; warning | A create row for an exact match, while loading, or without search, or a creation without its descriptor, fails. | `audit:MultiSelector/behavior` |-| FR10 | `MultiSelector.test.tsx` option-actions (grid), ring-under-mixed-input, and create-row-in-grid cases; `OptionActions.a11y.chromium.spec.ts` | Listbox and grid; RTL; search; hover; Tab | A grid without actions, a listbox with them, a wrong cell activation, reversed RTL arrows, or an action control as a tab stop fails. | `audit:MultiSelector/accessibility` |-| FR11 | `MultiSelector.focusableDisabled.test.tsx` cases; `MultiSelector.test.tsx` disabledMessage cases, "trigger keeps its tab stop when disabled (spec:AST-085 FR1)", "shows no disabled focus ring after a pointer pick (spec:AST-085 FR6)", "shows loading state with a spinner and aria-busy", "is excluded from form data when disabled"; `BusyOwnerAnnouncement.test.tsx` MultiSelector cases | Disabled with and without a reason; loading; pending Action | Native `disabled`, an open or caller handler while disabled, a value submitted while disabled, an unlinked reason, or a missing busy announcement fails. Evidence gap: no test asserts the busy-only paint. | `audit:MultiSelector/accessibility` |-| FR12 | `MultiSelector.test.tsx` keyboard cases ("supports keyboard navigation with ArrowDown/ArrowUp", "End/Home jump the highlight to the last/first option (non-search)", "PageDown/PageUp jump the highlight to the last/first filtered option", "Home/End move the search caret, not the option highlight", "toggles item with Enter key", "does not toggle the highlighted option on a composing Enter (IME)", "closes on Escape", "closes combobox on Tab and moves focus to next element", "opens the listbox with ArrowDown from a focused trigger", the Delete and Backspace clear cases), and "tabs from the search input to the clear button (keeping the popup open) when a query is showing it" | Current source and tests | A key that does the wrong move, a composing Enter that toggles, or a clear with nothing selected fails. | `audit:MultiSelector/accessibility` |-| 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` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- |+| FR1, FR2 | `MultiSelector.test.tsx` render, labels, count, sections, list-structure, search-affordance, select-all, and empty-state cases; "keeps a standalone secondary trigger out of the group geometry" | Standalone and grouped; search; sections; select-all; empty | A missing Field, trigger part, search row, option, divider, heading, or empty state fails; the no-options cases assert the current FR2 gap pending conformance. Evidence gap: no test asserts that the InputGroup path omits the Field. | `audit:MultiSelector/anatomy` |+| FR3, FR6 | `MultiSelector.test.tsx` theme-target cases (empty state, clear icon, indicator icon, disabled state, option row, popup); `themingTargets.test.ts` | Every local target; shared clear glyph | A missing or moved target, or a clear glyph with a component alias, fails. Evidence gap: no test asserts the `multi-selector-search` or section-heading targets. | `audit:MultiSelector/theming` |+| FR4 | `MultiSelector.test.tsx` "routes the clear glyph through the shared clear button" and statusVariant cases | Shared clear and status | A clear or status that leaves its shared owner fails. Evidence gap: no test asserts the CheckboxInput, Divider, Text, and BottomSheet delegation beyond rendering. | `audit:MultiSelector/theming` |+| FR5 | `MultiSelector.test.tsx` "uses a bottom sheet and stays open while toggling options", "uses a bottom sheet for adaptive presentation on compact touch", "moves keyboard focus into a bottom-sheet listbox" | Popover and sheet | A sheet that closes on a toggle or lacks the listbox fails. Evidence gap: no test asserts that both presentations host one panel tree. | `audit:MultiSelector/behavior` |+| FR7 | `MultiSelector.test.tsx` isReadOnly cases; "a read-only selector advertises no panel on the caller's control" | Read-only with loading; pointer, keyboard, typeahead | A read-only field that opens or changes fails. Evidence gap: no test asserts read-only form submission or `aria-readonly`. | `audit:MultiSelector/behavior` |+| FR8 | `MultiSelector.test.tsx` trigger render prop, read-only, and focus-return cases; `MultiSelector.fr10.test.tsx` renderTrigger cases | Caller control closed and open; handle; disabled; focus return | A caller control that does not open the panel, name the listbox, or get focus back, or a handle that opens a disabled selector, fails. | `audit:MultiSelector/behavior` |+| FR9 | `MultiSelector.test.tsx` hasCreate cases; `CreateRow.a11y.chromium.spec.ts` | Create offered, committed, skipped, absent while loading; warning | A create row for an exact match, while loading, or without search, or a creation without its descriptor, fails. | `audit:MultiSelector/behavior` |+| FR10 | `MultiSelector.test.tsx` option-actions (grid), ring-under-mixed-input, and create-row-in-grid cases; `OptionActions.a11y.chromium.spec.ts` | Listbox and grid; RTL; search; hover; Tab | A grid without actions, a listbox with them, a wrong cell activation, reversed RTL arrows, or an action control as a tab stop fails. | `audit:MultiSelector/accessibility` |+| FR11 | `MultiSelector.focusableDisabled.test.tsx` cases; `MultiSelector.test.tsx` disabledMessage cases, "trigger keeps its tab stop when disabled (spec:AST-085 FR1)", "shows no disabled focus ring after a pointer pick (spec:AST-085 FR6)", "shows loading state with a spinner and aria-busy", "is excluded from form data when disabled"; `BusyOwnerAnnouncement.test.tsx` MultiSelector cases | Disabled with and without a reason; loading; pending Action | Native `disabled`, an open or caller handler while disabled, a value submitted while disabled, an unlinked reason, or a missing busy announcement fails. Evidence gap: no test asserts the busy-only paint. | `audit:MultiSelector/accessibility` |+| FR12 | `MultiSelector.test.tsx` keyboard cases ("supports keyboard navigation with ArrowDown/ArrowUp", "End/Home jump the highlight to the last/first option (non-search)", "PageDown/PageUp jump the highlight to the last/first filtered option", "Home/End move the search caret, not the option highlight", "toggles item with Enter key", "does not toggle the highlighted option on a composing Enter (IME)", "closes on Escape", "closes combobox on Tab and moves focus to next element", "opens the listbox with ArrowDown from a focused trigger", the Delete and Backspace clear cases), and "tabs from the search input to the clear button (keeping the popup open) when a query is showing it" | Current source and tests | A key that does the wrong move, a composing Enter that toggles, or a clear with nothing selected fails. | `audit:MultiSelector/accessibility` |+| 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` |+| FR18 | `MultiSelector.openHighlight.test.tsx` | ArrowDown, ArrowUp, Enter and a press on a closed list whose first and last options are disabled; a list with no enabled option | An opening highlight on a disabled option, or any highlight when no option is enabled, 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` |## Current-state impactdiff --git a/packages/core/src/MultiSelector/MultiSelector.openHighlight.test.tsx b/packages/core/src/MultiSelector/MultiSelector.openHighlight.test.tsxnew file mode 100644index 0000000000..6f0de22998--- /dev/null+++ b/packages/core/src/MultiSelector/MultiSelector.openHighlight.test.tsx@@ -0,0 +1,126 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file MultiSelector.openHighlight.test.tsx+ * @input Uses MultiSelector, Testing Library+ * @output Tests which option a closed MultiSelector highlights when it opens:+ * the first enabled option (ArrowUp: the last), never a disabled one, and+ * nothing when no option is enabled+ * @position Colocated behavior test for MultiSelector opening+ */++import {describe, it, expect} from 'vitest';+import {render, screen, fireEvent} from '@testing-library/react';+import {MultiSelector} from './MultiSelector';++const OPTIONS = [+ {value: 'Archived', disabled: true},+ 'Easy',+ 'Hard',+ {value: 'Retired', disabled: true},+];++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 renderMultiSelector(+ options: ReadonlyArray<string | {value: string; disabled?: boolean}>,+ value: string[] = [],+) {+ render(+ <MultiSelector+ label="Levels"+ options={[...options]}+ value={value}+ onChange={() => {}}+ />,+ );+ return screen.getByRole('combobox');+}++describe('MultiSelector: the option a closed list highlights when it opens', () => {+ it('ArrowDown opens on the first enabled option, past a disabled first option', () => {+ const trigger = renderMultiSelector(OPTIONS);+ trigger.focus();+ fireEvent.keyDown(trigger, {key: 'ArrowDown'});+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ expect(activeOptionText(trigger)).toBe('Easy');+ });++ it('ArrowUp opens on the last enabled option, past a disabled last option', () => {+ const trigger = renderMultiSelector(OPTIONS);+ trigger.focus();+ fireEvent.keyDown(trigger, {key: 'ArrowUp'});+ expect(activeOptionText(trigger)).toBe('Hard');+ });++ it('Enter opens on the first enabled option', () => {+ const trigger = renderMultiSelector(OPTIONS);+ trigger.focus();+ fireEvent.keyDown(trigger, {key: 'Enter'});+ expect(activeOptionText(trigger)).toBe('Easy');+ });++ it('a press opens on the first enabled option', () => {+ const trigger = renderMultiSelector(OPTIONS);+ fireEvent.click(trigger);+ expect(activeOptionText(trigger)).toBe('Easy');+ });++ it('highlights nothing when no option is enabled', () => {+ const trigger = renderMultiSelector([+ {value: 'Archived', disabled: true},+ {value: 'Retired', disabled: true},+ ]);+ trigger.focus();+ fireEvent.keyDown(trigger, {key: 'ArrowDown'});+ expect(activeOptionText(trigger)).toBeNull();+ });++ describe('with a value selected, in the order the list opens in', () => {+ // The open list puts the selected options first.+ const LIST = [{value: 'Archived', disabled: true}, 'Easy', 'Hard'];++ it('ArrowDown opens on the selected option at the top', () => {+ const trigger = renderMultiSelector(LIST, ['Hard']);+ trigger.focus();+ fireEvent.keyDown(trigger, {key: 'ArrowDown'});+ expect(activeOptionText(trigger)).toBe('Hard');+ });++ it('Enter opens on the selected option at the top', () => {+ const trigger = renderMultiSelector(LIST, ['Hard']);+ trigger.focus();+ fireEvent.keyDown(trigger, {key: 'Enter'});+ expect(activeOptionText(trigger)).toBe('Hard');+ });++ it('a press opens on the selected option at the top', () => {+ const trigger = renderMultiSelector(LIST, ['Hard']);+ fireEvent.click(trigger);+ expect(activeOptionText(trigger)).toBe('Hard');+ });++ it('ArrowUp opens on the last enabled option when a disabled option is selected', () => {+ const trigger = renderMultiSelector(+ ['Easy', 'Hard', {value: 'Retired', disabled: true}],+ ['Retired'],+ );+ trigger.focus();+ fireEvent.keyDown(trigger, {key: 'ArrowUp'});+ expect(activeOptionText(trigger)).toBe('Hard');+ });++ it('typing opens on the typed match, never on a disabled option', () => {+ const trigger = renderMultiSelector(LIST, ['Hard']);+ trigger.focus();+ fireEvent.keyDown(trigger, {key: 'e'});+ expect(activeOptionText(trigger)).toBe('Easy');+ });+ });+});diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsxindex 6bb43241e2..a83de9a031 100644--- a/packages/core/src/MultiSelector/MultiSelector.tsx+++ b/packages/core/src/MultiSelector/MultiSelector.tsx@@ -1369,7 +1369,10 @@ export function MultiSelector<T extends MultiSelectorOptionType>({);const sortedItems = useMemo(() => {- const selectedSet = selectedAtOpen ?? new Set<string>();+ // Closed, the list keeps the order it opens in, so an index picked+ // before it opens (the opening highlight, a typed match) names the same+ // option after the selected options move to the top.+ const selectedSet = selectedAtOpen ?? new Set(optimisticValue);const result: MultiSelectorOptionData[] = [];let pendingFlat: MultiSelectorOptionData[] = [];@@ -1420,6 +1423,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({searchQuery,options,selectedAtOpen,+ optimisticValue,hasSelectAll,selectAllLabel,createQuery,diff --git a/packages/core/src/MultiSelector/hooks.ts b/packages/core/src/MultiSelector/hooks.tsindex 5811ec97e4..aab1a3deac 100644--- a/packages/core/src/MultiSelector/hooks.ts+++ b/packages/core/src/MultiSelector/hooks.ts@@ -19,6 +19,7 @@ import {isRtlElement} from '../hooks/isRtlElement';import {useHighlightedOptionScroll} from '../hooks/useHighlightedOptionScroll';import type {MultiSelectorOptionData} from './types';import {useTypeahead} from '../hooks/useTypeahead';+import {enabledEdgeIndex} from '../utils/enabledEdgeIndex';interface UseMultiComboboxOptions {selectableItems: MultiSelectorOptionData[];@@ -139,6 +140,12 @@ export function useMultiCombobox({.filter(i => i >= 0);}, [selectableItems]);+ /** Opening never lands on a disabled option; -1 when none is enabled. */+ const findOpeningIndex = useCallback(+ (fromEnd: boolean) => enabledEdgeIndex(selectableItems, fromEnd),+ [selectableItems],+ );+const closeAndReset = useCallback(() => {// Clear the typed prefix on close. Otherwise the next key extends it.resetTypeahead();@@ -155,7 +162,7 @@ export function useMultiCombobox({} else {const didOpen = onOpen() !== false;if (didOpen && !hasSearch) {- setHighlightedIndex(0);+ setHighlightedIndex(findOpeningIndex(false));}}}, [@@ -165,6 +172,7 @@ export function useMultiCombobox({closeAndReset,hasSearch,setHighlightedIndex,+ findOpeningIndex,]);// The scroll effect lives here, the highlight owner, so the hover/keyboard@@ -243,7 +251,7 @@ export function useMultiCombobox({e.preventDefault();if (!isOpen) {if (onOpen() !== false) {- setHighlightedIndex(0);+ setHighlightedIndex(findOpeningIndex(false));}} else {const currentEnabledPos = enabledIndices.indexOf(highlightedIndex);@@ -259,7 +267,7 @@ export function useMultiCombobox({e.preventDefault();if (!isOpen) {if (onOpen() !== false) {- setHighlightedIndex(selectableItems.length - 1);+ setHighlightedIndex(findOpeningIndex(true));}} else {const currentEnabledPos = enabledIndices.indexOf(highlightedIndex);@@ -289,7 +297,7 @@ export function useMultiCombobox({} else if (!isOpen) {const didOpen = onOpen() !== false;if (didOpen && !hasSearch) {- setHighlightedIndex(0);+ setHighlightedIndex(findOpeningIndex(false));}}break;@@ -365,6 +373,7 @@ export function useMultiCombobox({setHighlightedIndex,onToggle,getEnabledIndices,+ findOpeningIndex,hasSearch,typeahead,onClear,diff --git a/packages/core/src/MultiSelector/useMultiCombobox.doc.mjs b/packages/core/src/MultiSelector/useMultiCombobox.doc.mjsindex 59ad0c921c..b6d93d18f9 100644--- a/packages/core/src/MultiSelector/useMultiCombobox.doc.mjs+++ b/packages/core/src/MultiSelector/useMultiCombobox.doc.mjs@@ -32,7 +32,7 @@ export const docs = {name: 'options.selectableItems',type: 'MultiSelectorOptionData[]',description:- 'The options in the same order as they render. Options with `disabled` cannot be toggled and are skipped while moving through the open list; ArrowDown or ArrowUp that opens the list still lands on the first or last option.',+ 'The options in the same order as they render. Options with `disabled` cannot be toggled and are skipped while moving through the open list. Opening never lands on a disabled option: ArrowUp opens on the last enabled option, and ArrowDown, a press, Enter or Space on the first enabled option.',required: true,},{@@ -72,7 +72,7 @@ export const docs = {name: 'options.hasSearch',type: 'boolean',description:- 'Whether the list has its own search field. Space then types instead of toggling, opening by a press or Enter does not pre-highlight (ArrowDown and ArrowUp still open on the first and last option), Delete and Backspace edit the query, and type-to-select is off. Home and End still jump to the first and last option, so a search input that keeps them for the caret should stop them before this handler and rely on PageUp and PageDown.',+ 'Whether the list has its own search field. Space then types instead of toggling, opening by a press or Enter does not pre-highlight (ArrowDown and ArrowUp still open on the first and last enabled option), Delete and Backspace edit the query, and type-to-select is off. Home and End still jump to the first and last option, so a search input that keeps them for the caret should stop them before this handler and rely on PageUp and PageDown.',default: 'false',},{@@ -206,7 +206,7 @@ export const docsDense = {paramDescriptions: {options: 'config.','options.selectableItems':- 'options in render order; disabled ones not toggleable, skipped while moving in open list (ArrowDown/Up opening still lands first / last).',+ 'options in render order; disabled ones not toggleable, skipped while moving in open list; opening lands on the first / last enabled option (ArrowUp: last).','options.isOpen': 'list shown; caller owns state.','options.onOpen':'show list; return false to refuse (highlight untouched).',@@ -215,7 +215,7 @@ export const docsDense = {'options.listboxId':'listbox / grid id; option + action-cell ids derive from it.','options.hasSearch':- 'own search field: Space types, press / Enter opening does not pre-highlight (ArrowDown/Up still first / last), Delete / Backspace edit query, no type-to-select. Home / End still jump; stop them first to keep them for the caret, use PageUp / PageDown.',+ 'own search field: Space types, press / Enter opening does not pre-highlight (ArrowDown/Up still first / last enabled), Delete / Backspace edit query, no type-to-select. Home / End still jump; stop them first to keep them for the caret, use PageUp / PageDown.','options.onClear':'clear all; Delete / Backspace on closed control. ignored when open or hasSearch.','options.hasValue': 'anything selected; clear skipped when false.',diff --git a/packages/core/src/Selector/hooks.ts b/packages/core/src/Selector/hooks.tsindex 4e54eb7235..7c57c56624 100644--- a/packages/core/src/Selector/hooks.ts+++ b/packages/core/src/Selector/hooks.ts@@ -18,6 +18,7 @@*/import {useCallback, useState} from 'react';+import {enabledEdgeIndex} from '../utils/enabledEdgeIndex';import {useHighlightedOptionScroll} from '../hooks/useHighlightedOptionScroll';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import {LAYER_KEYBOARD_INSET_PROPERTY} from '../Layer/useLayerKeyboardClearance';@@ -404,14 +405,9 @@ export function useCombobox<T extends ComboboxOption = SelectorOptionData>({if (selectedIndex >= 0 && !selectableItems[selectedIndex].disabled) {return selectedIndex;}- const enabledIndices = getEnabledIndices();- return (- (fromEnd- ? enabledIndices[enabledIndices.length - 1]- : enabledIndices[0]) ?? -1- );+ return enabledEdgeIndex(selectableItems, fromEnd);},- [findSelectedIndex, getEnabledIndices, selectableItems],+ [findSelectedIndex, selectableItems],);const closeAndReset = useCallback(() => {diff --git a/packages/core/src/utils/enabledEdgeIndex.ts b/packages/core/src/utils/enabledEdgeIndex.tsnew file mode 100644index 0000000000..1f40aaa891--- /dev/null+++ b/packages/core/src/utils/enabledEdgeIndex.ts@@ -0,0 +1,29 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file enabledEdgeIndex.ts+ * @input A list of options and a direction+ * @output The index of the first, or the last, option that is not disabled+ * @position Internal utility; Selector's and MultiSelector's combobox hooks+ * pick the option a closed list opens on with it. Not exported from the+ * utils entry.+ */++/**+ * The index of the first option that is not disabled, or of the last one+ * when `fromEnd` is true. -1 when every option is disabled.+ */+export function enabledEdgeIndex(+ items: ReadonlyArray<{disabled?: boolean}>,+ fromEnd: boolean,+): number {+ if (fromEnd) {+ for (let index = items.length - 1; index >= 0; index--) {+ if (items[index].disabled !== true) {+ return index;+ }+ }+ return -1;+ }+ return items.findIndex(item => item.disabled !== true);+}