An open source design system that's fully customizable and agent ready
TypeScript
fix(Selector): keep group headers when searching; hide empty groups (#4459) (#4469)
Cindy Zhanga03e22862aa2
diff --git a/.changeset/selector-group-headers-on-search.md b/.changeset/selector-group-headers-on-search.mdnew file mode 100644index 0000000000..076558102c--- /dev/null+++ b/.changeset/selector-group-headers-on-search.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Selector & MultiSelector: keep group headers visible while searching; hide groups with no matching items. Previously, typing a query flattened grouped options into a single ungrouped list; now each group header stays above its matching items and a group is hidden only when none of its items match.++@cixzhangdiff --git a/apps/storybook/stories/MultiSelector.stories.tsx b/apps/storybook/stories/MultiSelector.stories.tsxindex 0a3fb54b5c..52baecc717 100644--- a/apps/storybook/stories/MultiSelector.stories.tsx+++ b/apps/storybook/stories/MultiSelector.stories.tsx@@ -94,6 +94,42 @@ export const Sections: Story = {decorators: [Story => <Story />],};+// Searchable with sections: filtering keeps group headers and drops empty groups+export const SearchableSections: Story = {+ render: () => {+ const [value, setValue] = useState<string[]>([]);+ return (+ <MultiSelector+ label="Permissions"+ hasSearch+ options={[+ {+ type: 'section',+ title: 'Read',+ options: [+ {value: 'read_posts', label: 'Read posts'},+ {value: 'read_comments', label: 'Read comments'},+ {value: 'read_users', label: 'Read users'},+ ],+ },+ {+ type: 'section',+ title: 'Write',+ options: [+ {value: 'write_posts', label: 'Write posts'},+ {value: 'write_comments', label: 'Write comments'},+ ],+ },+ ]}+ value={value}+ onChange={setValue}+ placeholder="Select permissions..."+ />+ );+ },+ decorators: [Story => <Story />],+};+// With Select Allexport const SelectAll: Story = {render: () => {@@ -411,7 +447,8 @@ export const StatusVariantComparison: Story = {const [a, setA] = useState<string[]>([]);const [b, setB] = useState<string[]>([]);return (- <div style={{display: 'flex', flexDirection: 'column', gap: 24, width: 300}}>+ <div+ style={{display: 'flex', flexDirection: 'column', gap: 24, width: 300}}><MultiSelectorlabel="Attached (default)"options={['Name', 'Email', 'Role']}diff --git a/apps/storybook/stories/Selector.stories.tsx b/apps/storybook/stories/Selector.stories.tsxindex eaffea1779..ef7254d257 100644--- a/apps/storybook/stories/Selector.stories.tsx+++ b/apps/storybook/stories/Selector.stories.tsx@@ -274,6 +274,54 @@ export const WithSections: Story = {},};+// Searchable with sections: filtering keeps group headers and drops empty groups+export const SearchableWithSections: Story = {+ render: args => {+ const {+ value: argsValue,+ onChange: _onChange,+ changeAction: _ca,+ hasClear: _hc,+ ...rest+ } = args;+ const [value, setValue] = useState(argsValue ?? undefined);+ return (+ <Selector+ {...rest}+ label="Fruit"+ hasSearch+ options={[+ {+ type: 'section',+ title: 'Citrus',+ options: [+ {value: 'orange', label: 'Orange'},+ {value: 'lemon', label: 'Lemon'},+ {value: 'lime', label: 'Lime'},+ {value: 'grapefruit', label: 'Grapefruit'},+ ],+ },+ {+ type: 'section',+ title: 'Tropical',+ options: [+ {value: 'mango', label: 'Mango'},+ {value: 'pineapple', label: 'Pineapple'},+ {value: 'papaya', label: 'Papaya'},+ {value: 'guava', label: 'Guava'},+ ],+ },+ ]}+ value={value}+ onChange={v => setValue(v)}+ />+ );+ },+ args: {+ placeholder: 'Select a fruit...',+ },+};+// Custom renderexport const CustomRender: Story = {render: args => {@@ -609,7 +657,8 @@ export const StatusVariantComparison: Story = {const [a, setA] = useState<string | undefined>();const [b, setB] = useState<string | undefined>();return (- <div style={{display: 'flex', flexDirection: 'column', gap: 24, width: 280}}>+ <div+ style={{display: 'flex', flexDirection: 'column', gap: 24, width: 280}}><Selectorlabel="Attached (default)"options={[diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsxindex 560ee23dac..d192a291ea 100644--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx@@ -565,6 +565,72 @@ describe('MultiSelector', () => {expect(options).toHaveLength(1);});+ describe('grouped search', () => {+ const GROUPED = [+ {+ type: 'section' as const,+ title: 'Citrus',+ options: [+ {value: 'orange', label: 'Orange'},+ {value: 'lemon', label: 'Lemon'},+ ],+ },+ {+ type: 'section' as const,+ title: 'Berries',+ options: [+ {value: 'strawberry', label: 'Strawberry'},+ {value: 'blueberry', label: 'Blueberry'},+ ],+ },+ ];++ it('keeps the group header above matching items while searching', async () => {+ const user = userEvent.setup();+ render(+ <MultiSelector+ label="Fruit"+ options={GROUPED}+ value={[]}+ onChange={() => {}}+ hasSearch+ />,+ );+ await user.click(screen.getByRole('button', {name: 'Fruit'}));+ await user.type(screen.getByRole('combobox', h), 'orange');++ expect(+ screen.getByRole('group', {name: 'Citrus', ...h}),+ ).toBeInTheDocument();+ const options = screen.getAllByRole('option', h);+ expect(options).toHaveLength(1);+ expect(options[0]).toHaveTextContent('Orange');+ });++ it('hides a group whose items have no match', async () => {+ const user = userEvent.setup();+ render(+ <MultiSelector+ label="Fruit"+ options={GROUPED}+ value={[]}+ onChange={() => {}}+ hasSearch+ />,+ );+ await user.click(screen.getByRole('button', {name: 'Fruit'}));+ await user.type(screen.getByRole('combobox', h), 'berry');++ expect(+ screen.getByRole('group', {name: 'Berries', ...h}),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole('group', {name: 'Citrus', ...h}),+ ).not.toBeInTheDocument();+ expect(screen.getAllByRole('option', h)).toHaveLength(2);+ });+ });+it('PageDown/PageUp jump the highlight to the last/first filtered option', async () => {const user = userEvent.setup();render(diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsxindex 96f34b72d4..cf0bb4a669 100644--- a/packages/core/src/MultiSelector/MultiSelector.tsx+++ b/packages/core/src/MultiSelector/MultiSelector.tsx@@ -570,6 +570,21 @@ export interface MultiSelectorProps<'data-testid'?: string;}+// Case-insensitive substring match for a single option. The one predicate used+// by both the flat filter (count + keyboard nav) and the grouped renderer, so+// what is shown while searching stays in lockstep with the announced count.+function optionMatchesQuery(+ option: MultiSelectorOptionData,+ query: string,+): boolean {+ if (!query) {+ return true;+ }+ return (option.label ?? option.value)+ .toLowerCase()+ .includes(query.toLowerCase());+}+// Case-insensitive substring filter over the selectable options. Shared by the// `filteredItems` memo (rendering) and the search-change handler, which needs// the count for the *next* query synchronously to announce it exactly once per@@ -581,10 +596,7 @@ function filterOptionsByQuery(if (!query) {return items;}- const q = query.toLowerCase();- return items.filter(item =>- (item.label ?? item.value).toLowerCase().includes(q),- );+ return items.filter(item => optionMatchesQuery(item, query));}/**@@ -725,35 +737,25 @@ export function MultiSelector<T extends MultiSelectorOptionType>({// Single source of truth for item order. Both the hook (keyboard navigation)// and renderOptions (DOM rendering) consume this list — no independent sorting.- // Selected-at-open items are placed first within each group/section.+ // Selected-at-open items are placed first within each group/section, and the+ // same walk applies while searching so group structure survives filtering+ // (only matching items are kept; the query is empty in non-search mode).const sortedItems = useMemo(() => {const selectedSet = selectedAtOpen ?? new Set<string>();- if (searchQuery) {- const selected = filteredItems.filter(item =>- selectedSet.has(item.value),- );- const unselected = filteredItems.filter(- item => !selectedSet.has(item.value),- );- const items = [...selected, ...unselected];- if (hasSelectAll) {- return [{value: SELECT_ALL_VALUE, label: selectAllLabel}, ...items];- }- return items;- }- // For non-search mode, flatten options in the same order as renderOptionsconst result: MultiSelectorOptionData[] = [];let pendingFlat: MultiSelectorOptionData[] = [];+ const orderSelectedFirst = (items: MultiSelectorOptionData[]) => {+ const selected = items.filter(item => selectedSet.has(item.value));+ const unselected = items.filter(item => !selectedSet.has(item.value));+ return [...selected, ...unselected];+ };+const flushFlat = () => {if (pendingFlat.length === 0) {return;}- const selected = pendingFlat.filter(item => selectedSet.has(item.value));- const unselected = pendingFlat.filter(- item => !selectedSet.has(item.value),- );- result.push(...selected, ...unselected);+ result.push(...orderSelectedFirst(pendingFlat));pendingFlat = [];};@@ -762,16 +764,15 @@ export function MultiSelector<T extends MultiSelectorOptionType>({flushFlat();} else if (isSection(option)) {flushFlat();- const sectionOptions = option.options.map(opt => normalizeOption(opt));- const selected = sectionOptions.filter(item =>- selectedSet.has(item.value),- );- const unselected = sectionOptions.filter(- item => !selectedSet.has(item.value),- );- result.push(...selected, ...unselected);+ const sectionOptions = option.options+ .map(opt => normalizeOption(opt))+ .filter(opt => optionMatchesQuery(opt, searchQuery));+ result.push(...orderSelectedFirst(sectionOptions));} else if (isOptionData(option)) {- pendingFlat.push(normalizeOption(option));+ const normalized = normalizeOption(option);+ if (optionMatchesQuery(normalized, searchQuery)) {+ pendingFlat.push(normalized);+ }}}flushFlat();@@ -781,7 +782,6 @@ export function MultiSelector<T extends MultiSelectorOptionType>({}return result;}, [- filteredItems,searchQuery,options,selectedAtOpen,@@ -1227,15 +1227,12 @@ export function MultiSelector<T extends MultiSelectorOptionType>({return elements;}- if (searchQuery) {- for (let i = cursor; i < sortedItems.length; i++) {- elements.push(renderItem(sortedItems[i], i));- }- return elements;- }-- // Non-search: consume items from sortedItems in order, interleaving- // structural elements (dividers, section headers) from the options prop.+ // Consume items from sortedItems in order, interleaving structural elements+ // (dividers, section headers) from the options prop. While searching, only+ // matching items are present in sortedItems, so a section consumes just its+ // matches and is skipped entirely when none match — no header left standing+ // over nothing, and the cursor stays aligned with the combobox indices.+ const isSearching = Boolean(searchQuery);let pendingCount = 0;const flushPending = () => {@@ -1251,12 +1248,25 @@ export function MultiSelector<T extends MultiSelectorOptionType>({if (isDivider(option)) {flushPending();- elements.push(<Divider key={`divider-${i}`} xstyle={styles.divider} />);+ // A standalone divider between groups would orphan itself once its+ // neighbors are filtered out, so skip it while searching.+ if (!isSearching) {+ elements.push(+ <Divider key={`divider-${i}`} xstyle={styles.divider} />,+ );+ }} else if (isSection(option)) {flushPending();- const count = option.options.length;+ const matchCount = isSearching+ ? option.options.filter(opt =>+ optionMatchesQuery(normalizeOption(opt), searchQuery),+ ).length+ : option.options.length;+ if (matchCount === 0) {+ continue;+ }const sectionItems: ReactNode[] = [];- for (let j = 0; j < count; j++) {+ for (let j = 0; j < matchCount; j++) {sectionItems.push(renderItem(sortedItems[cursor], cursor));cursor++;}@@ -1275,7 +1285,12 @@ export function MultiSelector<T extends MultiSelectorOptionType>({</div>,);} else if (isOptionData(option)) {- pendingCount++;+ if (+ !isSearching ||+ optionMatchesQuery(normalizeOption(option), searchQuery)+ ) {+ pendingCount++;+ }}}flushPending();diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsxindex c5aeeede1e..02cec29b55 100644--- a/packages/core/src/Selector/Selector.test.tsx+++ b/packages/core/src/Selector/Selector.test.tsx@@ -746,6 +746,125 @@ describe('Selector', () => {expect(politeRegion()?.textContent ?? '').toBe('');});});++ describe('grouped search', () => {+ const GROUPED = [+ {+ type: 'section' as const,+ title: 'Citrus',+ options: [+ {value: 'orange', label: 'Orange'},+ {value: 'lemon', label: 'Lemon'},+ ],+ },+ {+ type: 'section' as const,+ title: 'Berries',+ options: [+ {value: 'strawberry', label: 'Strawberry'},+ {value: 'blueberry', label: 'Blueberry'},+ ],+ },+ ];++ it('keeps the group header above matching items while searching', async () => {+ const user = userEvent.setup();+ render(+ <Selector+ label="Fruit"+ options={GROUPED}+ onChange={() => {}}+ hasSearch+ />,+ );+ await user.click(screen.getByRole('button', {name: 'Fruit'}));+ // "orange" only matches within the Citrus group.+ await user.type(screen.getByRole('combobox', h), 'orange');++ expect(+ screen.getByRole('group', {name: 'Citrus', ...h}),+ ).toBeInTheDocument();+ const options = screen.getAllByRole('option', h);+ expect(options).toHaveLength(1);+ expect(options[0]).toHaveTextContent('Orange');+ });++ it('hides a group whose items have no match', async () => {+ const user = userEvent.setup();+ render(+ <Selector+ label="Fruit"+ options={GROUPED}+ onChange={() => {}}+ hasSearch+ />,+ );+ await user.click(screen.getByRole('button', {name: 'Fruit'}));+ // "berry" only matches items inside the Berries group.+ await user.type(screen.getByRole('combobox', h), 'berry');++ expect(+ screen.getByRole('group', {name: 'Berries', ...h}),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole('group', {name: 'Citrus', ...h}),+ ).not.toBeInTheDocument();+ expect(screen.getAllByRole('option', h)).toHaveLength(2);+ });++ it('lands keyboard focus on the correct option after filtering', async () => {+ const user = userEvent.setup();+ render(+ <Selector+ label="Fruit"+ options={GROUPED}+ onChange={() => {}}+ hasSearch+ />,+ );+ await user.click(screen.getByRole('button', {name: 'Fruit'}));+ const search = screen.getByRole('combobox', h);+ // "berry" leaves Strawberry, Blueberry (in that document order).+ await user.type(search, 'berry');+ const options = screen.getAllByRole('option', h);+ expect(options.map(o => o.textContent)).toEqual([+ 'Strawberry',+ 'Blueberry',+ ]);+ await user.keyboard('{ArrowDown}');+ expect(search).toHaveAttribute(+ 'aria-activedescendant',+ options[0].id,+ );+ await user.keyboard('{ArrowDown}');+ expect(search).toHaveAttribute(+ 'aria-activedescendant',+ options[1].id,+ );+ });++ it('shows the empty state when no group has a match', async () => {+ const user = userEvent.setup();+ render(+ <Selector+ label="Fruit"+ options={GROUPED}+ onChange={() => {}}+ hasSearch+ />,+ );+ await user.click(screen.getByRole('button', {name: 'Fruit'}));+ await user.type(screen.getByRole('combobox', h), 'zzz');+ expect(screen.queryAllByRole('option', h)).toHaveLength(0);+ expect(+ screen.queryByRole('group', {name: 'Citrus', ...h}),+ ).not.toBeInTheDocument();+ const listbox = screen.getByRole('listbox', h);+ expect(+ within(listbox).getByText('No results found'),+ ).toBeInTheDocument();+ });+ });});describe('keyboard accessibility', () => {diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsxindex 86693a01bc..fd7bd94f67 100644--- a/packages/core/src/Selector/Selector.tsx+++ b/packages/core/src/Selector/Selector.tsx@@ -545,6 +545,21 @@ function DefaultOption({option}: {option: SelectorOptionData}) {);}+// Case-insensitive substring match for a single option. The one predicate used+// by both the flat filter (count + keyboard nav) and the grouped renderer, so+// what is shown while searching stays in lockstep with the announced count.+function optionMatchesQuery(+ option: SelectorOptionData,+ query: string,+): boolean {+ if (!query) {+ return true;+ }+ return (option.label ?? option.value)+ .toLowerCase()+ .includes(query.toLowerCase());+}+// Case-insensitive substring filter over the selectable options. Shared by the// `filteredItems` memo (rendering) and the search-change handler, which needs// the count for the *next* query synchronously to announce it exactly once per@@ -556,10 +571,7 @@ function filterOptionsByQuery(if (!query) {return items;}- const q = query.toLowerCase();- return items.filter(item =>- (item.label ?? item.value).toLowerCase().includes(q),- );+ return items.filter(item => optionMatchesQuery(item, query));}/**@@ -947,16 +959,15 @@ export function Selector<T extends SelectorOptionType>(// Render all options (handling sections/dividers)const renderOptions = useCallback(() => {- // When search is active, render filtered items flat (no sections/dividers)- if (hasSearch && searchQuery) {- if (filteredItems.length === 0) {- return [- <div key="empty" {...stylex.props(styles.emptyState)}>- No results found- </div>,- ];- }- return filteredItems.map((item, index) => renderItem(item, index));+ const isSearching = hasSearch && Boolean(searchQuery);++ // Nothing matched across every group/option: show the empty state.+ if (isSearching && filteredItems.length === 0) {+ return [+ <div key="empty" {...stylex.props(styles.emptyState)}>+ No results found+ </div>,+ ];}let flatIndex = 0;@@ -966,13 +977,27 @@ export function Selector<T extends SelectorOptionType>(const option = options[i];if (isDivider(option)) {+ // While searching, a standalone divider between groups would orphan+ // itself once its neighbors are filtered out, so skip it.+ if (isSearching) {+ continue;+ }elements.push(<Divider key={`divider-${i}`} xstyle={styles.divider} />);} else if (isSection(option)) {const sectionItems: ReactNode[] = [];for (const opt of option.options) {- sectionItems.push(renderItem(normalizeOption(opt), flatIndex));+ const normalized = normalizeOption(opt);+ if (isSearching && !optionMatchesQuery(normalized, searchQuery)) {+ continue;+ }+ sectionItems.push(renderItem(normalized, flatIndex));flatIndex++;}+ // Hide a group entirely (header + wrapper) when none of its items+ // match the query, so no header is left standing over nothing.+ if (sectionItems.length === 0) {+ continue;+ }if (option.title) {elements.push(<Divider@@ -988,7 +1013,11 @@ export function Selector<T extends SelectorOptionType>(</div>,);} else if (isOptionData(option)) {- elements.push(renderItem(normalizeOption(option), flatIndex));+ const normalized = normalizeOption(option);+ if (isSearching && !optionMatchesQuery(normalized, searchQuery)) {+ continue;+ }+ elements.push(renderItem(normalized, flatIndex));flatIndex++;}}