An open source design system that's fully customizable and agent ready
TypeScript
feat(core): add XDSTypeahead and XDSTokenizer components (#299)
Cindy Zhang3cf313e15840
diff --git a/apps/storybook/stories/Tokenizer.stories.tsx b/apps/storybook/stories/Tokenizer.stories.tsxnew file mode 100644index 0000000000..e4f14c91cf--- /dev/null+++ b/apps/storybook/stories/Tokenizer.stories.tsx@@ -0,0 +1,160 @@+import {useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {XDSTokenizer} from '@xds/core/Tokenizer';+import type {XDSSearchableItem, XDSSearchSource} from '@xds/core/Typeahead';++// Sample data+const users: XDSSearchableItem[] = [+ {id: '1', label: 'Alice Johnson'},+ {id: '2', label: 'Bob Smith'},+ {id: '3', label: 'Charlie Brown'},+ {id: '4', label: 'Diana Prince'},+ {id: '5', label: 'Eve Williams'},+ {id: '6', label: 'Frank Miller'},+ {id: '7', label: 'Grace Lee'},+ {id: '8', label: 'Henry Davis'},+];++const userSource: XDSSearchSource = {+ search: (query: string) =>+ users.filter(u => u.label.toLowerCase().includes(query.toLowerCase())),+ bootstrap: () => users.slice(0, 5),+};++const meta: Meta<typeof XDSTokenizer> = {+ title: 'Form/XDSTokenizer',+ component: XDSTokenizer,+ tags: ['autodocs'],+ argTypes: {+ label: {control: 'text'},+ placeholder: {control: 'text'},+ isDisabled: {control: 'boolean'},+ isRequired: {control: 'boolean'},+ isOptional: {control: 'boolean'},+ hasClear: {control: 'boolean'},+ maxEntries: {control: 'number'},+ },+ decorators: [+ Story => (+ <div style={{width: 400}}>+ <Story />+ </div>+ ),+ ],+};++export default meta;+type Story = StoryObj<typeof XDSTokenizer>;++export const Default: Story = {+ render: args => {+ const [value, setValue] = useState<XDSSearchableItem[]>([]);+ return (+ <XDSTokenizer+ {...args}+ searchSource={userSource}+ value={value}+ onChange={items => setValue(items)}+ />+ );+ },+ args: {+ label: 'Team Members',+ placeholder: 'Search people...',+ },+};++export const WithPreselected: Story = {+ render: args => {+ const [value, setValue] = useState([users[0], users[2]]);+ return (+ <XDSTokenizer+ {...args}+ searchSource={userSource}+ value={value}+ onChange={items => setValue(items)}+ />+ );+ },+ args: {+ label: 'Team Members',+ placeholder: 'Add more...',+ },+ name: 'Pre-selected Items',+};++export const WithClear: Story = {+ ...Default,+ args: {+ ...Default.args,+ hasClear: true,+ },+ name: 'With Clear All Button',+};++export const MaxEntries: Story = {+ ...Default,+ args: {+ ...Default.args,+ maxEntries: 3,+ },+ name: 'Max 3 Entries',+};++export const Required: Story = {+ ...Default,+ args: {+ ...Default.args,+ isRequired: true,+ },+};++export const WithDescription: Story = {+ ...Default,+ args: {+ ...Default.args,+ description: 'Select up to 5 team members for this project',+ },+};++export const WithError: Story = {+ ...Default,+ args: {+ ...Default.args,+ status: {type: 'error', message: 'At least one member is required'},+ },+};++export const WithWarning: Story = {+ ...Default,+ args: {+ ...Default.args,+ status: {type: 'warning', message: 'Some members may not have access'},+ },+};++export const WithSuccess: Story = {+ ...Default,+ args: {+ ...Default.args,+ status: {type: 'success', message: 'Team is ready!'},+ },+};++export const Disabled: Story = {+ render: args => {+ const [value] = useState([users[0], users[1]]);+ return (+ <XDSTokenizer+ {...args}+ searchSource={userSource}+ value={value}+ onChange={() => {}}+ />+ );+ },+ args: {+ label: 'Team Members',+ isDisabled: true,+ },+};diff --git a/apps/storybook/stories/Typeahead.stories.tsx b/apps/storybook/stories/Typeahead.stories.tsxnew file mode 100644index 0000000000..a257a76341--- /dev/null+++ b/apps/storybook/stories/Typeahead.stories.tsx@@ -0,0 +1,150 @@+import {useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {XDSTypeahead} from '@xds/core/Typeahead';+import type {XDSSearchableItem, XDSSearchSource} from '@xds/core/Typeahead';++// Sample data+const fruits: XDSSearchableItem[] = [+ {id: '1', label: 'Apple'},+ {id: '2', label: 'Banana'},+ {id: '3', label: 'Cherry'},+ {id: '4', label: 'Date'},+ {id: '5', label: 'Elderberry'},+ {id: '6', label: 'Fig'},+ {id: '7', label: 'Grape'},+ {id: '8', label: 'Honeydew'},+];++const fruitSource: XDSSearchSource = {+ search: (query: string) =>+ fruits.filter(f => f.label.toLowerCase().includes(query.toLowerCase())),+ bootstrap: () => fruits.slice(0, 5),+};++const meta: Meta<typeof XDSTypeahead> = {+ title: 'Form/XDSTypeahead',+ component: XDSTypeahead,+ tags: ['autodocs'],+ argTypes: {+ label: {control: 'text'},+ placeholder: {control: 'text'},+ isDisabled: {control: 'boolean'},+ isRequired: {control: 'boolean'},+ isOptional: {control: 'boolean'},+ hasEntriesOnFocus: {control: 'boolean'},+ hasClear: {control: 'boolean'},+ maxMenuItems: {control: 'number'},+ },+ decorators: [+ Story => (+ <div style={{width: 320}}>+ <Story />+ </div>+ ),+ ],+};++export default meta;+type Story = StoryObj<typeof XDSTypeahead>;++export const Default: Story = {+ render: args => {+ const [value, setValue] = useState<XDSSearchableItem | null>(null);+ return (+ <XDSTypeahead+ {...args}+ searchSource={fruitSource}+ value={value}+ onChange={setValue}+ />+ );+ },+ args: {+ label: 'Fruit',+ placeholder: 'Search fruits...',+ },+};++export const WithBootstrap: Story = {+ ...Default,+ args: {+ ...Default.args,+ hasEntriesOnFocus: true,+ },+ name: 'With Bootstrap Results',+};++export const Required: Story = {+ ...Default,+ args: {+ ...Default.args,+ isRequired: true,+ },+};++export const Optional: Story = {+ ...Default,+ args: {+ ...Default.args,+ isOptional: true,+ },+};++export const WithDescription: Story = {+ ...Default,+ args: {+ ...Default.args,+ description: 'Pick your favorite fruit from the list',+ },+};++export const WithError: Story = {+ ...Default,+ args: {+ ...Default.args,+ status: {type: 'error', message: 'Please select a fruit'},+ },+};++export const WithWarning: Story = {+ ...Default,+ args: {+ ...Default.args,+ status: {type: 'warning', message: 'This fruit may be out of season'},+ },+};++export const WithSuccess: Story = {+ ...Default,+ args: {+ ...Default.args,+ status: {type: 'success', message: 'Great choice!'},+ },+};++export const Disabled: Story = {+ ...Default,+ args: {+ ...Default.args,+ isDisabled: true,+ },+};++export const NoClear: Story = {+ ...Default,+ args: {+ ...Default.args,+ hasClear: false,+ },+ name: 'Without Clear Button',+};++export const LimitedResults: Story = {+ ...Default,+ args: {+ ...Default.args,+ hasEntriesOnFocus: true,+ maxMenuItems: 3,+ },+ name: 'Max 3 Results',+};diff --git a/packages/core/src/Token/XDSToken.tsx b/packages/core/src/Token/XDSToken.tsxindex 8dda754392..e6638ac660 100644--- a/packages/core/src/Token/XDSToken.tsx+++ b/packages/core/src/Token/XDSToken.tsx@@ -46,11 +46,18 @@ export type XDSTokenColor =| 'pink'| 'gray';+export type XDSTokenSize = 'sm' | 'md';+export interface XDSTokenProps {/*** The text label displayed in the token.*/label: string;+ /**+ * The size of the token.+ * @default 'md'+ */+ size?: XDSTokenSize;/*** The color variant of the token.* @default 'default'@@ -111,9 +118,7 @@ const styles = stylex.create({display: 'inline-flex',alignItems: 'center',gap: spacingVars['--spacing-1'],- height: sizeVars['--size-sm'],- paddingBlock: spacingVars['--spacing-1'],- paddingInline: spacingVars['--spacing-3'],+ paddingBlock: 0,borderWidth: 0,borderStyle: 'none',borderRadius: radiusVars['--radius-content'],@@ -202,6 +207,18 @@ const styles = stylex.create({},});+const sizeStyles = stylex.create({+ sm: {+ height: `calc(${sizeVars['--size-sm']} - 8px)`,+ fontSize: textSizeVars['--text-xsm'],+ paddingInline: spacingVars['--spacing-2'],+ },+ md: {+ height: `calc(${sizeVars['--size-md']} - 8px)`,+ paddingInline: spacingVars['--spacing-3'],+ },+});+const colorStyles = stylex.create({default: {backgroundColor: colorVars['--color-deemphasized'],@@ -275,6 +292,7 @@ export const XDSToken = forwardRef<HTMLElement, XDSTokenProps>(({label,+ size = 'md',color = 'default',icon,isDisabled = false,@@ -327,6 +345,7 @@ export const XDSToken = forwardRef<HTMLElement, XDSTokenProps>({...sharedProps}{...stylex.props(styles.base,+ sizeStyles[size],colorStyles[color],styles.interactive,isDisabled && styles.disabled,@@ -351,6 +370,7 @@ export const XDSToken = forwardRef<HTMLElement, XDSTokenProps>({...sharedProps}{...stylex.props(styles.base,+ sizeStyles[size],colorStyles[color],styles.interactive,styles.focusWithinOutline,@@ -391,6 +411,7 @@ export const XDSToken = forwardRef<HTMLElement, XDSTokenProps>({...sharedProps}{...stylex.props(styles.base,+ sizeStyles[size],colorStyles[color],isDisabled && styles.disabled,xstyle,diff --git a/packages/core/src/Token/index.ts b/packages/core/src/Token/index.tsindex 1f1aebe642..50b93b1904 100644--- a/packages/core/src/Token/index.ts+++ b/packages/core/src/Token/index.ts@@ -3,4 +3,4 @@*/export {XDSToken} from './XDSToken';-export type {XDSTokenProps, XDSTokenColor} from './XDSToken';+export type {XDSTokenProps, XDSTokenColor, XDSTokenSize} from './XDSToken';diff --git a/packages/core/src/Tokenizer/README.md b/packages/core/src/Tokenizer/README.mdnew file mode 100644index 0000000000..a196209bdd--- /dev/null+++ b/packages/core/src/Tokenizer/README.md@@ -0,0 +1,71 @@+# /packages/core/src/Tokenizer++Multi-select typeahead with token chips for selected items.++<!-- SYNC: When files in this directory change, update this document. -->++## Overview++XDSTokenizer combines XDSBaseTypeahead (search) with XDSToken (chips) for multi-item selection. It supports:++- **Token chips** for each selected item with remove buttons+- **Filtered search** that excludes already-selected items+- **Max entries** to limit selections+- **Clear all** button for bulk removal+- **Custom token and item rendering**+- **Backspace to remove** the last token++## Import++```tsx+import {XDSTokenizer} from '@xds/core/Tokenizer';+```++## Usage++```tsx+const source = {+ search: query => users.filter(u => u.label.includes(query)),+ bootstrap: () => users.slice(0, 5),+};++<XDSTokenizer+ label="Team Members"+ searchSource={source}+ value={selected}+ onChange={(items, change) => {+ setSelected(items);+ // change.type is 'add' | 'remove' | 'reorder'+ }}+ placeholder="Search people..."+ hasClear+ maxEntries={10}+/>;+```++## Key Props++| Prop | Type | Default | Description |+| -------------- | ------------------------------- | -------- | --------------------------------------- |+| `label` | `string` | required | Accessible label |+| `searchSource` | `XDSSearchSource` | required | Data source |+| `value` | `T[]` | required | Selected items |+| `onChange` | `(items, change) => void` | required | Selection callback with change metadata |+| `maxEntries` | `number` | — | Max number of selections |+| `hasClear` | `boolean` | `false` | Show "Clear all" button |+| `renderToken` | `(item, onRemove) => ReactNode` | — | Custom token renderer |+| `renderItem` | `(item) => ReactNode` | — | Custom dropdown item renderer |+| `placeholder` | `string` | — | Input placeholder |+| `isDisabled` | `boolean` | `false` | Disable input and tokens |+| `status` | `XDSInputStatus` | — | Validation status |++## Change Metadata++The `onChange` callback receives a second argument describing what changed:++```tsx+type XDSTokenizerChange<T> =+ | {item: T; type: 'add'}+ | {item: T; type: 'remove'}+ | {type: 'reorder'};+```diff --git a/packages/core/src/Tokenizer/XDSTokenizer.test.tsx b/packages/core/src/Tokenizer/XDSTokenizer.test.tsxnew file mode 100644index 0000000000..05f932898e--- /dev/null+++ b/packages/core/src/Tokenizer/XDSTokenizer.test.tsx@@ -0,0 +1,271 @@+/**+ * @file XDSTokenizer.test.tsx+ * @input Uses vitest, @testing-library/react, XDSTokenizer+ * @output Unit tests for XDSTokenizer component+ * @position Testing; validates XDSTokenizer.tsx+ *+ * SYNC: When XDSTokenizer.tsx changes, update tests to match+ */++import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';+import {render, screen, fireEvent} from '@testing-library/react';+import {XDSTokenizer} from './XDSTokenizer';+import type {XDSSearchSource, XDSSearchableItem} from '../Typeahead/types';++// Store original matches to restore later+const originalMatches = HTMLElement.prototype.matches;++// Track popover open state per element+const popoverOpenState = new WeakMap<HTMLElement, boolean>();++// Mock Popover API for jsdom+beforeAll(() => {+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {+ popoverOpenState.set(this, true);+ const event = new Event('toggle');+ Object.defineProperty(event, 'newState', {value: 'open'});+ this.dispatchEvent(event);+ });+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {+ popoverOpenState.set(this, false);+ const event = new Event('toggle');+ Object.defineProperty(event, 'newState', {value: 'closed'});+ this.dispatchEvent(event);+ });++ HTMLElement.prototype.matches = function (selector: string) {+ if (selector === ':popover-open') {+ return popoverOpenState.get(this) ?? false;+ }+ return originalMatches.call(this, selector);+ };+});++afterAll(() => {+ HTMLElement.prototype.matches = originalMatches;+});++// Test data+const users: XDSSearchableItem[] = [+ {id: '1', label: 'Alice'},+ {id: '2', label: 'Bob'},+ {id: '3', label: 'Charlie'},+ {id: '4', label: 'Diana'},+];++const userSource: XDSSearchSource = {+ search: (query: string) =>+ users.filter(u => u.label.toLowerCase().includes(query.toLowerCase())),+ bootstrap: () => users.slice(0, 3),+};++describe('XDSTokenizer', () => {+ it('renders with label', () => {+ render(+ <XDSTokenizer+ label="Members"+ searchSource={userSource}+ value={[]}+ onChange={() => {}}+ />,+ );+ // Label is rendered by XDSField+ expect(screen.getByText('Members')).toBeInTheDocument();+ });++ it('renders combobox input', () => {+ render(+ <XDSTokenizer+ label="Members"+ searchSource={userSource}+ value={[]}+ onChange={() => {}}+ />,+ );+ expect(screen.getByRole('combobox')).toBeInTheDocument();+ });++ it('renders placeholder when no tokens', () => {+ render(+ <XDSTokenizer+ label="Members"+ searchSource={userSource}+ value={[]}+ onChange={() => {}}+ placeholder="Search people..."+ />,+ );+ expect(screen.getByPlaceholderText('Search people...')).toBeInTheDocument();+ });++ it('renders tokens for selected items', () => {+ render(+ <XDSTokenizer+ label="Members"+ searchSource={userSource}+ value={[users[0], users[1]]}+ onChange={() => {}}+ />,+ );+ expect(screen.getByText('Alice')).toBeInTheDocument();+ expect(screen.getByText('Bob')).toBeInTheDocument();+ });++ it('renders remove buttons on tokens', () => {+ render(+ <XDSTokenizer+ label="Members"+ searchSource={userSource}+ value={[users[0]]}+ onChange={() => {}}+ />,+ );+ expect(+ screen.getByRole('button', {name: 'Remove Alice'}),+ ).toBeInTheDocument();+ });++ it('calls onChange with remove when token is removed', () => {+ const onChange = vi.fn();+ render(+ <XDSTokenizer+ label="Members"+ searchSource={userSource}+ value={[users[0], users[1]]}+ onChange={onChange}+ />,+ );+ fireEvent.click(screen.getByRole('button', {name: 'Remove Alice'}));+ expect(onChange).toHaveBeenCalledWith([users[1]], {+ item: users[0],+ type: 'remove',+ });+ });++ it('visually hides input when maxEntries is reached but preserves it for keyboard access', () => {+ render(+ <XDSTokenizer+ label="Members"+ searchSource={userSource}+ value={[users[0], users[1]]}+ onChange={() => {}}+ maxEntries={2}+ />,+ );+ // Input stays in the DOM for keyboard accessibility (backspace to remove)+ // but is visually hidden+ const input = screen.getByRole('combobox');+ expect(input).toBeInTheDocument();+ });++ it('shows input when under maxEntries', () => {+ render(+ <XDSTokenizer+ label="Members"+ searchSource={userSource}+ value={[users[0]]}+ onChange={() => {}}+ maxEntries={2}+ />,+ );+ expect(screen.getByRole('combobox')).toBeInTheDocument();+ });++ it('shows clear all button when hasClear is true', () => {+ render(+ <XDSTokenizer+ label="Members"+ searchSource={userSource}+ value={[users[0]]}+ onChange={() => {}}+ hasClear+ />,+ );+ expect(screen.getByRole('button', {name: 'Clear all'})).toBeInTheDocument();+ });++ it('does not show clear all when no tokens', () => {+ render(+ <XDSTokenizer+ label="Members"+ searchSource={userSource}+ value={[]}+ onChange={() => {}}+ hasClear+ />,+ );+ expect(+ screen.queryByRole('button', {name: 'Clear all'}),+ ).not.toBeInTheDocument();+ });++ it('renders description text', () => {+ render(+ <XDSTokenizer+ label="Members"+ description="Select team members"+ searchSource={userSource}+ value={[]}+ onChange={() => {}}+ />,+ );+ expect(screen.getByText('Select team members')).toBeInTheDocument();+ });++ it('renders error status', () => {+ render(+ <XDSTokenizer+ label="Members"+ searchSource={userSource}+ value={[]}+ onChange={() => {}}+ status={{type: 'error', message: 'At least one member required'}}+ />,+ );+ expect(+ screen.getByText('At least one member required'),+ ).toBeInTheDocument();+ });++ it('disables tokens and input when isDisabled', () => {+ render(+ <XDSTokenizer+ label="Members"+ searchSource={userSource}+ value={[users[0]]}+ onChange={() => {}}+ isDisabled+ />,+ );+ expect(screen.getByRole('combobox')).toBeDisabled();+ // Remove button should not be present when disabled+ expect(+ screen.queryByRole('button', {name: 'Remove Alice'}),+ ).not.toBeInTheDocument();+ });++ it('renders with data-testid', () => {+ render(+ <XDSTokenizer+ label="Members"+ searchSource={userSource}+ value={[]}+ onChange={() => {}}+ data-testid="my-tokenizer"+ />,+ );+ expect(screen.getByTestId('my-tokenizer')).toBeInTheDocument();+ });++ it('renders group with aria-label', () => {+ render(+ <XDSTokenizer+ label="Members"+ searchSource={userSource}+ value={[]}+ onChange={() => {}}+ />,+ );+ expect(screen.getByRole('group')).toHaveAttribute('aria-label', 'Members');+ });+});diff --git a/packages/core/src/Tokenizer/XDSTokenizer.tsx b/packages/core/src/Tokenizer/XDSTokenizer.tsxnew file mode 100644index 0000000000..fff9a4293d--- /dev/null+++ b/packages/core/src/Tokenizer/XDSTokenizer.tsx@@ -0,0 +1,545 @@+/**+ * @file XDSTokenizer.tsx+ * @input Uses React, XDSBaseTypeahead, XDSField, XDSToken+ * @output Exports XDSTokenizer multi-select typeahead component+ * @position Composed component; uses XDSBaseTypeahead for search + XDSToken for chips+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Tokenizer/README.md+ * - /packages/core/src/Tokenizer/index.ts+ * - /apps/storybook/stories/Tokenizer.stories.tsx+ */++import React, {+ useCallback,+ useId,+ useMemo,+ useRef,+ type ReactNode,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {StyleXStyles} from '@stylexjs/stylex';+import {XDSBaseTypeahead} from '../Typeahead/XDSBaseTypeahead';+import {XDSField, type XDSInputStatus} from '../Field';+import {XDSToken} from '../Token';+import {XDSIcon} from '../Icon';+import {+ colorVars,+ spacingVars,+ radiusVars,+ sizeVars,+ transitionVars,+ elevationVars,+} from '../theme/tokens.stylex';+import type {XDSSearchableItem, XDSSearchSource} from '../Typeahead/types';++// Re-export status types for convenience+export type {+ XDSInputStatus as XDSTokenizerStatus,+ XDSInputStatusType as XDSTokenizerStatusType,+} from '../Field';++// =============================================================================+// Types+// =============================================================================++/**+ * Change metadata for onChange callback.+ */+export type XDSTokenizerChange<T extends XDSSearchableItem> =+ | {item: T; type: 'add'}+ | {item: T; type: 'remove'}+ | {type: 'reorder'};++export interface XDSTokenizerProps<T extends XDSSearchableItem> {+ /** Accessible label (required). */+ label: string;+ /** Visually hide the label. @default false */+ isLabelHidden?: boolean;+ /** Helper text. */+ description?: string;+ /** Required field. @default false */+ isRequired?: boolean;+ /** Optional field. @default false */+ isOptional?: boolean;+ /** Validation status. */+ status?: XDSInputStatus;+ /** Label tooltip. */+ labelTooltip?: string;+ /** Search source providing items. */+ searchSource: XDSSearchSource<T>;+ /** Currently selected items. */+ value: T[];+ /** Callback when selection changes. Includes change metadata. */+ onChange: (items: T[], change: XDSTokenizerChange<T>) => void;+ /** Render function for dropdown items. Default: XDSTypeaheadItem. */+ renderItem?: (item: T) => ReactNode;+ /** Render function for selected tokens. Default: XDSToken with label + onRemove. */+ renderToken?: (item: T, onRemove: () => void) => ReactNode;+ /** Max number of selections. */+ maxEntries?: number;+ /** Placeholder text (shown when no tokens selected). */+ placeholder?: string;+ /** Show results on focus before typing. @default false */+ hasEntriesOnFocus?: boolean;+ /** Max dropdown items. @default 10 */+ maxMenuItems?: number;+ /** Text shown when no results found. @default 'No results found' */+ emptySearchResultsText?: string;+ /** Whether the input is disabled. @default false */+ isDisabled?: boolean;+ /** Show clear button (clears all tokens). @default false */+ hasClear?: boolean;+ /** Auto-focus on mount. @default false */+ hasAutoFocus?: boolean;+ /** Input size. @default 'md' */+ size?: 'sm' | 'md';+ /**+ * Debounce delay in ms before triggering search after typing.+ * Set to 0 for synchronous/local search sources that don't need debouncing.+ * @default 150+ */+ debounceMs?: number;+ /** Query change callback. */+ onChangeQuery?: (query: string) => void;+ /** StyleX overrides. */+ xstyle?: StyleXStyles;+ /** Test ID. */+ 'data-testid'?: string;+}++// =============================================================================+// Styles+// =============================================================================++const styles = stylex.create({+ wrapper: {+ boxSizing: 'border-box',+ position: 'relative',+ display: 'flex',+ alignItems: 'center',+ flexWrap: 'wrap',+ gap: spacingVars['--spacing-1'],+ // Standard padding minus border width to prevent height jump+ // when tokens (28px) are added inside the input+ paddingBlock: `calc(${spacingVars['--spacing-1']} - 1px)`,+ paddingInline: spacingVars['--spacing-2'],+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: {+ default: colorVars['--color-divider-emphasized'],+ ':hover': {+ '@media (hover: hover)': colorVars['--color-divider-high-contrast'],+ },+ },+ borderRadius: radiusVars['--radius-element'],+ backgroundColor: colorVars['--color-surface'],+ transitionProperty: 'border-color, outline, box-shadow',+ transitionDuration: transitionVars['--transition-fast'],+ boxShadow: {+ default: 'none',+ ':hover': {+ '@media (hover: hover)': elevationVars['--elevation-input-hover'],+ },+ },+ outline: {+ default: 'none',+ ':focus-within': `1px solid ${colorVars['--color-focus-outline']}`,+ },+ outlineOffset: '0',+ cursor: 'text',+ },+ wrapperDisabled: {+ cursor: 'not-allowed',+ opacity: 0.5,+ borderColor: colorVars['--color-divider-emphasized'],+ },+ tokenContainer: {+ display: 'flex',+ flexWrap: 'wrap',+ gap: spacingVars['--spacing-1'],+ alignItems: 'center',+ // Offset tokens so they sit 3px from the inner edge (4px from outer edge+ // accounting for 1px border). Default inline padding is 8px, so+ // -(8px - 3px) = -5px positions tokens equidistant from left edge as top.+ margin: `calc(-1 * (${spacingVars['--spacing-2']} - ${spacingVars['--spacing-1']} + 1px))`,+ },+ clearAllButton: {+ all: 'unset',+ display: 'inline-flex',+ alignItems: 'center',+ justifyContent: 'center',+ cursor: 'pointer',+ padding: spacingVars['--spacing-1'],+ borderRadius: radiusVars['--radius-rounded'],+ color: colorVars['--color-text-secondary'],+ opacity: {+ default: 0.7,+ ':hover': {+ '@media (hover: hover)': 1,+ },+ },+ marginInlineStart: 'auto',+ flexShrink: 0,+ },+ sizeSm: {+ minHeight: sizeVars['--size-sm'],+ },+ sizeMd: {+ minHeight: sizeVars['--size-md'],+ },+ inputAtMax: {+ width: 0,+ minWidth: 0,+ flex: '0 0 0',+ padding: 0,+ opacity: 0,+ position: 'absolute',+ },+ inputCompact: {+ minWidth: '40px',+ flex: '0 1 auto',+ width: '40px',+ },+});++const statusBorderStyles = stylex.create({+ warning: {+ borderColor: colorVars['--color-warning'],+ },+ error: {+ borderColor: colorVars['--color-negative'],+ },+ success: {+ borderColor: colorVars['--color-positive'],+ },+});++const statusHoverShadowStyles = stylex.create({+ warning: {+ boxShadow: {+ default: 'none',+ ':hover': {+ '@media (hover: hover)':+ elevationVars['--elevation-input-hover-warning'],+ },+ },+ },+ error: {+ boxShadow: {+ default: 'none',+ ':hover': {+ '@media (hover: hover)': elevationVars['--elevation-input-hover-error'],+ },+ },+ },+ success: {+ boxShadow: {+ default: 'none',+ ':hover': {+ '@media (hover: hover)':+ elevationVars['--elevation-input-hover-success'],+ },+ },+ },+});++const statusFocusStyles = stylex.create({+ warning: {+ outline: {+ default: 'none',+ ':focus-within': `1px solid ${colorVars['--color-focus-outline-warning']}`,+ },+ },+ error: {+ outline: {+ default: 'none',+ ':focus-within': `1px solid ${colorVars['--color-focus-outline-error']}`,+ },+ },+ success: {+ outline: {+ default: 'none',+ ':focus-within': `1px solid ${colorVars['--color-focus-outline-success']}`,+ },+ },+});++// =============================================================================+// Component+// =============================================================================++/**+ * Multi-select input with token chips and typeahead search.+ *+ * Composes XDSBaseTypeahead for search and XDSToken for selected items.+ * Tokens render inline before the text input. Selecting an item adds a token+ * and clears the query. Backspace on empty input removes the last token.+ *+ * @example+ * ```tsx+ * // Basic+ * const [members, setMembers] = useState<UserItem[]>([]);+ *+ * <XDSTokenizer+ * label="Team members"+ * searchSource={userSource}+ * value={members}+ * onChange={(items, change) => {+ * setMembers(items);+ * if (change.type === 'add') console.log('Added:', change.item.label);+ * }}+ * placeholder="Search people..."+ * />+ *+ * // Custom rendering+ * <XDSTokenizer+ * label="Tags"+ * searchSource={tagSource}+ * value={tags}+ * onChange={(items) => setTags(items)}+ * renderToken={(item, onRemove) => (+ * <XDSToken+ * label={item.label}+ * color={item.auxiliaryData.color}+ * onRemove={onRemove}+ * />+ * )}+ * maxEntries={5}+ * />+ * ```+ */+export function XDSTokenizer<T extends XDSSearchableItem>({+ label,+ isLabelHidden = false,+ description,+ isRequired = false,+ isOptional = false,+ status,+ labelTooltip,+ searchSource,+ value,+ onChange,+ renderItem,+ renderToken,+ maxEntries,+ placeholder,+ hasEntriesOnFocus,+ maxMenuItems,+ emptySearchResultsText,+ isDisabled = false,+ hasClear = false,+ hasAutoFocus,+ size = 'md',+ debounceMs,+ onChangeQuery,+ xstyle,+ 'data-testid': testId,+}: XDSTokenizerProps<T>) {+ const inputId = useId();+ const descriptionId = useId();+ const statusMessageId = useId();+ const inputRef = useRef<HTMLInputElement>(null);+ const wrapperRef = useRef<HTMLDivElement>(null);++ const isAtMax = maxEntries != null && value.length >= maxEntries;++ // Filter out already-selected items from search results+ const selectedIds = useMemo(+ () => new Set(value.map(item => item.id)),+ [value],+ );++ const filteredSource: XDSSearchSource<T> = useMemo(+ () => ({+ search: async (query: string) => {+ const results = await searchSource.search(query);+ return results.filter(item => !selectedIds.has(item.id));+ },+ bootstrap: async () => {+ const results = await searchSource.bootstrap();+ return results.filter(item => !selectedIds.has(item.id));+ },+ }),+ [searchSource, selectedIds],+ );++ const emptySource: XDSSearchSource<T> = useMemo(+ () => ({+ search: async () => [],+ bootstrap: async () => [],+ }),+ [],+ );++ // Handle adding an item+ const handleAdd = useCallback(+ (item: T | null) => {+ if (!item) return;+ if (isAtMax) return;+ if (selectedIds.has(item.id)) return;++ const newItems = [...value, item];+ onChange(newItems, {item, type: 'add'});+ },+ [value, onChange, isAtMax, selectedIds],+ );++ // Handle removing an item+ const handleRemove = useCallback(+ (item: T) => {+ const newItems = value.filter(v => v.id !== item.id);+ onChange(newItems, {item, type: 'remove'});+ inputRef.current?.focus();+ },+ [value, onChange],+ );++ // Handle clearing all items+ const handleClearAll = useCallback(() => {+ if (value.length === 0) return;+ // Report the last item as removed (convention)+ const lastItem = value[value.length - 1];+ onChange([], {item: lastItem, type: 'remove'});+ inputRef.current?.focus();+ }, [value, onChange]);++ // Handle backspace on empty input — remove last token+ const handleKeyDown = useCallback(+ (e: React.KeyboardEvent<HTMLInputElement>) => {+ if (+ e.key === 'Backspace' &&+ e.currentTarget.value === '' &&+ value.length > 0+ ) {+ e.preventDefault();+ const lastItem = value[value.length - 1];+ handleRemove(lastItem);+ }+ },+ [value, handleRemove],+ );++ // Click wrapper to focus input+ const handleWrapperClick = useCallback(() => {+ if (!isDisabled) {+ inputRef.current?.focus();+ }+ }, [isDisabled]);++ const ariaDescribedBy =+ [+ description ? descriptionId : null,+ status?.message ? statusMessageId : null,+ ]+ .filter(Boolean)+ .join(' ') || undefined;++ const sizeStyle = size === 'sm' ? styles.sizeSm : styles.sizeMd;++ // Render tokens+ const tokens = value.map(item => {+ const onRemoveItem = () => handleRemove(item);++ if (renderToken) {+ return (+ <React.Fragment key={item.id}>+ {renderToken(item, onRemoveItem)}+ </React.Fragment>+ );+ }++ return (+ <XDSToken+ key={item.id}+ label={item.label}+ size={size}+ onRemove={isDisabled ? undefined : onRemoveItem}+ isDisabled={isDisabled}+ />+ );+ });++ return (+ <XDSField+ label={label}+ isLabelHidden={isLabelHidden}+ description={description}+ inputID={inputId}+ descriptionID={description ? descriptionId : undefined}+ isOptional={isOptional}+ isRequired={isRequired}+ status={+ status+ ? {+ type: status.type,+ message: status.message,+ messageID: status.message ? statusMessageId : undefined,+ }+ : undefined+ }+ labelTooltip={labelTooltip}>+ <div+ ref={wrapperRef}+ role="group"+ aria-label={label}+ onClick={handleWrapperClick}+ data-testid={testId}+ {...stylex.props(+ styles.wrapper,+ sizeStyle,+ isDisabled && styles.wrapperDisabled,+ status && statusBorderStyles[status.type],+ status && statusHoverShadowStyles[status.type],+ status && statusFocusStyles[status.type],+ xstyle,+ )}>+ {tokens.length > 0 && (+ <div {...stylex.props(styles.tokenContainer)}>{tokens}</div>+ )}+ <XDSBaseTypeahead+ ref={inputRef}+ searchSource={isAtMax ? emptySource : filteredSource}+ value={null}+ onChange={handleAdd}+ renderItem={renderItem}+ placeholder={+ value.length === 0 ? placeholder : isAtMax ? '' : undefined+ }+ hasEntriesOnFocus={isAtMax ? false : hasEntriesOnFocus}+ maxMenuItems={maxMenuItems}+ emptySearchResultsText={emptySearchResultsText}+ isDisabled={isDisabled}+ hasAutoFocus={hasAutoFocus}+ inputId={inputId}+ ariaDescribedBy={ariaDescribedBy}+ onChangeQuery={onChangeQuery}+ debounceMs={debounceMs}+ onKeyDown={handleKeyDown}+ anchorRef={wrapperRef}+ inputXStyle={+ isAtMax+ ? styles.inputAtMax+ : value.length > 0+ ? styles.inputCompact+ : undefined+ }+ />+ {hasClear && value.length > 0 && !isDisabled && (+ <button+ type="button"+ aria-label="Clear all"+ onClick={e => {+ e.stopPropagation();+ handleClearAll();+ }}+ {...stylex.props(styles.clearAllButton)}>+ <XDSIcon icon="close" size="sm" />+ </button>+ )}+ </div>+ </XDSField>+ );+}++XDSTokenizer.displayName = 'XDSTokenizer';diff --git a/packages/core/src/Tokenizer/index.ts b/packages/core/src/Tokenizer/index.tsnew file mode 100644index 0000000000..b7053d4cda--- /dev/null+++ b/packages/core/src/Tokenizer/index.ts@@ -0,0 +1,16 @@+/**+ * @file index.ts+ * @input Tokenizer component+ * @output Exports all Tokenizer module public API+ * @position Entry point for Tokenizer module+ *+ * SYNC: When adding new Tokenizer files, update exports here+ */++export {XDSTokenizer} from './XDSTokenizer';+export type {+ XDSTokenizerProps,+ XDSTokenizerChange,+ XDSTokenizerStatus,+ XDSTokenizerStatusType,+} from './XDSTokenizer';diff --git a/packages/core/src/Typeahead/README.md b/packages/core/src/Typeahead/README.mdnew file mode 100644index 0000000000..b48dfb2ffc--- /dev/null+++ b/packages/core/src/Typeahead/README.md@@ -0,0 +1,80 @@+# /packages/core/src/Typeahead++Searchable dropdown components for single-item selection with keyboard navigation.++<!-- SYNC: When files in this directory change, update this document. -->++## Overview++The Typeahead module provides a search-as-you-type dropdown for selecting items from a data source. It supports:++- **Async and sync search** via a `searchSource` interface+- **Keyboard navigation** (arrow keys, Enter, Escape)+- **Bootstrap results** shown on focus before typing+- **Custom item rendering** for rich dropdown content+- **Combobox ARIA pattern** for full accessibility++## Import++```tsx+import {XDSTypeahead} from '@xds/core/Typeahead';+```++## Components++### XDSTypeahead++Styled typeahead with label, description, validation, and all field features. This is the primary component for most use cases.++```tsx+const source = {+ search: query => fruits.filter(f => f.label.includes(query)),+ bootstrap: () => fruits.slice(0, 5),+};++<XDSTypeahead+ label="Fruit"+ searchSource={source}+ value={selected}+ onChange={setSelected}+ placeholder="Search fruits..."+/>;+```++### XDSBaseTypeahead++Unstyled typeahead for custom compositions (used by XDSTypeahead and XDSTokenizer). Provides the combobox input, dropdown, and keyboard handling without any field chrome.++### XDSTypeaheadItem++Default dropdown item renderer. Shows label with optional icon, secondary text, and avatar.++## Search Source Interface++```tsx+type XDSSearchSource<T> = {+ search: (query: string) => T[] | Promise<T[]>;+ bootstrap?: () => T[] | Promise<T[]>;+};++type XDSSearchableItem = {+ id: string;+ label: string;+ [key: string]: unknown;+};+```++## Key Props++| Prop | Type | Default | Description |+| ------------------- | --------------------------- | -------- | ------------------------------- |+| `label` | `string` | required | Accessible label |+| `searchSource` | `XDSSearchSource` | required | Data source |+| `value` | `T \| null` | required | Selected item |+| `onChange` | `(item: T \| null) => void` | required | Selection callback |+| `placeholder` | `string` | — | Input placeholder |+| `hasEntriesOnFocus` | `boolean` | `false` | Show bootstrap results on focus |+| `hasClear` | `boolean` | `true` | Show clear button |+| `isDisabled` | `boolean` | `false` | Disable input |+| `maxMenuItems` | `number` | `10` | Max dropdown items |+| `status` | `XDSInputStatus` | — | Validation status |diff --git a/packages/core/src/Typeahead/XDSBaseTypeahead.tsx b/packages/core/src/Typeahead/XDSBaseTypeahead.tsxnew file mode 100644index 0000000000..24fc8ff665--- /dev/null+++ b/packages/core/src/Typeahead/XDSBaseTypeahead.tsx@@ -0,0 +1,624 @@+/**+ * @file XDSBaseTypeahead.tsx+ * @input Uses React, StyleX, useXDSLayer, XDSTypeaheadItem+ * @output Exports XDSBaseTypeahead combobox engine component+ * @position Core implementation; used by XDSTypeahead and XDSTokenizer+ *+ * Pure combobox engine: input, search, keyboard navigation, dropdown.+ * No wrapper div, no border styling, no token rendering.+ * Consumers provide their own wrapper and pass anchorRef for dropdown positioning.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Typeahead/README.md+ * - /packages/core/src/Typeahead/index.ts+ */++import React, {+ forwardRef,+ useCallback,+ useEffect,+ useId,+ useRef,+ useState,+ type ReactNode,+ type RefObject,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {StyleXStyles} from '@stylexjs/stylex';+import {useXDSLayer} from '../Layer/useXDSLayer';+import {XDSTypeaheadItem} from './XDSTypeaheadItem';+import {XDSIcon} from '../Icon';+import {+ colorVars,+ spacingVars,+ radiusVars,+ textSizeVars,+ lineHeightVars,+ typographyVars,+ fontWeightVars,+} from '../theme/tokens.stylex';+import type {XDSSearchableItem, XDSSearchSource} from './types';++// =============================================================================+// Types+// =============================================================================++export interface XDSBaseTypeaheadProps<T extends XDSSearchableItem> {+ /**+ * Search source providing items.+ */+ searchSource: XDSSearchSource<T>;++ /**+ * Currently selected item (null = nothing selected).+ */+ value: T | null;++ /**+ * Callback when selection changes.+ */+ onChange: (item: T | null) => void;++ /**+ * Render function for dropdown items. Default: XDSTypeaheadItem.+ */+ renderItem?: (item: T) => ReactNode;++ /**+ * Placeholder text.+ */+ placeholder?: string;++ /**+ * Show results on focus before typing.+ * @default false+ */+ hasEntriesOnFocus?: boolean;++ /**+ * Max dropdown items to display.+ * @default 10+ */+ maxMenuItems?: number;++ /**+ * Text shown when no results found.+ * @default 'No results found'+ */+ emptySearchResultsText?: string;++ /**+ * Whether the input is disabled.+ * @default false+ */+ isDisabled?: boolean;++ /**+ * Auto-focus on mount.+ * @default false+ */+ hasAutoFocus?: boolean;++ /**+ * Query change callback (for logging/external use).+ */+ onChangeQuery?: (query: string) => void;++ /**+ * Callback when dropdown opens/closes.+ */+ onOpenChange?: (isOpen: boolean) => void;++ /**+ * Debounce delay in ms before triggering search after typing.+ * Set to 0 for synchronous/local search sources that don't need debouncing.+ * @default 150+ */+ debounceMs?: number;++ /**+ * ID for the input element (for label association).+ */+ inputId?: string;++ /**+ * Additional aria-describedby IDs.+ */+ ariaDescribedBy?: string;++ /**+ * Additional StyleX styles for the input element.+ */+ inputXStyle?: StyleXStyles;++ /**+ * Ref to the anchor element for dropdown positioning.+ * The dropdown will be positioned relative to this element.+ * If not provided, the input itself is used as the anchor.+ */+ anchorRef?: RefObject<HTMLElement | null>;++ /**+ * Additional keydown handler called before internal keyboard navigation.+ * If the handler calls `e.preventDefault()`, internal handling is skipped.+ */+ onKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>) => void;+}++// =============================================================================+// Styles+// =============================================================================++const styles = stylex.create({+ input: {+ display: 'block',+ flex: 1,+ minWidth: '60px',+ borderWidth: 0,+ borderStyle: 'none',+ padding: 0,+ fontFamily: typographyVars['--font-body'],+ fontSize: textSizeVars['--text-base'],+ lineHeight: lineHeightVars['--leading-base'],+ color: colorVars['--color-text-primary'],+ backgroundColor: 'transparent',+ outline: 'none',+ '::placeholder': {+ color: colorVars['--color-text-placeholder'],+ },+ },+ inputDisabled: {+ cursor: 'not-allowed',+ },+ 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']}`,+ },+ popover: {+ minWidth: 'anchor-size(width)',+ },+ popoverGap: {+ marginBlockStart: spacingVars['--spacing-1'],+ marginBlockEnd: spacingVars['--spacing-1'],+ },+ item: {+ boxSizing: 'border-box',+ display: 'flex',+ alignItems: 'center',+ width: '100%',+ padding: spacingVars['--spacing-2'],+ borderRadius: radiusVars['--radius-content'],+ cursor: 'pointer',+ outline: 'none',+ backgroundColor: 'transparent',+ border: 'none',+ textAlign: 'left',+ },+ itemHighlighted: {+ backgroundColor: colorVars['--color-hover-overlay'],+ },+ itemSelected: {+ fontWeight: fontWeightVars['--font-weight-medium'],+ },+ itemContent: {+ display: 'flex',+ flex: 1,+ minWidth: 0,+ },+ emptyState: {+ padding: spacingVars['--spacing-3'],+ textAlign: 'center',+ fontSize: textSizeVars['--text-sm'],+ color: colorVars['--color-text-secondary'],+ },+ loadingSpinner: {+ display: 'inline-flex',+ alignItems: 'center',+ justifyContent: 'center',+ padding: spacingVars['--spacing-1'],+ },+});++// =============================================================================+// Component+// =============================================================================++/**+ * Combobox engine: input, search, keyboard navigation, and dropdown.+ *+ * Renders only the `<input>` and the dropdown popover. No wrapper div,+ * no border styling, no token rendering. Consumers (XDSTypeahead,+ * XDSTokenizer) provide their own wrapper and pass `anchorRef` for+ * dropdown positioning.+ *+ * @example+ * ```+ * <XDSBaseTypeahead+ * searchSource={source}+ * value={selected}+ * onChange={setSelected}+ * anchorRef={wrapperRef}+ * placeholder="Search..."+ * />+ * ```+ */+export const XDSBaseTypeahead = forwardRef(function XDSBaseTypeahead<+ T extends XDSSearchableItem,+>(+ {+ searchSource,+ value,+ onChange,+ renderItem,+ placeholder = 'Search...',+ hasEntriesOnFocus = false,+ maxMenuItems = 10,+ emptySearchResultsText = 'No results found',+ isDisabled = false,+ hasAutoFocus = false,+ onChangeQuery,+ onOpenChange,+ inputId: externalInputId,+ ariaDescribedBy,+ inputXStyle,+ anchorRef,+ onKeyDown: externalOnKeyDown,+ debounceMs = 150,+ }: XDSBaseTypeaheadProps<T>,+ ref: React.ForwardedRef<HTMLInputElement>,+) {+ const generatedId = useId();+ const inputId = externalInputId ?? generatedId;+ const listboxId = useId();++ const inputRef = useRef<HTMLInputElement>(null);+ const fallbackAnchorRef = useRef<HTMLInputElement>(null);++ const [query, setQuery] = useState('');+ const [results, setResults] = useState<T[]>([]);+ const [highlightedIndex, setHighlightedIndex] = useState(-1);+ const [isLoading, setIsLoading] = useState(false);+ const [hasSearched, setHasSearched] = useState(false);++ // Debounce ref+ const searchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ // Layer for dropdown+ const layer = useXDSLayer({+ mode: 'context',+ lightDismiss: true,+ onShow: () => onOpenChange?.(true),+ onHide: () => {+ onOpenChange?.(false);+ setHighlightedIndex(-1);+ searchSource.cancel?.();+ },+ });++ // Merge refs: forward ref + internal ref + fallback anchor ref+ const setInputRef = useCallback(+ (el: HTMLInputElement | null) => {+ (inputRef as React.MutableRefObject<HTMLInputElement | null>).current =+ el;+ (+ fallbackAnchorRef as React.MutableRefObject<HTMLInputElement | null>+ ).current = el;+ if (typeof ref === 'function') {+ ref(el);+ } else if (ref) {+ (ref as React.MutableRefObject<HTMLInputElement | null>).current = el;+ }+ },+ [ref],+ );++ // Set up anchor on the provided anchorRef or fall back to the input itself+ useEffect(() => {+ const el = anchorRef?.current ?? fallbackAnchorRef.current;+ if (el) {+ layer.ref(el);+ }+ return () => {+ layer.ref(null);+ };+ }, [layer, anchorRef]);++ // Perform search+ const performSearch = useCallback(+ async (searchQuery: string) => {+ searchSource.cancel?.();+ setIsLoading(true);+ setHasSearched(true);+ try {+ const searchResults = await searchSource.search(searchQuery);+ setResults(searchResults.slice(0, maxMenuItems));+ setHighlightedIndex(searchResults.length > 0 ? 0 : -1);+ if (searchResults.length > 0 || searchQuery.length > 0) {+ layer.show();+ }+ } catch {+ setResults([]);+ setHighlightedIndex(-1);+ } finally {+ setIsLoading(false);+ }+ },+ [searchSource, maxMenuItems, layer],+ );++ // Perform bootstrap+ const performBootstrap = useCallback(async () => {+ setIsLoading(true);+ try {+ const bootstrapResults = await searchSource.bootstrap();+ setResults(bootstrapResults.slice(0, maxMenuItems));+ setHighlightedIndex(bootstrapResults.length > 0 ? 0 : -1);+ if (bootstrapResults.length > 0) {+ layer.show();+ }+ } catch {+ setResults([]);+ } finally {+ setIsLoading(false);+ }+ }, [searchSource, maxMenuItems, layer]);++ // Handle query change+ const handleQueryChange = useCallback(+ (newQuery: string) => {+ setQuery(newQuery);+ onChangeQuery?.(newQuery);++ if (searchTimeoutRef.current) {+ clearTimeout(searchTimeoutRef.current);+ }++ if (newQuery.length === 0 && !hasEntriesOnFocus) {+ searchSource.cancel?.();+ setResults([]);+ layer.hide();+ return;+ }++ const triggerSearch = () => {+ if (newQuery.length > 0) {+ performSearch(newQuery);+ } else if (hasEntriesOnFocus) {+ performBootstrap();+ }+ };++ if (debounceMs <= 0) {+ triggerSearch();+ } else {+ searchTimeoutRef.current = setTimeout(triggerSearch, debounceMs);+ }+ },+ [+ onChangeQuery,+ hasEntriesOnFocus,+ performSearch,+ performBootstrap,+ layer,+ debounceMs,+ searchSource,+ ],+ );++ // Handle input change+ const handleInputChange = useCallback(+ (e: React.ChangeEvent<HTMLInputElement>) => {+ handleQueryChange(e.target.value);+ },+ [handleQueryChange],+ );++ // Handle item selection+ const handleSelect = useCallback(+ (item: T) => {+ onChange(item);+ setQuery('');+ setResults([]);+ layer.hide();+ inputRef.current?.focus();+ },+ [onChange, layer],+ );++ // Handle focus+ const handleFocus = useCallback(() => {+ if (isDisabled) return;+ if (hasEntriesOnFocus && results.length === 0 && query.length === 0) {+ performBootstrap();+ } else if (query.length > 0 && results.length > 0) {+ layer.show();+ }+ }, [+ isDisabled,+ hasEntriesOnFocus,+ results.length,+ query.length,+ performBootstrap,+ layer,+ ]);++ // Keyboard navigation+ const handleKeyDown = useCallback(+ (e: React.KeyboardEvent<HTMLInputElement>) => {+ externalOnKeyDown?.(e);+ if (e.defaultPrevented) return;++ if (!layer.isOpen) {+ if (e.key === 'ArrowDown' && (hasEntriesOnFocus || query.length > 0)) {+ e.preventDefault();+ if (results.length > 0) {+ layer.show();+ setHighlightedIndex(0);+ } else if (hasEntriesOnFocus) {+ performBootstrap();+ }+ }+ return;+ }++ switch (e.key) {+ case 'ArrowDown':+ e.preventDefault();+ setHighlightedIndex(prev =>+ prev < results.length - 1 ? prev + 1 : 0,+ );+ break;+ case 'ArrowUp':+ e.preventDefault();+ setHighlightedIndex(prev =>+ prev > 0 ? prev - 1 : results.length - 1,+ );+ break;+ case 'Enter':+ e.preventDefault();+ if (highlightedIndex >= 0 && highlightedIndex < results.length) {+ handleSelect(results[highlightedIndex]);+ }+ break;+ case 'Escape':+ e.preventDefault();+ layer.hide();+ break;+ case 'Home':+ if (layer.isOpen) {+ e.preventDefault();+ setHighlightedIndex(0);+ }+ break;+ case 'End':+ if (layer.isOpen) {+ e.preventDefault();+ setHighlightedIndex(results.length - 1);+ }+ break;+ }+ },+ [+ layer,+ results,+ highlightedIndex,+ handleSelect,+ hasEntriesOnFocus,+ query.length,+ performBootstrap,+ externalOnKeyDown,+ ],+ );++ // Generate item ID for accessibility+ const getItemId = useCallback(+ (index: number) => `${listboxId}-option-${index}`,+ [listboxId],+ );++ // Cleanup timeout and cancel in-flight searches on unmount+ useEffect(() => {+ return () => {+ if (searchTimeoutRef.current) {+ clearTimeout(searchTimeoutRef.current);+ }+ searchSource.cancel?.();+ };+ }, [searchSource]);++ return (+ <>+ <input+ ref={setInputRef}+ id={inputId}+ type="text"+ role="combobox"+ aria-expanded={layer.isOpen}+ aria-controls={listboxId}+ aria-activedescendant={+ layer.isOpen && highlightedIndex >= 0+ ? getItemId(highlightedIndex)+ : undefined+ }+ aria-autocomplete="list"+ aria-describedby={ariaDescribedBy}+ value={query}+ onChange={handleInputChange}+ onFocus={handleFocus}+ onKeyDown={handleKeyDown}+ placeholder={placeholder}+ disabled={isDisabled}+ autoFocus={hasAutoFocus}+ autoComplete="off"+ {...stylex.props(+ styles.input,+ isDisabled && styles.inputDisabled,+ inputXStyle,+ )}+ />+ {isLoading && (+ <span+ role="status"+ aria-label="Loading"+ {...stylex.props(styles.loadingSpinner)}>+ <XDSIcon icon="clock" size="sm" color="secondary" />+ </span>+ )}++ {layer.render(+ <div+ id={listboxId}+ role="listbox"+ aria-label="Search results"+ {...stylex.props(styles.dropdown)}>+ {results.length === 0 && hasSearched ? (+ <div {...stylex.props(styles.emptyState)}>+ {emptySearchResultsText}+ </div>+ ) : (+ results.map((item, index) => (+ <div+ key={item.id}+ id={getItemId(index)}+ role="option"+ aria-selected={value?.id === item.id}+ tabIndex={-1}+ onClick={() => handleSelect(item)}+ onMouseEnter={() => setHighlightedIndex(index)}+ {...stylex.props(+ styles.item,+ index === highlightedIndex && styles.itemHighlighted,+ value?.id === item.id && styles.itemSelected,+ )}>+ <span {...stylex.props(styles.itemContent)}>+ {renderItem ? (+ renderItem(item)+ ) : (+ <XDSTypeaheadItem item={item} />+ )}+ </span>+ {value?.id === item.id && (+ <XDSIcon icon="check" size="sm" color="accent" />+ )}+ </div>+ ))+ )}+ </div>,+ {+ placement: 'below',+ alignment: 'start',+ xstyle: [styles.popover, styles.popoverGap],+ },+ )}+ </>+ );+}) as <T extends XDSSearchableItem>(+ props: XDSBaseTypeaheadProps<T> & {ref?: React.Ref<HTMLInputElement>},+) => React.ReactElement;++(XDSBaseTypeahead as {displayName?: string}).displayName = 'XDSBaseTypeahead';diff --git a/packages/core/src/Typeahead/XDSTypeahead.test.tsx b/packages/core/src/Typeahead/XDSTypeahead.test.tsxnew file mode 100644index 0000000000..26f54b64d7--- /dev/null+++ b/packages/core/src/Typeahead/XDSTypeahead.test.tsx@@ -0,0 +1,289 @@+/**+ * @file XDSTypeahead.test.tsx+ * @input Uses vitest, @testing-library/react, XDSTypeahead, XDSBaseTypeahead+ * @output Unit tests for Typeahead components+ * @position Testing; validates XDSTypeahead.tsx and XDSBaseTypeahead.tsx+ *+ * SYNC: When Typeahead components change, update tests to match+ */++import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';+import {render, screen, fireEvent, waitFor} from '@testing-library/react';+import {XDSTypeahead} from './XDSTypeahead';+import {XDSBaseTypeahead} from './XDSBaseTypeahead';+import type {XDSSearchSource, XDSSearchableItem} from './types';++// Store original matches to restore later+const originalMatches = HTMLElement.prototype.matches;++// Track popover open state per element+const popoverOpenState = new WeakMap<HTMLElement, boolean>();++// Mock Popover API for jsdom+beforeAll(() => {+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {+ popoverOpenState.set(this, true);+ const event = new Event('toggle');+ Object.defineProperty(event, 'newState', {value: 'open'});+ this.dispatchEvent(event);+ });+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {+ popoverOpenState.set(this, false);+ const event = new Event('toggle');+ Object.defineProperty(event, 'newState', {value: 'closed'});+ this.dispatchEvent(event);+ });++ HTMLElement.prototype.matches = function (selector: string) {+ if (selector === ':popover-open') {+ return popoverOpenState.get(this) ?? false;+ }+ return originalMatches.call(this, selector);+ };+});++afterAll(() => {+ HTMLElement.prototype.matches = originalMatches;+});++// Test data+const fruits: XDSSearchableItem[] = [+ {id: '1', label: 'Apple'},+ {id: '2', label: 'Banana'},+ {id: '3', label: 'Cherry'},+ {id: '4', label: 'Date'},+ {id: '5', label: 'Elderberry'},+];++const fruitSource: XDSSearchSource = {+ search: (query: string) =>+ fruits.filter(f => f.label.toLowerCase().includes(query.toLowerCase())),+ bootstrap: () => fruits.slice(0, 3),+};++describe('XDSBaseTypeahead', () => {+ it('renders input with combobox role', () => {+ render(+ <XDSBaseTypeahead+ searchSource={fruitSource}+ value={null}+ onChange={() => {}}+ />,+ );+ expect(screen.getByRole('combobox')).toBeInTheDocument();+ });++ it('renders placeholder text', () => {+ render(+ <XDSBaseTypeahead+ searchSource={fruitSource}+ value={null}+ onChange={() => {}}+ placeholder="Pick a fruit..."+ />,+ );+ expect(screen.getByPlaceholderText('Pick a fruit...')).toBeInTheDocument();+ });++ it('sets aria-expanded=false initially', () => {+ render(+ <XDSBaseTypeahead+ searchSource={fruitSource}+ value={null}+ onChange={() => {}}+ />,+ );+ expect(screen.getByRole('combobox')).toHaveAttribute(+ 'aria-expanded',+ 'false',+ );+ });++ it('shows results on input change', async () => {+ render(+ <XDSBaseTypeahead+ searchSource={fruitSource}+ value={null}+ onChange={() => {}}+ />,+ );+ const input = screen.getByRole('combobox');+ fireEvent.change(input, {target: {value: 'App'}});++ await waitFor(() => {+ expect(screen.getByRole('listbox', {hidden: true})).toBeInTheDocument();+ });+ });++ it('disables input when isDisabled', () => {+ render(+ <XDSBaseTypeahead+ searchSource={fruitSource}+ value={null}+ onChange={() => {}}+ isDisabled+ />,+ );+ expect(screen.getByRole('combobox')).toBeDisabled();+ });++ it('uses anchorRef for dropdown positioning', () => {+ const anchorRef = {current: document.createElement('div')};+ render(+ <XDSBaseTypeahead+ searchSource={fruitSource}+ value={null}+ onChange={() => {}}+ anchorRef={anchorRef}+ />,+ );+ // Component renders without error — anchor is wired up internally+ expect(screen.getByRole('combobox')).toBeInTheDocument();+ });+});++describe('XDSTypeahead', () => {+ it('renders with label', () => {+ render(+ <XDSTypeahead+ label="Fruit"+ searchSource={fruitSource}+ value={null}+ onChange={() => {}}+ />,+ );+ expect(screen.getByLabelText('Fruit')).toBeInTheDocument();+ });++ it('renders description text', () => {+ render(+ <XDSTypeahead+ label="Fruit"+ description="Pick your favorite fruit"+ searchSource={fruitSource}+ value={null}+ onChange={() => {}}+ />,+ );+ expect(screen.getByText('Pick your favorite fruit')).toBeInTheDocument();+ });++ it('shows required indicator', () => {+ render(+ <XDSTypeahead+ label="Fruit"+ isRequired+ searchSource={fruitSource}+ value={null}+ onChange={() => {}}+ />,+ );+ expect(screen.getByText(/Required/)).toBeInTheDocument();+ });++ it('renders error status message', () => {+ render(+ <XDSTypeahead+ label="Fruit"+ searchSource={fruitSource}+ value={null}+ onChange={() => {}}+ status={{type: 'error', message: 'Selection required'}}+ />,+ );+ expect(screen.getByText('Selection required')).toBeInTheDocument();+ });++ it('shows selected value as a token with remove button', () => {+ render(+ <XDSTypeahead+ label="Fruit"+ searchSource={fruitSource}+ value={fruits[0]}+ onChange={() => {}}+ />,+ );+ expect(+ screen.getByRole('button', {name: `Remove ${fruits[0].label}`}),+ ).toBeInTheDocument();+ });++ it('calls onChange with null when token remove is clicked', () => {+ const onChange = vi.fn();+ render(+ <XDSTypeahead+ label="Fruit"+ searchSource={fruitSource}+ value={fruits[0]}+ onChange={onChange}+ />,+ );+ fireEvent.click(+ screen.getByRole('button', {name: `Remove ${fruits[0].label}`}),+ );+ expect(onChange).toHaveBeenCalledWith(null);+ });++ it('renders with data-testid', () => {+ render(+ <XDSTypeahead+ label="Fruit"+ searchSource={fruitSource}+ value={null}+ onChange={() => {}}+ data-testid="my-typeahead"+ />,+ );+ expect(screen.getByTestId('my-typeahead')).toBeInTheDocument();+ });+});++describe('XDSTypeahead edit mode', () => {+ it('enters edit mode on token container click', () => {+ const onChange = vi.fn();+ render(+ <XDSTypeahead+ label="Fruit"+ searchSource={fruitSource}+ value={fruits[0]}+ onChange={onChange}+ />,+ );+ const input = screen.getByRole('combobox');++ // Click the token area to enter edit mode+ const removeButton = screen.getByRole('button', {+ name: `Remove ${fruits[0].label}`,+ });+ const tokenContainer = removeButton.closest('div')!;+ fireEvent.click(tokenContainer);++ // onChange should NOT have been called (value is preserved for restore)+ expect(onChange).not.toHaveBeenCalled();+ });++ it('restores token on blur without action', async () => {+ const onChange = vi.fn();+ render(+ <XDSTypeahead+ label="Fruit"+ searchSource={fruitSource}+ value={fruits[0]}+ onChange={onChange}+ />,+ );+ const input = screen.getByRole('combobox');++ // Enter edit mode+ const removeButton = screen.getByRole('button', {+ name: `Remove ${fruits[0].label}`,+ });+ fireEvent.click(removeButton.closest('div')!);++ // Blur without selecting anything+ fireEvent.blur(input);++ // onChange should not have been called — value restored+ expect(onChange).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/Typeahead/XDSTypeahead.tsx b/packages/core/src/Typeahead/XDSTypeahead.tsxnew file mode 100644index 0000000000..4ea4be842d--- /dev/null+++ b/packages/core/src/Typeahead/XDSTypeahead.tsx@@ -0,0 +1,491 @@+/**+ * @file XDSTypeahead.tsx+ * @input Uses React, XDSBaseTypeahead, XDSField, XDSToken+ * @output Exports XDSTypeahead styled typeahead component+ * @position Styled wrapper; composes XDSBaseTypeahead with XDSField+ *+ * Owns the input wrapper (border, padding, status styles), selected value+ * token with spacing compensation, and edit mode behavior. Delegates+ * search, keyboard navigation, and dropdown to XDSBaseTypeahead.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Typeahead/README.md+ * - /packages/core/src/Typeahead/index.ts+ * - /apps/storybook/stories/Typeahead.stories.tsx+ */++import React, {useCallback, useId, useRef, useState} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {StyleXStyles} from '@stylexjs/stylex';+import {XDSBaseTypeahead} from './XDSBaseTypeahead';+import {XDSField, type XDSInputStatus} from '../Field';+import {XDSToken} from '../Token';+import {XDSIcon} from '../Icon';+import {+ colorVars,+ spacingVars,+ radiusVars,+ sizeVars,+ transitionVars,+ elevationVars,+} from '../theme/tokens.stylex';+import type {XDSSearchableItem, XDSSearchSource} from './types';+import type {ReactNode} from 'react';++export type {+ XDSInputStatus as XDSTypeaheadStatus,+ XDSInputStatusType as XDSTypeaheadStatusType,+} from '../Field';++export interface XDSTypeaheadProps<T extends XDSSearchableItem> {+ /** Accessible label (required). */+ label: string;+ /** Visually hide the label. @default false */+ isLabelHidden?: boolean;+ /** Helper text. */+ description?: string;+ /** Required field. @default false */+ isRequired?: boolean;+ /** Optional field. @default false */+ isOptional?: boolean;+ /** Validation status. */+ status?: XDSInputStatus;+ /** Label tooltip. */+ labelTooltip?: string;+ /** Search source providing items. */+ searchSource: XDSSearchSource<T>;+ /** Currently selected item (null = nothing selected). */+ value: T | null;+ /** Callback when selection changes. */+ onChange: (item: T | null) => void;+ /** Render function for dropdown items. Default: XDSTypeaheadItem. */+ renderItem?: (item: T) => ReactNode;+ /** Placeholder text. */+ placeholder?: string;+ /** Show results on focus before typing. @default false */+ hasEntriesOnFocus?: boolean;+ /** Max dropdown items. @default 10 */+ maxMenuItems?: number;+ /** Text shown when no results found. @default 'No results found' */+ emptySearchResultsText?: string;+ /** Whether the input is disabled. @default false */+ isDisabled?: boolean;+ /** Show clear button. @default true */+ hasClear?: boolean;+ /** Auto-focus on mount. @default false */+ hasAutoFocus?: boolean;+ /** Input size. @default 'md' */+ size?: 'sm' | 'md';+ /**+ * Debounce delay in ms before triggering search after typing.+ * Set to 0 for synchronous/local search sources that don't need debouncing.+ * @default 150+ */+ debounceMs?: number;+ /** Query change callback. */+ onChangeQuery?: (query: string) => void;+ /** Callback when dropdown opens/closes. */+ onOpenChange?: (isOpen: boolean) => void;+ /** StyleX overrides. */+ xstyle?: StyleXStyles;+ /** Test ID. */+ 'data-testid'?: string;+}++// =============================================================================+// Styles+// =============================================================================++const styles = stylex.create({+ wrapper: {+ boxSizing: 'border-box',+ position: 'relative',+ display: 'flex',+ alignItems: 'center',+ flexWrap: 'wrap',+ gap: spacingVars['--spacing-1'],+ // Standard padding minus border width to prevent height jump+ // when a token (28px) is added inside the input+ paddingBlock: `calc(${spacingVars['--spacing-1']} - 1px)`,+ paddingInline: spacingVars['--spacing-2'],+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: {+ default: colorVars['--color-divider-emphasized'],+ ':hover': {+ '@media (hover: hover)': colorVars['--color-divider-high-contrast'],+ },+ },+ borderRadius: radiusVars['--radius-element'],+ backgroundColor: colorVars['--color-surface'],+ transitionProperty: 'border-color, outline, box-shadow',+ transitionDuration: transitionVars['--transition-fast'],+ boxShadow: {+ default: 'none',+ ':hover': {+ '@media (hover: hover)': elevationVars['--elevation-input-hover'],+ },+ },+ outline: {+ default: 'none',+ ':focus-within': `1px solid ${colorVars['--color-focus-outline']}`,+ },+ outlineOffset: '0',+ cursor: 'text',+ },+ wrapperDisabled: {+ cursor: 'not-allowed',+ opacity: 0.5,+ borderColor: colorVars['--color-divider-emphasized'],+ },+ token: {+ // Offset token so it sits 3px from the inner edge (4px from outer edge+ // accounting for 1px border). Default inline padding is 8px, so+ // -(8px - 3px) = -5px positions token equidistant from left edge as top.+ margin: `calc(-1 * (${spacingVars['--spacing-2']} - ${spacingVars['--spacing-1']} + 1px))`,+ },+ clearButton: {+ all: 'unset',+ display: 'inline-flex',+ alignItems: 'center',+ justifyContent: 'center',+ cursor: 'pointer',+ padding: spacingVars['--spacing-1'],+ borderRadius: radiusVars['--radius-rounded'],+ color: colorVars['--color-text-secondary'],+ opacity: {+ default: 0.7,+ ':hover': {+ '@media (hover: hover)': 1,+ },+ },+ },+ sizeSmWrapper: {+ minHeight: sizeVars['--size-sm'],+ },+ sizeMdWrapper: {+ minHeight: sizeVars['--size-md'],+ },+ inputHidden: {+ width: 0,+ minWidth: 0,+ flex: '0 0 0',+ padding: 0,+ opacity: 0,+ position: 'absolute' as const,+ },+});++const statusBorderStyles = stylex.create({+ warning: {+ borderColor: colorVars['--color-warning'],+ },+ error: {+ borderColor: colorVars['--color-negative'],+ },+ success: {+ borderColor: colorVars['--color-positive'],+ },+});++const statusHoverShadowStyles = stylex.create({+ warning: {+ boxShadow: {+ default: 'none',+ ':hover': {+ '@media (hover: hover)':+ elevationVars['--elevation-input-hover-warning'],+ },+ },+ },+ error: {+ boxShadow: {+ default: 'none',+ ':hover': {+ '@media (hover: hover)': elevationVars['--elevation-input-hover-error'],+ },+ },+ },+ success: {+ boxShadow: {+ default: 'none',+ ':hover': {+ '@media (hover: hover)':+ elevationVars['--elevation-input-hover-success'],+ },+ },+ },+});++const statusFocusStyles = stylex.create({+ warning: {+ outline: {+ default: 'none',+ ':focus-within': `1px solid ${colorVars['--color-focus-outline-warning']}`,+ },+ },+ error: {+ outline: {+ default: 'none',+ ':focus-within': `1px solid ${colorVars['--color-focus-outline-error']}`,+ },+ },+ success: {+ outline: {+ default: 'none',+ ':focus-within': `1px solid ${colorVars['--color-focus-outline-success']}`,+ },+ },+});++// =============================================================================+// Component+// =============================================================================++/**+ * A search-as-you-type component for selecting an item from a search source.+ *+ * Wraps XDSBaseTypeahead with XDSField for label, description, and status.+ * Owns the input wrapper styling, selected value token, and edit mode.+ *+ * Edit mode: clicking the token or input area removes the token, populates+ * the input with the value's label, and selects all text. Blurring without+ * selecting restores the original token. Escape also restores.+ *+ * @example+ * ```+ * <XDSTypeahead+ * label="Assignee"+ * searchSource={userSource}+ * value={assignee}+ * onChange={setAssignee}+ * placeholder="Search users..."+ * />+ * ```+ */+export function XDSTypeahead<T extends XDSSearchableItem>({+ label,+ isLabelHidden = false,+ description,+ isRequired = false,+ isOptional = false,+ status,+ labelTooltip,+ searchSource,+ value,+ onChange,+ renderItem,+ placeholder,+ hasEntriesOnFocus,+ maxMenuItems,+ emptySearchResultsText,+ isDisabled = false,+ hasClear = true,+ hasAutoFocus,+ size = 'md',+ debounceMs,+ onChangeQuery,+ onOpenChange,+ xstyle,+ 'data-testid': testId,+}: XDSTypeaheadProps<T>) {+ const inputId = useId();+ const descriptionId = useId();+ const statusMessageId = useId();++ const wrapperRef = useRef<HTMLDivElement>(null);+ const inputRef = useRef<HTMLInputElement>(null);+ const tokenRef = useRef<HTMLElement>(null);++ // Edit mode: when the user clicks the token to edit the selected value+ const [isEditing, setIsEditing] = useState(false);+ const [editingValue, setEditingValue] = useState<T | null>(null);++ // Show token when value is selected and not in edit mode+ const showToken = value != null && !isEditing;++ // Enter edit mode: remove token visually, populate input with value label+ const handleEnterEditMode = useCallback(() => {+ if (isDisabled || !value) return;+ setEditingValue(value);+ setIsEditing(true);+ // The base will receive onChangeQuery with the value's label+ onChangeQuery?.(value.label);+ requestAnimationFrame(() => {+ const input = inputRef.current;+ if (input) {+ // Set the input value directly since the base manages its own query state+ // We trigger a synthetic change to sync the base's internal state+ const nativeInputValueSetter = Object.getOwnPropertyDescriptor(+ window.HTMLInputElement.prototype,+ 'value',+ )?.set;+ nativeInputValueSetter?.call(input, value.label);+ input.dispatchEvent(new Event('input', {bubbles: true}));+ input.focus();+ input.setSelectionRange(0, input.value.length);+ }+ });+ }, [isDisabled, value, onChangeQuery]);++ // Handle blur: restore token if editing and no selection was made+ const handleBlur = useCallback(+ (e: React.FocusEvent) => {+ // Don't restore if focus is moving within the wrapper (e.g. to dropdown)+ if (wrapperRef.current?.contains(e.relatedTarget as Node)) return;++ if (editingValue && isEditing) {+ setIsEditing(false);+ setEditingValue(null);+ // Value was never cleared from parent, so no onChange needed+ }+ },+ [editingValue, isEditing],+ );++ // Handle selection from dropdown — clears edit mode+ const handleChange = useCallback(+ (item: T | null) => {+ setIsEditing(false);+ setEditingValue(null);+ onChange(item);+ // After selection, focus the token so keyboard users stay in the component.+ // Use requestAnimationFrame because the token renders on the next cycle.+ if (item) {+ requestAnimationFrame(() => {+ const tokenEl = tokenRef.current;+ if (tokenEl) {+ // Focus the internal button inside the token+ const button = tokenEl.querySelector('button');+ (button ?? tokenEl).focus();+ }+ });+ }+ },+ [onChange],+ );++ // Handle clear (explicit X button on token)+ const handleClear = useCallback(() => {+ setIsEditing(false);+ setEditingValue(null);+ onChange(null);+ inputRef.current?.focus();+ }, [onChange]);++ // Handle Escape during edit mode — restore token+ const handleKeyDown = useCallback(+ (e: React.KeyboardEvent<HTMLInputElement>) => {+ if (e.key === 'Escape' && editingValue) {+ e.preventDefault();+ setIsEditing(false);+ setEditingValue(null);+ inputRef.current?.blur();+ }+ },+ [editingValue],+ );++ // Click wrapper to focus input or enter edit mode+ const handleWrapperClick = useCallback(() => {+ if (isDisabled) return;+ if (showToken) {+ handleEnterEditMode();+ } else {+ inputRef.current?.focus();+ }+ }, [isDisabled, showToken, handleEnterEditMode]);++ const ariaDescribedBy =+ [+ description ? descriptionId : null,+ status?.message ? statusMessageId : null,+ ]+ .filter(Boolean)+ .join(' ') || undefined;++ const sizeStyle = size === 'sm' ? styles.sizeSmWrapper : styles.sizeMdWrapper;++ return (+ <XDSField+ label={label}+ isLabelHidden={isLabelHidden}+ description={description}+ inputID={inputId}+ descriptionID={description ? descriptionId : undefined}+ isOptional={isOptional}+ isRequired={isRequired}+ status={+ status+ ? {+ type: status.type,+ message: status.message,+ messageID: status.message ? statusMessageId : undefined,+ }+ : undefined+ }+ labelTooltip={labelTooltip}>+ <div+ ref={wrapperRef}+ data-testid={testId}+ onClick={handleWrapperClick}+ onBlur={handleBlur}+ {...stylex.props(+ styles.wrapper,+ sizeStyle,+ status && statusBorderStyles[status.type],+ status && statusHoverShadowStyles[status.type],+ status && statusFocusStyles[status.type],+ isDisabled && styles.wrapperDisabled,+ xstyle,+ )}>+ {showToken && (+ <XDSToken+ ref={tokenRef}+ label={value.label}+ size={size}+ onClick={handleEnterEditMode}+ onRemove={hasClear && !isDisabled ? handleClear : undefined}+ isDisabled={isDisabled}+ xstyle={styles.token}+ />+ )}+ <XDSBaseTypeahead+ ref={inputRef}+ searchSource={searchSource}+ value={value}+ onChange={handleChange}+ renderItem={renderItem}+ placeholder={showToken ? undefined : placeholder}+ hasEntriesOnFocus={hasEntriesOnFocus}+ maxMenuItems={maxMenuItems}+ emptySearchResultsText={emptySearchResultsText}+ isDisabled={isDisabled}+ hasAutoFocus={hasAutoFocus}+ inputId={inputId}+ ariaDescribedBy={ariaDescribedBy}+ onChangeQuery={onChangeQuery}+ onOpenChange={onOpenChange}+ debounceMs={debounceMs}+ anchorRef={wrapperRef}+ onKeyDown={handleKeyDown}+ inputXStyle={showToken ? styles.inputHidden : undefined}+ />+ {hasClear && value && !isDisabled && isEditing && (+ <button+ type="button"+ aria-label="Clear selection"+ onClick={e => {+ e.stopPropagation();+ handleClear();+ }}+ {...stylex.props(styles.clearButton)}>+ <XDSIcon icon="close" size="sm" />+ </button>+ )}+ </div>+ </XDSField>+ );+}++XDSTypeahead.displayName = 'XDSTypeahead';diff --git a/packages/core/src/Typeahead/XDSTypeaheadItem.tsx b/packages/core/src/Typeahead/XDSTypeaheadItem.tsxnew file mode 100644index 0000000000..cbd0011250--- /dev/null+++ b/packages/core/src/Typeahead/XDSTypeaheadItem.tsx@@ -0,0 +1,151 @@+/**+ * @file XDSTypeaheadItem.tsx+ * @input Uses React, StyleX, XDSSearchableItem+ * @output Exports XDSTypeaheadItem component for rendering dropdown items+ * @position Presentational component; used as default renderItem in XDSBaseTypeahead+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Typeahead/README.md+ * - /packages/core/src/Typeahead/index.ts+ */++import type {ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ colorVars,+ spacingVars,+ textSizeVars,+ lineHeightVars,+ fontWeightVars,+} from '../theme/tokens.stylex';+import type {XDSSearchableItem} from './types';++// =============================================================================+// Types+// =============================================================================++export interface XDSTypeaheadItemProps<+ T extends XDSSearchableItem = XDSSearchableItem,+> {+ /**+ * The search result item.+ */+ item: T;++ /**+ * Icon or avatar to display before the label.+ */+ icon?: ReactNode;++ /**+ * Description text displayed below the label.+ */+ description?: string;++ /**+ * Whether this item is disabled.+ * @default false+ */+ isDisabled?: boolean;++ /**+ * Group label for grouping items visually.+ */+ group?: string;+}++// =============================================================================+// Styles+// =============================================================================++const styles = stylex.create({+ container: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-2'],+ minHeight: 0,+ },+ content: {+ display: 'flex',+ flexDirection: 'column',+ flex: 1,+ minWidth: 0,+ },+ label: {+ fontSize: textSizeVars['--text-base'],+ lineHeight: lineHeightVars['--leading-base'],+ fontWeight: fontWeightVars['--font-weight-normal'],+ color: colorVars['--color-text-primary'],+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ description: {+ fontSize: textSizeVars['--text-xsm'],+ lineHeight: lineHeightVars['--leading-snug'],+ color: colorVars['--color-text-secondary'],+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ disabled: {+ opacity: 0.5,+ },+});++// =============================================================================+// Component+// =============================================================================++/**+ * Default item component for typeahead dropdown results.+ *+ * Renders a label with optional icon and description.+ * Exported for use in custom `renderItem` implementations.+ *+ * @example+ * ```tsx+ * // Default usage (automatic)+ * <XDSTypeahead searchSource={source} value={v} onChange={setV} label="Search" />+ *+ * // Custom renderItem using XDSTypeaheadItem+ * <XDSTypeahead+ * searchSource={source}+ * value={v}+ * onChange={setV}+ * label="Search"+ * renderItem={(item) => (+ * <XDSTypeaheadItem+ * item={item}+ * icon={<XDSAvatar src={item.auxiliaryData.avatar} size="sm" />}+ * description={item.auxiliaryData.role}+ * />+ * )}+ * />+ * ```+ */+export function XDSTypeaheadItem<T extends XDSSearchableItem>({+ item,+ icon,+ description,+ isDisabled = false,+}: XDSTypeaheadItemProps<T>) {+ // If item has a pre-rendered element, use it+ if (item.element) {+ return <>{item.element}</>;+ }++ return (+ <div {...stylex.props(styles.container, isDisabled && styles.disabled)}>+ {icon}+ <div {...stylex.props(styles.content)}>+ <span {...stylex.props(styles.label)}>{item.label}</span>+ {description && (+ <span {...stylex.props(styles.description)}>{description}</span>+ )}+ </div>+ </div>+ );+}++XDSTypeaheadItem.displayName = 'XDSTypeaheadItem';diff --git a/packages/core/src/Typeahead/index.ts b/packages/core/src/Typeahead/index.tsnew file mode 100644index 0000000000..d509107f9d--- /dev/null+++ b/packages/core/src/Typeahead/index.ts@@ -0,0 +1,27 @@+/**+ * @file index.ts+ * @input Typeahead components and types+ * @output Exports all Typeahead module public API+ * @position Entry point for Typeahead module+ *+ * SYNC: When adding new Typeahead files, update exports here+ */++// Shared types+export type {XDSSearchableItem, XDSSearchSource} from './types';++// Base (unstyled) typeahead+export {XDSBaseTypeahead} from './XDSBaseTypeahead';+export type {XDSBaseTypeaheadProps} from './XDSBaseTypeahead';++// Styled typeahead+export {XDSTypeahead} from './XDSTypeahead';+export type {+ XDSTypeaheadProps,+ XDSTypeaheadStatus,+ XDSTypeaheadStatusType,+} from './XDSTypeahead';++// Typeahead item+export {XDSTypeaheadItem} from './XDSTypeaheadItem';+export type {XDSTypeaheadItemProps} from './XDSTypeaheadItem';diff --git a/packages/core/src/Typeahead/types.ts b/packages/core/src/Typeahead/types.tsnew file mode 100644index 0000000000..81dd74271d--- /dev/null+++ b/packages/core/src/Typeahead/types.ts@@ -0,0 +1,111 @@+/**+ * @file types.ts+ * @input None+ * @output Exports shared types for Typeahead and Tokenizer components+ * @position Shared type definitions; consumed by XDSBaseTypeahead, XDSTypeahead, XDSTokenizer+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Typeahead/README.md+ * - /packages/core/src/Typeahead/index.ts+ */++import type {ReactNode} from 'react';++/**+ * Minimal item interface for search results.+ * Extend with `auxiliaryData` for custom data per item.+ *+ * @example+ * ```tsx+ * interface UserItem extends XDSSearchableItem<{ avatar: string; role: string }> {}+ *+ * const user: UserItem = {+ * id: '1',+ * label: 'Jane Doe',+ * auxiliaryData: { avatar: '/jane.jpg', role: 'Engineer' },+ * };+ * ```+ */+export interface XDSSearchableItem<TAuxData = unknown> {+ /**+ * Unique identifier for the item.+ */+ id: string;++ /**+ * Display label for the item.+ */+ label: string;++ /**+ * Pre-rendered element for SSR compatibility.+ * When provided, takes priority over `renderItem` and default label rendering.+ */+ element?: ReactNode;++ /**+ * Arbitrary extra data associated with the item.+ * Use generics to type this for your specific use case.+ */+ auxiliaryData?: TAuxData;+}++/**+ * Search source interface for providing items to typeahead components.+ * Supports both synchronous and asynchronous search.+ *+ * @example+ * ```tsx+ * // Sync search source+ * const fruitSource: XDSSearchSource = {+ * search: (query) => fruits.filter(f => f.label.includes(query)),+ * bootstrap: () => fruits.slice(0, 5),+ * };+ *+ * // Async search source with cancel support+ * const userSource: XDSSearchSource<UserItem> = {+ * _controller: null as AbortController | null,+ * cancel() { this._controller?.abort(); },+ * async search(query) {+ * this.cancel();+ * this._controller = new AbortController();+ * const res = await fetch(`/api/users?q=${query}`, {+ * signal: this._controller.signal,+ * });+ * return res.json();+ * },+ * async bootstrap() {+ * const res = await fetch('/api/users/recent');+ * return res.json();+ * },+ * };+ * ```+ */+export interface XDSSearchSource<+ T extends XDSSearchableItem = XDSSearchableItem,+> {+ /**+ * Called on query change. Returns matching items.+ * Can be synchronous or asynchronous.+ *+ * For expensive operations (API calls, large datasets), consider caching+ * results internally to avoid redundant work on repeated queries.+ */+ search(query: string): Promise<T[]> | T[];++ /**+ * Called on init/focus. Returns initial/default items.+ * Can be synchronous or asynchronous.+ */+ bootstrap(): Promise<T[]> | T[];++ /**+ * Cancel any in-flight search. Called when a new search supersedes+ * a previous one, or when the dropdown closes.+ *+ * Useful for aborting network requests (e.g., via `AbortController`).+ * Optional — if not implemented, previous searches simply resolve and+ * their results are discarded.+ */+ cancel?(): void;+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 0a8fa4ad7e..47e747d718 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -8,7 +8,6 @@*/// Components-export * from './Collapsible';export * from './AppShell';export * from './AspectRatio';export * from './Avatar';@@ -43,6 +42,8 @@ export * from './TimeInput';export * from './NumberInput';export * from './Table';export * from './Token';+export * from './Typeahead';+export * from './Tokenizer';export * from './Dialog';export * from './DropdownMenu';export * from './TopNav';