Skip to content

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

TypeScript

feat(core): add XDSCommandPalette component (#453)

Cindy Zhang06925068b048
diff --git a/apps/storybook/stories/CommandPalette.stories.tsx b/apps/storybook/stories/CommandPalette.stories.tsx
new file mode 100644
index 0000000000..a5c1ff659a
--- /dev/null
+++ b/apps/storybook/stories/CommandPalette.stories.tsx
@@ -0,0 +1,222 @@
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {
+ XDSCommandPalette,
+ XDSCommandPaletteInput,
+ XDSCommandPaletteList,
+ XDSCommandPaletteItem,
+ XDSCommandPaletteGroup,
+ XDSCommandPaletteEmpty,
+ XDSCommandPaletteShortcut,
+ XDSCommandPaletteFooter,
+ XDSCommandPaletteSeparator,
+ XDSCommandPaletteLoading,
+ XDSCommandPaletteProvider,
+ useXDSCommandPaletteRegister,
+ useXDSCommandPalette,
+} from '@xds/core/CommandPalette';
+import {XDSIcon} from '@xds/core/Icon';
+import {XDSButton} from '@xds/core/Button';
+
+const meta: Meta<typeof XDSCommandPalette> = {
+ title: 'Components/CommandPalette',
+ component: XDSCommandPalette,
+ parameters: {
+ layout: 'centered',
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof XDSCommandPalette>;
+
+// =============================================================================
+// Layer 1: Composable
+// =============================================================================
+
+/**
+ * Basic composable command palette with groups and keyboard shortcuts.
+ * This demonstrates the Layer 1 API where you compose sub-components directly.
+ */
+export const Composable: Story = {
+ render: function ComposableStory() {
+ const [isShown, setIsShown] = useState(false);
+
+ return (
+ <>
+ <XDSButton label="Open Command Palette (⌘K)" onClick={() => setIsShown(true)} />
+ <XDSCommandPalette isShown={isShown} onHide={() => setIsShown(false)}>
+ <XDSCommandPaletteInput placeholder="Type a command or search..." />
+ <XDSCommandPaletteList>
+ <XDSCommandPaletteGroup heading="Navigation">
+ <XDSCommandPaletteItem value="home" onSelect={() => setIsShown(false)}>
+ <XDSIcon icon="home" size="sm" />
+ <span style={{flex: 1}}>Go Home</span>
+ <XDSCommandPaletteShortcut keys="mod+h" />
+ </XDSCommandPaletteItem>
+ <XDSCommandPaletteItem value="settings" onSelect={() => setIsShown(false)}>
+ <XDSIcon icon="settings" size="sm" />
+ <span style={{flex: 1}}>Settings</span>
+ <XDSCommandPaletteShortcut keys="mod+," />
+ </XDSCommandPaletteItem>
+ <XDSCommandPaletteItem value="profile" onSelect={() => setIsShown(false)}>
+ <XDSIcon icon="person" size="sm" />
+ <span style={{flex: 1}}>Profile</span>
+ </XDSCommandPaletteItem>
+ </XDSCommandPaletteGroup>
+ <XDSCommandPaletteSeparator />
+ <XDSCommandPaletteGroup heading="Actions">
+ <XDSCommandPaletteItem value="new-file" onSelect={() => setIsShown(false)}>
+ <XDSIcon icon="add" size="sm" />
+ <span style={{flex: 1}}>New File</span>
+ <XDSCommandPaletteShortcut keys="mod+n" />
+ </XDSCommandPaletteItem>
+ <XDSCommandPaletteItem value="save" onSelect={() => setIsShown(false)}>
+ <XDSIcon icon="check" size="sm" />
+ <span style={{flex: 1}}>Save</span>
+ <XDSCommandPaletteShortcut keys="mod+s" />
+ </XDSCommandPaletteItem>
+ </XDSCommandPaletteGroup>
+ <XDSCommandPaletteEmpty>No results found</XDSCommandPaletteEmpty>
+ </XDSCommandPaletteList>
+ <XDSCommandPaletteFooter>
+ <span>↑↓ Navigate</span>
+ <span>↵ Select</span>
+ <span>Esc Close</span>
+ </XDSCommandPaletteFooter>
+ </XDSCommandPalette>
+ </>
+ );
+ },
+};
+
+/**
+ * Demonstrates disabled items and custom content.
+ */
+export const DisabledItems: Story = {
+ render: function DisabledItemsStory() {
+ const [isShown, setIsShown] = useState(false);
+
+ return (
+ <>
+ <XDSButton label="Open Palette" onClick={() => setIsShown(true)} />
+ <XDSCommandPalette isShown={isShown} onHide={() => setIsShown(false)}>
+ <XDSCommandPaletteInput />
+ <XDSCommandPaletteList>
+ <XDSCommandPaletteItem value="enabled" onSelect={() => setIsShown(false)}>
+ Enabled Action
+ </XDSCommandPaletteItem>
+ <XDSCommandPaletteItem value="disabled" isDisabled onSelect={() => {}}>
+ Disabled Action (no permission)
+ </XDSCommandPaletteItem>
+ <XDSCommandPaletteItem value="another" onSelect={() => setIsShown(false)}>
+ Another Action
+ </XDSCommandPaletteItem>
+ </XDSCommandPaletteList>
+ </XDSCommandPalette>
+ </>
+ );
+ },
+};
+
+/**
+ * Demonstrates filtering behavior — type to filter items.
+ */
+export const Filtering: Story = {
+ render: function FilteringStory() {
+ const [isShown, setIsShown] = useState(false);
+
+ const items = [
+ {value: 'dashboard', label: 'Dashboard', keywords: ['home', 'overview']},
+ {value: 'users', label: 'User Management', keywords: ['people', 'accounts']},
+ {value: 'analytics', label: 'Analytics', keywords: ['data', 'reports', 'charts']},
+ {value: 'billing', label: 'Billing', keywords: ['payments', 'invoices']},
+ {value: 'notifications', label: 'Notification Settings', keywords: ['alerts', 'emails']},
+ {value: 'api-keys', label: 'API Keys', keywords: ['tokens', 'credentials']},
+ ];
+
+ return (
+ <>
+ <XDSButton label="Open Palette" onClick={() => setIsShown(true)} />
+ <XDSCommandPalette isShown={isShown} onHide={() => setIsShown(false)}>
+ <XDSCommandPaletteInput placeholder="Search pages..." />
+ <XDSCommandPaletteList>
+ {items.map((item) => (
+ <XDSCommandPaletteItem
+ key={item.value}
+ value={item.value}
+ keywords={item.keywords}
+ onSelect={() => setIsShown(false)}>
+ {item.label}
+ </XDSCommandPaletteItem>
+ ))}
+ <XDSCommandPaletteEmpty>No pages found</XDSCommandPaletteEmpty>
+ </XDSCommandPaletteList>
+ </XDSCommandPalette>
+ </>
+ );
+ },
+};
+
+// =============================================================================
+// Layer 2: Provider
+// =============================================================================
+
+function NavigationCommands() {
+ useXDSCommandPaletteRegister([
+ {id: 'nav-home', label: 'Go Home', icon: 'home', group: 'Navigation', onSelect: () => alert('Home')},
+ {id: 'nav-settings', label: 'Settings', icon: 'settings', shortcut: 'mod+,', group: 'Navigation', onSelect: () => alert('Settings')},
+ {id: 'nav-profile', label: 'Profile', icon: 'person', group: 'Navigation', onSelect: () => alert('Profile')},
+ ]);
+ return null;
+}
+
+function ActionCommands() {
+ useXDSCommandPaletteRegister([
+ {id: 'act-new', label: 'New File', icon: 'add', shortcut: 'mod+n', group: 'Actions', onSelect: () => alert('New File')},
+ {id: 'act-save', label: 'Save', icon: 'check', shortcut: 'mod+s', group: 'Actions', onSelect: () => alert('Save')},
+ ]);
+ return null;
+}
+
+function OpenButton() {
+ const {open} = useXDSCommandPalette();
+ return <XDSButton label="Open Command Palette (⌘K)" onClick={open} />;
+}
+
+/**
+ * Provider pattern with distributed command registration.
+ * Commands are registered from separate components via useXDSCommandPaletteRegister.
+ * Press ⌘K (or click the button) to open.
+ */
+export const Provider: Story = {
+ render: function ProviderStory() {
+ return (
+ <XDSCommandPaletteProvider shortcut="mod+k">
+ <NavigationCommands />
+ <ActionCommands />
+ <OpenButton />
+ </XDSCommandPaletteProvider>
+ );
+ },
+};
+
+/**
+ * Loading state for async command fetching.
+ */
+export const Loading: Story = {
+ render: function LoadingStory() {
+ const [isShown, setIsShown] = useState(false);
+
+ return (
+ <>
+ <XDSButton label="Open Palette" onClick={() => setIsShown(true)} />
+ <XDSCommandPalette isShown={isShown} onHide={() => setIsShown(false)}>
+ <XDSCommandPaletteInput placeholder="Search..." />
+ <XDSCommandPaletteList>
+ <XDSCommandPaletteLoading>Searching...</XDSCommandPaletteLoading>
+ </XDSCommandPaletteList>
+ </XDSCommandPalette>
+ </>
+ );
+ },
+};
diff --git a/packages/core/package.json b/packages/core/package.json
index fa0db75c8f..a27c15cb38 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -19,15 +19,6 @@
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
- "./reset.css": "./src/reset.css",
- "./typography.css": "./src/typography.css",
- "./theme/tokens.stylex": {
- "source": "./src/theme/tokens.stylex.ts",
- "types": "./dist/theme/tokens.stylex.d.ts",
- "import": "./dist/theme/tokens.stylex.mjs",
- "require": "./dist/theme/tokens.stylex.js"
- },
- "./xds.md": "./xds.md",
"./AppShell": {
"source": "./src/AppShell/index.ts",
"types": "./dist/AppShell/index.d.ts",
@@ -100,6 +91,12 @@
"import": "./dist/Collapsible/index.mjs",
"require": "./dist/Collapsible/index.js"
},
+ "./CommandPalette": {
+ "source": "./src/CommandPalette/index.ts",
+ "types": "./dist/CommandPalette/index.d.ts",
+ "import": "./dist/CommandPalette/index.mjs",
+ "require": "./dist/CommandPalette/index.js"
+ },
"./DateInput": {
"source": "./src/DateInput/index.ts",
"types": "./dist/DateInput/index.d.ts",
@@ -340,18 +337,27 @@
"import": "./dist/hooks/index.mjs",
"require": "./dist/hooks/index.js"
},
+ "./reset.css": "./src/reset.css",
"./theme": {
"source": "./src/theme/index.ts",
"types": "./dist/theme/index.d.ts",
"import": "./dist/theme/index.mjs",
"require": "./dist/theme/index.js"
},
+ "./theme/tokens.stylex": {
+ "source": "./src/theme/tokens.stylex.ts",
+ "types": "./dist/theme/tokens.stylex.d.ts",
+ "import": "./dist/theme/tokens.stylex.mjs",
+ "require": "./dist/theme/tokens.stylex.js"
+ },
+ "./typography.css": "./src/typography.css",
"./utils": {
"source": "./src/utils/index.ts",
"types": "./dist/utils/index.d.ts",
"import": "./dist/utils/index.mjs",
"require": "./dist/utils/index.js"
- }
+ },
+ "./xds.md": "./xds.md"
},
"files": [
"dist",
diff --git a/packages/core/src/CommandPalette/CommandPaletteContext.ts b/packages/core/src/CommandPalette/CommandPaletteContext.ts
new file mode 100644
index 0000000000..047ede0341
--- /dev/null
+++ b/packages/core/src/CommandPalette/CommandPaletteContext.ts
@@ -0,0 +1,51 @@
+/**
+ * @file CommandPaletteContext.ts
+ * @input Uses React createContext
+ * @output Exports CommandPaletteContext for internal state sharing
+ * @position Internal context; consumed by composable sub-components
+ */
+
+import {createContext, useContext} from 'react';
+import type {CommandPaletteFilterFn} from './types';
+
+export interface CommandPaletteContextValue {
+ /** Current search query. */
+ search: string;
+ /** Update the search query. */
+ setSearch: (search: string) => void;
+ /** Currently selected value. */
+ 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. */
+ listId: string;
+ /** Index of the currently highlighted item. */
+ 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. */
+ selectItem: (value: string) => void;
+ /** Close the palette. */
+ onHide: () => void;
+}
+
+export const CommandPaletteContext =
+ createContext<CommandPaletteContextValue | null>(null);
+
+export function useCommandPaletteContext(): CommandPaletteContextValue {
+ const context = useContext(CommandPaletteContext);
+ if (context == null) {
+ throw new Error(
+ 'CommandPalette compound components must be used within <XDSCommandPalette>',
+ );
+ }
+ return context;
+}
diff --git a/packages/core/src/CommandPalette/README.md b/packages/core/src/CommandPalette/README.md
new file mode 100644
index 0000000000..e4a5e0e250
--- /dev/null
+++ b/packages/core/src/CommandPalette/README.md
@@ -0,0 +1,89 @@
+# CommandPalette
+
+A composable command palette (Cmd+K) for XDS applications.
+
+## Architecture
+
+Three layers, each building on the last:
+
+1. **Composable Primitives** — Full rendering control via compound components
+2. **Registry Provider** — Distributed command registration via hooks
+3. **History Hook** — Optional opt-in history tracking
+
+## File Manifest
+
+| File | Purpose |
+|------|---------|
+| `index.ts` | Public exports |
+| `types.ts` | Shared types (XDSCommand, filter function) |
+| `filter.ts` | Default substring filter |
+| `CommandPaletteContext.ts` | Internal context for compound components |
+| `XDSCommandPalette.tsx` | Root component (wraps XDSDialog) |
+| `XDSCommandPaletteInput.tsx` | Search input with combobox ARIA |
+| `XDSCommandPaletteList.tsx` | Scrollable results container (listbox) |
+| `XDSCommandPaletteItem.tsx` | Selectable item (option) |
+| `XDSCommandPaletteGroup.tsx` | Visual grouping with heading |
+| `XDSCommandPaletteEmpty.tsx` | Empty state |
+| `XDSCommandPaletteLoading.tsx` | Loading indicator |
+| `XDSCommandPaletteSeparator.tsx` | Visual divider (wraps XDSDivider) |
+| `XDSCommandPaletteShortcut.tsx` | Keyboard shortcut display |
+| `XDSCommandPaletteFooter.tsx` | Footer bar |
+| `XDSCommandPaletteProvider.tsx` | Registry provider + hooks |
+| `useXDSCommandPaletteHistory.ts` | Optional history hook |
+
+## Usage
+
+### Layer 1: Composable
+
+```tsx
+<XDSCommandPalette isShown={isShown} onHide={() => setIsShown(false)}>
+ <XDSCommandPaletteInput placeholder="Search..." />
+ <XDSCommandPaletteList>
+ <XDSCommandPaletteGroup heading="Navigation">
+ <XDSCommandPaletteItem value="home" onSelect={() => navigate("/")}>
+ <XDSIcon icon="home" size="sm" />
+ <span>Go Home</span>
+ <XDSCommandPaletteShortcut keys="mod+h" />
+ </XDSCommandPaletteItem>
+ </XDSCommandPaletteGroup>
+ <XDSCommandPaletteEmpty>No results</XDSCommandPaletteEmpty>
+ </XDSCommandPaletteList>
+ <XDSCommandPaletteFooter>
+ <span>↑↓ Navigate</span>
+ <span>↵ Select</span>
+ </XDSCommandPaletteFooter>
+</XDSCommandPalette>
+```
+
+### Layer 2: Provider
+
+```tsx
+// Wrap your app
+<XDSCommandPaletteProvider shortcut="mod+k">
+ <App />
+</XDSCommandPaletteProvider>
+
+// Register commands from anywhere
+function Navigation() {
+ useXDSCommandPaletteRegister([
+ { id: "home", label: "Go Home", icon: "home", onSelect: () => navigate("/") },
+ { id: "settings", label: "Settings", shortcut: "mod+,", onSelect: () => navigate("/settings") },
+ ]);
+ return <nav>...</nav>;
+}
+
+// Imperative control
+function SearchButton() {
+ const { open } = useXDSCommandPalette();
+ return <XDSButton label="Search" onClick={open} />;
+}
+```
+
+### Layer 3: History
+
+```tsx
+const { history, record, clear } = useXDSCommandPaletteHistory({
+ persist: true,
+ maxEntries: 10,
+});
+```
diff --git a/packages/core/src/CommandPalette/XDSCommandPalette.test.tsx b/packages/core/src/CommandPalette/XDSCommandPalette.test.tsx
new file mode 100644
index 0000000000..a505193682
--- /dev/null
+++ b/packages/core/src/CommandPalette/XDSCommandPalette.test.tsx
@@ -0,0 +1,334 @@
+/**
+ * @file XDSCommandPalette.test.tsx
+ * @input Tests for CommandPalette composable components and provider
+ * @output Test results
+ * @position Test file; validates XDSCommandPalette behavior
+ */
+
+import {render, screen, fireEvent, act} from '@testing-library/react';
+import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {XDSCommandPalette} from './XDSCommandPalette';
+import {XDSCommandPaletteInput} from './XDSCommandPaletteInput';
+import {XDSCommandPaletteList} from './XDSCommandPaletteList';
+import {XDSCommandPaletteItem} from './XDSCommandPaletteItem';
+import {XDSCommandPaletteGroup} from './XDSCommandPaletteGroup';
+import {XDSCommandPaletteEmpty} from './XDSCommandPaletteEmpty';
+import {XDSCommandPaletteShortcut} from './XDSCommandPaletteShortcut';
+import {XDSCommandPaletteFooter} from './XDSCommandPaletteFooter';
+import {XDSCommandPaletteLoading} from './XDSCommandPaletteLoading';
+import {useXDSCommandPaletteHistory} from './useXDSCommandPaletteHistory';
+import {defaultFilter} from './filter';
+
+
+// Mock showModal and close methods since they're not fully implemented in jsdom
+beforeEach(() => {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ });
+});
+
+// =============================================================================
+// Filter tests
+// =============================================================================
+
+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.6 for keyword starts-with', () => {
+ expect(defaultFilter('Go Home', 'nav', ['navigation'])).toBe(0.6);
+ });
+
+ it('returns 0.5 for keyword contains', () => {
+ expect(defaultFilter('Go Home', 'vig', ['navigation'])).toBe(0.5);
+ });
+
+ it('returns 0 for no match', () => {
+ expect(defaultFilter('Settings', 'xyz')).toBe(0);
+ });
+});
+
+// =============================================================================
+// Shortcut display tests
+// =============================================================================
+
+describe('XDSCommandPaletteShortcut', () => {
+ it('renders modifier keys as symbols', () => {
+ const {container} = render(<XDSCommandPaletteShortcut keys="mod+k" />);
+ const kbds = container.querySelectorAll('kbd');
+ expect(kbds).toHaveLength(2);
+ expect(kbds[0].textContent).toBe('\u2318'); // ⌘
+ expect(kbds[1].textContent).toBe('K');
+ });
+
+ it('renders multi-key shortcuts', () => {
+ const {container} = render(
+ <XDSCommandPaletteShortcut keys="mod+shift+p" />,
+ );
+ const kbds = container.querySelectorAll('kbd');
+ expect(kbds).toHaveLength(3);
+ });
+});
+
+// =============================================================================
+// Composable component tests (Layer 1)
+// =============================================================================
+
+describe('XDSCommandPalette (composable)', () => {
+ it('renders when isShown is true', () => {
+ render(
+ <XDSCommandPalette isShown={true} onHide={vi.fn()}>
+ <XDSCommandPaletteInput />
+ <XDSCommandPaletteList>
+ <XDSCommandPaletteItem value="test" onSelect={vi.fn()}>
+ Test Item
+ </XDSCommandPaletteItem>
+ </XDSCommandPaletteList>
+ </XDSCommandPalette>,
+ );
+ expect(screen.getByRole('combobox')).toBeInTheDocument();
+ expect(screen.getByText('Test Item')).toBeInTheDocument();
+ });
+
+ it('renders groups with headings', () => {
+ render(
+ <XDSCommandPalette isShown={true} onHide={vi.fn()}>
+ <XDSCommandPaletteInput />
+ <XDSCommandPaletteList>
+ <XDSCommandPaletteGroup heading="Navigation">
+ <XDSCommandPaletteItem value="home" onSelect={vi.fn()}>
+ Home
+ </XDSCommandPaletteItem>
+ </XDSCommandPaletteGroup>
+ </XDSCommandPaletteList>
+ </XDSCommandPalette>,
+ );
+ expect(screen.getByText('Navigation')).toBeInTheDocument();
+ expect(screen.getByText('Home')).toBeInTheDocument();
+ });
+
+ it('renders empty state', () => {
+ render(
+ <XDSCommandPalette isShown={true} onHide={vi.fn()}>
+ <XDSCommandPaletteInput />
+ <XDSCommandPaletteList>
+ <XDSCommandPaletteEmpty>No results found</XDSCommandPaletteEmpty>
+ </XDSCommandPaletteList>
+ </XDSCommandPalette>,
+ );
+ expect(screen.getByText('No results found')).toBeInTheDocument();
+ });
+
+ it('renders loading state', () => {
+ render(
+ <XDSCommandPalette isShown={true} onHide={vi.fn()}>
+ <XDSCommandPaletteInput />
+ <XDSCommandPaletteList>
+ <XDSCommandPaletteLoading>Searching...</XDSCommandPaletteLoading>
+ </XDSCommandPaletteList>
+ </XDSCommandPalette>,
+ );
+ expect(screen.getByText('Searching...')).toBeInTheDocument();
+ });
+
+ it('renders footer', () => {
+ render(
+ <XDSCommandPalette isShown={true} onHide={vi.fn()}>
+ <XDSCommandPaletteInput />
+ <XDSCommandPaletteList>
+ <XDSCommandPaletteItem value="test" onSelect={vi.fn()}>
+ Test
+ </XDSCommandPaletteItem>
+ </XDSCommandPaletteList>
+ <XDSCommandPaletteFooter>
+ <span>↵ Select</span>
+ </XDSCommandPaletteFooter>
+ </XDSCommandPalette>,
+ );
+ expect(screen.getByText('↵ Select')).toBeInTheDocument();
+ });
+
+ it('calls onSelect when item is clicked', () => {
+ const onSelect = vi.fn();
+ render(
+ <XDSCommandPalette isShown={true} onHide={vi.fn()}>
+ <XDSCommandPaletteInput />
+ <XDSCommandPaletteList>
+ <XDSCommandPaletteItem value="test" onSelect={onSelect}>
+ Test Item
+ </XDSCommandPaletteItem>
+ </XDSCommandPaletteList>
+ </XDSCommandPalette>,
+ );
+ fireEvent.click(screen.getByText('Test Item'));
+ expect(onSelect).toHaveBeenCalledWith('test');
+ });
+
+ it('does not call onSelect for disabled items', () => {
+ const onSelect = vi.fn();
+ render(
+ <XDSCommandPalette isShown={true} onHide={vi.fn()}>
+ <XDSCommandPaletteInput />
+ <XDSCommandPaletteList>
+ <XDSCommandPaletteItem
+ value="test"
+ onSelect={onSelect}
+ isDisabled>
+ Disabled Item
+ </XDSCommandPaletteItem>
+ </XDSCommandPaletteList>
+ </XDSCommandPalette>,
+ );
+ fireEvent.click(screen.getByText('Disabled Item'));
+ expect(onSelect).not.toHaveBeenCalled();
+ });
+
+ it('has correct ARIA attributes', () => {
+ render(
+ <XDSCommandPalette isShown={true} onHide={vi.fn()} label="Test palette">
+ <XDSCommandPaletteInput placeholder="Search..." />
+ <XDSCommandPaletteList>
+ <XDSCommandPaletteItem value="test" onSelect={vi.fn()}>
+ Test
+ </XDSCommandPaletteItem>
+ </XDSCommandPaletteList>
+ </XDSCommandPalette>,
+ );
+
+ const input = screen.getByRole('combobox');
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ expect(input).toHaveAttribute('aria-autocomplete', 'list');
+
+ const listbox = screen.getByRole('listbox');
+ expect(listbox).toBeInTheDocument();
+ });
+});
+
+// =============================================================================
+// History hook tests (Layer 3)
+// =============================================================================
+
+describe('useXDSCommandPaletteHistory', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ });
+
+ it('starts with empty history', () => {
+ const {result} = renderHook(() => useXDSCommandPaletteHistory());
+ expect(result.current.history).toEqual([]);
+ });
+
+ it('records entries', () => {
+ const {result} = renderHook(() => useXDSCommandPaletteHistory());
+
+ act(() => {
+ result.current.record('cmd-1');
+ });
+
+ expect(result.current.history).toHaveLength(1);
+ expect(result.current.history[0].id).toBe('cmd-1');
+ });
+
+ it('moves re-selected entries to top', () => {
+ const {result} = renderHook(() => useXDSCommandPaletteHistory());
+
+ act(() => {
+ result.current.record('cmd-1');
+ result.current.record('cmd-2');
+ result.current.record('cmd-1');
+ });
+
+ expect(result.current.history).toHaveLength(2);
+ expect(result.current.history[0].id).toBe('cmd-1');
+ });
+
+ it('respects maxEntries', () => {
+ const {result} = renderHook(() =>
+ useXDSCommandPaletteHistory({maxEntries: 2}),
+ );
+
+ act(() => {
+ result.current.record('cmd-1');
+ result.current.record('cmd-2');
+ result.current.record('cmd-3');
+ });
+
+ expect(result.current.history).toHaveLength(2);
+ expect(result.current.history[0].id).toBe('cmd-3');
+ });
+
+ it('clears history', () => {
+ const {result} = renderHook(() => useXDSCommandPaletteHistory());
+
+ act(() => {
+ result.current.record('cmd-1');
+ result.current.clear();
+ });
+
+ expect(result.current.history).toEqual([]);
+ });
+
+ it('clears individual entries', () => {
+ const {result} = renderHook(() => useXDSCommandPaletteHistory());
+
+ act(() => {
+ result.current.record('cmd-1');
+ result.current.record('cmd-2');
+ result.current.clearEntry('cmd-1');
+ });
+
+ expect(result.current.history).toHaveLength(1);
+ expect(result.current.history[0].id).toBe('cmd-2');
+ });
+
+ it('persists to localStorage when enabled', () => {
+ const {result} = renderHook(() =>
+ useXDSCommandPaletteHistory({
+ persist: true,
+ storageKey: 'test-history',
+ }),
+ );
+
+ act(() => {
+ result.current.record('cmd-1');
+ });
+
+ const stored = JSON.parse(localStorage.getItem('test-history') ?? '[]');
+ expect(stored).toHaveLength(1);
+ expect(stored[0].id).toBe('cmd-1');
+ });
+});
+
+// =============================================================================
+// Helper: renderHook (minimal implementation for vitest)
+// =============================================================================
+
+function renderHook<T>(hook: () => T) {
+ const result = {current: {} as T};
+
+ function TestComponent() {
+ result.current = hook();
+ return null;
+ }
+
+ render(<TestComponent />);
+ return {result};
+}
diff --git a/packages/core/src/CommandPalette/XDSCommandPalette.tsx b/packages/core/src/CommandPalette/XDSCommandPalette.tsx
new file mode 100644
index 0000000000..2f82a2ddd6
--- /dev/null
+++ b/packages/core/src/CommandPalette/XDSCommandPalette.tsx
@@ -0,0 +1,228 @@
+/**
+ * @file XDSCommandPalette.tsx
+ * @input Uses React, StyleX, XDSDialog, CommandPaletteContext
+ * @output Exports XDSCommandPalette root component and props
+ * @position Core root component; wraps composable sub-components
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/CommandPalette/README.md
+ * - /packages/core/src/CommandPalette/index.ts
+ * - /apps/storybook/stories/CommandPalette.stories.tsx
+ */
+
+import {
+ useCallback,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import type {StyleXStyles} from '@stylexjs/stylex';
+import {XDSDialog} from '../Dialog';
+import {CommandPaletteContext} from './CommandPaletteContext';
+import {defaultFilter} from './filter';
+import type {CommandPaletteFilterFn} from './types';
+
+const styles = stylex.create({
+ dialog: {
+ // Override dialog defaults for command palette appearance
+ overflow: 'hidden',
+ },
+});
+
+export interface XDSCommandPaletteProps {
+ /**
+ * Whether the command palette is shown.
+ * Matches XDSDialog convention.
+ */
+ isShown: boolean;
+
+ /**
+ * Called when the palette requests to close.
+ * Matches XDSDialog convention.
+ */
+ onHide: () => void;
+
+ /**
+ * Controlled selected value.
+ */
+ value?: string;
+
+ /**
+ * Called when the selected value changes.
+ */
+ onValueChange?: (value: string) => void;
+
+ /**
+ * Custom filter function. Return a score between 0 and 1.
+ * When provided, replaces the built-in substring filter.
+ */
+ filter?: CommandPaletteFilterFn;
+
+ /**
+ * Disable built-in filtering entirely.
+ * Useful when filtering is handled externally (e.g., server-side search).
+ * @default true
+ */
+ isFiltered?: boolean;
+
+ /**
+ * Accessible label for the command palette.
+ * @default "Command palette"
+ */
+ label?: string;
+
+ /**
+ * Width of the command palette dialog.
+ * @default 640
+ */
+ width?: number | string;
+
+ /**
+ * Maximum height of the command palette dialog.
+ * @default 480
+ */
+ maxHeight?: number | string;
+
+ /**
+ * StyleX overrides for the dialog container.
+ */
+ xstyle?: StyleXStyles;
+
+ /**
+ * Composable content: XDSCommandPaletteInput, XDSCommandPaletteList, etc.
+ *
+ * @example
+ * ```
+ * <XDSCommandPalette isShown={isShown} onHide={() => setIsShown(false)}>
+ * <XDSCommandPaletteInput placeholder="Search commands..." />
+ * <XDSCommandPaletteList>
+ * <XDSCommandPaletteItem value="home" onSelect={() => navigate("/")}>
+ * Go Home
+ * </XDSCommandPaletteItem>
+ * </XDSCommandPaletteList>
+ * </XDSCommandPalette>
+ * ```
+ */
+ children: ReactNode;
+}
+
+/**
+ * Command palette root component.
+ *
+ * Composes with XDSDialog for modal behavior and provides context
+ * for composable sub-components (Input, List, Item, Group, etc.).
+ *
+ * Supports two usage patterns:
+ * 1. Composable (Layer 1): Render sub-components directly as children
+ * 2. Provider (Layer 2): Use XDSCommandPaletteProvider for distributed command registration
+ */
+export function XDSCommandPalette({
+ isShown,
+ onHide,
+ value: controlledValue,
+ onValueChange,
+ filter = defaultFilter,
+ isFiltered = true,
+ label = 'Command palette',
+ width = 640,
+ maxHeight = 480,
+ xstyle,
+ children,
+}: XDSCommandPaletteProps) {
+ 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 value = controlledValue ?? internalValue;
+
+ const setValue = useCallback(
+ (newValue: string) => {
+ if (controlledValue === undefined) {
+ setInternalValue(newValue);
+ }
+ onValueChange?.(newValue);
+ },
+ [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,
+ );
+ };
+ },
+ [],
+ );
+
+ const selectItem = useCallback(
+ (itemValue: string) => {
+ setValue(itemValue);
+ },
+ [setValue],
+ );
+
+ // Reset search and highlight when opening/closing
+ const handleHide = useCallback(() => {
+ setSearch('');
+ setHighlightedIndex(0);
+ onHide();
+ }, [onHide]);
+
+ const contextValue = useMemo(
+ () => ({
+ search,
+ setSearch,
+ value,
+ setValue,
+ filter,
+ isFiltered,
+ listId,
+ highlightedIndex,
+ setHighlightedIndex,
+ items: itemsRef.current,
+ registerItem,
+ selectItem,
+ onHide: handleHide,
+ }),
+ [
+ search,
+ value,
+ setValue,
+ filter,
+ isFiltered,
+ listId,
+ highlightedIndex,
+ registerItem,
+ selectItem,
+ handleHide,
+ ],
+ );
+
+ return (
+ <XDSDialog
+ isShown={isShown}
+ onHide={handleHide}
+ width={width}
+ maxHeight={maxHeight}
+ purpose="info"
+ aria-label={label}
+ {...stylex.props(styles.dialog, xstyle)}>
+ <CommandPaletteContext.Provider value={contextValue}>
+ {children}
+ </CommandPaletteContext.Provider>
+ </XDSDialog>
+ );
+}
+
+XDSCommandPalette.displayName = 'XDSCommandPalette';
diff --git a/packages/core/src/CommandPalette/XDSCommandPaletteEmpty.tsx b/packages/core/src/CommandPalette/XDSCommandPaletteEmpty.tsx
new file mode 100644
index 0000000000..c5d6f255ca
--- /dev/null
+++ b/packages/core/src/CommandPalette/XDSCommandPaletteEmpty.tsx
@@ -0,0 +1,47 @@
+/**
+ * @file XDSCommandPaletteEmpty.tsx
+ * @input Uses React, StyleX
+ * @output Exports XDSCommandPaletteEmpty component
+ * @position Sub-component; shown when no results match
+ */
+
+import type {ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ spacingVars,
+ textSizeVars,
+ typographyVars,
+} from '../theme/tokens.stylex';
+
+const styles = stylex.create({
+ empty: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ paddingBlock: spacingVars['--spacing-6'],
+ paddingInline: spacingVars['--spacing-4'],
+ fontFamily: typographyVars['--font-body'],
+ fontSize: textSizeVars['--text-sm'],
+ color: colorVars['--color-text-secondary'],
+ userSelect: 'none',
+ },
+});
+
+export interface XDSCommandPaletteEmptyProps {
+ /** Content to display when no results are found. */
+ children: ReactNode;
+}
+
+/**
+ * Empty state shown when no command palette items match the search.
+ */
+export function XDSCommandPaletteEmpty({children}: XDSCommandPaletteEmptyProps) {
+ return (
+ <div role="status" {...stylex.props(styles.empty)}>
+ {children}
+ </div>
+ );
+}
+
+XDSCommandPaletteEmpty.displayName = 'XDSCommandPaletteEmpty';
diff --git a/packages/core/src/CommandPalette/XDSCommandPaletteFooter.tsx b/packages/core/src/CommandPalette/XDSCommandPaletteFooter.tsx
new file mode 100644
index 0000000000..71dd3ae64c
--- /dev/null
+++ b/packages/core/src/CommandPalette/XDSCommandPaletteFooter.tsx
@@ -0,0 +1,60 @@
+/**
+ * @file XDSCommandPaletteFooter.tsx
+ * @input Uses React, StyleX
+ * @output Exports XDSCommandPaletteFooter component
+ * @position Sub-component; footer bar with hints
+ */
+
+import type {ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ spacingVars,
+ textSizeVars,
+ typographyVars,
+} from '../theme/tokens.stylex';
+
+const styles = stylex.create({
+ footer: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-4'],
+ paddingInline: spacingVars['--spacing-4'],
+ paddingBlock: spacingVars['--spacing-2'],
+ borderTopWidth: '1px',
+ borderTopStyle: 'solid',
+ borderTopColor: colorVars['--color-divider'],
+ fontFamily: typographyVars['--font-body'],
+ fontSize: textSizeVars['--text-xsm'],
+ color: colorVars['--color-text-secondary'],
+ userSelect: 'none',
+ },
+});
+
+export interface XDSCommandPaletteFooterProps {
+ /** Footer content — typically keyboard navigation hints. */
+ children: ReactNode;
+}
+
+/**
+ * Footer bar for the command palette.
+ * Typically shows keyboard navigation hints.
+ *
+ * @example
+ * ```
+ * <XDSCommandPaletteFooter>
+ * <span>↑↓ Navigate</span>
+ * <span>↵ Select</span>
+ * <span>Esc Close</span>
+ * </XDSCommandPaletteFooter>
+ * ```
+ */
+export function XDSCommandPaletteFooter({children}: XDSCommandPaletteFooterProps) {
+ return (
+ <div {...stylex.props(styles.footer)}>
+ {children}
+ </div>
+ );
+}
+
+XDSCommandPaletteFooter.displayName = 'XDSCommandPaletteFooter';
diff --git a/packages/core/src/CommandPalette/XDSCommandPaletteGroup.tsx b/packages/core/src/CommandPalette/XDSCommandPaletteGroup.tsx
new file mode 100644
index 0000000000..4b3af920b6
--- /dev/null
+++ b/packages/core/src/CommandPalette/XDSCommandPaletteGroup.tsx
@@ -0,0 +1,79 @@
+/**
+ * @file XDSCommandPaletteGroup.tsx
+ * @input Uses React, StyleX
+ * @output Exports XDSCommandPaletteGroup component
+ * @position Sub-component; visual grouping with heading
+ */
+
+import type {ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import type {StyleXStyles} from '@stylexjs/stylex';
+import {
+ colorVars,
+ spacingVars,
+ textSizeVars,
+ typographyVars,
+ fontWeightVars,
+} from '../theme/tokens.stylex';
+
+const styles = stylex.create({
+ group: {
+ paddingBlock: spacingVars['--spacing-1'],
+ },
+ heading: {
+ paddingInline: spacingVars['--spacing-3'],
+ paddingBlock: spacingVars['--spacing-1'],
+ fontFamily: typographyVars['--font-body'],
+ fontSize: textSizeVars['--text-xsm'],
+ fontWeight: fontWeightVars['--font-weight-semibold'],
+ color: colorVars['--color-text-secondary'],
+ textTransform: 'uppercase' as const,
+ letterSpacing: '0.05em',
+ userSelect: 'none',
+ },
+});
+
+export interface XDSCommandPaletteGroupProps {
+ /**
+ * Group heading text.
+ */
+ heading: string;
+
+ /**
+ * Items within this group.
+ */
+ children: ReactNode;
+
+ /**
+ * StyleX overrides for the group container.
+ */
+ xstyle?: StyleXStyles;
+}
+
+/**
+ * Visual grouping for command palette items.
+ *
+ * @example
+ * ```
+ * <XDSCommandPaletteGroup heading="Navigation">
+ * <XDSCommandPaletteItem value="home" onSelect={goHome}>Home</XDSCommandPaletteItem>
+ * <XDSCommandPaletteItem value="settings" onSelect={goSettings}>Settings</XDSCommandPaletteItem>
+ * </XDSCommandPaletteGroup>
+ * ```
+ */
+export function XDSCommandPaletteGroup({
+ heading,
+ children,
+ xstyle,
+}: XDSCommandPaletteGroupProps) {
+ return (
+ <div role="group" aria-label={heading} {...stylex.props(styles.group, xstyle)}>
+ <div aria-hidden="true" {...stylex.props(styles.heading)}>
+ {heading}
+ </div>
+ {children}
+ </div>
+ );
+}
+
+XDSCommandPaletteGroup.displayName = 'XDSCommandPaletteGroup';
diff --git a/packages/core/src/CommandPalette/XDSCommandPaletteInput.tsx b/packages/core/src/CommandPalette/XDSCommandPaletteInput.tsx
new file mode 100644
index 0000000000..f5fc6b8a1f
--- /dev/null
+++ b/packages/core/src/CommandPalette/XDSCommandPaletteInput.tsx
@@ -0,0 +1,209 @@
+/**
+ * @file XDSCommandPaletteInput.tsx
+ * @input Uses React, StyleX, CommandPaletteContext, XDSIcon
+ * @output Exports XDSCommandPaletteInput component
+ * @position Sub-component; renders the search input inside XDSCommandPalette
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/CommandPalette/README.md
+ * - /packages/core/src/CommandPalette/index.ts
+ */
+
+import {useCallback, useRef, useEffect, type KeyboardEvent} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import type {StyleXStyles} from '@stylexjs/stylex';
+import {
+ colorVars,
+ spacingVars,
+ typographyVars,
+ textSizeVars,
+ lineHeightVars,
+} from '../theme/tokens.stylex';
+import {XDSIcon} from '../Icon';
+import {useCommandPaletteContext} from './CommandPaletteContext';
+
+
+const styles = stylex.create({
+ wrapper: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ paddingInline: spacingVars['--spacing-4'],
+ paddingBlock: spacingVars['--spacing-3'],
+ borderBottomWidth: '1px',
+ borderBottomStyle: 'solid',
+ borderBottomColor: colorVars['--color-divider'],
+ },
+ icon: {
+ flexShrink: 0,
+ color: colorVars['--color-text-secondary'],
+ },
+ input: {
+ flex: 1,
+ border: 'none',
+ outline: 'none',
+ backgroundColor: 'transparent',
+ color: colorVars['--color-text-primary'],
+ fontFamily: typographyVars['--font-body'],
+ fontSize: textSizeVars['--text-base'],
+ lineHeight: lineHeightVars['--leading-base'],
+ padding: 0,
+ '::placeholder': {
+ color: colorVars['--color-text-placeholder'],
+ },
+ },
+});
+
+export interface XDSCommandPaletteInputProps {
+ /**
+ * Placeholder text for the search input.
+ * @default "Search..."
+ */
+ placeholder?: string;
+
+ /**
+ * StyleX overrides for the input wrapper.
+ */
+ xstyle?: StyleXStyles;
+}
+
+/**
+ * Search input for the command palette.
+ * Handles keyboard navigation (arrow keys, enter, escape).
+ *
+ * @example
+ * ```
+ * <XDSCommandPalette isShown={isShown} onHide={onHide}>
+ * <XDSCommandPaletteInput placeholder="Search commands..." />
+ * <XDSCommandPaletteList>...</XDSCommandPaletteList>
+ * </XDSCommandPalette>
+ * ```
+ */
+export function XDSCommandPaletteInput({
+ placeholder = 'Search...',
+ xstyle,
+}: XDSCommandPaletteInputProps) {
+ const {
+ search,
+ setSearch,
+ listId,
+ highlightedIndex,
+ setHighlightedIndex,
+ items,
+ selectItem,
+ onHide,
+ } = useCommandPaletteContext();
+
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ // Auto-focus when mounted
+ useEffect(() => {
+ inputRef.current?.focus();
+ }, []);
+
+ // Keyboard navigation is handled here rather than via useListFocus because
+ // filtering causes items to appear/disappear dynamically. useListFocus is
+ // designed for static lists and doesn't account for items being filtered out
+ // mid-navigation. The combobox pattern (input + listbox) also requires the
+ // input to own focus while aria-activedescendant tracks the highlighted item.
+ const handleKeyDown = useCallback(
+ (e: KeyboardEvent<HTMLInputElement>) => {
+ switch (e.key) {
+ case 'ArrowDown': {
+ e.preventDefault();
+ // Find next enabled item
+ let next = highlightedIndex + 1;
+ while (next < items.length && items[next]?.isDisabled) {
+ next++;
+ }
+ if (next < items.length) {
+ setHighlightedIndex(next);
+ }
+ break;
+ }
+ case 'ArrowUp': {
+ e.preventDefault();
+ let prev = highlightedIndex - 1;
+ while (prev >= 0 && items[prev]?.isDisabled) {
+ prev--;
+ }
+ if (prev >= 0) {
+ setHighlightedIndex(prev);
+ }
+ break;
+ }
+ case 'Home': {
+ e.preventDefault();
+ let first = 0;
+ while (first < items.length && items[first]?.isDisabled) {
+ first++;
+ }
+ if (first < items.length) {
+ setHighlightedIndex(first);
+ }
+ break;
+ }
+ case 'End': {
+ e.preventDefault();
+ let last = items.length - 1;
+ while (last >= 0 && items[last]?.isDisabled) {
+ last--;
+ }
+ if (last >= 0) {
+ setHighlightedIndex(last);
+ }
+ break;
+ }
+ case 'Enter': {
+ e.preventDefault();
+ if (highlightedIndex >= 0 && highlightedIndex < items.length) {
+ const item = items[highlightedIndex];
+ if (item && !item.isDisabled) {
+ selectItem(item.value);
+ }
+ }
+ break;
+ }
+ case 'Escape': {
+ e.preventDefault();
+ onHide();
+ break;
+ }
+ }
+ },
+ [highlightedIndex, items, setHighlightedIndex, selectItem, onHide],
+ );
+
+ const activeDescendant =
+ highlightedIndex >= 0 ? `${listId}-item-${highlightedIndex}` : undefined;
+
+ return (
+ <div {...stylex.props(styles.wrapper, xstyle)}>
+ <div {...stylex.props(styles.icon)}>
+ <XDSIcon icon="search" size="sm" color="secondary" />
+ </div>
+ <input
+ ref={inputRef}
+ type="text"
+ value={search}
+ onChange={(e) => {
+ setSearch(e.target.value);
+ setHighlightedIndex(0);
+ }}
+ onKeyDown={handleKeyDown}
+ placeholder={placeholder}
+ role="combobox"
+ aria-expanded={true}
+ aria-controls={listId}
+ aria-activedescendant={activeDescendant}
+ aria-autocomplete="list"
+ autoComplete="off"
+ autoCorrect="off"
+ spellCheck={false}
+ {...stylex.props(styles.input)}
+ />
+ </div>
+ );
+}
+
+XDSCommandPaletteInput.displayName = 'XDSCommandPaletteInput';
diff --git a/packages/core/src/CommandPalette/XDSCommandPaletteItem.tsx b/packages/core/src/CommandPalette/XDSCommandPaletteItem.tsx
new file mode 100644
index 0000000000..50bd098c38
--- /dev/null
+++ b/packages/core/src/CommandPalette/XDSCommandPaletteItem.tsx
@@ -0,0 +1,181 @@
+/**
+ * @file XDSCommandPaletteItem.tsx
+ * @input Uses React, StyleX, CommandPaletteContext
+ * @output Exports XDSCommandPaletteItem component
+ * @position Sub-component; individual selectable item
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/CommandPalette/README.md
+ * - /packages/core/src/CommandPalette/index.ts
+ */
+
+import {useCallback, useEffect, useRef, type ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import type {StyleXStyles} from '@stylexjs/stylex';
+import {
+ colorVars,
+ spacingVars,
+ radiusVars,
+ typographyVars,
+ textSizeVars,
+} from '../theme/tokens.stylex';
+import {useCommandPaletteContext} from './CommandPaletteContext';
+
+const HOVER_HOVER = '@media (hover: hover)';
+
+const styles = stylex.create({
+ item: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ width: '100%',
+ paddingInline: spacingVars['--spacing-3'],
+ paddingBlock: spacingVars['--spacing-2'],
+ borderRadius: radiusVars['--radius-content'],
+ fontFamily: typographyVars['--font-body'],
+ fontSize: textSizeVars['--text-base'],
+ color: colorVars['--color-text-primary'],
+ backgroundColor: 'transparent',
+ border: 'none',
+ cursor: 'pointer',
+ textAlign: 'left',
+ outline: 'none',
+ userSelect: 'none',
+ },
+ itemHover: {
+ ':hover': {
+ [HOVER_HOVER]: {
+ backgroundColor: colorVars['--color-hover-overlay'],
+ },
+ },
+ },
+ itemHighlighted: {
+ backgroundColor: colorVars['--color-hover-overlay'],
+ },
+ itemDisabled: {
+ opacity: 0.5,
+ cursor: 'not-allowed',
+ },
+ itemSelected: {
+ backgroundColor: colorVars['--color-accent-deemphasized'],
+ },
+});
+
+export interface XDSCommandPaletteItemProps {
+ /**
+ * Unique value for filtering and selection.
+ */
+ value: string;
+
+ /**
+ * Called when this item is selected (via click or Enter).
+ */
+ onSelect?: (value: string) => void;
+
+ /**
+ * Additional search terms for filtering.
+ */
+ keywords?: string[];
+
+ /**
+ * Whether the item is disabled.
+ * @default false
+ */
+ isDisabled?: boolean;
+
+ /**
+ * Item content. Fully custom — render icons, descriptions, shortcuts, etc.
+ */
+ children: ReactNode;
+
+ /**
+ * StyleX overrides for the item.
+ */
+ xstyle?: StyleXStyles;
+}
+
+/**
+ * A selectable item in the command palette.
+ * Accepts arbitrary children for full rendering control.
+ *
+ * @example
+ * ```
+ * <XDSCommandPaletteItem value="settings" onSelect={() => navigate("/settings")}>
+ * <XDSIcon icon="settings" size="sm" />
+ * <span>Settings</span>
+ * <XDSCommandPaletteShortcut keys="mod+," />
+ * </XDSCommandPaletteItem>
+ * ```
+ */
+export function XDSCommandPaletteItem({
+ value,
+ onSelect,
+ keywords,
+ isDisabled = false,
+ children,
+ xstyle,
+}: XDSCommandPaletteItemProps) {
+ const ctx = useCommandPaletteContext();
+ const itemRef = useRef<HTMLDivElement>(null);
+
+ // Register with context on mount
+ useEffect(() => {
+ const unregister = ctx.registerItem(value, isDisabled);
+ return unregister;
+ }, [value, isDisabled, ctx.registerItem]);
+
+ // Determine this item's index in the items array
+ const itemIndex = ctx.items.findIndex((item) => item.value === value);
+ const isHighlighted = itemIndex === ctx.highlightedIndex;
+ const isSelected = ctx.value === value;
+
+ // Filter: check if this item matches the search
+ const score = ctx.isFiltered
+ ? ctx.filter(value, ctx.search, keywords)
+ : 1;
+
+ // Scroll highlighted item into view
+ useEffect(() => {
+ if (isHighlighted && itemRef.current) {
+ itemRef.current.scrollIntoView?.({block: 'nearest'});
+ }
+ }, [isHighlighted]);
+
+ const handleClick = useCallback(() => {
+ if (isDisabled) return;
+ onSelect?.(value);
+ ctx.selectItem(value);
+ ctx.onHide();
+ }, [isDisabled, value, onSelect, ctx]);
+
+ const handleMouseEnter = useCallback(() => {
+ if (isDisabled) return;
+ ctx.setHighlightedIndex(itemIndex);
+ }, [isDisabled, itemIndex, ctx]);
+
+ // Don't render if filtered out
+ if (score === 0) return null;
+
+ return (
+ <div
+ ref={itemRef}
+ id={`${ctx.listId}-item-${itemIndex}`}
+ role="option"
+ aria-selected={isHighlighted}
+ aria-disabled={isDisabled || undefined}
+ onClick={handleClick}
+ onMouseEnter={handleMouseEnter}
+ {...stylex.props(
+ styles.item,
+ !isDisabled && styles.itemHover,
+ isHighlighted && styles.itemHighlighted,
+ isSelected && styles.itemSelected,
+ isDisabled && styles.itemDisabled,
+ xstyle,
+ )}>
+ {children}
+ </div>
+ );
+}
+
+XDSCommandPaletteItem.displayName = 'XDSCommandPaletteItem';
diff --git a/packages/core/src/CommandPalette/XDSCommandPaletteList.tsx b/packages/core/src/CommandPalette/XDSCommandPaletteList.tsx
new file mode 100644
index 0000000000..bada751669
--- /dev/null
+++ b/packages/core/src/CommandPalette/XDSCommandPaletteList.tsx
@@ -0,0 +1,68 @@
+/**
+ * @file XDSCommandPaletteList.tsx
+ * @input Uses React, StyleX, CommandPaletteContext
+ * @output Exports XDSCommandPaletteList component
+ * @position Sub-component; scrollable results container
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/CommandPalette/README.md
+ * - /packages/core/src/CommandPalette/index.ts
+ */
+
+import type {ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import type {StyleXStyles} from '@stylexjs/stylex';
+import {spacingVars} from '../theme/tokens.stylex';
+import {useCommandPaletteContext} from './CommandPaletteContext';
+
+const styles = stylex.create({
+ list: {
+ overflowY: 'auto',
+ maxHeight: '100%',
+ padding: spacingVars['--spacing-1'],
+ flex: 1,
+ },
+});
+
+export interface XDSCommandPaletteListProps {
+ /**
+ * Command palette items, groups, empty states, etc.
+ */
+ children: ReactNode;
+
+ /**
+ * StyleX overrides for the list container.
+ */
+ xstyle?: StyleXStyles;
+}
+
+/**
+ * Scrollable results container for the command palette.
+ * Renders as a listbox for ARIA compliance.
+ *
+ * @example
+ * ```
+ * <XDSCommandPaletteList>
+ * <XDSCommandPaletteItem value="home" onSelect={goHome}>
+ * Go Home
+ * </XDSCommandPaletteItem>
+ * </XDSCommandPaletteList>
+ * ```
+ */
+export function XDSCommandPaletteList({
+ children,
+ xstyle,
+}: XDSCommandPaletteListProps) {
+ const {listId} = useCommandPaletteContext();
+
+ return (
+ <div
+ id={listId}
+ role="listbox"
+ {...stylex.props(styles.list, xstyle)}>
+ {children}
+ </div>
+ );
+}
+
+XDSCommandPaletteList.displayName = 'XDSCommandPaletteList';
diff --git a/packages/core/src/CommandPalette/XDSCommandPaletteLoading.tsx b/packages/core/src/CommandPalette/XDSCommandPaletteLoading.tsx
new file mode 100644
index 0000000000..fdd25e4496
--- /dev/null
+++ b/packages/core/src/CommandPalette/XDSCommandPaletteLoading.tsx
@@ -0,0 +1,49 @@
+/**
+ * @file XDSCommandPaletteLoading.tsx
+ * @input Uses React, StyleX, XDSSpinner
+ * @output Exports XDSCommandPaletteLoading component
+ * @position Sub-component; loading indicator
+ */
+
+import type {ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ spacingVars,
+ textSizeVars,
+ typographyVars,
+} from '../theme/tokens.stylex';
+
+const styles = stylex.create({
+ loading: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: spacingVars['--spacing-2'],
+ paddingBlock: spacingVars['--spacing-4'],
+ paddingInline: spacingVars['--spacing-4'],
+ fontFamily: typographyVars['--font-body'],
+ fontSize: textSizeVars['--text-sm'],
+ color: colorVars['--color-text-secondary'],
+ },
+});
+
+export interface XDSCommandPaletteLoadingProps {
+ /** Loading content. */
+ children?: ReactNode;
+}
+
+/**
+ * Loading indicator for async command fetching.
+ */
+export function XDSCommandPaletteLoading({
+ children = 'Loading...',
+}: XDSCommandPaletteLoadingProps) {
+ return (
+ <div role="status" aria-live="polite" {...stylex.props(styles.loading)}>
+ {children}
+ </div>
+ );
+}
+
+XDSCommandPaletteLoading.displayName = 'XDSCommandPaletteLoading';
diff --git a/packages/core/src/CommandPalette/XDSCommandPaletteProvider.tsx b/packages/core/src/CommandPalette/XDSCommandPaletteProvider.tsx
new file mode 100644
index 0000000000..a126d52c79
--- /dev/null
+++ b/packages/core/src/CommandPalette/XDSCommandPaletteProvider.tsx
@@ -0,0 +1,405 @@
+/**
+ * @file XDSCommandPaletteProvider.tsx
+ * @input Uses React, CommandPalette composable components
+ * @output Exports XDSCommandPaletteProvider, useXDSCommandPaletteRegister, useXDSCommandPalette
+ * @position Layer 2 convenience wrapper; composes Layer 1 primitives
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/CommandPalette/README.md
+ * - /packages/core/src/CommandPalette/index.ts
+ */
+
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from 'react';
+import {XDSCommandPalette} from './XDSCommandPalette';
+import {XDSCommandPaletteInput} from './XDSCommandPaletteInput';
+import {XDSCommandPaletteList} from './XDSCommandPaletteList';
+import {XDSCommandPaletteItem} from './XDSCommandPaletteItem';
+import {XDSCommandPaletteGroup} from './XDSCommandPaletteGroup';
+import {XDSCommandPaletteEmpty} from './XDSCommandPaletteEmpty';
+import {XDSCommandPaletteShortcut} from './XDSCommandPaletteShortcut';
+import {XDSCommandPaletteFooter} from './XDSCommandPaletteFooter';
+import {XDSCommandPaletteLoading} from './XDSCommandPaletteLoading';
+import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ textSizeVars,
+} from '../theme/tokens.stylex';
+import {XDSIcon} from '../Icon';
+import type {XDSCommand, CommandPaletteFilterFn} from './types';
+
+// =============================================================================
+// Provider context
+// =============================================================================
+
+interface ProviderContextValue {
+ /** Open the command palette. */
+ open: () => void;
+ /** Close the command palette. */
+ close: () => void;
+ /** Whether the palette is currently open. */
+ isOpen: boolean;
+ /** Register commands. Returns unregister function. */
+ register: (commands: XDSCommand[]) => () => void;
+}
+
+const ProviderContext = createContext<ProviderContextValue | null>(null);
+
+// =============================================================================
+// Hooks
+// =============================================================================
+
+/**
+ * Imperative control for the command palette.
+ *
+ * @example
+ * ```
+ * function SearchButton() {
+ * const { open, isOpen } = useXDSCommandPalette();
+ * return <XDSButton label="Search" onClick={open} />;
+ * }
+ * ```
+ */
+export function useXDSCommandPalette() {
+ const context = useContext(ProviderContext);
+ if (context == null) {
+ throw new Error(
+ 'useXDSCommandPalette must be used within <XDSCommandPaletteProvider>',
+ );
+ }
+ return {
+ open: context.open,
+ close: context.close,
+ isOpen: context.isOpen,
+ };
+}
+
+/**
+ * Register commands from any component in the tree.
+ * Commands are automatically unregistered when the component unmounts.
+ *
+ * @example
+ * ```
+ * function Navigation() {
+ * useXDSCommandPaletteRegister([
+ * { id: 'home', label: 'Go Home', icon: 'home', onSelect: () => navigate('/') },
+ * { id: 'settings', label: 'Settings', shortcut: 'mod+,', onSelect: () => navigate('/settings') },
+ * ]);
+ * return <nav>...</nav>;
+ * }
+ * ```
+ */
+export function useXDSCommandPaletteRegister(
+ commands: XDSCommand[],
+ deps?: React.DependencyList,
+) {
+ const context = useContext(ProviderContext);
+ if (context == null) {
+ throw new Error(
+ 'useXDSCommandPaletteRegister must be used within <XDSCommandPaletteProvider>',
+ );
+ }
+
+ // Use a ref to avoid the deps footgun from PR #304
+ const commandsRef = useRef(commands);
+ commandsRef.current = commands;
+
+ useEffect(() => {
+ const unregister = context.register(commandsRef.current);
+ return unregister;
+ }, deps ?? []);
+}
+
+// =============================================================================
+// Provider
+// =============================================================================
+
+export interface XDSCommandPaletteProviderProps {
+ /** App content. */
+ children: ReactNode;
+
+ /**
+ * Keyboard shortcut to open the palette.
+ * @default "mod+k"
+ */
+ shortcut?: string;
+
+ /**
+ * Placeholder text for the search input.
+ * @default "Search commands..."
+ */
+ placeholder?: string;
+
+ /**
+ * Content shown when no results match.
+ * @default "No results found"
+ */
+ emptyContent?: ReactNode;
+
+ /**
+ * Footer content.
+ */
+ footer?: ReactNode;
+
+ /**
+ * Custom filter function.
+ */
+ filter?: CommandPaletteFilterFn;
+
+ /**
+ * Async command source. Called when the search query changes.
+ * Results are merged with registered commands.
+ */
+ commandFetcher?: (query: string) => Promise<XDSCommand[]>;
+
+ /**
+ * Debounce delay for commandFetcher in ms.
+ * @default 200
+ */
+ fetchDebounceMs?: number;
+}
+
+/**
+ * Provider for distributed command registration.
+ *
+ * Wraps the app and renders the command palette dialog.
+ * Components anywhere in the tree can register commands via useXDSCommandPaletteRegister.
+ *
+ * @example
+ * ```
+ * <XDSCommandPaletteProvider shortcut="mod+k">
+ * <App />
+ * </XDSCommandPaletteProvider>
+ * ```
+ */
+export function XDSCommandPaletteProvider({
+ children,
+ shortcut = 'mod+k',
+ placeholder = 'Search commands...',
+ emptyContent = 'No results found',
+ footer,
+ filter,
+ commandFetcher,
+ fetchDebounceMs = 200,
+}: XDSCommandPaletteProviderProps) {
+ const [isOpen, setIsOpen] = useState(false);
+ const [commands, setCommands] = useState<XDSCommand[]>([]);
+ const [fetchedCommands, setFetchedCommands] = useState<XDSCommand[]>([]);
+ const [isFetching, setIsFetching] = useState(false);
+ const [search, setSearch] = useState('');
+ const fetchTimeoutRef = useRef<ReturnType<typeof setTimeout>>(undefined);
+
+ const open = useCallback(() => setIsOpen(true), []);
+ const close = useCallback(() => {
+ setIsOpen(false);
+ setSearch('');
+ setFetchedCommands([]);
+ }, []);
+
+ const register = useCallback((newCommands: XDSCommand[]) => {
+ setCommands((prev) => [...prev, ...newCommands]);
+ return () => {
+ setCommands((prev) =>
+ prev.filter((cmd) => !newCommands.some((nc) => nc.id === cmd.id)),
+ );
+ };
+ }, []);
+
+ // Keyboard shortcut listener
+ useEffect(() => {
+ const parts = shortcut.split('+').map((p) => p.trim().toLowerCase());
+ const key = parts[parts.length - 1];
+ const needsMod = parts.includes('mod');
+ const needsShift = parts.includes('shift');
+ const needsAlt = parts.includes('alt');
+
+ const handleKeyDown = (e: KeyboardEvent) => {
+ const modPressed = e.metaKey || e.ctrlKey;
+ if (
+ e.key.toLowerCase() === key &&
+ (!needsMod || modPressed) &&
+ (!needsShift || e.shiftKey) &&
+ (!needsAlt || e.altKey)
+ ) {
+ e.preventDefault();
+ setIsOpen((prev) => !prev);
+ }
+ };
+
+ document.addEventListener('keydown', handleKeyDown);
+ return () => document.removeEventListener('keydown', handleKeyDown);
+ }, [shortcut]);
+
+ // Async command fetching with debounce
+ useEffect(() => {
+ if (!commandFetcher || !isOpen) return;
+
+ if (fetchTimeoutRef.current) {
+ clearTimeout(fetchTimeoutRef.current);
+ }
+
+ if (search.length === 0) {
+ setFetchedCommands([]);
+ setIsFetching(false);
+ return;
+ }
+
+ setIsFetching(true);
+ fetchTimeoutRef.current = setTimeout(async () => {
+ try {
+ const results = await commandFetcher(search);
+ setFetchedCommands(results);
+ } catch {
+ setFetchedCommands([]);
+ } finally {
+ setIsFetching(false);
+ }
+ }, fetchDebounceMs);
+
+ return () => {
+ if (fetchTimeoutRef.current) {
+ clearTimeout(fetchTimeoutRef.current);
+ }
+ };
+ }, [search, commandFetcher, fetchDebounceMs, isOpen]);
+
+ // Merge registered + fetched commands, sort by priority and group
+ const allCommands = useMemo(() => {
+ const merged = [...commands, ...fetchedCommands];
+ return merged.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
+ }, [commands, fetchedCommands]);
+
+ // Group commands
+ const groupedCommands = useMemo(() => {
+ const groups = new Map<string, XDSCommand[]>();
+ const ungrouped: XDSCommand[] = [];
+
+ for (const cmd of allCommands) {
+ // Only show root-level commands (no parent)
+ if (cmd.parent) continue;
+
+ if (cmd.group) {
+ const group = groups.get(cmd.group) ?? [];
+ group.push(cmd);
+ groups.set(cmd.group, group);
+ } else {
+ ungrouped.push(cmd);
+ }
+ }
+
+ return {groups, ungrouped};
+ }, [allCommands]);
+
+ const contextValue = useMemo(
+ () => ({open, close, isOpen, register}),
+ [open, close, isOpen, register],
+ );
+
+ const handleValueChange = useCallback(
+ (value: string) => {
+ const cmd = allCommands.find((c) => c.id === value);
+ if (cmd && !cmd.isDisabled) {
+ cmd.onSelect();
+ close();
+ }
+ },
+ [allCommands, close],
+ );
+
+ // Default footer with keyboard hints
+ const defaultFooter = (
+ <XDSCommandPaletteFooter>
+ <span>↑↓ Navigate</span>
+ <span>↵ Select</span>
+ <span>Esc Close</span>
+ </XDSCommandPaletteFooter>
+ );
+
+ return (
+ <ProviderContext.Provider value={contextValue}>
+ {children}
+ <XDSCommandPalette
+ isShown={isOpen}
+ onHide={close}
+ onValueChange={handleValueChange}
+ filter={filter}>
+ <XDSCommandPaletteInput placeholder={placeholder} />
+ <XDSCommandPaletteList>
+ {groupedCommands.ungrouped.map((cmd) => (
+ <CommandItem key={cmd.id} command={cmd} />
+ ))}
+ {Array.from(groupedCommands.groups.entries()).map(
+ ([groupName, cmds]) => (
+ <XDSCommandPaletteGroup key={groupName} heading={groupName}>
+ {cmds.map((cmd) => (
+ <CommandItem key={cmd.id} command={cmd} />
+ ))}
+ </XDSCommandPaletteGroup>
+ ),
+ )}
+ {isFetching && <XDSCommandPaletteLoading />}
+ {!isFetching && allCommands.length === 0 && (
+ <XDSCommandPaletteEmpty>{emptyContent}</XDSCommandPaletteEmpty>
+ )}
+ </XDSCommandPaletteList>
+ {footer ?? defaultFooter}
+ </XDSCommandPalette>
+ </ProviderContext.Provider>
+ );
+}
+
+XDSCommandPaletteProvider.displayName = 'XDSCommandPaletteProvider';
+
+// =============================================================================
+// Default command item renderer
+// =============================================================================
+
+const commandItemStyles = stylex.create({
+ label: {
+ flex: 1,
+ },
+ description: {
+ color: colorVars['--color-text-secondary'],
+ fontSize: textSizeVars['--text-sm'],
+ },
+});
+
+function CommandItem({command}: {command: XDSCommand}) {
+ if (command.renderItem) {
+ // Custom render — still wrap in Item for registration/keyboard/filtering
+ return (
+ <XDSCommandPaletteItem
+ value={command.id}
+ onSelect={command.onSelect}
+ keywords={command.keywords}
+ isDisabled={command.isDisabled}>
+ {command.renderItem({command, isHighlighted: false})}
+ </XDSCommandPaletteItem>
+ );
+ }
+
+ return (
+ <XDSCommandPaletteItem
+ value={command.id}
+ onSelect={command.onSelect}
+ keywords={command.keywords}
+ isDisabled={command.isDisabled}>
+ {command.icon && <XDSIcon icon={command.icon} size="sm" />}
+ <span {...stylex.props(commandItemStyles.label)}>{command.label}</span>
+ {command.description && (
+ <span {...stylex.props(commandItemStyles.description)}>
+ {command.description}
+ </span>
+ )}
+ {command.shortcut && <XDSCommandPaletteShortcut keys={command.shortcut} />}
+ </XDSCommandPaletteItem>
+ );
+}
diff --git a/packages/core/src/CommandPalette/XDSCommandPaletteSeparator.tsx b/packages/core/src/CommandPalette/XDSCommandPaletteSeparator.tsx
new file mode 100644
index 0000000000..1f36b5656d
--- /dev/null
+++ b/packages/core/src/CommandPalette/XDSCommandPaletteSeparator.tsx
@@ -0,0 +1,26 @@
+/**
+ * @file XDSCommandPaletteSeparator.tsx
+ * @input Uses XDSDivider
+ * @output Exports XDSCommandPaletteSeparator component
+ * @position Sub-component; visual divider between groups
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import {spacingVars} from '../theme/tokens.stylex';
+import {XDSDivider} from '../Divider';
+
+const styles = stylex.create({
+ separator: {
+ marginBlock: spacingVars['--spacing-1'],
+ },
+});
+
+/**
+ * Visual separator between command palette groups.
+ * Uses XDSDivider internally for theming/swizzle compatibility.
+ */
+export function XDSCommandPaletteSeparator() {
+ return <XDSDivider xstyle={styles.separator} />;
+}
+
+XDSCommandPaletteSeparator.displayName = 'XDSCommandPaletteSeparator';
diff --git a/packages/core/src/CommandPalette/XDSCommandPaletteShortcut.tsx b/packages/core/src/CommandPalette/XDSCommandPaletteShortcut.tsx
new file mode 100644
index 0000000000..30cd9ad20f
--- /dev/null
+++ b/packages/core/src/CommandPalette/XDSCommandPaletteShortcut.tsx
@@ -0,0 +1,98 @@
+/**
+ * @file XDSCommandPaletteShortcut.tsx
+ * @input Uses React, StyleX
+ * @output Exports XDSCommandPaletteShortcut component
+ * @position Sub-component; keyboard shortcut display
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ spacingVars,
+ radiusVars,
+ textSizeVars,
+ typographyVars,
+ fontWeightVars,
+ lineHeightVars,
+} from '../theme/tokens.stylex';
+
+const styles = stylex.create({
+ wrapper: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-1'],
+ marginInlineStart: 'auto',
+ flexShrink: 0,
+ },
+ kbd: {
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ minWidth: '20px',
+ height: '20px',
+ paddingInline: spacingVars['--spacing-1'],
+ borderRadius: radiusVars['--radius-element'],
+ backgroundColor: colorVars['--color-wash'],
+ color: colorVars['--color-text-secondary'],
+ fontFamily: typographyVars['--font-body'],
+ fontSize: textSizeVars['--text-xsm'],
+ fontWeight: fontWeightVars['--font-weight-medium'],
+ lineHeight: lineHeightVars['--leading-tight'],
+ userSelect: 'none',
+ },
+});
+
+/**
+ * Map of modifier key names to display symbols.
+ */
+const KEY_DISPLAY: Record<string, string> = {
+ mod: '\u2318', // ⌘
+ ctrl: '\u2303', // ⌃
+ alt: '\u2325', // ⌥
+ shift: '\u21E7', // ⇧
+ enter: '\u21B5', // ↵
+ backspace: '\u232B', // ⌫
+ escape: 'Esc',
+ tab: '\u21E5', // ⇥
+ up: '\u2191',
+ down: '\u2193',
+ left: '\u2190',
+ right: '\u2192',
+};
+
+export interface XDSCommandPaletteShortcutProps {
+ /**
+ * Keyboard shortcut string. Use "+" to separate keys.
+ * Special keys: mod (Cmd on Mac), ctrl, alt, shift, enter, backspace, escape.
+ *
+ * @example "mod+k", "mod+shift+p", "enter"
+ */
+ keys: string;
+}
+
+/**
+ * Displays a keyboard shortcut as styled <kbd> elements.
+ *
+ * @example
+ * ```
+ * <XDSCommandPaletteShortcut keys="mod+k" />
+ * // Renders: ⌘ K
+ * ```
+ */
+export function XDSCommandPaletteShortcut({
+ keys,
+}: XDSCommandPaletteShortcutProps) {
+ const parts = keys.split('+').map((key) => key.trim().toLowerCase());
+
+ return (
+ <span {...stylex.props(styles.wrapper)} aria-hidden="true">
+ {parts.map((key, i) => (
+ <kbd key={i} {...stylex.props(styles.kbd)}>
+ {KEY_DISPLAY[key] ?? key.toUpperCase()}
+ </kbd>
+ ))}
+ </span>
+ );
+}
+
+XDSCommandPaletteShortcut.displayName = 'XDSCommandPaletteShortcut';
diff --git a/packages/core/src/CommandPalette/filter.ts b/packages/core/src/CommandPalette/filter.ts
new file mode 100644
index 0000000000..5776ab2a1d
--- /dev/null
+++ b/packages/core/src/CommandPalette/filter.ts
@@ -0,0 +1,45 @@
+/**
+ * @file filter.ts
+ * @input Search string and item value/keywords
+ * @output Score between 0 and 1 indicating match quality
+ * @position Utility; used by XDSCommandPalette 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/core/src/CommandPalette/index.ts b/packages/core/src/CommandPalette/index.ts
new file mode 100644
index 0000000000..c901c32f08
--- /dev/null
+++ b/packages/core/src/CommandPalette/index.ts
@@ -0,0 +1,60 @@
+/**
+ * @file index.ts
+ * @input Imports all CommandPalette components, hooks, and types
+ * @output Exports public API for @xds/core CommandPalette
+ * @position Component entry point; re-exported by /packages/core/src/index.ts
+ *
+ * SYNC: When modified, update /packages/core/src/CommandPalette/README.md
+ */
+
+// Layer 1: Composable primitives
+export {XDSCommandPalette} from './XDSCommandPalette';
+export type {XDSCommandPaletteProps} from './XDSCommandPalette';
+
+export {XDSCommandPaletteInput} from './XDSCommandPaletteInput';
+export type {XDSCommandPaletteInputProps} from './XDSCommandPaletteInput';
+
+export {XDSCommandPaletteList} from './XDSCommandPaletteList';
+export type {XDSCommandPaletteListProps} from './XDSCommandPaletteList';
+
+export {XDSCommandPaletteItem} from './XDSCommandPaletteItem';
+export type {XDSCommandPaletteItemProps} from './XDSCommandPaletteItem';
+
+export {XDSCommandPaletteGroup} from './XDSCommandPaletteGroup';
+export type {XDSCommandPaletteGroupProps} from './XDSCommandPaletteGroup';
+
+export {XDSCommandPaletteEmpty} from './XDSCommandPaletteEmpty';
+export type {XDSCommandPaletteEmptyProps} from './XDSCommandPaletteEmpty';
+
+export {XDSCommandPaletteLoading} from './XDSCommandPaletteLoading';
+export type {XDSCommandPaletteLoadingProps} from './XDSCommandPaletteLoading';
+
+export {XDSCommandPaletteSeparator} from './XDSCommandPaletteSeparator';
+
+export {XDSCommandPaletteShortcut} from './XDSCommandPaletteShortcut';
+export type {XDSCommandPaletteShortcutProps} from './XDSCommandPaletteShortcut';
+
+export {XDSCommandPaletteFooter} from './XDSCommandPaletteFooter';
+export type {XDSCommandPaletteFooterProps} from './XDSCommandPaletteFooter';
+
+// Layer 2: Registry provider
+export {
+ XDSCommandPaletteProvider,
+ useXDSCommandPalette,
+ useXDSCommandPaletteRegister,
+} from './XDSCommandPaletteProvider';
+export type {XDSCommandPaletteProviderProps} from './XDSCommandPaletteProvider';
+
+// Layer 3: Optional history
+export {useXDSCommandPaletteHistory} from './useXDSCommandPaletteHistory';
+export type {
+ CommandPaletteHistoryOptions,
+ CommandPaletteHistoryEntry,
+} from './useXDSCommandPaletteHistory';
+
+// Shared types
+export type {
+ XDSCommand,
+ CommandItemRenderProps,
+ CommandPaletteFilterFn,
+} from './types';
diff --git a/packages/core/src/CommandPalette/types.ts b/packages/core/src/CommandPalette/types.ts
new file mode 100644
index 0000000000..d3ca02d454
--- /dev/null
+++ b/packages/core/src/CommandPalette/types.ts
@@ -0,0 +1,67 @@
+/**
+ * @file types.ts
+ * @input None
+ * @output Exports shared types for CommandPalette components
+ * @position Type definitions; consumed by all CommandPalette components
+ */
+
+import type {ReactNode} from 'react';
+import type {XDSIconType} from '../Icon';
+
+// =============================================================================
+// Command type (for registry pattern — Layer 2)
+// =============================================================================
+
+/**
+ * A command registered via the provider pattern.
+ */
+export interface XDSCommand {
+ /** Unique identifier for the command. */
+ id: string;
+ /** Display label. */
+ label: string;
+ /** Callback when the command is selected. */
+ onSelect: () => void;
+ /** Optional description/subtitle. */
+ description?: string;
+ /** Icon to display. */
+ icon?: XDSIconType;
+ /** Keyboard shortcut display string (e.g., "mod+k"). */
+ shortcut?: string;
+ /** Additional search terms for filtering. */
+ keywords?: string[];
+ /** Visual group heading. */
+ group?: string;
+ /** Sort priority within group (higher = first). */
+ priority?: number;
+ /** Whether the command is disabled. */
+ isDisabled?: boolean;
+ /** Parent command ID for nested navigation. */
+ parent?: string;
+ /** Custom render function for the item. */
+ renderItem?: (props: CommandItemRenderProps) => ReactNode;
+}
+
+/**
+ * Render props passed to custom item renderers.
+ */
+export interface CommandItemRenderProps {
+ /** The command being rendered. */
+ command: XDSCommand;
+ /** Whether this item is currently highlighted via keyboard/mouse. */
+ isHighlighted: boolean;
+}
+
+// =============================================================================
+// Filter function type
+// =============================================================================
+
+/**
+ * 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;
diff --git a/packages/core/src/CommandPalette/useXDSCommandPaletteHistory.ts b/packages/core/src/CommandPalette/useXDSCommandPaletteHistory.ts
new file mode 100644
index 0000000000..c498048abc
--- /dev/null
+++ b/packages/core/src/CommandPalette/useXDSCommandPaletteHistory.ts
@@ -0,0 +1,136 @@
+/**
+ * @file useXDSCommandPaletteHistory.ts
+ * @input Uses React hooks, localStorage
+ * @output Exports useXDSCommandPaletteHistory hook
+ * @position Layer 3 optional enhancement; not baked into core
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/CommandPalette/README.md
+ * - /packages/core/src/CommandPalette/index.ts
+ */
+
+import {useCallback, useState} from 'react';
+
+export interface CommandPaletteHistoryOptions {
+ /**
+ * Whether to persist history to localStorage.
+ * @default false
+ */
+ persist?: boolean;
+
+ /**
+ * Maximum number of history entries.
+ * @default 10
+ */
+ maxEntries?: number;
+
+ /**
+ * localStorage key for persistence.
+ * @default "xds-command-palette-history"
+ */
+ storageKey?: string;
+}
+
+export interface CommandPaletteHistoryEntry {
+ /** The command ID that was selected. */
+ id: string;
+ /** When the command was last selected. */
+ timestamp: number;
+}
+
+function loadHistory(
+ storageKey: string,
+ persist: boolean,
+): CommandPaletteHistoryEntry[] {
+ if (!persist || typeof window === 'undefined') return [];
+ try {
+ const stored = localStorage.getItem(storageKey);
+ return stored ? JSON.parse(stored) : [];
+ } catch {
+ return [];
+ }
+}
+
+function saveHistory(
+ storageKey: string,
+ persist: boolean,
+ entries: CommandPaletteHistoryEntry[],
+) {
+ if (!persist || typeof window === 'undefined') return;
+ try {
+ localStorage.setItem(storageKey, JSON.stringify(entries));
+ } catch {
+ // localStorage may be unavailable
+ }
+}
+
+/**
+ * Optional history tracking for the command palette.
+ * Not baked into the core — consumers opt in when they need it.
+ *
+ * @example
+ * ```
+ * const { history, record, clear } = useXDSCommandPaletteHistory({
+ * persist: true,
+ * maxEntries: 10,
+ * });
+ *
+ * // Record when a command is selected
+ * const handleSelect = (id: string) => {
+ * record(id);
+ * // ... execute command
+ * };
+ *
+ * // Show recent commands
+ * <XDSCommandPaletteGroup heading="Recent">
+ * {history.map(entry => (
+ * <XDSCommandPaletteItem key={entry.id} value={entry.id} onSelect={...}>
+ * {entry.id}
+ * </XDSCommandPaletteItem>
+ * ))}
+ * </XDSCommandPaletteGroup>
+ * ```
+ */
+export function useXDSCommandPaletteHistory({
+ persist = false,
+ maxEntries = 10,
+ storageKey = 'xds-command-palette-history',
+}: CommandPaletteHistoryOptions = {}) {
+ const [history, setHistory] = useState<CommandPaletteHistoryEntry[]>(() =>
+ loadHistory(storageKey, persist),
+ );
+
+ const record = useCallback(
+ (id: string) => {
+ setHistory((prev) => {
+ // Remove existing entry for this id (will be re-added at top)
+ const filtered = prev.filter((entry) => entry.id !== id);
+ const updated = [
+ {id, timestamp: Date.now()},
+ ...filtered,
+ ].slice(0, maxEntries);
+ saveHistory(storageKey, persist, updated);
+ return updated;
+ });
+ },
+ [maxEntries, persist, storageKey],
+ );
+
+ const clear = useCallback(() => {
+ setHistory([]);
+ saveHistory(storageKey, persist, []);
+ }, [persist, storageKey]);
+
+ const clearEntry = useCallback(
+ (id: string) => {
+ setHistory((prev) => {
+ const updated = prev.filter((entry) => entry.id !== id);
+ saveHistory(storageKey, persist, updated);
+ return updated;
+ });
+ },
+ [persist, storageKey],
+ );
+
+ return {history, record, clear, clearEntry};
+}
diff --git a/packages/core/src/Icon/IconRegistry.tsx b/packages/core/src/Icon/IconRegistry.tsx
index 95e5142f2c..f48866d284 100644
--- a/packages/core/src/Icon/IconRegistry.tsx
+++ b/packages/core/src/Icon/IconRegistry.tsx
@@ -39,7 +39,8 @@ export type XDSIconName =
| 'clock'
| 'externalLink'
| 'menu'
- | 'moreHorizontal';
+ | 'moreHorizontal'
+ | 'search';
/**
* Icon registry mapping semantic names to React nodes.
diff --git a/packages/core/src/Icon/defaultIcons.tsx b/packages/core/src/Icon/defaultIcons.tsx
index bedcd4166c..b17add46b2 100644
--- a/packages/core/src/Icon/defaultIcons.tsx
+++ b/packages/core/src/Icon/defaultIcons.tsx
@@ -169,4 +169,12 @@ export const defaultIcons: XDSIconRegistry = {
<circle cx="19" cy="12" r="1.5" />
</svg>
),
+
+ /** 🔍 — magnifying glass (search) */
+ search: (
+ <svg {...svgProps}>
+ <circle cx="11" cy="11" r="8" />
+ <path d="M21 21l-4.35-4.35" />
+ </svg>
+ ),
};
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index e52d5de187..c8fdbfd0f8 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -45,6 +45,7 @@ export * from './Table';
export * from './Token';
export * from './Typeahead';
export * from './Tokenizer';
+export * from './CommandPalette';
export * from './Dialog';
export * from './DropdownMenu';
export * from './MoreMenu';
diff --git a/packages/themes/default/src/icons.tsx b/packages/themes/default/src/icons.tsx
index 20b77368d2..cec06db8af 100644
--- a/packages/themes/default/src/icons.tsx
+++ b/packages/themes/default/src/icons.tsx
@@ -22,6 +22,7 @@ import {
InformationCircleIcon,
Bars3Icon,
EllipsisHorizontalIcon,
+ MagnifyingGlassIcon,
} from '@heroicons/react/24/outline';
import {
@@ -52,4 +53,5 @@ export const defaultIconRegistry: XDSIconRegistry = {
externalLink: <ArrowTopRightOnSquareIcon {...iconProps} />,
menu: <Bars3Icon {...iconProps} />,
moreHorizontal: <EllipsisHorizontalIcon {...iconProps} />,
+ search: <MagnifyingGlassIcon {...iconProps} />,
};
diff --git a/packages/themes/neutral/src/icons.tsx b/packages/themes/neutral/src/icons.tsx
index 1eeda0af8a..a27c7ac8ad 100644
--- a/packages/themes/neutral/src/icons.tsx
+++ b/packages/themes/neutral/src/icons.tsx
@@ -26,6 +26,7 @@ import {
ExternalLink,
Menu,
MoreHorizontal,
+ Search,
} from 'lucide-react';
const iconProps = {
@@ -48,4 +49,5 @@ export const neutralIconRegistry: XDSIconRegistry = {
externalLink: <ExternalLink {...iconProps} />,
menu: <Menu {...iconProps} />,
moreHorizontal: <MoreHorizontal {...iconProps} />,
+ search: <Search {...iconProps} />,
};