An open source design system that's fully customizable and agent ready
TypeScript
XDSSelector (#70)
Cindy Zhang899db8c67a38
diff --git a/.context/proposals/xds-selector-api.md b/.context/proposals/xds-selector-api.mdnew file mode 100644index 0000000000..0d171c4fe2--- /dev/null+++ b/.context/proposals/xds-selector-api.md@@ -0,0 +1,110 @@+# XDSSelector API Proposal++## Status++Approved++## Decision++Use `items` prop with optional render function.++## API++### Basic++```tsx+<XDSSelector+ items={['Apple', 'Banana', 'Orange']}+ value={value}+ onChange={setValue}+/>+```++### With Objects++```tsx+<XDSSelector+ items={[+ {value: 'apple', label: 'Apple'},+ {value: 'banana', label: 'Banana', disabled: true},+ ]}+ value={value}+ onChange={setValue}+/>+```++### Custom Rendering++```tsx+<XDSSelector items={users} value={value} onChange={setValue}>+ {user => <XDSSelectorItem icon={user.avatar}>{user.name}</XDSSelectorItem>}+</XDSSelector>+```++### Dividers & Groups++```tsx+<XDSSelector+ items={[+ {value: 'apple', label: 'Apple'},+ {type: 'divider'},+ {+ type: 'section',+ title: 'Citrus',+ items: [{value: 'orange', label: 'Orange'}],+ },+ ]}+/>+```++## Types++```typescript+type XDSSelectorItem = {+ value: string;+ label?: string;+ disabled?: boolean;+ icon?: XDSIconType;+};++type XDSSelectorOption =+ | string+ | XDSSelectorItem+ | {type: 'divider'}+ | {type: 'section'; title?: string; items: XDSSelectorItem[]};++interface XDSSelectorProps<T extends XDSSelectorOption> {+ // Data+ items: T[];++ // Value+ value?: string;+ onChange?: (value: string) => void;++ // Display+ placeholder?: string;+ children?: (item: Extract<T, XDSSelectorItem>) => React.ReactNode;++ // State+ isDisabled?: boolean;+}+```++## Future: Async/Searchable++Deferred for later. Will use `searchSource` pattern:++```typescript+interface SearchSource<T> {+ bootstrap(): Promise<T[]>;+ search(query: string): Promise<T[]>;+}+```++## Rationale++1. **No two-pass render** — data known upfront+2. **RSC compatible** — server can return items via React Flight+3. **Async-friendly** — `searchSource` encapsulates fetch logic+4. **Still compositional** — render function uses JSX+5. **LLM-friendly** — simple data structure, one componentdiff --git a/apps/storybook/stories/Selector.stories.tsx b/apps/storybook/stories/Selector.stories.tsxnew file mode 100644index 0000000000..7bd3e539f6--- /dev/null+++ b/apps/storybook/stories/Selector.stories.tsx@@ -0,0 +1,437 @@+import type {Meta, StoryObj} from '@storybook/react';+import {useState} from 'react';+import {XDSSelector, XDSSelectorItem} from '@xds/core/Selector';+import {UserIcon, CogIcon, BellIcon} from '@heroicons/react/24/outline';++const meta: Meta<typeof XDSSelector> = {+ title: 'Core/XDSSelector',+ component: XDSSelector,+ tags: ['autodocs'],+ parameters: {+ layout: 'centered',+ },+ decorators: [+ Story => (+ <div style={{width: 250}}>+ <Story />+ </div>+ ),+ ],+ argTypes: {+ label: {+ control: 'text',+ description: 'Label text for the selector',+ },+ isLabelHidden: {+ control: 'boolean',+ description: 'Whether to visually hide the label',+ },+ description: {+ control: 'text',+ description: 'Description text displayed between label and selector',+ },+ items: {+ control: 'object',+ description:+ 'Array of items to display. Can be strings, objects, dividers, or sections.',+ },+ value: {+ control: 'text',+ description: 'The currently selected value',+ },+ placeholder: {+ control: 'text',+ description: 'Placeholder text when no value is selected',+ },+ size: {+ control: 'radio',+ options: ['sm', 'md'],+ description: 'Size variant of the selector',+ },+ isDisabled: {+ control: 'boolean',+ description: 'Whether the selector is disabled',+ },+ isOptional: {+ control: 'boolean',+ description: 'Whether the field is optional',+ },+ isRequired: {+ control: 'boolean',+ description: 'Whether the field is required',+ },+ children: {+ description: 'Optional render function for custom item rendering',+ table: {+ type: {summary: '(item: XDSSelectorItemData) => ReactNode'},+ },+ },+ 'data-testid': {+ control: 'text',+ description: 'Test ID for testing frameworks',+ },+ },+};++export default meta;+type Story = StoryObj<typeof XDSSelector>;++// Basic with strings+export const Default: Story = {+ render: args => {+ const [value, setValue] = useState<string | undefined>(args.value);+ return (+ <XDSSelector+ {...args}+ label={args.label ?? 'Fruit'}+ items={+ args.items ?? ['Apple', 'Banana', 'Orange', 'Mango', 'Pineapple']+ }+ value={value}+ onChange={setValue}+ />+ );+ },+ args: {+ placeholder: 'Select a fruit...',+ },+};++// With hidden label+export const HiddenLabel: Story = {+ render: args => {+ const [value, setValue] = useState<string | undefined>(args.value);+ return (+ <XDSSelector+ {...args}+ label="Fruit"+ isLabelHidden+ items={['Apple', 'Banana', 'Orange', 'Mango', 'Pineapple']}+ value={value}+ onChange={setValue}+ placeholder="Select a fruit..."+ />+ );+ },+};++// With description+export const WithDescription: Story = {+ render: args => {+ const [value, setValue] = useState<string | undefined>(args.value);+ return (+ <XDSSelector+ {...args}+ label="Fruit"+ description="Choose your favorite fruit from the list"+ items={['Apple', 'Banana', 'Orange', 'Mango', 'Pineapple']}+ value={value}+ onChange={setValue}+ placeholder="Select a fruit..."+ />+ );+ },+};++// With objects+export const WithObjects: Story = {+ render: args => {+ const [value, setValue] = useState<string | undefined>(args.value);+ return (+ <XDSSelector+ {...args}+ label="Fruit"+ items={[+ {value: 'apple', label: 'Apple'},+ {value: 'banana', label: 'Banana'},+ {value: 'orange', label: 'Orange', disabled: true},+ {value: 'mango', label: 'Mango'},+ ]}+ value={value}+ onChange={setValue}+ />+ );+ },+ args: {+ placeholder: 'Select a fruit...',+ },+};++// With icons+export const WithIcons: Story = {+ render: args => {+ const [value, setValue] = useState<string | undefined>(args.value);+ return (+ <XDSSelector+ {...args}+ label="Settings"+ items={[+ {value: 'profile', label: 'Profile', icon: UserIcon},+ {value: 'settings', label: 'Settings', icon: CogIcon},+ {value: 'notifications', label: 'Notifications', icon: BellIcon},+ ]}+ value={value}+ onChange={setValue}+ />+ );+ },+ args: {+ placeholder: 'Select an option...',+ },+};++// With sections and dividers+export const WithSections: Story = {+ render: args => {+ const [value, setValue] = useState<string | undefined>(args.value);+ return (+ <XDSSelector+ {...args}+ label="Fruit"+ items={[+ {value: 'apple', label: 'Apple'},+ {value: 'banana', label: 'Banana'},+ {+ type: 'section',+ title: 'Citrus',+ items: [+ {value: 'orange', label: 'Orange'},+ {value: 'lemon', label: 'Lemon'},+ {value: 'lime', label: 'Lime'},+ ],+ },+ {+ type: 'section',+ title: 'Tropical',+ items: [+ {value: 'mango', label: 'Mango'},+ {value: 'pineapple', label: 'Pineapple'},+ ],+ },+ ]}+ value={value}+ onChange={setValue}+ />+ );+ },+ args: {+ placeholder: 'Select a fruit...',+ },+};++// Custom render+export const CustomRender: Story = {+ render: args => {+ const [value, setValue] = useState<string | undefined>(args.value);+ const users = [+ {value: 'user1', label: 'Alice Johnson', email: '[email protected]'},+ {value: 'user2', label: 'Bob Smith', email: '[email protected]'},+ {value: 'user3', label: 'Carol White', email: '[email protected]'},+ ];+ return (+ <XDSSelector+ {...args}+ label="User"+ items={users}+ value={value}+ onChange={setValue}+ placeholder="Select a user...">+ {user => (+ <XDSSelectorItem+ icon={UserIcon}+ label={user.label}+ description={(user as (typeof users)[number]).email}+ />+ )}+ </XDSSelector>+ );+ },+};++// Size variants+export const SizeVariants: Story = {+ render: () => {+ const [value1, setValue1] = useState<string | undefined>();+ const [value2, setValue2] = useState<string | undefined>();+ return (+ <div+ style={{display: 'flex', flexDirection: 'column', gap: 16, width: 250}}>+ <XDSSelector+ label="Small"+ size="sm"+ items={['Apple', 'Banana', 'Orange']}+ value={value1}+ onChange={setValue1}+ placeholder="Small size"+ />+ <XDSSelector+ label="Medium"+ size="md"+ items={['Apple', 'Banana', 'Orange']}+ value={value2}+ onChange={setValue2}+ placeholder="Medium size (default)"+ />+ </div>+ );+ },+ decorators: [Story => <Story />],+};++// With status+export const WithStatus: Story = {+ render: () => {+ const [value1, setValue1] = useState<string | undefined>();+ const [value2, setValue2] = useState<string | undefined>('banana');+ const [value3, setValue3] = useState<string | undefined>('apple');+ return (+ <div+ style={{display: 'flex', flexDirection: 'column', gap: 16, width: 250}}>+ <XDSSelector+ label="Error status"+ items={[+ {value: 'apple', label: 'Apple'},+ {value: 'banana', label: 'Banana'},+ ]}+ value={value1}+ onChange={setValue1}+ placeholder="Select a fruit..."+ status={{type: 'error', message: 'Please select a fruit'}}+ />+ <XDSSelector+ label="Warning status"+ items={[+ {value: 'apple', label: 'Apple'},+ {value: 'banana', label: 'Banana'},+ ]}+ value={value2}+ onChange={setValue2}+ status={{type: 'warning', message: 'Banana is out of season'}}+ />+ <XDSSelector+ label="Success status"+ items={[+ {value: 'apple', label: 'Apple'},+ {value: 'banana', label: 'Banana'},+ ]}+ value={value3}+ onChange={setValue3}+ status={{type: 'success'}}+ />+ </div>+ );+ },+ decorators: [Story => <Story />],+};++// Optional and Required+export const OptionalRequired: Story = {+ render: () => {+ const [value1, setValue1] = useState<string | undefined>();+ const [value2, setValue2] = useState<string | undefined>();+ return (+ <div+ style={{display: 'flex', flexDirection: 'column', gap: 16, width: 250}}>+ <XDSSelector+ label="Optional field"+ isOptional+ items={['Apple', 'Banana', 'Orange']}+ value={value1}+ onChange={setValue1}+ placeholder="Select a fruit..."+ />+ <XDSSelector+ label="Required field"+ isRequired+ items={['Apple', 'Banana', 'Orange']}+ value={value2}+ onChange={setValue2}+ placeholder="Select a fruit..."+ />+ </div>+ );+ },+ decorators: [Story => <Story />],+};++// Disabled+export const Disabled: Story = {+ args: {+ label: 'Fruit',+ items: ['Apple', 'Banana', 'Orange'],+ value: 'Apple',+ isDisabled: true,+ placeholder: 'Select a fruit...',+ },+};++// Pre-selected+export const PreSelected: Story = {+ render: args => {+ const [value, setValue] = useState('Banana');+ return (+ <XDSSelector+ {...args}+ label="Fruit"+ items={['Apple', 'Banana', 'Orange', 'Mango']}+ value={value}+ onChange={setValue}+ />+ );+ },+};++// All variations+export const AllVariations: Story = {+ render: () => {+ const [value1, setValue1] = useState<string | undefined>();+ const [value2, setValue2] = useState<string | undefined>('banana');+ const [value3, setValue3] = useState<string | undefined>();+ const [value4, setValue4] = useState<string | undefined>();+ return (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: '16px',+ width: '250px',+ }}>+ <XDSSelector+ label="Default"+ items={['Apple', 'Banana', 'Orange']}+ value={value1}+ onChange={setValue1}+ placeholder="Select..."+ />+ <XDSSelector+ label="Pre-selected"+ items={[+ {value: 'apple', label: 'Apple'},+ {value: 'banana', label: 'Banana'},+ ]}+ value={value2}+ onChange={setValue2}+ />+ <XDSSelector+ label="With disabled option"+ items={[+ {value: 'apple', label: 'Apple', disabled: true},+ {value: 'banana', label: 'Banana'},+ ]}+ value={value3}+ onChange={setValue3}+ placeholder="Select..."+ />+ <XDSSelector+ label="Disabled selector"+ items={['Apple', 'Banana']}+ value={value4}+ onChange={setValue4}+ isDisabled+ placeholder="Select..."+ />+ </div>+ );+ },+ decorators: [Story => <Story />],+};diff --git a/packages/core/package.json b/packages/core/package.jsonindex 9b59556c82..c2de2df5d1 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -54,6 +54,11 @@"import": "./dist/Icon/index.mjs","require": "./dist/Icon/index.js"},+ "./Selector": {+ "types": "./dist/Selector/index.d.ts",+ "import": "./dist/Selector/index.mjs",+ "require": "./dist/Selector/index.js"+ },"./Layout": {"types": "./dist/Layout/index.d.ts","import": "./dist/Layout/index.mjs",diff --git a/packages/core/src/Layer/useXDSHoverCard.tsx b/packages/core/src/Layer/useXDSHoverCard.tsxindex addd519c2f..255669d3e9 100644--- a/packages/core/src/Layer/useXDSHoverCard.tsx+++ b/packages/core/src/Layer/useXDSHoverCard.tsx@@ -259,9 +259,11 @@ export function useXDSHoverCard(mode: 'context',onShow,onHide,- xstyle: [styles.container, marginStyle, themeContainerOverride],});+ // StyleX for the popover container+ const popoverXstyle = [styles.container, marginStyle, themeContainerOverride];+const showTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);const hideTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);const triggerRef = useRef<HTMLElement | null>(null);@@ -418,6 +420,7 @@ export function useXDSHoverCard(const renderProps = {placement: props?.placement ?? placement,alignment: props?.alignment ?? alignment,+ xstyle: popoverXstyle,};return layer.render(@@ -474,6 +477,7 @@ export function useXDSHoverCard(clearTimeouts,scheduleHide,themeContentOverride,+ popoverXstyle,],);diff --git a/packages/core/src/Layer/useXDSLayer.tsx b/packages/core/src/Layer/useXDSLayer.tsxindex e64cf1531f..179d0cd949 100644--- a/packages/core/src/Layer/useXDSLayer.tsx+++ b/packages/core/src/Layer/useXDSLayer.tsx@@ -65,6 +65,10 @@ export type LayerAlignment = 'start' | 'center' | 'end';export interface ContextRenderProps {placement?: LayerPlacement;alignment?: LayerAlignment;+ /**+ * StyleX styles for the popover container.+ */+ xstyle?: StyleXStyles;}/**@@ -89,11 +93,6 @@ interface BaseLayerOptions {*/onHide?: () => void;- /**- * StyleX styles for the layer container- */- xstyle?: StyleXStyles;-/*** Whether clicking outside should dismiss the layer.* When true, uses popover="auto" for native light-dismiss behavior.@@ -251,7 +250,7 @@ export function useXDSLayer(options: FixedLayerOptions): FixedLayerReturn;export function useXDSLayer(options: ContextLayerOptions | FixedLayerOptions,): ContextLayerReturn | FixedLayerReturn {- const {mode, onShow, onHide, xstyle, lightDismiss = false} = options;+ const {mode, onShow, onHide, lightDismiss = false} = options;const id = useId();const anchorId = `--xds-layer-${id.replace(/:/g, '')}`;@@ -313,9 +312,9 @@ export function useXDSLayer(// Render function for context modeconst renderContext = useCallback((children: ReactNode, props?: ContextRenderProps) => {- const {placement = 'above', alignment = 'center'} = props || {};+ const {placement = 'above', alignment = 'center', xstyle} = props || {};- // CSS anchor positioning properties (dynamic, not in StyleX)+ // CSS anchor positioning (dynamic, not in StyleX)const anchorStyle: React.CSSProperties = {positionAnchor: anchorId,positionArea: getPositionArea(placement, alignment),@@ -338,7 +337,7 @@ export function useXDSLayer(</div>);},- [anchorId, handleToggle, id, lightDismiss, xstyle],+ [anchorId, handleToggle, id, lightDismiss],);// Render function for fixed mode@@ -362,13 +361,13 @@ export function useXDSLayer(}}id={id}popover={lightDismiss ? 'auto' : 'manual'}- {...stylex.props(styles.base, styles.fixed, xstyle)}+ {...stylex.props(styles.base, styles.fixed)}style={positionStyle}>{children}</div>);},- [handleToggle, id, lightDismiss, xstyle],+ [handleToggle, id, lightDismiss],);if (mode === 'context') {diff --git a/packages/core/src/Layer/useXDSPopover.tsx b/packages/core/src/Layer/useXDSPopover.tsxindex dca6c41367..4112fb8410 100644--- a/packages/core/src/Layer/useXDSPopover.tsx+++ b/packages/core/src/Layer/useXDSPopover.tsx@@ -279,7 +279,6 @@ export function useXDSPopover(const layer = useXDSLayer({mode: 'context',lightDismiss: hasLightDismiss,- xstyle,onShow,onHide,});@@ -371,7 +370,7 @@ export function useXDSPopover(</button>)}</div>,- props,+ {...props, xstyle: xstyle ?? props?.xstyle},);},[@@ -381,6 +380,7 @@ export function useXDSPopover(isCloseButtonFocused,contentRef,dialogLabel,+ xstyle,],);diff --git a/packages/core/src/Layer/useXDSTooltip.tsx b/packages/core/src/Layer/useXDSTooltip.tsxindex bd3ea77e1e..3477da576b 100644--- a/packages/core/src/Layer/useXDSTooltip.tsx+++ b/packages/core/src/Layer/useXDSTooltip.tsx@@ -264,9 +264,11 @@ export function useXDSTooltip(mode: 'context',onShow,onHide,- xstyle: [styles.container, marginStyle, themeContainerOverride],});+ // StyleX for the popover container+ const popoverXstyle = [styles.container, marginStyle, themeContainerOverride];+const showTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);const hideTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);const triggerRef = useRef<HTMLElement | null>(null);@@ -383,6 +385,7 @@ export function useXDSTooltip(const renderProps = {placement: props?.placement ?? placement,alignment: props?.alignment ?? alignment,+ xstyle: popoverXstyle,};return layer.render(@@ -392,7 +395,7 @@ export function useXDSTooltip(renderProps,);},- [layer, placement, alignment, themeContentOverride],+ [layer, placement, alignment, themeContentOverride, popoverXstyle],);return {diff --git a/packages/core/src/Selector/README.md b/packages/core/src/Selector/README.mdnew file mode 100644index 0000000000..23550536f6--- /dev/null+++ b/packages/core/src/Selector/README.md@@ -0,0 +1,115 @@+# XDSSelector++Dropdown selector for choosing from a list of options. Follows XDS input conventions with label, status, and field props.++## Usage++```tsx+import {XDSSelector, XDSSelectorItem} from '@xds/core/Selector';++// Basic usage (label is required)+<XDSSelector+ label="Fruit"+ items={['Apple', 'Banana', 'Orange']}+ value={value}+ onChange={setValue}+/>++// With object items (supports disabled, icons)+<XDSSelector+ label="Settings"+ items={[+ {value: 'profile', label: 'Profile', icon: UserIcon},+ {value: 'settings', label: 'Settings', icon: CogIcon, disabled: true},+ ]}+ value={value}+ onChange={setValue}+/>++// Sections (automatically include labeled dividers)+<XDSSelector+ label="Fruit"+ items={[+ {value: 'apple', label: 'Apple'},+ {type: 'section', title: 'Citrus', items: [+ {value: 'orange', label: 'Orange'},+ ]},+ ]}+ value={value}+ onChange={setValue}+/>++// Custom rendering with XDSSelectorItem+<XDSSelector label="User" items={users} value={value} onChange={setValue}>+ {user => (+ <XDSSelectorItem+ icon={UserIcon}+ label={user.label}+ description={user.email}+ />+ )}+</XDSSelector>++// With status and field props+<XDSSelector+ label="Fruit"+ isRequired+ status={{type: 'error', message: 'Required'}}+ items={['Apple', 'Banana']}+ value={value}+ onChange={setValue}+/>+```++## Props++| Prop | Type | Description |+| --------------------------- | --------------------------------------------------------- | ------------------------------------------------------------------- |+| `label` | `string` | **Required.** Label text for accessibility |+| `items` | `XDSSelectorOption[]` | **Required.** Array of items (strings, objects, dividers, sections) |+| `value` | `string` | Selected value |+| `onChange` | `(value: string) => void` | Selection callback |+| `placeholder` | `string` | Placeholder text (default: `'Select...'`) |+| `size` | `'sm' \| 'md'` | Size variant (default: `'md'`) |+| `isDisabled` | `boolean` | Disable selector |+| `isLabelHidden` | `boolean` | Visually hide label |+| `description` | `string` | Helper text below label |+| `isOptional` / `isRequired` | `boolean` | Field requirement indicators |+| `status` | `{type: 'error'\|'warning'\|'success', message?: string}` | Status with optional message |+| `children` | `(item: XDSSelectorItemData) => ReactNode` | Custom item renderer |++## Item Types++```tsx+// String - converted to {value: 'Apple', label: 'Apple'}+'Apple'++// Object - with optional icon, disabled+{value: 'apple', label: 'Apple', icon?: IconComponent, disabled?: boolean}++// Divider - horizontal separator+{type: 'divider'}++// Section - grouped items with labeled divider+{type: 'section', title: 'Group Name', items: [...]}+```++## XDSSelectorItem++Helper for custom item rendering:++```tsx+<XDSSelectorItem+ icon={UserIcon} // Optional XDSIconType+ label="Primary text" // Required ReactNode+ description="Secondary" // Optional ReactNode+/>+```++## Keyboard++↑↓ navigate, Enter/Space select, Escape close, Home/End jump, A-Z typeahead.++## Accessibility++Uses `role="combobox"` trigger, `role="listbox"` dropdown, `role="group"` for sections, `aria-activedescendant` for focus.diff --git a/packages/core/src/Selector/XDSSelector.tsx b/packages/core/src/Selector/XDSSelector.tsxnew file mode 100644index 0000000000..4d1b499389--- /dev/null+++ b/packages/core/src/Selector/XDSSelector.tsx@@ -0,0 +1,615 @@+/**+ * @file XDSSelector.tsx+ * @input Uses React, StyleX, useXDSLayer, XDSIcon+ * @output Exports XDSSelector component+ * @position Core implementation; consumed by index.ts+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Selector/README.md+ * - /packages/core/src/Selector/index.ts+ */++import React, {+ useCallback,+ useId,+ useMemo,+ useRef,+ type ReactNode,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import {useXDSLayer} from '../Layer/useXDSLayer';+import {XDSIcon} from '../Icon';+import type {XDSIconType} from '../Icon';+import {CheckIcon, ChevronDownIcon} from '@heroicons/react/16/solid';+import {+ CheckCircleIcon,+ ExclamationTriangleIcon,+ XCircleIcon,+} from '@heroicons/react/24/solid';+import {XDSField} from '../Field';+import {XDSDivider} from '../Divider';+import {+ colorVars,+ spacingVars,+ radiusVars,+ transitionVars,+ typographyVars,+ textSizeVars,+ fontWeightVars,+} from '../theme/tokens.stylex';+import {type XDSSelectorOption, type XDSSelectorItemData} from './types';+import {+ isItemData,+ isDivider,+ isSection,+ normalizeItem,+ getSelectableItems,+} from './utils';+import {useCombobox, useSelectedItemOffset} from './hooks';+import {XDSSelectorItem} from './XDSSelectorItem';++const styles = stylex.create({+ // Trigger button+ trigger: {+ position: 'relative',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: spacingVars['--spacing-2'],+ width: '100%',+ paddingBlock: spacingVars['--spacing-2'],+ paddingInline: spacingVars['--spacing-3'],+ borderWidth: 1,+ borderStyle: 'solid',+ borderColor: {+ default: colorVars['--color-divider-emphasized'],+ ':hover': colorVars['--color-divider-high-contrast'],+ },+ borderRadius: radiusVars['--radius-element'],+ backgroundColor: colorVars['--color-surface'],+ fontFamily: typographyVars['--font-body'],+ fontSize: textSizeVars['--text-base'],+ lineHeight: 1.429,+ color: colorVars['--color-text-primary'],+ cursor: 'pointer',+ transitionProperty: 'border-color, outline',+ transitionDuration: transitionVars['--transition-fast'],+ outline: {+ default: 'none',+ ':focus': `2px solid ${colorVars['--color-focus-outline']}`,+ },+ outlineOffset: {+ default: '0',+ ':focus': '1px',+ },+ },+ triggerDisabled: {+ cursor: 'not-allowed',+ opacity: 0.5,+ borderColor: colorVars['--color-divider-emphasized'],+ },+ triggerPlaceholder: {+ color: colorVars['--color-text-placeholder'],+ },+ triggerIcon: {+ flexShrink: 0,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ width: 16,+ height: 16,+ transition: `transform ${transitionVars['--transition-fast']}`,+ transformOrigin: 'center',+ color: colorVars['--color-icon-secondary'],+ },+ triggerIconOpen: {+ transform: 'rotate(180deg)',+ },+ triggerIconStatus: {+ // Disable rotation transition for status icons+ transition: 'none',+ },++ // Dropdown container+ dropdown: {+ boxSizing: 'border-box',+ maxHeight: '300px',+ overflowY: 'auto',+ padding: spacingVars['--spacing-1'],+ borderRadius: radiusVars['--radius-element'],+ backgroundColor: colorVars['--color-surface'],+ boxShadow: `0 4px 12px ${colorVars['--color-shadow-elevation']}`,+ opacity: 1,+ transition: `opacity ${transitionVars['--transition-fast']}`,+ },+ dropdownHidden: {+ opacity: 0,+ transition: 'none',+ },+ dropdownOffset: (offset: number) => ({+ marginTop: offset,+ }),++ // Popover container (for anchor positioning)+ popover: {+ minWidth: 'anchor-size(width)',+ },++ // Section divider with label+ sectionDivider: {+ marginBlock: spacingVars['--spacing-1'],+ },++ // Divider+ divider: {+ marginBlock: spacingVars['--spacing-1'],+ },++ // Individual item+ item: {+ boxSizing: 'border-box',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: spacingVars['--spacing-2'],+ width: '100%',+ padding: spacingVars['--spacing-2'],+ borderRadius: radiusVars['--radius-content'],+ fontFamily: typographyVars['--font-body'],+ fontSize: textSizeVars['--text-base'],+ color: colorVars['--color-text-primary'],+ backgroundColor: 'transparent',+ border: 'none',+ cursor: 'pointer',+ textAlign: 'left',+ outline: 'none',+ },+ itemContent: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-2'],+ flex: 1,+ minWidth: 0,+ },+ itemCheckmark: {+ flexShrink: 0,+ width: 16,+ height: 16,+ color: colorVars['--color-icon-primary'],+ },+ itemHighlighted: {+ backgroundColor: colorVars['--color-hover-overlay'],+ },+ itemSelected: {+ fontWeight: fontWeightVars['--font-weight-medium'],+ },+ itemDisabled: {+ opacity: 0.5,+ cursor: 'not-allowed',+ },+});++const sizeStyles = stylex.create({+ sm: {+ paddingBlock: spacingVars['--spacing-1'],+ },+ md: {+ paddingBlock: spacingVars['--spacing-2'],+ },+});++const statusBorderStyles = stylex.create({+ warning: {+ borderColor: colorVars['--color-warning'],+ },+ error: {+ borderColor: colorVars['--color-negative'],+ },+ success: {+ borderColor: colorVars['--color-positive'],+ },+});++const STATUS_ICON_MAP: Record<XDSSelectorStatusType, XDSIconType> = {+ warning: ExclamationTriangleIcon,+ error: XCircleIcon,+ success: CheckCircleIcon,+};++const STATUS_ICON_COLOR_MAP: Record<+ XDSSelectorStatusType,+ 'warning' | 'negative' | 'positive'+> = {+ warning: 'warning',+ error: 'negative',+ success: 'positive',+};++export type XDSSelectorSize = 'sm' | 'md';++export type XDSSelectorStatusType = 'warning' | 'error' | 'success';++export interface XDSSelectorStatus {+ /**+ * The type of status to display.+ */+ type: XDSSelectorStatusType;+ /**+ * Optional message to display below the input.+ */+ message?: string;+}++export interface XDSSelectorProps<+ T extends XDSSelectorOption = XDSSelectorOption,+> {+ /**+ * Label text for the selector (always rendered for accessibility).+ */+ label: string;++ /**+ * Whether to visually hide the label (still accessible to screen readers).+ * @default false+ */+ isLabelHidden?: boolean;++ /**+ * Description text displayed between the label and selector.+ */+ description?: string;++ /**+ * Whether the field is optional. Mutually exclusive with isRequired.+ * @default false+ */+ isOptional?: boolean;++ /**+ * Whether the field is required. Mutually exclusive with isOptional.+ * @default false+ */+ isRequired?: boolean;++ /**+ * Whether the selector is disabled.+ * @default false+ */+ isDisabled?: boolean;++ /**+ * The items to display in the selector.+ * Can be strings, objects, dividers, or sections.+ */+ items: T[];++ /**+ * The currently selected value.+ */+ value?: string;++ /**+ * Callback when selection changes.+ */+ onChange?: (value: string) => void;++ /**+ * Placeholder text when no value is selected.+ * @default 'Select...'+ */+ placeholder?: string;++ /**+ * The size of the selector.+ * - 'sm': Compact size+ * - 'md': Default size+ * @default 'md'+ */+ size?: XDSSelectorSize;++ /**+ * Status indicator for the selector.+ * When set, displays a colored border and status icon.+ * If message is provided, displays a message box below the selector.+ */+ status?: XDSSelectorStatus;++ /**+ * Tooltip text to display in an info icon at the end of the label.+ */+ labelTooltip?: string;++ /**+ * Custom render function for items.+ * Only called for selectable items (not dividers/sections).+ */+ children?: (item: XDSSelectorItemData) => ReactNode;++ /**+ * Test ID for testing frameworks.+ */+ 'data-testid'?: string;+}++/**+ * Default item renderer+ */+function DefaultItem({item}: {item: XDSSelectorItemData}) {+ return <XDSSelectorItem icon={item.icon} label={item.label ?? item.value} />;+}++/**+ * A selector/dropdown component for choosing from a list of options.+ *+ * @example+ * ```tsx+ * <XDSSelector+ * label="Fruit"+ * items={['Apple', 'Banana', 'Orange']}+ * value={fruit}+ * onChange={setFruit}+ * placeholder="Select a fruit..."+ * />+ * ```+ */+export function XDSSelector<T extends XDSSelectorOption>({+ label,+ isLabelHidden = false,+ description,+ isOptional = false,+ isRequired = false,+ isDisabled = false,+ items,+ value,+ onChange,+ placeholder = 'Select...',+ size = 'md',+ status,+ labelTooltip,+ children,+ 'data-testid': testId,+}: XDSSelectorProps<T>) {+ const triggerId = useId();+ const listboxId = useId();+ const descriptionId = useId();+ const statusMessageId = useId();+ const triggerRef = useRef<HTMLButtonElement>(null);++ // Build aria-describedby+ const ariaDescribedBy =+ [+ description ? descriptionId : null,+ status?.message ? statusMessageId : null,+ ]+ .filter(Boolean)+ .join(' ') || undefined;++ // Flatten items for keyboard navigation+ const selectableItems = useMemo(() => getSelectableItems(items), [items]);++ // Find selected item and its index for positioning+ const selectedItemIndex = useMemo(() => {+ return selectableItems.findIndex(item => item.value === value);+ }, [selectableItems, value]);++ const selectedItem = useMemo(() => {+ return selectedItemIndex >= 0+ ? selectableItems[selectedItemIndex]+ : undefined;+ }, [selectableItems, selectedItemIndex]);++ // Ref for listbox to measure selected item position+ const listboxRef = useRef<HTMLDivElement>(null);++ // Layer for dropdown positioning+ const layer = useXDSLayer({+ mode: 'context',+ lightDismiss: true,+ onHide: () => {+ triggerRef.current?.focus();+ },+ });++ // Calculate offset to position selected item over trigger+ const {offset: selectedItemOffset, isPositioned} = useSelectedItemOffset({+ isOpen: layer.isOpen,+ selectedItemIndex,+ listboxId,+ listboxRef,+ triggerRef,+ });++ // Selector behavior (keyboard nav, typeahead, selection)+ const {+ highlightedIndex,+ setHighlightedIndex: _,+ getItemId,+ onTriggerClick,+ onKeyDown,+ onItemSelect,+ onItemMouseEnter,+ } = useCombobox({+ selectableItems,+ value,+ isDisabled,+ isOpen: layer.isOpen,+ onOpen: layer.show,+ onClose: layer.hide,+ onSelect: onChange,+ listboxId,+ });++ // Render an individual item+ const renderItem = useCallback(+ (item: XDSSelectorItemData, flatIndex: number) => {+ const isHighlighted = flatIndex === highlightedIndex;+ const isSelected = item.value === value;++ return (+ <div+ key={item.value}+ id={getItemId(flatIndex)}+ role="option"+ aria-selected={isSelected}+ aria-disabled={item.disabled}+ onClick={() => onItemSelect(item)}+ onMouseEnter={() => onItemMouseEnter(item, flatIndex)}+ {...stylex.props(+ styles.item,+ isHighlighted && styles.itemHighlighted,+ isSelected && styles.itemSelected,+ item.disabled && styles.itemDisabled,+ )}>+ <span {...stylex.props(styles.itemContent)}>+ {children ? children(item) : <DefaultItem item={item} />}+ </span>+ {isSelected && <CheckIcon {...stylex.props(styles.itemCheckmark)} />}+ </div>+ );+ },+ [+ children,+ highlightedIndex,+ value,+ getItemId,+ onItemSelect,+ onItemMouseEnter,+ ],+ );++ // Render all options (handling sections/dividers)+ const renderOptions = useCallback(() => {+ let flatIndex = 0;+ const elements: ReactNode[] = [];++ for (let i = 0; i < items.length; i++) {+ const option = items[i];++ if (isDivider(option)) {+ elements.push(+ <XDSDivider key={`divider-${i}`} xstyle={styles.divider} />,+ );+ } else if (isSection(option)) {+ const sectionItems: ReactNode[] = [];+ for (const item of option.items) {+ sectionItems.push(renderItem(normalizeItem(item), flatIndex));+ flatIndex++;+ }+ // Render divider with label before the group+ if (option.title) {+ elements.push(+ <XDSDivider+ key={`section-divider-${i}`}+ label={option.title}+ xstyle={styles.sectionDivider}+ />,+ );+ }+ elements.push(+ <div key={`section-${i}`} role="group" aria-label={option.title}>+ {sectionItems}+ </div>,+ );+ } else if (isItemData(option)) {+ elements.push(renderItem(normalizeItem(option), flatIndex));+ flatIndex++;+ }+ }++ return elements;+ }, [items, renderItem, listboxId]);++ return (+ <XDSField+ label={label}+ isLabelHidden={isLabelHidden}+ description={description}+ inputID={triggerId}+ descriptionID={description ? descriptionId : undefined}+ isOptional={isOptional}+ isRequired={isRequired}+ status={+ status+ ? {+ type: status.type,+ message: status.message,+ messageID: status.message ? statusMessageId : undefined,+ }+ : undefined+ }+ labelTooltip={labelTooltip}>+ <button+ ref={el => {+ (+ triggerRef as React.MutableRefObject<HTMLButtonElement | null>+ ).current = el;+ layer.ref(el);+ }}+ id={triggerId}+ type="button"+ role="combobox"+ aria-haspopup="listbox"+ aria-expanded={layer.isOpen}+ aria-controls={listboxId}+ aria-activedescendant={+ layer.isOpen && highlightedIndex >= 0+ ? getItemId(highlightedIndex)+ : undefined+ }+ aria-describedby={ariaDescribedBy}+ aria-required={isRequired ? 'true' : undefined}+ aria-invalid={status?.type === 'error' ? 'true' : undefined}+ disabled={isDisabled}+ onClick={onTriggerClick}+ onKeyDown={onKeyDown}+ data-testid={testId}+ {...stylex.props(+ styles.trigger,+ sizeStyles[size],+ isDisabled && styles.triggerDisabled,+ !selectedItem && styles.triggerPlaceholder,+ status && statusBorderStyles[status.type],+ )}>+ <span>{selectedItem?.label ?? placeholder}</span>+ <span+ {...stylex.props(+ styles.triggerIcon,+ !status && layer.isOpen && styles.triggerIconOpen,+ status && styles.triggerIconStatus,+ )}>+ {status ? (+ <XDSIcon+ icon={STATUS_ICON_MAP[status.type]}+ size="sm"+ color={STATUS_ICON_COLOR_MAP[status.type]}+ />+ ) : (+ <ChevronDownIcon />+ )}+ </span>+ </button>++ {layer.render(+ <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',+ xstyle: styles.popover,+ },+ )}+ </XDSField>+ );+}++XDSSelector.displayName = 'XDSSelector';diff --git a/packages/core/src/Selector/XDSSelectorItem.tsx b/packages/core/src/Selector/XDSSelectorItem.tsxnew file mode 100644index 0000000000..b3eb486b94--- /dev/null+++ b/packages/core/src/Selector/XDSSelectorItem.tsx@@ -0,0 +1,110 @@+/**+ * @file XDSSelectorItem.tsx+ * @output Exports XDSSelectorItem component for custom item rendering+ * @position Sub-component; used by XDSSelector and consumers for custom items+ */++import type {ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {StyleXStyles} from '@stylexjs/stylex';+import {XDSIcon} from '../Icon';+import type {XDSIconType} from '../Icon';+import {XDSText} from '../Text';+import {spacingVars} from '../theme/tokens.stylex';++const styles = stylex.create({+ root: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-2'],+ flex: 1,+ minWidth: 0,+ },+ content: {+ display: 'flex',+ flexDirection: 'column',+ flex: 1,+ minWidth: 0,+ },+});++export interface XDSSelectorItemProps {+ /**+ * Icon to display before the label.+ */+ icon?: XDSIconType;++ /**+ * Primary label text.+ */+ label: ReactNode;++ /**+ * Secondary description text displayed below the label.+ */+ description?: ReactNode;++ /**+ * Additional content to render after the label/description.+ */+ children?: ReactNode;++ /**+ * StyleX styles for the root container.+ */+ xstyle?: StyleXStyles;+}++/**+ * A helper component for rendering custom selector items with consistent styling.+ *+ * Use this inside the `children` render prop of XDSSelector to create+ * custom item layouts while maintaining design system consistency.+ *+ * @example+ * ```tsx+ * <XDSSelector+ * label="User"+ * items={users}+ * value={value}+ * onChange={setValue}>+ * {item => (+ * <XDSSelectorItem+ * icon={UserIcon}+ * label={item.label}+ * description={item.email}+ * />+ * )}+ * </XDSSelector>+ * ```+ */+export function XDSSelectorItem({+ icon,+ label,+ description,+ children,+ xstyle,+}: XDSSelectorItemProps) {+ return (+ <span {...stylex.props(styles.root, xstyle)}>+ {icon && <XDSIcon icon={icon} size="sm" color="secondary" />}+ <span {...stylex.props(styles.content)}>+ {typeof label === 'string' ? (+ <XDSText type="body" maxLines={1}>+ {label}+ </XDSText>+ ) : (+ label+ )}+ {description && (+ <XDSText type="supporting" maxLines={1}>+ {description}+ </XDSText>+ )}+ </span>+ {children}+ </span>+ );+}++XDSSelectorItem.displayName = 'XDSSelectorItem';diff --git a/packages/core/src/Selector/hooks.ts b/packages/core/src/Selector/hooks.tsnew file mode 100644index 0000000000..97ffa5efe2--- /dev/null+++ b/packages/core/src/Selector/hooks.ts@@ -0,0 +1,300 @@+/**+ * @file hooks.ts+ * @output Hooks for XDSSelector+ * @position Internal hooks; used by XDSSelector.tsx+ */++import {useCallback, useLayoutEffect, useRef, useState} from 'react';+import type {RefObject} from 'react';+import type {XDSSelectorItemData} from './types';++// =============================================================================+// useSelectedItemOffset - Position dropdown to center selected item over trigger+// =============================================================================++interface UseSelectedItemOffsetOptions {+ isOpen: boolean;+ selectedItemIndex: number;+ listboxId: string;+ listboxRef: RefObject<HTMLDivElement>;+ triggerRef: RefObject<HTMLButtonElement>;+}++interface UseSelectedItemOffsetResult {+ offset: number;+ isPositioned: boolean;+}++/**+ * Calculates the offset needed to position the dropdown so that the selected+ * item appears centered over the trigger button (macOS-style selector).+ */+export function useSelectedItemOffset({+ isOpen,+ selectedItemIndex,+ listboxId,+ listboxRef,+ triggerRef,+}: UseSelectedItemOffsetOptions): UseSelectedItemOffsetResult {+ const [offset, setOffset] = useState(0);+ const [isPositioned, setIsPositioned] = useState(false);++ useLayoutEffect(() => {+ if (!isOpen) {+ // Reset offset when closed+ setOffset(0);+ setIsPositioned(false);+ return;+ }++ if (!listboxRef.current || !triggerRef.current) {+ setIsPositioned(true);+ return;+ }++ // Find the target item: selected item or first item+ const targetIndex = selectedItemIndex >= 0 ? selectedItemIndex : 0;+ const targetItemId = `${listboxId}-item-${targetIndex}`;+ // Use getElementById - works with special characters without escaping+ const targetItem = document.getElementById(targetItemId);++ if (!targetItem) {+ setOffset(0);+ setIsPositioned(true);+ return;+ }++ // Get positions+ const listboxRect = listboxRef.current.getBoundingClientRect();+ const itemRect = targetItem.getBoundingClientRect();+ const triggerRect = triggerRef.current.getBoundingClientRect();++ // Calculate offset to center the item over the trigger+ // The listbox is positioned below the trigger by anchor positioning (top of listbox at bottom of trigger)+ // We need to move it UP so the selected item's center aligns with trigger's center+ //+ // Item center relative to listbox top:+ const itemCenterInListbox =+ itemRect.top - listboxRect.top + itemRect.height / 2;+ //+ // To center item over trigger, we need to move up by:+ // (item center in listbox) + (half trigger height to reach trigger's center from its bottom edge)+ const calculatedOffset = itemCenterInListbox + triggerRect.height / 2;++ setOffset(calculatedOffset);+ setIsPositioned(true);+ }, [isOpen, selectedItemIndex, listboxId, listboxRef, triggerRef]);++ return {offset, isPositioned};+}++// =============================================================================+// useCombobox - Keyboard navigation, typeahead, and selection+// =============================================================================++interface UseComboboxOptions {+ selectableItems: XDSSelectorItemData[];+ value?: string;+ isDisabled?: boolean;+ isOpen: boolean;+ onOpen: () => void;+ onClose: () => void;+ onSelect?: (value: string) => void;+ listboxId: string;+}++interface UseComboboxResult {+ highlightedIndex: number;+ setHighlightedIndex: (index: number) => void;+ getItemId: (index: number) => string;+ onTriggerClick: () => void;+ onKeyDown: (e: React.KeyboardEvent) => void;+ onItemSelect: (item: XDSSelectorItemData) => void;+ onItemMouseEnter: (item: XDSSelectorItemData, index: number) => void;+}++/**+ * Handles keyboard navigation, typeahead search, and selection for combobox/listbox patterns.+ */+export function useCombobox({+ selectableItems,+ value,+ isDisabled = false,+ isOpen,+ onOpen,+ onClose,+ onSelect,+ listboxId,+}: UseComboboxOptions): UseComboboxResult {+ const [highlightedIndex, setHighlightedIndex] = useState<number>(-1);+ const [typeahead, setTypeahead] = useState('');+ const typeaheadTimeoutRef = useRef<ReturnType<typeof setTimeout>>();++ const getItemId = useCallback(+ (index: number) => `${listboxId}-item-${index}`,+ [listboxId],+ );++ const getEnabledIndices = useCallback(() => {+ return selectableItems+ .map((item, i) => (!item.disabled ? i : -1))+ .filter(i => i >= 0);+ }, [selectableItems]);++ const findSelectedIndex = useCallback(() => {+ return selectableItems.findIndex(item => item.value === value);+ }, [selectableItems, value]);++ const closeAndReset = useCallback(() => {+ setHighlightedIndex(-1);+ onClose();+ }, [onClose]);++ const selectItem = useCallback(+ (item: XDSSelectorItemData) => {+ if (item.disabled) return;+ onSelect?.(item.value);+ closeAndReset();+ },+ [onSelect, closeAndReset],+ );++ const onTriggerClick = useCallback(() => {+ if (isDisabled) return;+ if (isOpen) {+ closeAndReset();+ } else {+ onOpen();+ const selectedIndex = findSelectedIndex();+ setHighlightedIndex(selectedIndex >= 0 ? selectedIndex : 0);+ }+ }, [isDisabled, isOpen, onOpen, closeAndReset, findSelectedIndex]);++ const onItemMouseEnter = useCallback(+ (item: XDSSelectorItemData, index: number) => {+ if (!item.disabled) {+ setHighlightedIndex(index);+ }+ },+ [],+ );++ const onKeyDown = useCallback(+ (e: React.KeyboardEvent) => {+ if (isDisabled) return;++ const enabledIndices = getEnabledIndices();++ switch (e.key) {+ case 'ArrowDown':+ e.preventDefault();+ if (!isOpen) {+ onOpen();+ setHighlightedIndex(0);+ } else {+ const currentEnabledPos = enabledIndices.indexOf(highlightedIndex);+ const nextPos = Math.min(+ currentEnabledPos + 1,+ enabledIndices.length - 1,+ );+ setHighlightedIndex(enabledIndices[nextPos] ?? highlightedIndex);+ }+ break;++ case 'ArrowUp':+ e.preventDefault();+ if (!isOpen) {+ onOpen();+ setHighlightedIndex(selectableItems.length - 1);+ } else {+ const currentEnabledPos = enabledIndices.indexOf(highlightedIndex);+ const prevPos = Math.max(currentEnabledPos - 1, 0);+ setHighlightedIndex(enabledIndices[prevPos] ?? highlightedIndex);+ }+ break;++ case 'Enter':+ case ' ':+ e.preventDefault();+ if (isOpen && highlightedIndex >= 0) {+ const item = selectableItems[highlightedIndex];+ if (item && !item.disabled) {+ selectItem(item);+ }+ } else if (!isOpen) {+ onOpen();+ const selectedIndex = findSelectedIndex();+ setHighlightedIndex(selectedIndex >= 0 ? selectedIndex : 0);+ }+ break;++ case 'Escape':+ e.preventDefault();+ closeAndReset();+ break;++ case 'Home':+ e.preventDefault();+ if (isOpen && enabledIndices.length > 0) {+ setHighlightedIndex(enabledIndices[0]);+ }+ break;++ case 'End':+ e.preventDefault();+ if (isOpen && enabledIndices.length > 0) {+ setHighlightedIndex(enabledIndices[enabledIndices.length - 1]);+ }+ break;++ default:+ if (e.key.length === 1 && !e.ctrlKey && !e.metaKey) {+ const newTypeahead = typeahead + e.key.toLowerCase();+ setTypeahead(newTypeahead);++ if (typeaheadTimeoutRef.current) {+ clearTimeout(typeaheadTimeoutRef.current);+ }+ typeaheadTimeoutRef.current = setTimeout(() => {+ setTypeahead('');+ }, 500);++ const matchIndex = selectableItems.findIndex(+ item =>+ !item.disabled &&+ item.label?.toLowerCase().startsWith(newTypeahead),+ );+ if (matchIndex >= 0) {+ if (!isOpen) {+ onOpen();+ }+ setHighlightedIndex(matchIndex);+ }+ }+ break;+ }+ },+ [+ isDisabled,+ isOpen,+ onOpen,+ closeAndReset,+ selectableItems,+ highlightedIndex,+ selectItem,+ findSelectedIndex,+ getEnabledIndices,+ typeahead,+ ],+ );++ return {+ highlightedIndex,+ setHighlightedIndex,+ getItemId,+ onTriggerClick,+ onKeyDown,+ onItemSelect: selectItem,+ onItemMouseEnter,+ };+}diff --git a/packages/core/src/Selector/index.ts b/packages/core/src/Selector/index.tsnew file mode 100644index 0000000000..ea394ffb53--- /dev/null+++ b/packages/core/src/Selector/index.ts@@ -0,0 +1,28 @@+/**+ * @file index.ts+ * @output Exports XDSSelector and types+ * @position Public API entry point+ */++export {+ XDSSelector,+ type XDSSelectorProps,+ type XDSSelectorSize,+ type XDSSelectorStatus,+ type XDSSelectorStatusType,+} from './XDSSelector';+export {XDSSelectorItem, type XDSSelectorItemProps} from './XDSSelectorItem';+export type {+ XDSSelectorOption,+ XDSSelectorItemData,+ XDSSelectorDivider,+ XDSSelectorSection,+} from './types';+export {+ isItemData,+ isDivider,+ isSection,+ normalizeItem,+ getSelectableItems,+} from './utils';+export {useCombobox, useSelectedItemOffset} from './hooks';diff --git a/packages/core/src/Selector/types.ts b/packages/core/src/Selector/types.tsnew file mode 100644index 0000000000..ce2900655f--- /dev/null+++ b/packages/core/src/Selector/types.ts@@ -0,0 +1,42 @@+/**+ * @file types.ts+ * @output Type definitions for XDSSelector+ * @position Type definitions; used by XDSSelector.tsx+ */++import type {XDSIconType} from '../Icon';++/**+ * A selectable item in the selector+ */+export type XDSSelectorItemData = {+ value: string;+ label?: string;+ disabled?: boolean;+ icon?: XDSIconType;+};++/**+ * A divider between items+ */+export type XDSSelectorDivider = {+ type: 'divider';+};++/**+ * A section/group of items with optional title+ */+export type XDSSelectorSection = {+ type: 'section';+ title?: string;+ items: XDSSelectorItemData[];+};++/**+ * Union of all option types+ */+export type XDSSelectorOption =+ | string+ | XDSSelectorItemData+ | XDSSelectorDivider+ | XDSSelectorSection;diff --git a/packages/core/src/Selector/utils.ts b/packages/core/src/Selector/utils.tsnew file mode 100644index 0000000000..bc54ec5158--- /dev/null+++ b/packages/core/src/Selector/utils.ts@@ -0,0 +1,81 @@+/**+ * @file utils.ts+ * @output Utility functions for XDSSelector+ * @position Utilities; used by XDSSelector.tsx+ */++import type {+ XDSSelectorOption,+ XDSSelectorItemData,+ XDSSelectorDivider,+ XDSSelectorSection,+} from './types';++/**+ * Type guard: check if option is a selectable item (string or ItemData)+ */+export function isItemData(+ option: XDSSelectorOption,+): option is XDSSelectorItemData | string {+ if (typeof option === 'string') return true;+ return !('type' in option);+}++/**+ * Type guard: check if option is a divider+ */+export function isDivider(+ option: XDSSelectorOption,+): option is XDSSelectorDivider {+ return (+ typeof option === 'object' && 'type' in option && option.type === 'divider'+ );+}++/**+ * Type guard: check if option is a section+ */+export function isSection(+ option: XDSSelectorOption,+): option is XDSSelectorSection {+ return (+ typeof option === 'object' && 'type' in option && option.type === 'section'+ );+}++/**+ * Normalize string or item to consistent shape+ */+export function normalizeItem(+ option: string | XDSSelectorItemData,+): XDSSelectorItemData {+ if (typeof option === 'string') {+ return {value: option, label: option};+ }+ return {+ ...option,+ label: option.label ?? option.value,+ };+}++/**+ * Get all selectable items from options (flattening sections)+ */+export function getSelectableItems(+ options: XDSSelectorOption[],+): XDSSelectorItemData[] {+ const items: XDSSelectorItemData[] = [];++ for (const option of options) {+ if (isItemData(option)) {+ items.push(normalizeItem(option));+ } else if (isSection(option)) {+ for (const item of option.items) {+ items.push(normalizeItem(item));+ }+ }+ // Skip dividers+ }++ return items;+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 4949e3fa40..a5f71b071d 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -18,6 +18,7 @@ export * from './Divider';export * from './DateInput';export * from './Field';export * from './Grid';+export * from './Selector';export * from './Icon';export * from './Text';export * from './TextInput';diff --git a/packages/core/xds.md b/packages/core/xds.mdindex ad67fc6a3a..ae1c8e55ea 100644--- a/packages/core/xds.md+++ b/packages/core/xds.md@@ -25,6 +25,7 @@ Each component has a README.md in its source directory with usage examples, prop| `@xds/core/TextInput` | [src/TextInput/README.md](src/TextInput/README.md) | XDSTextInput || `@xds/core/TextArea` | [src/TextArea/README.md](src/TextArea/README.md) | XDSTextArea || `@xds/core/CheckboxInput` | [src/CheckboxInput/README.md](src/CheckboxInput/README.md) | XDSCheckboxInput |+| `@xds/core/Selector` | [src/Selector/README.md](src/Selector/README.md) | XDSSelector || `@xds/core/Field` | [src/Field/README.md](src/Field/README.md) | XDSField || `@xds/core/Avatar` | [src/Avatar/README.md](src/Avatar/README.md) | XDSAvatar || `@xds/core/Skeleton` | [src/Skeleton/README.md](src/Skeleton/README.md) | XDSSkeleton |