An open source design system that's fully customizable and agent ready
TypeScript
fix(MultiSelector): type-to-select cycles on a repeated letter and searches from the next option (#9961)
Ojas Mutrejad5dd0ec26b08
diff --git a/.changeset/multiselector-type-to-select-cycles.md b/.changeset/multiselector-type-to-select-cycles.mdnew file mode 100644index 0000000000..99dbeb2e56--- /dev/null+++ b/.changeset/multiselector-type-to-select-cycles.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] MultiSelector: in the open list, a repeated letter now moves to the next option that starts with it, so `t`, `t`, `t` over Tea, Toast and Tofu walks Toast, Tofu, Tea instead of staying on Tea. A single letter typed after a pause searches from the option after the highlighted one, not from the top of the list, as in Selector. Space still toggles the highlighted option, so a typed Space does not extend the prefix as it does in Selector. `useMultiCombobox` gets the same behavior. (#9921)++@HelloOjasMutrejadiff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsxindex 41fc3bef1f..d08862973f 100644--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx@@ -798,6 +798,119 @@ describe('MultiSelector', () => {expect(trigger).toHaveAttribute('aria-activedescendant', options[2].id);});+ it('typeahead walks to the next match on a repeated letter', async () => {+ const user = userEvent.setup();+ render(+ <MultiSelector+ label="Food"+ options={['Tea', 'Toast', 'Tofu']}+ value={[]}+ onChange={() => {}}+ />,+ );++ const trigger = screen.getByRole('combobox');+ await user.click(trigger);+ const options = screen.getAllByRole('option', h);+ expect(trigger).toHaveAttribute('aria-activedescendant', options[0].id);++ await user.keyboard('t');+ expect(trigger).toHaveAttribute('aria-activedescendant', options[1].id);+ await user.keyboard('t');+ expect(trigger).toHaveAttribute('aria-activedescendant', options[2].id);+ await user.keyboard('t');+ expect(trigger).toHaveAttribute('aria-activedescendant', options[0].id);+ });++ it('typeahead searches a letter typed after a pause from the next option', async () => {+ vi.useFakeTimers({shouldAdvanceTime: true});+ try {+ const user = userEvent.setup({advanceTimers: vi.advanceTimersByTime});+ render(+ <MultiSelector+ label="Food"+ options={['Tea', 'Toast', 'Tofu']}+ value={[]}+ onChange={() => {}}+ />,+ );++ const trigger = screen.getByRole('combobox');+ await user.click(trigger);+ const options = screen.getAllByRole('option', h);++ await user.keyboard('{ArrowDown}');+ expect(trigger).toHaveAttribute('aria-activedescendant', options[1].id);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });+ await user.keyboard('t');+ expect(trigger).toHaveAttribute('aria-activedescendant', options[2].id);+ } finally {+ vi.useRealTimers();+ }+ });++ it('typeahead keeps refining a longer prefix from the current option', async () => {+ const user = userEvent.setup();+ render(+ <MultiSelector+ label="Food"+ options={['Tea', 'Toast', 'Tofu']}+ value={[]}+ onChange={() => {}}+ />,+ );++ const trigger = screen.getByRole('combobox');+ await user.click(trigger);+ const options = screen.getAllByRole('option', h);++ await user.keyboard('tof');+ expect(trigger).toHaveAttribute('aria-activedescendant', options[2].id);+ });++ it('Space still toggles the option a typed letter jumped to', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <MultiSelector+ label="Status"+ options={['Open', 'Pending', 'Done']}+ value={[]}+ onChange={onChange}+ />,+ );++ const trigger = screen.getByRole('combobox');+ await user.click(trigger);+ const options = screen.getAllByRole('option', h);++ await user.keyboard('p');+ expect(trigger).toHaveAttribute('aria-activedescendant', options[1].id);+ await user.keyboard(' ');+ expect(onChange).toHaveBeenCalledWith(['Pending']);+ });++ it('typeahead opens a closed list on the match', async () => {+ const user = userEvent.setup();+ render(+ <MultiSelector+ label="Food"+ options={['Apple', 'Banana', 'Cherry']}+ value={[]}+ onChange={() => {}}+ />,+ );++ const trigger = screen.getByRole('combobox');+ await act(async () => trigger.focus());+ await user.keyboard('c');+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ const options = screen.getAllByRole('option', h);+ expect(trigger).toHaveAttribute('aria-activedescendant', options[2].id);+ });+it('toggles item with Enter key', async () => {const user = userEvent.setup();const onChange = vi.fn();diff --git a/packages/core/src/MultiSelector/hooks.ts b/packages/core/src/MultiSelector/hooks.tsindex 7849f00e6c..5811ec97e4 100644--- a/packages/core/src/MultiSelector/hooks.ts+++ b/packages/core/src/MultiSelector/hooks.ts@@ -4,7 +4,7 @@/*** @file hooks.ts- * @input Uses React hooks, MultiSelectorOptionData type+ * @input Uses React hooks, the shared useTypeahead hook, MultiSelectorOptionData type* @output Exports useMultiCombobox hook* @position Public hook, exported from the MultiSelector entry point; used by* MultiSelector.tsx@@ -14,11 +14,11 @@* - /packages/core/src/MultiSelector/useMultiCombobox.doc.mjs*/-import {useCallback, useRef, useState} from 'react';+import {useCallback, useState} from 'react';import {isRtlElement} from '../hooks/isRtlElement';import {useHighlightedOptionScroll} from '../hooks/useHighlightedOptionScroll';import type {MultiSelectorOptionData} from './types';-import {findTypeaheadMatch} from '../utils/typeaheadMatch';+import {useTypeahead} from '../hooks/useTypeahead';interface UseMultiComboboxOptions {selectableItems: MultiSelectorOptionData[];@@ -104,10 +104,19 @@ export function useMultiCombobox({setHighlightedIndexState(index);setHighlightedCell('option');}, []);- const [typeahead, setTypeahead] = useState('');- const typeaheadTimeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(- undefined,- );++ // A match on the closed control opens the list on that option.+ const typeahead = useTypeahead({+ getItemLabels: () => selectableItems.map(item => item.label),+ isDisabled: index => selectableItems[index]?.disabled === true,+ getCurrentIndex: () => (isOpen ? highlightedIndex : -1),+ onMatch: index => {+ if (isOpen || onOpen() !== false) {+ setHighlightedIndex(index);+ }+ },+ });+ const resetTypeahead = typeahead.reset;const getItemId = useCallback((index: number) => `${listboxId}-item-${index}`,@@ -131,9 +140,11 @@ export function useMultiCombobox({}, [selectableItems]);const closeAndReset = useCallback(() => {+ // Clear the typed prefix on close. Otherwise the next key extends it.+ resetTypeahead();setHighlightedIndex(-1);onClose();- }, [onClose, setHighlightedIndex]);+ }, [onClose, resetTypeahead, setHighlightedIndex]);const onTriggerClick = useCallback(() => {if (isDisabled) {@@ -190,6 +201,14 @@ export function useMultiCombobox({return;}+ // With hasSearch the query input owns typing, so type-to-select is off.+ // Space stays the toggle: after a letter jumps to an option, Space picks+ // it, so Space never extends the typed prefix here.+ if (!hasSearch && e.key !== ' ' && typeahead.onKeyDown(e)) {+ e.preventDefault();+ return;+ }+const enabledIndices = getEnabledIndices();// In a grid the horizontal arrows move between the row's two cells,@@ -330,32 +349,6 @@ export function useMultiCombobox({onClear();}break;-- default:- // Typeahead only when search is not present- if (!hasSearch && e.key.length === 1 && !e.ctrlKey && !e.metaKey) {- const newTypeahead = typeahead + e.key;- // INV17: the shared type-to-select fold, as Selector uses.- const matchIndex = findTypeaheadMatch(- selectableItems.flatMap((item, i) => (item.disabled ? [] : [i])),- i => selectableItems[i].label,- newTypeahead,- );- const didOpen = isOpen || matchIndex < 0 || onOpen() !== false;- if (didOpen) {- setTypeahead(newTypeahead);- if (typeaheadTimeoutRef.current) {- clearTimeout(typeaheadTimeoutRef.current);- }- typeaheadTimeoutRef.current = setTimeout(() => {- setTypeahead('');- }, 500);- if (matchIndex >= 0) {- setHighlightedIndex(matchIndex);- }- }- }- break;}},[@@ -372,8 +365,8 @@ export function useMultiCombobox({setHighlightedIndex,onToggle,getEnabledIndices,- typeahead,hasSearch,+ typeahead,onClear,hasValue,],diff --git a/packages/core/src/MultiSelector/useMultiCombobox.doc.mjs b/packages/core/src/MultiSelector/useMultiCombobox.doc.mjsindex fc6a5be340..59ad0c921c 100644--- a/packages/core/src/MultiSelector/useMultiCombobox.doc.mjs+++ b/packages/core/src/MultiSelector/useMultiCombobox.doc.mjs@@ -158,7 +158,7 @@ export const docs = {name: 'onKeyDown',type: '(e: React.KeyboardEvent) => void',description:- 'Key handler for the control that keeps focus. ArrowDown and ArrowUp open the list or move the active row; Enter (and Space without search) toggles the active option and keeps the list open; Escape and Tab close it; Home, End, PageUp and PageDown jump to the first or last option; without search, typed characters move to the first option whose label starts with them.',+ 'Key handler for the control that keeps focus. ArrowDown and ArrowUp open the list or move the active row; Enter (and Space without search) toggles the active option and keeps the list open; Escape and Tab close it; Home, End, PageUp and PageDown jump to the first or last option; without search, typed characters move to the next option whose label starts with them, as in Selector (a repeated letter cycles, and a single letter searches from the option after the active one), and Space still toggles.',},{name: 'onItemMouseEnter',@@ -236,7 +236,7 @@ export const docsDense = {getActionCellId: 'grid: id for action cell of row index.',onTriggerClick: 'toggle list from a press on control.',onKeyDown:- 'control keydown: ArrowDown/Up open or move; Enter (Space w/o search) toggles, stays open; Escape / Tab close; Home / End / PageUp / PageDown jump; typed chars jump by label prefix (w/o search).',+ 'control keydown: ArrowDown/Up open or move; Enter (Space w/o search) toggles, stays open; Escape / Tab close; Home / End / PageUp / PageDown jump; typed chars jump to the next option by label prefix, as in Selector (w/o search); Space still toggles.',onItemMouseEnter:'hover makes option / action cell active; no scroll, no focus move.',},