Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

refactor(CommandPalette): searchSource API + createStaticSource (#1034)

Cindy Zhang26d13c0d96fd
diff --git a/apps/storybook/stories/CommandPalette.stories.tsx b/apps/storybook/stories/CommandPalette.stories.tsx
index 35d9a67514..af5c20a624 100644
--- a/apps/storybook/stories/CommandPalette.stories.tsx
+++ b/apps/storybook/stories/CommandPalette.stories.tsx
@@ -1,193 +1,368 @@
-import {useState} from 'react';
+/**
+ * CommandPalette with searchSource API — story sketches
+ *
+ * Progressive disclosure:
+ * 1. No children -> default rendering (label text, auto-groups by auxiliaryData.group)
+ * 2. children render function -> full control over item layout and grouping
+ */
+import {useState, useMemo} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
import {
XDSCommandPalette,
XDSCommandPaletteInput,
- XDSCommandPaletteList,
XDSCommandPaletteItem,
XDSCommandPaletteGroup,
XDSCommandPaletteFooter,
} from '@xds/lab';
import {XDSButton} from '@xds/core/Button';
import {XDSIcon} from '@xds/core/Icon';
-import {XDSDivider} from '@xds/core/Divider';
+import {createStaticSource} from '@xds/core/Typeahead';
+import type {XDSSearchSource, XDSSearchableItem} from '@xds/core/Typeahead';
const meta: Meta<typeof XDSCommandPalette> = {
title: 'Lab/XDSCommandPalette',
component: XDSCommandPalette,
tags: ['autodocs'],
- argTypes: {
- isOpen: {
- control: 'boolean',
- description: 'Whether the command palette is open',
- },
- width: {
- control: 'number',
- description: 'Width of the dialog',
- },
- maxHeight: {
- control: 'number',
- description: 'Maximum height of the dialog',
- },
- label: {
- control: 'text',
- description: 'Accessible label',
- },
- },
};
export default meta;
type Story = StoryObj<typeof XDSCommandPalette>;
-/**
- * Full command palette with context-driven filtering and selection.
- * Type to filter items. Arrow keys to navigate. Enter to select.
- */
+// --- Simplest case ---
+
+/** No children -- default rendering. Each item renders its label. */
export const Default: Story = {
render: function Render() {
const [isOpen, setIsOpen] = useState(false);
+ const source = useMemo(() => createStaticSource([
+ {id: 'home', label: 'Home'},
+ {id: 'settings', label: 'Settings'},
+ {id: 'profile', label: 'Profile'},
+ {id: 'dashboard', label: 'Dashboard'},
+ {id: 'help', label: 'Help'},
+ ]), []);
return (
<>
- <XDSButton
- label="Open Command Palette (or press ⌘K)"
- onClick={() => setIsOpen(true)}
- />
+ <XDSButton label="Open Command Palette" onClick={() => setIsOpen(true)} />
<XDSCommandPalette
isOpen={isOpen}
onOpenChange={setIsOpen}
- onValueChange={value => {
- console.log('Selected:', value);
- }}>
- <XDSCommandPaletteInput placeholder="Type a command..." />
- <XDSDivider />
- <XDSCommandPaletteList>
- <XDSCommandPaletteGroup heading="Navigation">
- <XDSCommandPaletteItem value="Go to Dashboard">
- <XDSIcon icon="home" size="sm" />
- Go to Dashboard
- </XDSCommandPaletteItem>
- <XDSCommandPaletteItem value="Open Settings">
- <XDSIcon icon="settings" size="sm" />
- Open Settings
- </XDSCommandPaletteItem>
- <XDSCommandPaletteItem value="View Profile">
- <XDSIcon icon="user" size="sm" />
- View Profile
- </XDSCommandPaletteItem>
- </XDSCommandPaletteGroup>
- <XDSCommandPaletteGroup heading="Actions">
- <XDSCommandPaletteItem
- value="Toggle Dark Mode"
- keywords={['theme', 'appearance']}>
- Toggle Dark Mode
- </XDSCommandPaletteItem>
- <XDSCommandPaletteItem value="Create New File">
- Create New File
- </XDSCommandPaletteItem>
- <XDSCommandPaletteItem value="Search Files">
- <XDSIcon icon="search" size="sm" />
- Search Files
- </XDSCommandPaletteItem>
- </XDSCommandPaletteGroup>
- </XDSCommandPaletteList>
- <XDSCommandPaletteFooter />
- </XDSCommandPalette>
+ searchSource={source}
+ input={<XDSCommandPaletteInput placeholder="Type a command..." />}
+ footer={<XDSCommandPaletteFooter />}
+ />
</>
);
},
};
+// --- Auto-grouping ---
+
/**
- * Flat list without groups — items filter automatically.
+ * Groups detected automatically from auxiliaryData.group.
+ * Still no children -- the default renderer handles grouping.
*/
-export const FlatList: Story = {
+export const AutoGrouped: Story = {
render: function Render() {
const [isOpen, setIsOpen] = useState(false);
+ const source = useMemo(() => createStaticSource([
+ {id: 'home', label: 'Home', auxiliaryData: {group: 'Navigation'}},
+ {id: 'settings', label: 'Settings', auxiliaryData: {group: 'Navigation'}},
+ {id: 'profile', label: 'Profile', auxiliaryData: {group: 'Navigation'}},
+ {id: 'new-file', label: 'New File', auxiliaryData: {group: 'Actions'}},
+ {id: 'save', label: 'Save', auxiliaryData: {group: 'Actions'}},
+ {id: 'export', label: 'Export', auxiliaryData: {group: 'Actions'}},
+ ]), []);
return (
<>
- <XDSButton label="Open Flat Palette" onClick={() => setIsOpen(true)} />
- <XDSCommandPalette isOpen={isOpen} onOpenChange={setIsOpen}>
- <XDSCommandPaletteInput placeholder="Search..." />
- <XDSDivider />
- <XDSCommandPaletteList>
- <XDSCommandPaletteItem value="Home">Go Home</XDSCommandPaletteItem>
- <XDSCommandPaletteItem value="Settings">
- Settings
- </XDSCommandPaletteItem>
- <XDSCommandPaletteItem value="Disabled Item" isDisabled>
- Disabled Item
- </XDSCommandPaletteItem>
- <XDSCommandPaletteItem value="Profile">
- Profile
- </XDSCommandPaletteItem>
- </XDSCommandPaletteList>
- <XDSCommandPaletteFooter />
+ <XDSButton label="Open Grouped" onClick={() => setIsOpen(true)} />
+ <XDSCommandPalette
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ searchSource={source}
+ input={<XDSCommandPaletteInput placeholder="Search commands..." />}
+ footer={<XDSCommandPaletteFooter />}
+ />
+ </>
+ );
+ },
+};
+
+// --- Keywords ---
+
+/** Type "theme" or "appearance" to find "Toggle Dark Mode". */
+export const WithKeywords: Story = {
+ render: function Render() {
+ const [isOpen, setIsOpen] = useState(false);
+
+ const commands: XDSSearchableItem<{aliases?: string[]}>[] = [
+ {id: 'home', label: 'Home'},
+ {id: 'dark-mode', label: 'Toggle Dark Mode', auxiliaryData: {aliases: ['theme', 'appearance']}},
+ {id: 'font-size', label: 'Change Font Size', auxiliaryData: {aliases: ['text', 'zoom']}},
+ ];
+
+ const source = useMemo(
+ () => createStaticSource(commands, {
+ keywords: (item) => item.auxiliaryData?.aliases ?? [],
+ }),
+ [],
+ );
+
+ return (
+ <>
+ <XDSButton label="Open (try 'theme')" onClick={() => setIsOpen(true)} />
+ <XDSCommandPalette
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ searchSource={source}
+ input={<XDSCommandPaletteInput placeholder="Search..." />}
+ footer={<XDSCommandPaletteFooter />}
+ />
+ </>
+ );
+ },
+};
+
+// --- Custom rendering with groups ---
+
+type CommandItem = XDSSearchableItem<{
+ icon?: string;
+ group?: string;
+ shortcut?: string;
+ keywords?: string[];
+}>;
+
+/** Full control via render function. Groups, icons, shortcuts -- all explicit. */
+export const CustomRendering: Story = {
+ render: function Render() {
+ const [isOpen, setIsOpen] = useState(false);
+
+ const commands: CommandItem[] = [
+ {id: 'dashboard', label: 'Go to Dashboard', auxiliaryData: {icon: 'home', group: 'Navigation'}},
+ {id: 'settings', label: 'Open Settings', auxiliaryData: {icon: 'settings', group: 'Navigation', shortcut: '\u2318,'}},
+ {id: 'profile', label: 'View Profile', auxiliaryData: {icon: 'user', group: 'Navigation'}},
+ {id: 'dark-mode', label: 'Toggle Dark Mode', auxiliaryData: {group: 'Actions', keywords: ['theme', 'appearance']}},
+ {id: 'new-file', label: 'Create New File', auxiliaryData: {group: 'Actions', shortcut: '\u2318N'}},
+ {id: 'search', label: 'Search Files', auxiliaryData: {icon: 'search', group: 'Actions', shortcut: '\u2318P'}},
+ ];
+
+ const source = useMemo(
+ () => createStaticSource(commands, {
+ keywords: (item) => item.auxiliaryData?.keywords ?? [],
+ }),
+ [],
+ );
+
+ return (
+ <>
+ <XDSButton label="Open Rich Palette" onClick={() => setIsOpen(true)} />
+ <XDSCommandPalette
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ searchSource={source}
+ input={<XDSCommandPaletteInput placeholder="Type a command..." />}
+ footer={<XDSCommandPaletteFooter />}>
+ {(items) => {
+ const groups = new Map<string, CommandItem[]>();
+ const ungrouped: CommandItem[] = [];
+
+ for (const item of items as CommandItem[]) {
+ const group = item.auxiliaryData?.group;
+ if (group) {
+ if (!groups.has(group)) groups.set(group, []);
+ groups.get(group)!.push(item);
+ } else {
+ ungrouped.push(item);
+ }
+ }
+
+ return (
+ <>
+ {Array.from(groups.entries()).map(([heading, groupItems]) => (
+ <XDSCommandPaletteGroup key={heading} heading={heading}>
+ {groupItems.map(item => (
+ <XDSCommandPaletteItem
+ key={item.id}
+ value={item.id}
+ onSelect={() => console.log('Selected:', item.id)}>
+ <div style={{display: 'flex', alignItems: 'center', gap: 8, flex: 1}}>
+ {item.auxiliaryData?.icon && (
+ <XDSIcon icon={item.auxiliaryData.icon} size="sm" />
+ )}
+ <span style={{flex: 1}}>{item.label}</span>
+ {item.auxiliaryData?.shortcut && (
+ <span style={{fontSize: 12, opacity: 0.5}}>
+ {item.auxiliaryData.shortcut}
+ </span>
+ )}
+ </div>
+ </XDSCommandPaletteItem>
+ ))}
+ </XDSCommandPaletteGroup>
+ ))}
+ {ungrouped.map(item => (
+ <XDSCommandPaletteItem key={item.id} value={item.id}>
+ {item.label}
+ </XDSCommandPaletteItem>
+ ))}
+ </>
+ );
+ }}
</XDSCommandPalette>
</>
);
},
};
-/**
- * With custom footer content.
- */
-export const CustomFooter: Story = {
+// --- Async search ---
+
+/** Server-side search. Input shows spinner while pending. */
+export const AsyncSearch: Story = {
render: function Render() {
const [isOpen, setIsOpen] = useState(false);
+ const source = useMemo<XDSSearchSource>(() => ({
+ _controller: null as AbortController | null,
+ cancel() { this._controller?.abort(); },
+ async search(query: string) {
+ this.cancel();
+ this._controller = new AbortController();
+ await new Promise(r => setTimeout(r, 300));
+ const all = [
+ {id: 'readme', label: 'README.md'},
+ {id: 'package', label: 'package.json'},
+ {id: 'tsconfig', label: 'tsconfig.json'},
+ {id: 'index', label: 'src/index.ts'},
+ {id: 'app', label: 'src/App.tsx'},
+ ];
+ return all.filter(f => f.label.toLowerCase().includes(query.toLowerCase()));
+ },
+ bootstrap() { return []; },
+ }), []);
+
return (
<>
- <XDSButton label="Open Custom Footer" onClick={() => setIsOpen(true)} />
- <XDSCommandPalette isOpen={isOpen} onOpenChange={setIsOpen}>
- <XDSCommandPaletteInput placeholder="Search..." />
- <XDSDivider />
- <XDSCommandPaletteList>
- <XDSCommandPaletteItem value="Option A">
- Option A
- </XDSCommandPaletteItem>
- <XDSCommandPaletteItem value="Option B">
- Option B
- </XDSCommandPaletteItem>
- </XDSCommandPaletteList>
- <XDSCommandPaletteFooter>
- <span>Tip: Use ⌘K to open this palette</span>
- </XDSCommandPaletteFooter>
+ <XDSButton label="Open File Search" onClick={() => setIsOpen(true)} />
+ <XDSCommandPalette
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ searchSource={source}
+ input={<XDSCommandPaletteInput placeholder="Search files..." />}
+ />
+ </>
+ );
+ },
+};
+
+// --- Hybrid: static + async ---
+
+/** Recent files (static) + project files (API) in one source. */
+export const HybridSearch: Story = {
+ render: function Render() {
+ const [isOpen, setIsOpen] = useState(false);
+
+ const recentFiles: XDSSearchableItem<{recent: boolean}>[] = [
+ {id: 'recent-1', label: 'App.tsx', auxiliaryData: {recent: true}},
+ {id: 'recent-2', label: 'index.ts', auxiliaryData: {recent: true}},
+ ];
+
+ const source = useMemo<XDSSearchSource>(() => ({
+ async search(query: string) {
+ const lower = query.toLowerCase();
+ const matchingRecent = recentFiles.filter(f =>
+ f.label.toLowerCase().includes(lower),
+ );
+ await new Promise(r => setTimeout(r, 200));
+ const apiResults: XDSSearchableItem[] = [
+ {id: 'api-1', label: 'utils/helpers.ts'},
+ {id: 'api-2', label: 'components/Button.tsx'},
+ {id: 'api-3', label: 'hooks/useAuth.ts'},
+ ].filter(f => f.label.toLowerCase().includes(lower));
+ return [...matchingRecent, ...apiResults];
+ },
+ bootstrap() { return recentFiles; },
+ }), []);
+
+ return (
+ <>
+ <XDSButton label="Open File Finder" onClick={() => setIsOpen(true)} />
+ <XDSCommandPalette
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ searchSource={source}
+ input={<XDSCommandPaletteInput placeholder="Search project files..." />}>
+ {(items) => {
+ const recent = items.filter(i => {
+ const aux = i.auxiliaryData as Record<string, unknown> | undefined;
+ return aux?.recent === true;
+ });
+ const other = items.filter(i => {
+ const aux = i.auxiliaryData as Record<string, unknown> | undefined;
+ return aux?.recent !== true;
+ });
+ return (
+ <>
+ {recent.length > 0 && (
+ <XDSCommandPaletteGroup heading="Recent">
+ {recent.map(item => (
+ <XDSCommandPaletteItem key={item.id} value={item.id}>
+ {item.label}
+ </XDSCommandPaletteItem>
+ ))}
+ </XDSCommandPaletteGroup>
+ )}
+ {other.length > 0 && (
+ <XDSCommandPaletteGroup heading="Project">
+ {other.map(item => (
+ <XDSCommandPaletteItem key={item.id} value={item.id}>
+ {item.label}
+ </XDSCommandPaletteItem>
+ ))}
+ </XDSCommandPaletteGroup>
+ )}
+ </>
+ );
+ }}
</XDSCommandPalette>
</>
);
},
};
-/**
- * With external filtering disabled — all items always shown.
- */
-export const UnfilteredList: Story = {
+// --- Picker ---
+
+/** Selection persists across opens. Uses isSelected for visual state. */
+export const Picker: Story = {
render: function Render() {
const [isOpen, setIsOpen] = useState(false);
+ const [theme, setTheme] = useState('light');
+
+ const source = useMemo(() => createStaticSource([
+ {id: 'light', label: 'Light'},
+ {id: 'dark', label: 'Dark'},
+ {id: 'system', label: 'System'},
+ ]), []);
return (
<>
- <XDSButton label="Open Unfiltered" onClick={() => setIsOpen(true)} />
+ <XDSButton label={`Theme: ${theme}`} onClick={() => setIsOpen(true)} />
<XDSCommandPalette
isOpen={isOpen}
onOpenChange={setIsOpen}
- isFiltered={false}>
- <XDSCommandPaletteInput placeholder="Search (no filtering)..." />
- <XDSDivider />
- <XDSCommandPaletteList>
- <XDSCommandPaletteItem value="Always Visible A">
- Always Visible A
- </XDSCommandPaletteItem>
- <XDSCommandPaletteItem value="Always Visible B">
- Always Visible B
- </XDSCommandPaletteItem>
- <XDSCommandPaletteItem value="Always Visible C">
- Always Visible C
+ searchSource={source}
+ value={theme}
+ onValueChange={setTheme}
+ input={<XDSCommandPaletteInput placeholder="Choose theme..." />}>
+ {(items) => items.map(item => (
+ <XDSCommandPaletteItem
+ key={item.id}
+ value={item.id}
+ isSelected={item.id === theme}>
+ {item.label}
</XDSCommandPaletteItem>
- </XDSCommandPaletteList>
- <XDSCommandPaletteFooter />
+ ))}
</XDSCommandPalette>
</>
);
diff --git a/packages/core/src/Typeahead/createStaticSource.ts b/packages/core/src/Typeahead/createStaticSource.ts
new file mode 100644
index 0000000000..52572d1cab
--- /dev/null
+++ b/packages/core/src/Typeahead/createStaticSource.ts
@@ -0,0 +1,79 @@
+/**
+ * @file createStaticSource.ts
+ * @input Array of searchable items, optional config
+ * @output XDSSearchSource that filters items by label and keywords
+ * @position Utility; convenience factory for static search sources
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Typeahead/README.md
+ * - /packages/core/src/Typeahead/index.ts
+ */
+
+import type {XDSSearchableItem, XDSSearchSource} from './types';
+
+export interface CreateStaticSourceOptions {
+ /**
+ * Extract additional search terms from an item.
+ * These are checked alongside the label during search.
+ *
+ * @example
+ * ```tsx
+ * createStaticSource(items, {
+ * keywords: (item) => item.auxiliaryData?.aliases ?? [],
+ * });
+ * ```
+ */
+ keywords?: (item: XDSSearchableItem) => string[];
+}
+
+/**
+ * Create a search source from a static array of items.
+ *
+ * Filters by substring match on `label` and optional keywords.
+ * For anything beyond substring matching (fuzzy, ranked, server-side),
+ * implement `XDSSearchSource` directly.
+ *
+ * @compositionHint Pass the result to `searchSource` on XDSTypeahead,
+ * XDSTokenizer, or XDSCommandPalette.
+ *
+ * @example
+ * ```tsx
+ * // Simple — label-only matching
+ * const source = createStaticSource([
+ * { id: 'home', label: 'Home' },
+ * { id: 'settings', label: 'Settings' },
+ * ]);
+ *
+ * // With keywords — also matches on aliases
+ * const source = createStaticSource(commands, {
+ * keywords: (item) => item.auxiliaryData?.aliases ?? [],
+ * });
+ * ```
+ */
+export function createStaticSource<T extends XDSSearchableItem>(
+ items: T[],
+ options?: CreateStaticSourceOptions,
+): XDSSearchSource<T> {
+ const getKeywords = options?.keywords;
+
+ return {
+ search(query: string): T[] {
+ const lower = query.toLowerCase().trim();
+ if (lower === '') return items;
+
+ return items.filter(item => {
+ if (item.label.toLowerCase().includes(lower)) return true;
+ if (getKeywords) {
+ return getKeywords(item).some(kw =>
+ kw.toLowerCase().includes(lower),
+ );
+ }
+ return false;
+ });
+ },
+
+ bootstrap(): T[] {
+ return items;
+ },
+ };
+}
diff --git a/packages/core/src/Typeahead/index.ts b/packages/core/src/Typeahead/index.ts
index 0855b55c6f..9949832748 100644
--- a/packages/core/src/Typeahead/index.ts
+++ b/packages/core/src/Typeahead/index.ts
@@ -12,6 +12,10 @@
// Shared types
export type {XDSSearchableItem, XDSSearchSource} from './types';
+// Search source utilities
+export {createStaticSource} from './createStaticSource';
+export type {CreateStaticSourceOptions} from './createStaticSource';
+
// Base (unstyled) typeahead
export {XDSBaseTypeahead} from './XDSBaseTypeahead';
export type {XDSBaseTypeaheadProps} from './XDSBaseTypeahead';
diff --git a/packages/lab/src/CommandPalette/CommandPalette.doc.mjs b/packages/lab/src/CommandPalette/CommandPalette.doc.mjs
index 37422d9f83..26e235930f 100644
--- a/packages/lab/src/CommandPalette/CommandPalette.doc.mjs
+++ b/packages/lab/src/CommandPalette/CommandPalette.doc.mjs
@@ -3,31 +3,65 @@
export const docs = {
name: 'CommandPalette',
description:
- 'A modal dialog shell for command palette interfaces. Provides the structural container with composable slots for input, list, and footer areas.',
+ 'A searchSource-driven command palette dialog. Provide a search source, get filtering, keyboard navigation, and selection for free. Uses the same XDSSearchSource interface as XDSTypeahead.',
features: [
- 'Dialog shell: Wraps XDSDialog with command palette defaults (640×480, centered, info purpose)',
- 'Composable slots: Children render as a flex column — input at top, scrollable list in middle, footer at bottom',
- 'Accessible: Uses native <dialog> with aria-label for screen readers',
- 'Keyboard dismissal: Escape key closes the palette (inherited from XDSDialog purpose="info")',
- 'Configurable size: width and maxHeight props for custom dimensions',
+ 'searchSource: Same XDSSearchSource interface as XDSTypeahead — static, async, or hybrid',
+ 'Progressive disclosure: No children = default rendering; children render function = full control',
+ 'Auto-grouping: Items with auxiliaryData.group are auto-grouped in default rendering',
+ 'createStaticSource: Utility for static lists with optional keyword matching',
+ 'Async support: isBusy context signal + spinner in input while search resolves',
+ 'Keyboard navigation: Arrow keys, Enter to select, Escape to close',
+ 'Picker mode: value/onValueChange for persistent selection',
],
examples: [
{
- label: 'Basic command palette',
- code: `import {XDSCommandPalette} from '@xds/core/CommandPalette';
+ label: 'Simplest — default rendering',
+ code: `import {XDSCommandPalette, XDSCommandPaletteInput, XDSCommandPaletteFooter} from '@xds/lab';
+import {createStaticSource} from '@xds/core/Typeahead';
import {useState} from 'react';
+const source = createStaticSource([
+ {id: 'home', label: 'Home'},
+ {id: 'settings', label: 'Settings'},
+]);
+
function Example() {
const [isOpen, setIsOpen] = useState(false);
-
return (
- <XDSCommandPalette isOpen={isOpen} onOpenChange={setIsOpen}>
- <input placeholder="Type a command..." />
- <div>List of commands</div>
- </XDSCommandPalette>
+ <XDSCommandPalette
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ searchSource={source}
+ input={<XDSCommandPaletteInput placeholder="Search..." />}
+ footer={<XDSCommandPaletteFooter />}
+ />
);
}`,
},
+ {
+ label: 'Custom rendering with groups',
+ code: `import {XDSCommandPalette, XDSCommandPaletteInput, XDSCommandPaletteItem, XDSCommandPaletteGroup} from '@xds/lab';
+import {createStaticSource} from '@xds/core/Typeahead';
+
+<XDSCommandPalette
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ searchSource={source}
+ input={<XDSCommandPaletteInput placeholder="Search..." />}>
+ {(items) => {
+ const grouped = items.filter(i => i.auxiliaryData?.group === 'Navigation');
+ return (
+ <XDSCommandPaletteGroup heading="Navigation">
+ {grouped.map(item => (
+ <XDSCommandPaletteItem key={item.id} value={item.id}>
+ {item.label}
+ </XDSCommandPaletteItem>
+ ))}
+ </XDSCommandPaletteGroup>
+ );
+ }}
+</XDSCommandPalette>`,
+ },
],
props: {
isOpen: {
@@ -38,8 +72,32 @@ function Example() {
onOpenChange: {
type: '(isOpen: boolean) => void',
required: true,
- description:
- 'Called when the palette visibility changes. Called with false on Escape or backdrop click.',
+ description: 'Called when the palette visibility changes.',
+ },
+ searchSource: {
+ type: 'XDSSearchSource<T>',
+ required: true,
+ description: 'Search source providing items via search(query) and bootstrap(). Use createStaticSource for static lists.',
+ },
+ input: {
+ type: 'ReactNode',
+ description: 'Input slot — typically XDSCommandPaletteInput.',
+ },
+ footer: {
+ type: 'ReactNode',
+ description: 'Footer slot — typically XDSCommandPaletteFooter.',
+ },
+ children: {
+ type: '(items: T[]) => ReactNode',
+ description: 'Custom render function. When omitted, default rendering is used (label text, auto-grouped by auxiliaryData.group).',
+ },
+ value: {
+ type: 'string',
+ description: 'Controlled selected value for picker mode.',
+ },
+ onValueChange: {
+ type: '(value: string) => void',
+ description: 'Called when the selected value changes.',
},
label: {
type: 'string',
@@ -49,20 +107,12 @@ function Example() {
width: {
type: 'number | string',
default: '640',
- description:
- 'Width of the dialog. Numbers are pixels, strings are CSS values.',
+ description: 'Width of the dialog.',
},
maxHeight: {
type: 'number | string',
default: '480',
- description:
- 'Maximum height of the dialog. Numbers are pixels, strings are CSS values.',
- },
- children: {
- type: 'ReactNode',
- required: true,
- description:
- 'Composable sub-components: input, list, footer, etc.',
+ description: 'Maximum height of the dialog.',
},
},
};
diff --git a/packages/lab/src/CommandPalette/CommandPaletteContext.ts b/packages/lab/src/CommandPalette/CommandPaletteContext.ts
index 68ca67113a..3f95a0ea4e 100644
--- a/packages/lab/src/CommandPalette/CommandPaletteContext.ts
+++ b/packages/lab/src/CommandPalette/CommandPaletteContext.ts
@@ -6,7 +6,7 @@
*/
import {createContext, useContext} from 'react';
-import type {CommandPaletteFilterFn} from './types';
+import type {XDSSearchableItem} from '@xds/core/Typeahead';
export interface CommandPaletteContextValue {
/** Current search query. */
@@ -17,24 +17,28 @@ export interface CommandPaletteContextValue {
value: string;
/** Update the selected value. */
setValue: (value: string) => void;
- /** Filter function. */
- filter: CommandPaletteFilterFn;
- /** Whether built-in filtering is enabled. */
- isFiltered: boolean;
- /** Unique ID prefix for ARIA. */
+ /** Unique ID prefix for ARIA (listbox id). */
listId: string;
- /** Index of the currently highlighted item. */
+ /** Index-based highlight from useCombobox. -1 = none. */
highlightedIndex: number;
/** Update highlighted index. */
setHighlightedIndex: (index: number) => void;
- /** All registered item values (for keyboard navigation). */
- items: Array<{value: string; isDisabled?: boolean}>;
- /** Register an item. Returns unregister function. */
- registerItem: (value: string, isDisabled?: boolean) => () => void;
- /** Select an item by value. */
+ /** Get the DOM id for an item by its flat index. */
+ getItemId: (index: number) => string;
+ /** Flat list of selectable items in DOM order (after grouping/filtering). */
+ selectableItems: Array<{value: string; label?: string; disabled?: boolean}>;
+ /** The search result items (typed). */
+ searchResults: XDSSearchableItem[];
+ /** Select an item by value and close. */
selectItem: (value: string) => void;
+ /** Keyboard handler from useCombobox — attach to the input. */
+ onKeyDown: (e: React.KeyboardEvent) => void;
/** Close the palette. */
onClose: () => void;
+ /** Whether the palette is open (for aria-expanded). */
+ isOpen: boolean;
+ /** Whether an async search is in flight. */
+ isBusy: boolean;
}
export const CommandPaletteContext =
@@ -42,8 +46,7 @@ export const CommandPaletteContext =
/**
* Access the command palette context.
- * Throws if used outside of a CommandPalette with context enabled.
- * Returns null when context is not available (for standalone usage).
+ * Returns null when used outside a CommandPalette (for standalone usage).
*/
export function useCommandPaletteContext(): CommandPaletteContextValue | null {
return useContext(CommandPaletteContext);
diff --git a/packages/lab/src/CommandPalette/XDSCommandPalette.test.tsx b/packages/lab/src/CommandPalette/XDSCommandPalette.test.tsx
index 1f3cf559d4..6b109ec609 100644
--- a/packages/lab/src/CommandPalette/XDSCommandPalette.test.tsx
+++ b/packages/lab/src/CommandPalette/XDSCommandPalette.test.tsx
@@ -3,13 +3,22 @@
* @input Uses vitest, @testing-library/react, XDSCommandPalette
* @output Unit tests for XDSCommandPalette dialog shell
* @position Testing; validates XDSCommandPalette.tsx implementation
- *
- * SYNC: When XDSCommandPalette.tsx changes, update tests to match
*/
import {describe, it, expect, vi, beforeEach} from 'vitest';
-import {render, screen} from '@testing-library/react';
+import {render, screen, waitFor} from '@testing-library/react';
import {XDSCommandPalette} from './XDSCommandPalette';
+import {createStaticSource} from '@xds/core/Typeahead';
+
+const simpleSource = createStaticSource([
+ {id: 'home', label: 'Home'},
+ {id: 'settings', label: 'Settings'},
+]);
+
+const groupedSource = createStaticSource([
+ {id: 'home', label: 'Home', auxiliaryData: {group: 'Navigation'}},
+ {id: 'save', label: 'Save', auxiliaryData: {group: 'Actions'}},
+]);
// Mock showModal and close since jsdom doesn't implement them
beforeEach(() => {
@@ -26,19 +35,24 @@ beforeEach(() => {
describe('XDSCommandPalette', () => {
it('renders when isOpen is true', () => {
render(
- <XDSCommandPalette isOpen={true} onOpenChange={() => {}}>
- <div>Content</div>
- </XDSCommandPalette>,
+ <XDSCommandPalette
+ isOpen={true}
+ onOpenChange={() => {}}
+ searchSource={simpleSource}
+ input={<div>Input</div>}
+ />,
);
expect(screen.getByRole('dialog')).toBeInTheDocument();
- expect(screen.getByText('Content')).toBeInTheDocument();
});
it('does not show content when isOpen is false', () => {
render(
- <XDSCommandPalette isOpen={false} onOpenChange={() => {}}>
- <div>Hidden</div>
- </XDSCommandPalette>,
+ <XDSCommandPalette
+ isOpen={false}
+ onOpenChange={() => {}}
+ searchSource={simpleSource}
+ input={<div>Input</div>}
+ />,
);
const dialog = screen.getByRole('dialog', {hidden: true});
expect(dialog).not.toHaveAttribute('open');
@@ -46,9 +60,12 @@ describe('XDSCommandPalette', () => {
it('has correct aria-label', () => {
render(
- <XDSCommandPalette isOpen={true} onOpenChange={() => {}}>
- <div>Content</div>
- </XDSCommandPalette>,
+ <XDSCommandPalette
+ isOpen={true}
+ onOpenChange={() => {}}
+ searchSource={simpleSource}
+ input={<div>Input</div>}
+ />,
);
expect(screen.getByRole('dialog')).toHaveAttribute(
'aria-label',
@@ -61,9 +78,10 @@ describe('XDSCommandPalette', () => {
<XDSCommandPalette
isOpen={true}
onOpenChange={() => {}}
- label="Quick search">
- <div>Content</div>
- </XDSCommandPalette>,
+ searchSource={simpleSource}
+ label="Quick search"
+ input={<div>Input</div>}
+ />,
);
expect(screen.getByRole('dialog')).toHaveAttribute(
'aria-label',
@@ -71,28 +89,97 @@ describe('XDSCommandPalette', () => {
);
});
- it('renders children as composable slots', () => {
+ it('renders input and footer slots', () => {
render(
- <XDSCommandPalette isOpen={true} onOpenChange={() => {}}>
- <div data-testid="input-slot">Input</div>
- <div data-testid="list-slot">List</div>
- <div data-testid="footer-slot">Footer</div>
- </XDSCommandPalette>,
+ <XDSCommandPalette
+ isOpen={true}
+ onOpenChange={() => {}}
+ searchSource={simpleSource}
+ input={<div data-testid="input-slot">Input</div>}
+ footer={<div data-testid="footer-slot">Footer</div>}
+ />,
);
expect(screen.getByTestId('input-slot')).toBeInTheDocument();
- expect(screen.getByTestId('list-slot')).toBeInTheDocument();
expect(screen.getByTestId('footer-slot')).toBeInTheDocument();
});
- it('calls onOpenChange(false) when Escape is pressed', () => {
- const handleOpenChange = vi.fn();
+ it('renders without footer slot', () => {
+ render(
+ <XDSCommandPalette
+ isOpen={true}
+ onOpenChange={() => {}}
+ searchSource={simpleSource}
+ input={<div>Input</div>}
+ />,
+ );
+ expect(screen.getByRole('dialog')).toBeInTheDocument();
+ });
+ it('default renders items from searchSource bootstrap', async () => {
render(
- <XDSCommandPalette isOpen={true} onOpenChange={handleOpenChange}>
- <div>Content</div>
+ <XDSCommandPalette
+ isOpen={true}
+ onOpenChange={() => {}}
+ searchSource={simpleSource}
+ input={<div>Input</div>}
+ />,
+ );
+ await waitFor(() => {
+ expect(screen.getByText('Home')).toBeInTheDocument();
+ expect(screen.getByText('Settings')).toBeInTheDocument();
+ });
+ });
+
+ it('auto-groups items by auxiliaryData.group', async () => {
+ render(
+ <XDSCommandPalette
+ isOpen={true}
+ onOpenChange={() => {}}
+ searchSource={groupedSource}
+ input={<div>Input</div>}
+ />,
+ );
+ await waitFor(() => {
+ expect(screen.getByText('Navigation')).toBeInTheDocument();
+ expect(screen.getByText('Actions')).toBeInTheDocument();
+ expect(screen.getByText('Home')).toBeInTheDocument();
+ expect(screen.getByText('Save')).toBeInTheDocument();
+ });
+ });
+
+ it('uses render function children when provided', async () => {
+ render(
+ <XDSCommandPalette
+ isOpen={true}
+ onOpenChange={() => {}}
+ searchSource={simpleSource}
+ input={<div>Input</div>}>
+ {(items) => (
+ <div data-testid="custom-render">
+ {items.map(item => (
+ <span key={item.id}>{item.label.toUpperCase()}</span>
+ ))}
+ </div>
+ )}
</XDSCommandPalette>,
);
+ await waitFor(() => {
+ expect(screen.getByTestId('custom-render')).toBeInTheDocument();
+ expect(screen.getByText('HOME')).toBeInTheDocument();
+ expect(screen.getByText('SETTINGS')).toBeInTheDocument();
+ });
+ });
+ it('calls onOpenChange(false) when Escape is pressed', () => {
+ const handleOpenChange = vi.fn();
+ render(
+ <XDSCommandPalette
+ isOpen={true}
+ onOpenChange={handleOpenChange}
+ searchSource={simpleSource}
+ input={<div>Input</div>}
+ />,
+ );
const dialog = screen.getByRole('dialog');
const escapeEvent = new KeyboardEvent('keydown', {
key: 'Escape',
@@ -100,7 +187,6 @@ describe('XDSCommandPalette', () => {
cancelable: true,
});
dialog.dispatchEvent(escapeEvent);
-
expect(handleOpenChange).toHaveBeenCalledWith(false);
});
});
diff --git a/packages/lab/src/CommandPalette/XDSCommandPalette.tsx b/packages/lab/src/CommandPalette/XDSCommandPalette.tsx
index 015beddbdc..c9f2c34f4c 100644
--- a/packages/lab/src/CommandPalette/XDSCommandPalette.tsx
+++ b/packages/lab/src/CommandPalette/XDSCommandPalette.tsx
@@ -1,12 +1,11 @@
/**
* @file XDSCommandPalette.tsx
- * @input Uses React, StyleX, XDSDialog, CommandPaletteContext
+ * @input Uses React, XDSDialog, XDSLayout, CommandPaletteContext, XDSSearchSource, useCombobox
* @output Exports XDSCommandPalette root component and props
- * @position Core root component; dialog shell with optional state management
+ * @position Core root component; dialog shell with searchSource-driven items
*
* SYNC: When modified, update these files to stay in sync:
- * - /packages/core/src/CommandPalette/README.md
- * - /packages/core/src/CommandPalette/index.ts
+ * - /packages/lab/src/CommandPalette/README.md
* - /apps/storybook/stories/CommandPalette.stories.tsx
*/
@@ -14,80 +13,67 @@
import {
useCallback,
+ useEffect,
useId,
useMemo,
useRef,
useState,
type ReactNode,
} from 'react';
-import * as stylex from '@stylexjs/stylex';
import {XDSDialog} from '@xds/core/Dialog';
-import type {XDSBaseProps} from '@xds/core/XDSBaseProps';
-import {xdsClassName, mergeProps} from '@xds/core/utils';
+import {
+ XDSLayout,
+ XDSLayoutHeader,
+ XDSLayoutContent,
+ XDSLayoutFooter,
+} from '@xds/core/Layout';
+import type {XDSSearchSource, XDSSearchableItem} from '@xds/core/Typeahead';
+import {useCombobox} from '@xds/core/Selector';
+import type {XDSSelectorOptionData} from '@xds/core/Selector';
import {CommandPaletteContext} from './CommandPaletteContext';
-import {defaultFilter} from './filter';
-import type {CommandPaletteFilterFn} from './types';
-
-const styles = stylex.create({
- wrapper: {
- display: 'flex',
- flexDirection: 'column',
- height: '100%',
- overflow: 'hidden',
- },
-});
-
-// =============================================================================
-// Module Augmentation - Register CommandPalette's style surfaces
-// =============================================================================
-
-declare module '../theme/types' {
- interface ComponentStyles {
- commandPalette?: {
- root?: import('../theme/types').StyleXStyles;
- };
- }
-}
+import {XDSCommandPaletteList} from './XDSCommandPaletteList';
+import {XDSCommandPaletteItem} from './XDSCommandPaletteItem';
+import {XDSCommandPaletteGroup} from './XDSCommandPaletteGroup';
-export interface XDSCommandPaletteProps extends XDSBaseProps<HTMLDivElement> {
- /**
- * Ref forwarded to the root wrapper element inside the dialog.
- */
- ref?: React.Ref<HTMLDivElement>;
- /**
- * Whether the command palette is open.
- */
+export interface XDSCommandPaletteProps<
+ T extends XDSSearchableItem = XDSSearchableItem,
+> {
+ /** Whether the command palette is open. */
isOpen: boolean;
- /**
- * Called when the command palette visibility changes.
- * Called with `false` when the palette requests to close
- * (via Escape key or backdrop click).
- */
+ /** Called when the command palette visibility changes. */
onOpenChange: (isOpen: boolean) => void;
/**
- * Controlled selected value.
+ * Search source providing items. Implements `search(query)` and `bootstrap()`.
+ * Same interface as XDSTypeahead's searchSource.
+ * Use `createStaticSource` for simple static lists.
*/
- value?: string;
+ searchSource: XDSSearchSource<T>;
/**
- * Called when the selected value changes.
+ * The search input slot. Pass XDSCommandPaletteInput here.
*/
- onValueChange?: (value: string) => void;
+ input?: ReactNode;
/**
- * Custom filter function. Return a score between 0 and 1.
- * When provided, replaces the built-in substring filter.
+ * The footer slot. Pass XDSCommandPaletteFooter here.
*/
- filter?: CommandPaletteFilterFn;
+ footer?: ReactNode;
/**
- * Whether built-in filtering is enabled.
- * Set to false when filtering is handled externally (e.g., server-side).
- * @default true
+ * Custom render function for items. Receives the filtered items array.
+ * When omitted, items are rendered with default rendering:
+ * - Each item shows its `label` text
+ * - Items with `auxiliaryData.group` are auto-grouped
*/
- isFiltered?: boolean;
+ children?: (items: T[]) => ReactNode;
+
+ /** Controlled selected value (for picker mode). */
+ value?: string;
+
+ /** Called when the selected value changes. */
+ onValueChange?: (value: string) => void;
/**
* Accessible label for the command palette dialog.
@@ -97,87 +83,192 @@ export interface XDSCommandPaletteProps extends XDSBaseProps<HTMLDivElement> {
/**
* Width of the command palette dialog.
- * Numbers are treated as pixels, strings are used as-is.
* @default 640
*/
width?: number | string;
/**
* Maximum height of the command palette dialog.
- * Numbers are treated as pixels, strings are used as-is.
* @default 480
*/
maxHeight?: number | string;
+}
- /**
- * Composable content slots.
- * Typically includes XDSCommandPaletteInput, XDSCommandPaletteList, and XDSCommandPaletteFooter.
- *
- * @example
- * ```
- * <XDSCommandPalette isOpen={isOpen} onOpenChange={setIsOpen}>
- * <XDSCommandPaletteInput placeholder="Search commands..." />
- * <XDSCommandPaletteList>
- * <XDSCommandPaletteItem value="home">Go Home</XDSCommandPaletteItem>
- * </XDSCommandPaletteList>
- * <XDSCommandPaletteFooter />
- * </XDSCommandPalette>
- * ```
- */
- children: ReactNode;
+function getGroup(item: XDSSearchableItem): string | undefined {
+ const aux = item.auxiliaryData as Record<string, unknown> | undefined;
+ return typeof aux?.group === 'string' ? aux.group : undefined;
+}
+
+/**
+ * Build a flat list of selectable items in DOM order from search results.
+ * When groups are present, items are ordered by group (preserving insertion order),
+ * with ungrouped items at the end — matching the DefaultRenderer layout.
+ */
+function buildSelectableItems(
+ items: XDSSearchableItem[],
+): XDSSelectorOptionData[] {
+ const hasGroups = items.some(item => getGroup(item) != null);
+
+ if (!hasGroups) {
+ return items.map(item => ({
+ value: item.id,
+ label: item.label,
+ }));
+ }
+
+ // Group items preserving insertion order of groups
+ const groupOrder: string[] = [];
+ const groups = new Map<string, XDSSearchableItem[]>();
+ const ungrouped: XDSSearchableItem[] = [];
+
+ for (const item of items) {
+ const group = getGroup(item);
+ if (group != null) {
+ if (!groups.has(group)) {
+ groupOrder.push(group);
+ groups.set(group, []);
+ }
+ groups.get(group)!.push(item);
+ } else {
+ ungrouped.push(item);
+ }
+ }
+
+ const result: XDSSelectorOptionData[] = [];
+ for (const heading of groupOrder) {
+ for (const item of groups.get(heading)!) {
+ result.push({value: item.id, label: item.label});
+ }
+ }
+ for (const item of ungrouped) {
+ result.push({value: item.id, label: item.label});
+ }
+ return result;
+}
+
+/**
+ * Default renderer for search results.
+ * Renders items as XDSCommandPaletteItem with label text.
+ * Auto-groups items by auxiliaryData.group when present.
+ */
+function DefaultRenderer({items}: {items: XDSSearchableItem[]}) {
+ const hasGroups = items.some(item => getGroup(item) != null);
+
+ if (!hasGroups) {
+ return (
+ <>
+ {items.map(item => (
+ <XDSCommandPaletteItem key={item.id} value={item.id}>
+ {item.label}
+ </XDSCommandPaletteItem>
+ ))}
+ </>
+ );
+ }
+
+ // Group items preserving insertion order of groups
+ const groupOrder: string[] = [];
+ const groups = new Map<string, XDSSearchableItem[]>();
+ const ungrouped: XDSSearchableItem[] = [];
+
+ for (const item of items) {
+ const group = getGroup(item);
+ if (group != null) {
+ if (!groups.has(group)) {
+ groupOrder.push(group);
+ groups.set(group, []);
+ }
+ groups.get(group)!.push(item);
+ } else {
+ ungrouped.push(item);
+ }
+ }
+
+ return (
+ <>
+ {groupOrder.map(heading => (
+ <XDSCommandPaletteGroup key={heading} heading={heading}>
+ {groups.get(heading)!.map(item => (
+ <XDSCommandPaletteItem key={item.id} value={item.id}>
+ {item.label}
+ </XDSCommandPaletteItem>
+ ))}
+ </XDSCommandPaletteGroup>
+ ))}
+ {ungrouped.map(item => (
+ <XDSCommandPaletteItem key={item.id} value={item.id}>
+ {item.label}
+ </XDSCommandPaletteItem>
+ ))}
+ </>
+ );
}
/**
* Command palette root component.
*
- * Wraps XDSDialog with command palette defaults and provides context
- * for state management (search, filtering, keyboard navigation, selection).
+ * Uses `searchSource` for all search logic — same interface as XDSTypeahead.
+ * For static lists, use `createStaticSource` from `@xds/core/Typeahead`.
+ *
+ * Keyboard navigation is handled by `useCombobox` from XDSSelector,
+ * ensuring consistent arrow key, Home/End, Enter, and Escape behavior
+ * across all combobox-pattern components.
*
- * Sub-components (Input, List, Item, Group, Footer) can be used as
- * controlled components via props, or they can consume the context
- * for automatic state wiring.
+ * Progressive disclosure:
+ * - No children: default rendering (label text, auto-groups by auxiliaryData.group)
+ * - Children render function: full control over item layout and grouping
*
- * @compositionHint Compose with XDSCommandPaletteInput (search),
- * XDSCommandPaletteList (scrollable items), and XDSCommandPaletteFooter
- * (keyboard hints) as children.
+ * @compositionHint
+ * - `input` slot: XDSCommandPaletteInput
+ * - `children`: optional render function `(items) => ReactNode`
+ * - `footer` slot: XDSCommandPaletteFooter
*
* @example
* ```
- * const [isOpen, setIsOpen] = useState(false);
+ * // Simplest — no children, default rendering
+ * <XDSCommandPalette
+ * isOpen={isOpen}
+ * onOpenChange={setIsOpen}
+ * searchSource={createStaticSource(commands)}
+ * input={<XDSCommandPaletteInput placeholder="Search..." />}
+ * footer={<XDSCommandPaletteFooter />}
+ * />
*
- * <XDSCommandPalette isOpen={isOpen} onOpenChange={setIsOpen}>
- * <XDSCommandPaletteInput placeholder="Type a command..." />
- * <XDSCommandPaletteList>
- * <XDSCommandPaletteItem value="home" onSelect={() => navigate('/')}>
- * Go Home
+ * // Custom rendering
+ * <XDSCommandPalette
+ * isOpen={isOpen}
+ * onOpenChange={setIsOpen}
+ * searchSource={source}
+ * input={<XDSCommandPaletteInput placeholder="Search..." />}>
+ * {(items) => items.map(item => (
+ * <XDSCommandPaletteItem key={item.id} value={item.id}>
+ * {item.label}
* </XDSCommandPaletteItem>
- * </XDSCommandPaletteList>
- * <XDSCommandPaletteFooter />
+ * ))}
* </XDSCommandPalette>
* ```
*/
-export function XDSCommandPalette({
+export function XDSCommandPalette<
+ T extends XDSSearchableItem = XDSSearchableItem,
+>({
isOpen,
onOpenChange,
+ searchSource,
+ input,
+ children,
+ footer,
value: controlledValue,
onValueChange,
- filter = defaultFilter,
- isFiltered = true,
label = 'Command palette',
width = 640,
maxHeight = 480,
- children,
- ref,
- xstyle,
- className,
- style,
- ...props
-}: XDSCommandPaletteProps) {
+}: XDSCommandPaletteProps<T>) {
const listId = useId();
const [search, setSearch] = useState('');
const [internalValue, setInternalValue] = useState('');
- const [highlightedIndex, setHighlightedIndex] = useState(0);
- const itemsRef = useRef<Array<{value: string; isDisabled?: boolean}>>([]);
+ const [searchResults, setSearchResults] = useState<T[]>([]);
+ const [isBusy, setIsBusy] = useState(false);
+ const searchVersionRef = useRef(0);
const value = controlledValue ?? internalValue;
@@ -191,18 +282,22 @@ export function XDSCommandPalette({
[controlledValue, onValueChange],
);
- const registerItem = useCallback(
- (itemValue: string, isDisabled?: boolean) => {
- itemsRef.current = [...itemsRef.current, {value: itemValue, isDisabled}];
- return () => {
- itemsRef.current = itemsRef.current.filter(
- item => item.value !== itemValue,
- );
- };
- },
- [],
+ // Build flat selectable items in DOM order from search results.
+ // This must match the order that DefaultRenderer (or custom children) renders.
+ const selectableItems = useMemo(
+ () => buildSelectableItems(searchResults),
+ [searchResults],
);
+ const handleClose = useCallback(() => {
+ setSearch('');
+ if (controlledValue === undefined) {
+ setInternalValue('');
+ }
+ searchSource.cancel?.();
+ onOpenChange(false);
+ }, [onOpenChange, searchSource, controlledValue]);
+
const selectItem = useCallback(
(itemValue: string) => {
setValue(itemValue);
@@ -210,12 +305,93 @@ export function XDSCommandPalette({
[setValue],
);
- // Reset search and highlight when closing
- const handleClose = useCallback(() => {
- setSearch('');
- setHighlightedIndex(0);
- onOpenChange(false);
- }, [onOpenChange]);
+ // useCombobox handles all keyboard navigation and highlight state.
+ // We treat the palette as always "open" from the combobox's perspective
+ // (since the dialog itself handles open/close), and use onClose as a no-op
+ // for the combobox — the palette's own close is handled by handleClose.
+ const combobox = useCombobox({
+ selectableItems,
+ value,
+ isOpen: true, // Always "open" from combobox POV — the dialog handles visibility
+ onOpen: () => {}, // Dialog handles open
+ onClose: () => {}, // We handle close via handleClose
+ onSelect: (itemValue: string) => {
+ selectItem(itemValue);
+ handleClose();
+ },
+ listboxId: listId,
+ });
+
+ // When the dialog opens, set highlight to selected item or first item
+ useEffect(() => {
+ if (isOpen && selectableItems.length > 0) {
+ const selectedIdx = selectableItems.findIndex(
+ item => item.value === value,
+ );
+ combobox.setHighlightedIndex(selectedIdx >= 0 ? selectedIdx : 0);
+ }
+ }, [isOpen, selectableItems, value, combobox]);
+
+ // Unified search effect: bootstrap on open or empty query, search otherwise
+ useEffect(() => {
+ if (!isOpen) return;
+
+ searchSource.cancel?.();
+ const version = ++searchVersionRef.current;
+
+ const result =
+ search === '' ? searchSource.bootstrap() : searchSource.search(search);
+
+ if (result instanceof Promise) {
+ setIsBusy(true);
+ result
+ .then(items => {
+ if (searchVersionRef.current === version) {
+ setSearchResults(items);
+ setIsBusy(false);
+ }
+ })
+ .catch(() => {
+ if (searchVersionRef.current === version) {
+ setIsBusy(false);
+ }
+ });
+ } else {
+ setSearchResults(result);
+ setIsBusy(false);
+ }
+ }, [search, isOpen, searchSource]);
+
+ // Wrap combobox's onKeyDown to intercept Escape (close palette) and
+ // Enter on highlight (select + close), since we're not using combobox's
+ // built-in open/close lifecycle.
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ handleClose();
+ return;
+ }
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ if (
+ combobox.highlightedIndex >= 0 &&
+ combobox.highlightedIndex < selectableItems.length
+ ) {
+ const item = selectableItems[combobox.highlightedIndex];
+ if (item && !item.disabled) {
+ selectItem(item.value);
+ handleClose();
+ }
+ }
+ return;
+ }
+ // Space should type in the input, not trigger selection
+ if (e.key === ' ') return;
+ combobox.onKeyDown(e);
+ },
+ [combobox, handleClose, selectableItems, selectItem],
+ );
const contextValue = useMemo(
() => ({
@@ -223,30 +399,42 @@ export function XDSCommandPalette({
setSearch,
value,
setValue,
- filter,
- isFiltered,
listId,
- highlightedIndex,
- setHighlightedIndex,
- items: itemsRef.current,
- registerItem,
+ highlightedIndex: combobox.highlightedIndex,
+ setHighlightedIndex: combobox.setHighlightedIndex,
+ getItemId: combobox.getItemId,
+ selectableItems,
+ searchResults,
selectItem,
+ onKeyDown: handleKeyDown,
onClose: handleClose,
+ isOpen,
+ isBusy,
}),
[
search,
value,
setValue,
- filter,
- isFiltered,
listId,
- highlightedIndex,
- registerItem,
+ combobox.highlightedIndex,
+ combobox.setHighlightedIndex,
+ combobox.getItemId,
+ selectableItems,
+ searchResults,
selectItem,
+ handleKeyDown,
handleClose,
+ isOpen,
+ isBusy,
],
);
+ const listContent = children ? (
+ children(searchResults)
+ ) : (
+ <DefaultRenderer items={searchResults} />
+ );
+
return (
<XDSDialog
isOpen={isOpen}
@@ -259,17 +447,28 @@ export function XDSCommandPalette({
purpose="info"
aria-label={label}>
<CommandPaletteContext.Provider value={contextValue}>
- <div
- ref={ref}
- {...mergeProps(
- xdsClassName('command-palette'),
- stylex.props(styles.wrapper, xstyle),
- className,
- style,
- )}
- {...props}>
- {children}
- </div>
+ <XDSLayout
+ defaultHasDividers
+ header={
+ input != null ? (
+ <XDSLayoutHeader hasDivider padding={0}>
+ {input}
+ </XDSLayoutHeader>
+ ) : undefined
+ }
+ content={
+ <XDSLayoutContent padding={0}>
+ <XDSCommandPaletteList>{listContent}</XDSCommandPaletteList>
+ </XDSLayoutContent>
+ }
+ footer={
+ footer != null ? (
+ <XDSLayoutFooter hasDivider padding={0}>
+ {footer}
+ </XDSLayoutFooter>
+ ) : undefined
+ }
+ />
</CommandPaletteContext.Provider>
</XDSDialog>
);
diff --git a/packages/lab/src/CommandPalette/XDSCommandPaletteFooter.test.tsx b/packages/lab/src/CommandPalette/XDSCommandPaletteFooter.test.tsx
index 972cff6bb9..c150e5cdc9 100644
--- a/packages/lab/src/CommandPalette/XDSCommandPaletteFooter.test.tsx
+++ b/packages/lab/src/CommandPalette/XDSCommandPaletteFooter.test.tsx
@@ -26,8 +26,10 @@ describe('XDSCommandPaletteFooter', () => {
expect(screen.queryByText(/Navigate/)).not.toBeInTheDocument();
});
- it('renders a divider', () => {
- render(<XDSCommandPaletteFooter />);
- expect(screen.getByRole('separator')).toBeInTheDocument();
+ it('renders a single root element (separator is CSS border, not a DOM node)', () => {
+ const {container} = render(<XDSCommandPaletteFooter />);
+ // The top separator is a borderBlockStart CSS property — no extra DOM node.
+ expect(container.firstChild).toBeInTheDocument();
+ expect(screen.queryByRole('separator')).not.toBeInTheDocument();
});
});
diff --git a/packages/lab/src/CommandPalette/XDSCommandPaletteFooter.tsx b/packages/lab/src/CommandPalette/XDSCommandPaletteFooter.tsx
index 9b8ecda837..aa107d815b 100644
--- a/packages/lab/src/CommandPalette/XDSCommandPaletteFooter.tsx
+++ b/packages/lab/src/CommandPalette/XDSCommandPaletteFooter.tsx
@@ -1,12 +1,11 @@
/**
* @file XDSCommandPaletteFooter.tsx
- * @input Uses React, StyleX, XDSDivider
+ * @input Uses React, StyleX, XDSKbd
* @output Exports XDSCommandPaletteFooter component
* @position Sub-component; footer with keyboard hints
*
* SYNC: When modified, update:
- * - /packages/core/src/CommandPalette/README.md
- * - /packages/core/src/CommandPalette/index.ts
+ * - /packages/lab/src/CommandPalette/README.md
*/
'use client';
@@ -18,10 +17,10 @@ import {xdsClassName, mergeProps} from '@xds/core/utils';
import {
colorVars,
spacingVars,
- textSizeVars,
+ typeScaleVars,
typographyVars,
} from '@xds/core/theme/tokens.stylex';
-import {XDSDivider} from '@xds/core/Divider';
+import {XDSKbd} from '@xds/core/Kbd';
const styles = stylex.create({
footer: {
@@ -31,26 +30,27 @@ const styles = stylex.create({
paddingInline: spacingVars['--spacing-4'],
paddingBlock: spacingVars['--spacing-2'],
flexShrink: 0,
+ // Inherit font so custom children match hint text treatment
+ fontFamily: typographyVars['--font-family-body'],
+ fontSize: typeScaleVars['--text-supporting-size'],
+ lineHeight: typeScaleVars['--text-supporting-leading'],
+ color: colorVars['--color-text-secondary'],
},
hint: {
display: 'flex',
alignItems: 'center',
gap: spacingVars['--spacing-1'],
- fontFamily: typographyVars['--font-family-body'],
- fontSize: textSizeVars['--font-size-xs'],
- color: colorVars['--color-text-secondary'],
},
});
export interface XDSCommandPaletteFooterProps extends XDSBaseProps<HTMLDivElement> {
- /**
- * Ref forwarded to the footer element.
- */
+ /** Ref forwarded to the footer element. */
ref?: React.Ref<HTMLDivElement>;
/**
* Footer content. When provided, renders custom content instead of default hints.
- * When omitted, renders default keyboard navigation hints.
+ * Custom children inherit the footer font treatment (supporting/12px, secondary color).
+ * When omitted, renders default keyboard navigation hints using XDSKbd.
*/
children?: ReactNode;
}
@@ -58,17 +58,19 @@ export interface XDSCommandPaletteFooterProps extends XDSBaseProps<HTMLDivElemen
/**
* Footer for the command palette showing keyboard navigation hints.
*
- * When no children are provided, renders default hints for
- * arrow keys, Enter to select, and Escape to close.
+ * When no children are provided, renders default hints using XDSKbd
+ * for arrow keys, Enter to select, and Escape to close.
*
- * @compositionHint Place as the last child of XDSCommandPalette.
+ * @compositionHint Pass to XDSCommandPalette's `footer` slot.
*
* @example
* ```
- * <XDSCommandPalette isOpen={isOpen} onOpenChange={setIsOpen}>
- * <XDSCommandPaletteInput />
+ * <XDSCommandPalette
+ * isOpen={isOpen}
+ * onOpenChange={setIsOpen}
+ * input={<XDSCommandPaletteInput />}
+ * footer={<XDSCommandPaletteFooter />}>
* <XDSCommandPaletteList>...</XDSCommandPaletteList>
- * <XDSCommandPaletteFooter />
* </XDSCommandPalette>
* ```
*/
@@ -81,26 +83,33 @@ export function XDSCommandPaletteFooter({
...props
}: XDSCommandPaletteFooterProps) {
return (
- <>
- <XDSDivider />
- <div
- ref={ref}
- {...mergeProps(
- xdsClassName('command-palette-footer'),
- stylex.props(styles.footer, xstyle),
- className,
- style,
- )}
- {...props}>
- {children ?? (
- <>
- <span {...stylex.props(styles.hint)}>\u2191\u2193 Navigate</span>
- <span {...stylex.props(styles.hint)}>\u21b5 Select</span>
- <span {...stylex.props(styles.hint)}>Esc Close</span>
- </>
- )}
- </div>
- </>
+ <div
+ ref={ref}
+ {...mergeProps(
+ xdsClassName('command-palette-footer'),
+ stylex.props(styles.footer, xstyle),
+ className,
+ style,
+ )}
+ {...props}>
+ {children ?? (
+ <>
+ <span {...stylex.props(styles.hint)}>
+ <XDSKbd keys="up" />
+ <XDSKbd keys="down" />
+ Navigate
+ </span>
+ <span {...stylex.props(styles.hint)}>
+ <XDSKbd keys="enter" />
+ Select
+ </span>
+ <span {...stylex.props(styles.hint)}>
+ <XDSKbd keys="escape" />
+ Close
+ </span>
+ </>
+ )}
+ </div>
);
}
diff --git a/packages/lab/src/CommandPalette/XDSCommandPaletteGroup.tsx b/packages/lab/src/CommandPalette/XDSCommandPaletteGroup.tsx
index 3da9412fd1..0597eeca50 100644
--- a/packages/lab/src/CommandPalette/XDSCommandPaletteGroup.tsx
+++ b/packages/lab/src/CommandPalette/XDSCommandPaletteGroup.tsx
@@ -5,8 +5,7 @@
* @position Sub-component; visual grouping with heading
*
* SYNC: When modified, update:
- * - /packages/core/src/CommandPalette/README.md
- * - /packages/core/src/CommandPalette/index.ts
+ * - /packages/lab/src/CommandPalette/README.md
*/
'use client';
@@ -18,48 +17,43 @@ import {xdsClassName, mergeProps} from '@xds/core/utils';
import {
colorVars,
spacingVars,
- textSizeVars,
+ typeScaleVars,
typographyVars,
- fontWeightVars,
} from '@xds/core/theme/tokens.stylex';
const styles = stylex.create({
group: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-0-5'],
paddingBlock: spacingVars['--spacing-1'],
},
heading: {
paddingInline: spacingVars['--spacing-3'],
paddingBlock: spacingVars['--spacing-1'],
fontFamily: typographyVars['--font-family-body'],
- fontSize: textSizeVars['--font-size-xs'],
- fontWeight: fontWeightVars['--font-weight-semibold'],
+ fontSize: typeScaleVars['--text-supporting-size'],
+ lineHeight: typeScaleVars['--text-supporting-leading'],
color: colorVars['--color-text-secondary'],
- textTransform: 'uppercase' as const,
- letterSpacing: '0.05em',
userSelect: 'none',
},
});
export interface XDSCommandPaletteGroupProps extends XDSBaseProps<HTMLDivElement> {
- /**
- * Ref forwarded to the root element.
- */
+ /** Ref forwarded to the root element. */
ref?: React.Ref<HTMLDivElement>;
-
- /**
- * Group heading text.
- */
+ /** Group heading text. */
heading: string;
-
- /**
- * Items within this group.
- */
+ /** Items within this group. */
children: ReactNode;
}
/**
* Visual grouping for command palette items with a heading label.
*
+ * Heading style matches DropdownMenu section headings:
+ * supporting-size (12px), secondary color, no uppercase/letterSpacing.
+ *
* @compositionHint Place inside XDSCommandPaletteList.
* Contains XDSCommandPaletteItem children.
*
diff --git a/packages/lab/src/CommandPalette/XDSCommandPaletteInput.tsx b/packages/lab/src/CommandPalette/XDSCommandPaletteInput.tsx
index 72bd5fece4..085d1a79c5 100644
--- a/packages/lab/src/CommandPalette/XDSCommandPaletteInput.tsx
+++ b/packages/lab/src/CommandPalette/XDSCommandPaletteInput.tsx
@@ -5,8 +5,7 @@
* @position Search input for the command palette
*
* SYNC: When modified, update these files to stay in sync:
- * - /packages/core/src/CommandPalette/README.md
- * - /packages/core/src/CommandPalette/index.ts
+ * - /packages/lab/src/CommandPalette/README.md
* - /apps/storybook/stories/CommandPalette.stories.tsx
*/
@@ -16,6 +15,7 @@ import {useCallback, useEffect, useRef, type InputHTMLAttributes} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {XDSIcon} from '@xds/core/Icon';
+import {XDSSpinner} from '@xds/core/Spinner';
import {xdsClassName, mergeProps} from '@xds/core/utils';
import {
colorVars,
@@ -35,7 +35,10 @@ const styles = stylex.create({
paddingBlock: spacingVars['--spacing-3'],
flexShrink: 0,
},
+ // The icon span needs explicit flex centering to avoid line-height offset
icon: {
+ display: 'flex',
+ alignItems: 'center',
flexShrink: 0,
color: colorVars['--color-text-secondary'],
},
@@ -60,9 +63,7 @@ export interface XDSCommandPaletteInputProps extends Omit<
InputHTMLAttributes<HTMLInputElement>,
'type' | 'role' | 'children' | 'autoFocus'
> {
- /**
- * Ref forwarded to the input element (for focus management).
- */
+ /** Ref forwarded to the input element (for focus management). */
ref?: React.Ref<HTMLInputElement>;
/**
@@ -89,9 +90,7 @@ export interface XDSCommandPaletteInputProps extends Omit<
*/
hasAutoFocus?: boolean;
- /**
- * StyleX styles for the wrapper element.
- */
+ /** StyleX styles for the wrapper element. */
xstyle?: StyleXStyles;
}
@@ -102,17 +101,15 @@ export interface XDSCommandPaletteInputProps extends Omit<
* so users can start typing immediately.
*
* When used inside XDSCommandPalette, automatically wires to the
- * context for search state. Can also be used standalone with explicit
- * value/onValueChange props.
+ * context for search state and keyboard navigation (via useCombobox).
+ * Can also be used standalone with explicit value/onValueChange props.
*
* @compositionHint Place as the first child of XDSCommandPalette.
*
* @example
* ```
* <XDSCommandPalette isOpen={isOpen} onOpenChange={setIsOpen}>
- * <XDSCommandPaletteInput
- * placeholder="Search commands..."
- * />
+ * <XDSCommandPaletteInput placeholder="Search commands..." />
* </XDSCommandPalette>
* ```
*/
@@ -155,47 +152,13 @@ export function XDSCommandPaletteInput({
}
}, [hasAutoFocus]);
- // Keyboard navigation when context is available
+ // Keyboard navigation — delegates to useCombobox via context
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLInputElement>) => {
onKeyDown?.(e);
- if (!ctx || e.defaultPrevented) return;
-
- const items = ctx.items.filter(item => !item.isDisabled);
- if (items.length === 0) return;
-
- switch (e.key) {
- case 'ArrowDown': {
- e.preventDefault();
- ctx.setHighlightedIndex(
- Math.min(ctx.highlightedIndex + 1, items.length - 1),
- );
- break;
- }
- case 'ArrowUp': {
- e.preventDefault();
- ctx.setHighlightedIndex(Math.max(ctx.highlightedIndex - 1, 0));
- break;
- }
- case 'Home': {
- e.preventDefault();
- ctx.setHighlightedIndex(0);
- break;
- }
- case 'End': {
- e.preventDefault();
- ctx.setHighlightedIndex(items.length - 1);
- break;
- }
- case 'Enter': {
- e.preventDefault();
- const highlighted = items[ctx.highlightedIndex];
- if (highlighted) {
- ctx.selectItem(highlighted.value);
- }
- break;
- }
- }
+ if (e.defaultPrevented) return;
+ // Delegate to useCombobox's keyboard handler from context
+ ctx?.onKeyDown(e);
},
[ctx, onKeyDown],
);
@@ -207,18 +170,22 @@ export function XDSCommandPaletteInput({
stylex.props(styles.wrapper, xstyle),
)}>
<span {...stylex.props(styles.icon)}>
- <XDSIcon icon="search" size="sm" color="inherit" />
+ {ctx?.isBusy ? (
+ <XDSSpinner size="sm" />
+ ) : (
+ <XDSIcon icon="search" size="sm" color="inherit" />
+ )}
</span>
<input
ref={setRefs}
type="text"
role="combobox"
- aria-expanded={true}
+ aria-expanded={ctx?.isOpen ?? true}
aria-autocomplete="list"
aria-controls={ctx?.listId}
aria-activedescendant={
ctx && ctx.highlightedIndex >= 0
- ? `${ctx.listId}-item-${ctx.highlightedIndex}`
+ ? ctx.getItemId(ctx.highlightedIndex)
: undefined
}
placeholder={placeholder}
@@ -226,8 +193,6 @@ export function XDSCommandPaletteInput({
onChange={e => {
handleValueChange?.(e.target.value);
onChange?.(e);
- // Reset highlight when search changes
- ctx?.setHighlightedIndex(0);
}}
onKeyDown={handleKeyDown}
{...stylex.props(styles.input)}
diff --git a/packages/lab/src/CommandPalette/XDSCommandPaletteItem.test.tsx b/packages/lab/src/CommandPalette/XDSCommandPaletteItem.test.tsx
index 18b74145da..d891bd069e 100644
--- a/packages/lab/src/CommandPalette/XDSCommandPaletteItem.test.tsx
+++ b/packages/lab/src/CommandPalette/XDSCommandPaletteItem.test.tsx
@@ -52,15 +52,26 @@ describe('XDSCommandPaletteItem', () => {
expect(screen.getByRole('option')).toHaveAttribute('aria-disabled', 'true');
});
- it('sets aria-selected when highlighted', () => {
+ it('sets aria-selected when selected (not highlighted)', () => {
render(
- <XDSCommandPaletteItem value="test" isHighlighted>
+ <XDSCommandPaletteItem value="test" isSelected>
Item
</XDSCommandPaletteItem>,
);
expect(screen.getByRole('option')).toHaveAttribute('aria-selected', 'true');
});
+ it('does not set aria-selected when only highlighted', () => {
+ // Highlight is visual only — aria-activedescendant on the input conveys
+ // keyboard focus, so aria-selected must not be set on highlight alone.
+ render(
+ <XDSCommandPaletteItem value="test" isHighlighted>
+ Item
+ </XDSCommandPaletteItem>,
+ );
+ expect(screen.getByRole('option')).toHaveAttribute('aria-selected', 'false');
+ });
+
it('sets data-value attribute', () => {
render(
<XDSCommandPaletteItem value="my-value">Item</XDSCommandPaletteItem>,
diff --git a/packages/lab/src/CommandPalette/XDSCommandPaletteItem.tsx b/packages/lab/src/CommandPalette/XDSCommandPaletteItem.tsx
index 35a5ddc56c..cf57a99a0c 100644
--- a/packages/lab/src/CommandPalette/XDSCommandPaletteItem.tsx
+++ b/packages/lab/src/CommandPalette/XDSCommandPaletteItem.tsx
@@ -5,13 +5,12 @@
* @position Sub-component; individual selectable item
*
* SYNC: When modified, update:
- * - /packages/core/src/CommandPalette/README.md
- * - /packages/core/src/CommandPalette/index.ts
+ * - /packages/lab/src/CommandPalette/README.md
*/
'use client';
-import {useCallback, useEffect, useRef, type ReactNode} from 'react';
+import {useCallback, useEffect, useMemo, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {XDSBaseProps} from '@xds/core/XDSBaseProps';
import {xdsClassName, mergeProps} from '@xds/core/utils';
@@ -51,6 +50,9 @@ const styles = stylex.create({
backgroundColor: colorVars['--color-overlay-hover'],
},
},
+ ':active': {
+ backgroundColor: colorVars['--color-overlay-pressed'],
+ },
},
itemHighlighted: {
backgroundColor: colorVars['--color-overlay-hover'],
@@ -65,49 +67,29 @@ const styles = stylex.create({
});
export interface XDSCommandPaletteItemProps extends XDSBaseProps<HTMLDivElement> {
- /**
- * Ref forwarded to the root element.
- */
+ /** Ref forwarded to the root element. */
ref?: React.Ref<HTMLDivElement>;
-
- /**
- * Unique value for identification and selection.
- */
+ /** Unique value for identification and selection. */
value: string;
-
- /**
- * Called when this item is selected (via click or Enter).
- */
+ /** Called when this item is selected (via click or Enter). */
onSelect?: (value: string) => void;
-
/**
- * Additional search terms for filtering (used by context filter).
- */
- keywords?: string[];
-
- /**
- * Whether this item is visually highlighted (e.g., via keyboard navigation).
+ * Whether this item is visually highlighted (keyboard focus).
* When omitted inside XDSCommandPalette, derived from context.
* @default false
*/
isHighlighted?: boolean;
-
/**
- * Whether this item is currently selected.
- * When omitted inside XDSCommandPalette, derived from context.
+ * Whether this item is currently selected (picker mode).
* @default false
*/
isSelected?: boolean;
-
/**
* Whether the item is disabled.
* @default false
*/
isDisabled?: boolean;
-
- /**
- * Item content. Fully custom — render icons, descriptions, shortcuts, etc.
- */
+ /** Item content. Fully custom — render icons, descriptions, shortcuts, etc. */
children: ReactNode;
}
@@ -116,7 +98,7 @@ export interface XDSCommandPaletteItemProps extends XDSBaseProps<HTMLDivElement>
* Accepts arbitrary children for full rendering control.
*
* When used inside XDSCommandPalette, registers with context for
- * filtering, keyboard navigation, and selection. Can also be used
+ * keyboard navigation and selection. Can also be used
* standalone with explicit isHighlighted/isSelected props.
*
* @compositionHint Place inside XDSCommandPaletteList or XDSCommandPaletteGroup.
@@ -131,7 +113,6 @@ export interface XDSCommandPaletteItemProps extends XDSBaseProps<HTMLDivElement>
export function XDSCommandPaletteItem({
value,
onSelect,
- keywords,
isHighlighted: controlledHighlighted,
isSelected: controlledSelected,
isDisabled = false,
@@ -145,7 +126,6 @@ export function XDSCommandPaletteItem({
const ctx = useCommandPaletteContext();
const itemRef = useRef<HTMLDivElement>(null);
- // Merge refs
const setRefs = (element: HTMLDivElement | null) => {
(itemRef as React.MutableRefObject<HTMLDivElement | null>).current =
element;
@@ -156,24 +136,19 @@ export function XDSCommandPaletteItem({
}
};
- // Register with context on mount
- useEffect(() => {
- if (!ctx) return;
- const unregister = ctx.registerItem(value, isDisabled);
- return unregister;
- }, [value, isDisabled, ctx]);
+ // Find this item's index in the flat selectable items list (DOM order).
+ // This aligns with useCombobox's index-based navigation.
+ const itemIndex = useMemo(
+ () => ctx?.selectableItems.findIndex(item => item.value === value) ?? -1,
+ [ctx?.selectableItems, value],
+ );
- // Derive state from context or props
- const itemIndex = ctx?.items.findIndex(item => item.value === value) ?? -1;
+ // Highlight from useCombobox: index-based, matches DOM order
const isHighlighted =
- controlledHighlighted ?? (ctx ? itemIndex === ctx.highlightedIndex : false);
+ controlledHighlighted ??
+ (ctx ? ctx.highlightedIndex === itemIndex && itemIndex >= 0 : false);
const isSelected = controlledSelected ?? (ctx ? ctx.value === value : false);
- // Filter: check if this item matches the search
- const score =
- ctx?.isFiltered && ctx.search ? ctx.filter(value, ctx.search, keywords) : 1;
-
- // Scroll highlighted item into view
useEffect(() => {
if (isHighlighted && itemRef.current) {
itemRef.current.scrollIntoView?.({block: 'nearest'});
@@ -190,19 +165,16 @@ export function XDSCommandPaletteItem({
}, [isDisabled, value, onSelect, ctx]);
const handleMouseEnter = useCallback(() => {
- if (isDisabled || !ctx) return;
+ if (isDisabled || !ctx || itemIndex < 0) return;
ctx.setHighlightedIndex(itemIndex);
}, [isDisabled, itemIndex, ctx]);
- // Don't render if filtered out
- if (score === 0) return null;
-
return (
<div
ref={setRefs}
- id={ctx ? `${ctx.listId}-item-${itemIndex}` : undefined}
+ id={ctx && itemIndex >= 0 ? ctx.getItemId(itemIndex) : undefined}
role="option"
- aria-selected={isHighlighted}
+ aria-selected={isSelected}
aria-disabled={isDisabled || undefined}
data-value={value}
onClick={handleClick}
diff --git a/packages/lab/src/CommandPalette/XDSCommandPaletteList.tsx b/packages/lab/src/CommandPalette/XDSCommandPaletteList.tsx
index 16e0672389..19d2ff89ba 100644
--- a/packages/lab/src/CommandPalette/XDSCommandPaletteList.tsx
+++ b/packages/lab/src/CommandPalette/XDSCommandPaletteList.tsx
@@ -24,6 +24,9 @@ const styles = stylex.create({
maxHeight: '100%',
padding: spacingVars['--spacing-1'],
flex: 1,
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-0-5'],
},
});
diff --git a/packages/lab/src/CommandPalette/filter.test.ts b/packages/lab/src/CommandPalette/filter.test.ts
deleted file mode 100644
index bc5bf0c0f7..0000000000
--- a/packages/lab/src/CommandPalette/filter.test.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-/**
- * @file filter.test.ts
- * @input Uses vitest
- * @output Unit tests for default filter function
- */
-
-import {describe, it, expect} from 'vitest';
-import {defaultFilter} from './filter';
-
-describe('defaultFilter', () => {
- it('returns 1 for empty search', () => {
- expect(defaultFilter('anything', '')).toBe(1);
- });
-
- it('returns 1 for exact match', () => {
- expect(defaultFilter('settings', 'settings')).toBe(1);
- });
-
- it('returns 0.9 for starts-with match', () => {
- expect(defaultFilter('settings', 'set')).toBe(0.9);
- });
-
- it('returns 0.7 for contains match', () => {
- expect(defaultFilter('settings', 'ting')).toBe(0.7);
- });
-
- it('returns 0 for no match', () => {
- expect(defaultFilter('settings', 'xyz')).toBe(0);
- });
-
- it('is case-insensitive', () => {
- expect(defaultFilter('Settings', 'settings')).toBe(1);
- expect(defaultFilter('settings', 'SET')).toBe(0.9);
- });
-
- it('matches keywords', () => {
- expect(defaultFilter('theme', 'dark', ['dark mode', 'appearance'])).toBe(
- 0.6,
- );
- });
-
- it('returns 0.5 for keyword contains match', () => {
- expect(defaultFilter('theme', 'ear', ['dark mode', 'appearance'])).toBe(
- 0.5,
- );
- });
-});
diff --git a/packages/lab/src/CommandPalette/filter.ts b/packages/lab/src/CommandPalette/filter.ts
deleted file mode 100644
index a83abf1d10..0000000000
--- a/packages/lab/src/CommandPalette/filter.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * @file filter.ts
- * @input Search string and item value/keywords
- * @output Score between 0 and 1 indicating match quality
- * @position Utility; used by CommandPaletteContext for default filtering
- */
-
-import type {CommandPaletteFilterFn} from './types';
-
-/**
- * Default filter function for command palette.
- * Uses substring matching with keyword support.
- * Returns a score between 0 (no match) and 1 (exact match).
- */
-export const defaultFilter: CommandPaletteFilterFn = (
- value: string,
- search: string,
- keywords?: string[],
-): number => {
- if (search.length === 0) return 1;
-
- const searchLower = search.toLowerCase();
- const valueLower = value.toLowerCase();
-
- // Exact match
- if (valueLower === searchLower) return 1;
-
- // Starts with
- if (valueLower.startsWith(searchLower)) return 0.9;
-
- // Contains
- if (valueLower.includes(searchLower)) return 0.7;
-
- // Check keywords
- if (keywords) {
- for (const keyword of keywords) {
- const keywordLower = keyword.toLowerCase();
- if (keywordLower.startsWith(searchLower)) return 0.6;
- if (keywordLower.includes(searchLower)) return 0.5;
- }
- }
-
- // No match
- return 0;
-};
diff --git a/packages/lab/src/CommandPalette/index.ts b/packages/lab/src/CommandPalette/index.ts
index 7645732dd4..66297c169d 100644
--- a/packages/lab/src/CommandPalette/index.ts
+++ b/packages/lab/src/CommandPalette/index.ts
@@ -2,7 +2,7 @@
* @file index.ts
* @input Imports CommandPalette components and types
* @output Exports all CommandPalette components and types
- * @position Component entry point; re-exported by /packages/core/src/index.ts
+ * @position Component entry point; re-exported by /packages/lab/src/index.ts
*
* SYNC: When modified, update this header
*/
@@ -27,6 +27,3 @@ export type {XDSCommandPaletteFooterProps} from './XDSCommandPaletteFooter';
export {useCommandPaletteContext} from './CommandPaletteContext';
export type {CommandPaletteContextValue} from './CommandPaletteContext';
-
-export {defaultFilter} from './filter';
-export type {CommandPaletteFilterFn} from './types';
diff --git a/packages/lab/src/CommandPalette/types.ts b/packages/lab/src/CommandPalette/types.ts
deleted file mode 100644
index 77acba9266..0000000000
--- a/packages/lab/src/CommandPalette/types.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-/**
- * @file types.ts
- * @input None
- * @output Exports shared types for CommandPalette components
- * @position Type definitions; consumed by CommandPalette components
- */
-
-/**
- * Custom filter function. Return a score between 0 and 1.
- * 0 means no match (hidden), 1 means perfect match.
- */
-export type CommandPaletteFilterFn = (
- value: string,
- search: string,
- keywords?: string[],
-) => number;