An open source design system that's fully customizable and agent ready
TypeScript
feat(Selector): add hasSearch prop for filtering options (#2131) (#2142)
Mike Rumblea747054dc43a
diff --git a/packages/core/src/Selector/Selector.doc.mjs b/packages/core/src/Selector/Selector.doc.mjsindex 88610acbcf..5d9ef19af3 100644--- a/packages/core/src/Selector/Selector.doc.mjs+++ b/packages/core/src/Selector/Selector.doc.mjs@@ -47,6 +47,18 @@ export const docs = {'Shows a clear (\u00d7) button when a value is selected. When true, onChange also accepts null to signal the user cleared the selection.',default: 'false',},+ {+ name: 'hasSearch',+ type: 'boolean',+ description: 'Whether to show a search input for filtering options.',+ default: 'false',+ },+ {+ name: 'searchPlaceholder',+ type: 'string',+ description: 'Placeholder text for the search input.',+ default: "'Search...'",+ },{name: 'placeholder',type: 'string',@@ -193,6 +205,18 @@ export const docsZh = {description: '选中值时显示清除 (×) 按鈕。启用后,onChange 还接受 null 表示用户已清除选择。',default: 'false',},+ {+ name: 'hasSearch',+ type: 'boolean',+ description: '是否显示用于过滤选项的搜索输入。',+ default: 'false',+ },+ {+ name: 'searchPlaceholder',+ type: 'string',+ description: '搜索输入的占位文本。',+ default: "'Search...'",+ },{name: 'placeholder',type: 'string',@@ -330,6 +354,8 @@ export const docsDense = {value: 'Currently selected value.',onChange: 'Callback fired when selection changes.',hasClear: 'Shows clear button when value selected. onChange also accepts null on clear.',+ hasSearch: 'Shows search input for filtering options.',+ searchPlaceholder: 'Placeholder text for search input.',placeholder: 'Placeholder text when no value selected.',size: 'Size variant for selector.',isDisabled: 'Disables selector.',diff --git a/packages/core/src/Selector/XDSSelector.test.tsx b/packages/core/src/Selector/XDSSelector.test.tsxindex cd24612272..0c9fbaff3e 100644--- a/packages/core/src/Selector/XDSSelector.test.tsx+++ b/packages/core/src/Selector/XDSSelector.test.tsx@@ -9,11 +9,38 @@* SYNC: When XDSSelector.tsx API changes, update these tests.*/-import {describe, it, expect, vi} from 'vitest';+import {describe, it, expect, vi, beforeEach} from 'vitest';import {render, screen} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {XDSSelector} from './XDSSelector';+// Mock showPopover and hidePopover methods since they're not implemented in jsdom+beforeEach(() => {+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {+ this.setAttribute('popover-open', '');+ const event = new Event('toggle', {bubbles: false});+ Object.defineProperty(event, 'newState', {value: 'open'});+ this.dispatchEvent(event);+ });+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {+ this.removeAttribute('popover-open');+ const event = new Event('toggle', {bubbles: false});+ Object.defineProperty(event, 'newState', {value: 'closed'});+ this.dispatchEvent(event);+ });+ const originalMatches = HTMLElement.prototype.matches;+ HTMLElement.prototype.matches = function (selector: string) {+ if (selector === ':popover-open') {+ return this.hasAttribute('popover-open');+ }+ return originalMatches.call(this, selector);+ };+});++// Helper: jsdom popover content is in the DOM but may not be+// "visible" in the accessibility tree. Use hidden: true to find it.+const h = {hidden: true} as const;+const OPTIONS = ['Apple', 'Banana', 'Cherry'];describe('XDSSelector', () => {@@ -158,4 +185,129 @@ describe('XDSSelector', () => {expect(screen.getByRole('combobox')).toHaveTextContent('Yellow Banana');});});++ describe('hasSearch', () => {+ it('renders search input when hasSearch is true', async () => {+ const user = userEvent.setup();+ render(+ <XDSSelector+ label="Fruit"+ options={OPTIONS}+ value="Apple"+ onChange={() => {}}+ hasSearch+ />,+ );+ await user.click(screen.getByRole('combobox'));+ expect(screen.getByRole('searchbox', h)).toBeInTheDocument();+ });++ it('does not render search input when hasSearch is false', async () => {+ const user = userEvent.setup();+ render(+ <XDSSelector+ label="Fruit"+ options={OPTIONS}+ value="Apple"+ onChange={() => {}}+ />,+ );+ await user.click(screen.getByRole('combobox'));+ expect(screen.queryByRole('searchbox', h)).not.toBeInTheDocument();+ });++ it('filters options by search query', async () => {+ const user = userEvent.setup();+ render(+ <XDSSelector+ label="Fruit"+ options={OPTIONS}+ value="Apple"+ onChange={() => {}}+ hasSearch+ />,+ );+ await user.click(screen.getByRole('combobox'));+ await user.type(screen.getByRole('searchbox', h), 'ban');+ const options = screen.getAllByRole('option', h);+ expect(options).toHaveLength(1);+ expect(options[0]).toHaveTextContent('Banana');+ });++ it('shows empty state when no options match', async () => {+ const user = userEvent.setup();+ render(+ <XDSSelector+ label="Fruit"+ options={OPTIONS}+ value="Apple"+ onChange={() => {}}+ hasSearch+ />,+ );+ await user.click(screen.getByRole('combobox'));+ await user.type(screen.getByRole('searchbox', h), 'xyz');+ expect(screen.queryAllByRole('option', h)).toHaveLength(0);+ expect(screen.getByText('No results found')).toBeInTheDocument();+ });++ it('calls onChange when selecting a filtered option', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <XDSSelector+ label="Fruit"+ options={OPTIONS}+ value="Apple"+ onChange={onChange}+ hasSearch+ />,+ );+ await user.click(screen.getByRole('combobox'));+ await user.type(screen.getByRole('searchbox', h), 'ban');+ await user.click(screen.getByRole('option', {name: /Banana/, ...h}));+ expect(onChange).toHaveBeenCalledWith('Banana');+ });++ it('closes dropdown on Tab without preventing default focus movement', async () => {+ const user = userEvent.setup();+ render(+ <>+ <XDSSelector+ label="Fruit"+ options={OPTIONS}+ value="Apple"+ onChange={() => {}}+ hasSearch+ />+ <button type="button">Next</button>+ </>,+ );++ const trigger = screen.getByRole('combobox');+ await user.click(trigger);+ expect(trigger).toHaveAttribute('aria-expanded', 'true');++ await user.keyboard('{Tab}');+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ });++ it('uses custom search placeholder', async () => {+ const user = userEvent.setup();+ render(+ <XDSSelector+ label="Fruit"+ options={OPTIONS}+ value="Apple"+ onChange={() => {}}+ hasSearch+ searchPlaceholder="Find a fruit..."+ />,+ );+ await user.click(screen.getByRole('combobox'));+ expect(+ screen.getByPlaceholderText('Find a fruit...'),+ ).toBeInTheDocument();+ });+ });});diff --git a/packages/core/src/Selector/XDSSelector.tsx b/packages/core/src/Selector/XDSSelector.tsxindex f8acb0d7a4..84dbaa644a 100644--- a/packages/core/src/Selector/XDSSelector.tsx+++ b/packages/core/src/Selector/XDSSelector.tsx@@ -21,6 +21,7 @@ import React, {useMemo,useOptimistic,useRef,+ useState,useTransition,type ReactNode,} from 'react';@@ -206,6 +207,42 @@ const styles = stylex.create({popover: {minWidth: 'anchor-size(width)',},+ // Search input+ searchWrapper: {+ paddingInline: spacingVars['--spacing-2'],+ paddingBlock: spacingVars['--spacing-1'],+ },+ searchInput: {+ boxSizing: 'border-box',+ width: '100%',+ paddingBlock: spacingVars['--spacing-1'],+ paddingInline: spacingVars['--spacing-2'],+ borderWidth: borderVars['--border-width'],+ borderStyle: 'solid',+ borderColor: colorVars['--color-border-emphasized'],+ borderRadius: radiusVars['--radius-element'],+ backgroundColor: colorVars['--color-background-surface'],+ fontFamily: typographyVars['--font-family-body'],+ fontSize: {+ default: typeScaleVars['--text-label-size'],+ '@media (pointer: coarse)': `max(1rem, ${typeScaleVars['--text-label-size']})`,+ },+ color: colorVars['--color-text-primary'],+ outline: {+ default: 'none',+ ':focus': `${borderVars['--border-width']} solid ${colorVars['--color-accent']}`,+ },+ outlineOffset: '0',+ },++ // Empty state+ emptyState: {+ padding: spacingVars['--spacing-3'],+ textAlign: 'center',+ color: colorVars['--color-text-secondary'],+ fontFamily: typographyVars['--font-family-body'],+ fontSize: typeScaleVars['--text-label-size'],+ },// Section divider with labelsectionDivider: {@@ -401,6 +438,18 @@ interface XDSSelectorPropsBase<*/children?: (option: XDSSelectorOptionData) => ReactNode;+ /**+ * Whether to show a search input for filtering options.+ * @default false+ */+ hasSearch?: boolean;++ /**+ * Placeholder text for the search input.+ * @default 'Search...'+ */+ searchPlaceholder?: string;+/*** Whether the dropdown starts open on mount.* Useful for showcases and previews.@@ -492,6 +541,8 @@ export function XDSSelector<T extends XDSSelectorOptionType>(status,labelTooltip,children,+ hasSearch = false,+ searchPlaceholder = 'Search...',isDefaultOpen = false,'data-testid': testId,xstyle,@@ -509,7 +560,11 @@ export function XDSSelector<T extends XDSSelectorOptionType>(const listboxId = useId();const descriptionId = useId();const statusMessageId = useId();+ const searchId = useId();const triggerRef = useRef<HTMLButtonElement>(null);+ const searchRef = useRef<HTMLInputElement>(null);++ const [searchQuery, setSearchQuery] = useState('');const [, startTransition] = useTransition();const [optimisticValue, setOptimisticValue] = useOptimistic(normalizedValue);@@ -530,6 +585,15 @@ export function XDSSelector<T extends XDSSelectorOptionType>([options],);+ // Filter items by search query+ const filteredItems = useMemo(() => {+ if (!searchQuery) return selectableItems;+ const query = searchQuery.toLowerCase();+ return selectableItems.filter(item =>+ (item.label ?? item.value).toLowerCase().includes(query),+ );+ }, [selectableItems, searchQuery]);+// Find selected item and its index for positioningconst selectedItemIndex = useMemo(() => {return selectableItems.findIndex(item => item.value === optimisticValue);@@ -546,6 +610,7 @@ export function XDSSelector<T extends XDSSelectorOptionType>(// Layer for dropdown positioningconst handleLayerHide = useCallback(() => {+ setSearchQuery('');triggerRef.current?.focus();}, []);@@ -564,13 +629,18 @@ export function XDSSelector<T extends XDSSelectorOptionType>(}, []);// Calculate offset to position selected item over trigger- const {offset: selectedItemOffset, isPositioned} = useSelectedItemOffset({- isOpen: popover.isOpen,- selectedItemIndex,- listboxId,- listboxRef,- triggerRef,- });+ const {offset: rawOffset, isPositioned: rawIsPositioned} =+ useSelectedItemOffset({+ isOpen: popover.isOpen,+ selectedItemIndex,+ listboxId,+ listboxRef,+ triggerRef,+ });++ // Disable macOS overlay positioning when search is active+ const selectedItemOffset = hasSearch ? 0 : rawOffset;+ const isPositioned = hasSearch ? true : rawIsPositioned;// Selector behavior (keyboard nav, typeahead, selection)const {@@ -582,11 +652,19 @@ export function XDSSelector<T extends XDSSelectorOptionType>(onItemSelect,onItemMouseEnter,} = useCombobox({- selectableItems,+ selectableItems: filteredItems,value: normalizedValue,isDisabled,isOpen: popover.isOpen,- onOpen: popover.show,+ hasSearch,+ onOpen: useCallback(() => {+ popover.show();+ if (hasSearch) {+ requestAnimationFrame(() => {+ searchRef.current?.focus();+ });+ }+ }, [popover, hasSearch]),onClose: popover.hide,onSelect: useCallback((newValue: string) => {@@ -620,6 +698,44 @@ export function XDSSelector<T extends XDSSelectorOptionType>([onChange, changeAction, startTransition, setOptimisticValue],);+ // Render search input+ const renderSearch = useCallback(() => {+ if (!hasSearch) return null;+ return (+ <div {...stylex.props(styles.searchWrapper)}>+ <input+ ref={searchRef}+ id={searchId}+ role="searchbox"+ aria-controls={listboxId}+ aria-label="Search options"+ type="text"+ value={searchQuery}+ onChange={e => setSearchQuery(e.target.value)}+ onKeyDown={e => {+ if (+ e.key === 'ArrowDown' ||+ e.key === 'ArrowUp' ||+ e.key === 'Escape' ||+ e.key === 'Tab'+ ) {+ onKeyDown(e);+ }+ }}+ placeholder={searchPlaceholder}+ {...stylex.props(styles.searchInput)}+ />+ </div>+ );+ }, [+ hasSearch,+ searchId,+ listboxId,+ searchQuery,+ searchPlaceholder,+ onKeyDown,+ ]);+// Render an individual itemconst renderItem = useCallback((item: XDSSelectorOptionData, flatIndex: number) => {@@ -662,6 +778,18 @@ export function XDSSelector<T extends XDSSelectorOptionType>(// 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));+ }+let flatIndex = 0;const elements: ReactNode[] = [];@@ -678,7 +806,6 @@ export function XDSSelector<T extends XDSSelectorOptionType>(sectionItems.push(renderItem(normalizeOption(opt), flatIndex));flatIndex++;}- // Render divider with label before the groupif (option.title) {elements.push(<XDSDivider@@ -700,7 +827,7 @@ export function XDSSelector<T extends XDSSelectorOptionType>(}return elements;- }, [options, renderItem, listboxId]);+ }, [options, renderItem, listboxId, hasSearch, searchQuery, filteredItems]);return (<XDSField@@ -798,18 +925,32 @@ export function XDSSelector<T extends XDSSelectorOptionType>(</div>{popover.render(- <div- ref={listboxRef}- id={listboxId}- role="listbox"- aria-labelledby={triggerId}- {...stylex.props(- styles.dropdown,- !isPositioned && styles.dropdownHidden,- styles.dropdownOffset(-selectedItemOffset),- )}>- {renderOptions()}- </div>,+ hasSearch ? (+ <div>+ {renderSearch()}+ <div+ ref={listboxRef}+ id={listboxId}+ role="listbox"+ aria-labelledby={triggerId}+ {...stylex.props(styles.dropdown)}>+ {renderOptions()}+ </div>+ </div>+ ) : (+ <div+ ref={listboxRef}+ id={listboxId}+ role="listbox"+ aria-labelledby={triggerId}+ {...stylex.props(+ styles.dropdown,+ !isPositioned && styles.dropdownHidden,+ styles.dropdownOffset(-selectedItemOffset),+ )}>+ {renderOptions()}+ </div>+ ),{placement: 'below',alignment: 'start',diff --git a/packages/core/src/Selector/hooks.ts b/packages/core/src/Selector/hooks.tsindex 8dbc8132ec..624e3fe7fa 100644--- a/packages/core/src/Selector/hooks.ts+++ b/packages/core/src/Selector/hooks.ts@@ -133,6 +133,7 @@ interface UseComboboxOptions {value?: string;isDisabled?: boolean;isOpen: boolean;+ hasSearch?: boolean;onOpen: () => void;onClose: () => void;onSelect?: (value: string) => void;@@ -157,6 +158,7 @@ export function useCombobox({value,isDisabled = false,isOpen,+ hasSearch = false,onOpen,onClose,onSelect,@@ -203,10 +205,12 @@ export function useCombobox({closeAndReset();} else {onOpen();- const selectedIndex = findSelectedIndex();- setHighlightedIndex(selectedIndex >= 0 ? selectedIndex : 0);+ if (!hasSearch) {+ const selectedIndex = findSelectedIndex();+ setHighlightedIndex(selectedIndex >= 0 ? selectedIndex : 0);+ }}- }, [isDisabled, isOpen, onOpen, closeAndReset, findSelectedIndex]);+ }, [isDisabled, isOpen, onOpen, closeAndReset, findSelectedIndex, hasSearch]);const onItemMouseEnter = useCallback((item: XDSSelectorOptionData, index: number) => {@@ -251,8 +255,12 @@ export function useCombobox({}break;- case 'Enter':case ' ':+ if (hasSearch) {+ break;+ }+ // falls through+ case 'Enter':e.preventDefault();if (isOpen && highlightedIndex >= 0) {const item = selectableItems[highlightedIndex];@@ -261,8 +269,10 @@ export function useCombobox({}} else if (!isOpen) {onOpen();- const selectedIndex = findSelectedIndex();- setHighlightedIndex(selectedIndex >= 0 ? selectedIndex : 0);+ if (!hasSearch) {+ const selectedIndex = findSelectedIndex();+ setHighlightedIndex(selectedIndex >= 0 ? selectedIndex : 0);+ }}break;@@ -273,6 +283,12 @@ export function useCombobox({}break;+ case 'Tab':+ if (isOpen) {+ closeAndReset();+ }+ break;+case 'Home':e.preventDefault();if (isOpen && enabledIndices.length > 0) {@@ -288,7 +304,7 @@ export function useCombobox({break;default:- if (e.key.length === 1 && !e.ctrlKey && !e.metaKey) {+ if (!hasSearch && e.key.length === 1 && !e.ctrlKey && !e.metaKey) {const newTypeahead = typeahead + e.key.toLowerCase();setTypeahead(newTypeahead);@@ -325,6 +341,7 @@ export function useCombobox({findSelectedIndex,getEnabledIndices,typeahead,+ hasSearch,],);