Skip to content

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

TypeScript

feat(CommandPalette): renderItem, default slots, empty states (#1124)

Cindy Zhang8036aef60126
diff --git a/apps/storybook/stories/CommandPalette.stories.tsx b/apps/storybook/stories/CommandPalette.stories.tsx
index af5c20a624..a8af2a92db 100644
--- a/apps/storybook/stories/CommandPalette.stories.tsx
+++ b/apps/storybook/stories/CommandPalette.stories.tsx
@@ -1,9 +1,9 @@
/**
- * CommandPalette with searchSource API — story sketches
+ * CommandPalette stories
*
* 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
+ * 1. No props beyond searchSource — default input, footer, rendering
+ * 2. renderItem — custom item content, grouping still automatic
*/
import {useState, useMemo} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
@@ -28,53 +28,69 @@ const meta: Meta<typeof XDSCommandPalette> = {
export default meta;
type Story = StoryObj<typeof XDSCommandPalette>;
-// --- Simplest case ---
+// ─── Default ─────────────────────────────────────────────────────────────────
-/** No children -- default rendering. Each item renders its label. */
+/** Simplest case — no input/footer/renderItem needed. */
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'},
- ]), []);
-
+ 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" onClick={() => setIsOpen(true)} />
+ <XDSButton
+ label="Open Command Palette"
+ onClick={() => setIsOpen(true)}
+ />
<XDSCommandPalette
isOpen={isOpen}
onOpenChange={setIsOpen}
searchSource={source}
- input={<XDSCommandPaletteInput placeholder="Type a command..." />}
- footer={<XDSCommandPaletteFooter />}
/>
</>
);
},
};
-// --- Auto-grouping ---
+// ─── Auto-grouping ────────────────────────────────────────────────────────────
-/**
- * Groups detected automatically from auxiliaryData.group.
- * Still no children -- the default renderer handles grouping.
- */
+/** Groups detected automatically from auxiliaryData.group. No custom rendering needed. */
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'}},
- ]), []);
-
+ 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 Grouped" onClick={() => setIsOpen(true)} />
@@ -82,166 +98,168 @@ export const AutoGrouped: Story = {
isOpen={isOpen}
onOpenChange={setIsOpen}
searchSource={source}
- input={<XDSCommandPaletteInput placeholder="Search commands..." />}
- footer={<XDSCommandPaletteFooter />}
/>
</>
);
},
};
-// --- Keywords ---
+// ─── Custom rendering via renderItem ─────────────────────────────────────────
-/** Type "theme" or "appearance" to find "Toggle Dark Mode". */
-export const WithKeywords: Story = {
+type RichCommand = XDSSearchableItem<{
+ icon?: string;
+ group?: string;
+ shortcut?: string;
+ keywords?: string[];
+}>;
+
+/**
+ * Custom item content via renderItem — icons and shortcuts.
+ * Grouping remains automatic via auxiliaryData.group.
+ */
+export const WithRenderItem: 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 commands: RichCommand[] = [
+ {
+ id: 'dashboard',
+ label: 'Go to Dashboard',
+ auxiliaryData: {icon: 'home', group: 'Navigation'},
+ },
+ {
+ id: 'settings',
+ label: 'Open Settings',
+ auxiliaryData: {icon: 'settings', group: 'Navigation', shortcut: '⌘,'},
+ },
+ {
+ 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: '⌘N'},
+ },
+ {
+ id: 'search',
+ label: 'Search Files',
+ auxiliaryData: {icon: 'search', group: 'Actions', shortcut: '⌘P'},
+ },
];
-
const source = useMemo(
- () => createStaticSource(commands, {
- keywords: (item) => item.auxiliaryData?.aliases ?? [],
- }),
+ () =>
+ createStaticSource(commands, {
+ keywords: item => item.auxiliaryData?.keywords ?? [],
+ }),
[],
);
-
return (
<>
- <XDSButton label="Open (try 'theme')" onClick={() => setIsOpen(true)} />
+ <XDSButton label="Open Rich Palette" onClick={() => setIsOpen(true)} />
<XDSCommandPalette
isOpen={isOpen}
onOpenChange={setIsOpen}
searchSource={source}
- input={<XDSCommandPaletteInput placeholder="Search..." />}
- footer={<XDSCommandPaletteFooter />}
+ renderItem={(item: RichCommand) => (
+ <span
+ 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>
+ )}
+ </span>
+ )}
/>
</>
);
},
};
-// --- Custom rendering with groups ---
+// ─── Picker mode ─────────────────────────────────────────────────────────────
-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 = {
+/** Selection persists across opens. isSelected passed to renderItem. */
+export const Picker: 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 [theme, setTheme] = useState('light');
const source = useMemo(
- () => createStaticSource(commands, {
- keywords: (item) => item.auxiliaryData?.keywords ?? [],
- }),
+ () =>
+ createStaticSource([
+ {id: 'light', label: 'Light'},
+ {id: 'dark', label: 'Dark'},
+ {id: 'system', label: 'System'},
+ ]),
[],
);
-
return (
<>
- <XDSButton label="Open Rich Palette" onClick={() => setIsOpen(true)} />
+ <XDSButton label={`Theme: ${theme}`} 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>
- ))}
- </>
- );
+ value={theme}
+ onValueChange={v => {
+ setTheme(v);
+ setIsOpen(false);
}}
- </XDSCommandPalette>
+ renderItem={(item, isSelected) => (
+ <span
+ style={{display: 'flex', alignItems: 'center', gap: 8, flex: 1}}>
+ <span style={{flex: 1}}>{item.label}</span>
+ {isSelected && <XDSIcon icon="check" size="sm" />}
+ </span>
+ )}
+ />
</>
);
},
};
-// --- Async search ---
+// ─── Async search ─────────────────────────────────────────────────────────────
-/** Server-side search. Input shows spinner while pending. */
+/** Server-side search. Spinner shown while pending. Empty state on no results. */
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 []; },
- }), []);
-
+ 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, 400));
+ 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 File Search" onClick={() => setIsOpen(true)} />
@@ -250,120 +268,109 @@ export const AsyncSearch: Story = {
onOpenChange={setIsOpen}
searchSource={source}
input={<XDSCommandPaletteInput placeholder="Search files..." />}
+ emptyBootstrapText="Type a filename to search"
+ emptySearchText="No files found"
/>
</>
);
},
};
-// --- Hybrid: static + async ---
+// ─── Keywords ────────────────────────────────────────────────────────────────
-/** Recent files (static) + project files (API) in one source. */
-export const HybridSearch: Story = {
+/** Type "theme" or "appearance" to find "Toggle Dark Mode". */
+export const WithKeywords: 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];
+ const commands: XDSSearchableItem<{aliases?: string[]}>[] = [
+ {id: 'home', label: 'Home'},
+ {
+ id: 'dark-mode',
+ label: 'Toggle Dark Mode',
+ auxiliaryData: {aliases: ['theme', 'appearance']},
},
- bootstrap() { return recentFiles; },
- }), []);
-
+ {
+ 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 File Finder" onClick={() => setIsOpen(true)} />
+ <XDSButton label="Open (try 'theme')" 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>
+ />
</>
);
},
};
-// --- Picker ---
+// ─── Many items (overflow / scroll test) ─────────────────────────────────────
-/** Selection persists across opens. Uses isSelected for visual state. */
-export const Picker: Story = {
+/**
+ * 50 items across 5 groups. Verifies the list scrolls within the dialog
+ * rather than expanding it past maxHeight.
+ */
+export const ManyItems: Story = {
render: function Render() {
const [isOpen, setIsOpen] = useState(false);
- const [theme, setTheme] = useState('light');
+ const groups = ['Files', 'Actions', 'Navigation', 'Settings', 'Recent'];
+ const items = Array.from({length: 50}, (_, i) => ({
+ id: `item-${i}`,
+ label: `Item ${i + 1}`,
+ auxiliaryData: {group: groups[i % groups.length]},
+ }));
+ const source = useMemo(() => createStaticSource(items), []);
+ return (
+ <>
+ <XDSButton label="Open (50 items)" onClick={() => setIsOpen(true)} />
+ <XDSCommandPalette
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ searchSource={source}
+ />
+ </>
+ );
+ },
+};
- const source = useMemo(() => createStaticSource([
- {id: 'light', label: 'Light'},
- {id: 'dark', label: 'Dark'},
- {id: 'system', label: 'System'},
- ]), []);
+// ─── Custom footer ────────────────────────────────────────────────────────────
+/** Replacing the footer with custom content. */
+export const CustomFooter: Story = {
+ render: function Render() {
+ const [isOpen, setIsOpen] = useState(false);
+ const source = useMemo(
+ () =>
+ createStaticSource([
+ {id: 'home', label: 'Home'},
+ {id: 'settings', label: 'Settings'},
+ ]),
+ [],
+ );
return (
<>
- <XDSButton label={`Theme: ${theme}`} onClick={() => setIsOpen(true)} />
+ <XDSButton label="Open" onClick={() => setIsOpen(true)} />
<XDSCommandPalette
isOpen={isOpen}
onOpenChange={setIsOpen}
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>
- ))}
- </XDSCommandPalette>
+ footer={
+ <XDSCommandPaletteFooter>
+ <span>Pro tip: use ⌘K to open anywhere</span>
+ </XDSCommandPaletteFooter>
+ }
+ />
</>
);
},
diff --git a/packages/lab/src/CommandPalette/XDSCommandPalette.test.tsx b/packages/lab/src/CommandPalette/XDSCommandPalette.test.tsx
index 6b109ec609..88f136ef72 100644
--- a/packages/lab/src/CommandPalette/XDSCommandPalette.test.tsx
+++ b/packages/lab/src/CommandPalette/XDSCommandPalette.test.tsx
@@ -20,6 +20,8 @@ const groupedSource = createStaticSource([
{id: 'save', label: 'Save', auxiliaryData: {group: 'Actions'}},
]);
+const emptySource = createStaticSource([]);
+
// Mock showModal and close since jsdom doesn't implement them
beforeEach(() => {
HTMLDialogElement.prototype.showModal = vi.fn(function (
@@ -39,7 +41,6 @@ describe('XDSCommandPalette', () => {
isOpen={true}
onOpenChange={() => {}}
searchSource={simpleSource}
- input={<div>Input</div>}
/>,
);
expect(screen.getByRole('dialog')).toBeInTheDocument();
@@ -51,7 +52,6 @@ describe('XDSCommandPalette', () => {
isOpen={false}
onOpenChange={() => {}}
searchSource={simpleSource}
- input={<div>Input</div>}
/>,
);
const dialog = screen.getByRole('dialog', {hidden: true});
@@ -64,7 +64,6 @@ describe('XDSCommandPalette', () => {
isOpen={true}
onOpenChange={() => {}}
searchSource={simpleSource}
- input={<div>Input</div>}
/>,
);
expect(screen.getByRole('dialog')).toHaveAttribute(
@@ -80,7 +79,6 @@ describe('XDSCommandPalette', () => {
onOpenChange={() => {}}
searchSource={simpleSource}
label="Quick search"
- input={<div>Input</div>}
/>,
);
expect(screen.getByRole('dialog')).toHaveAttribute(
@@ -89,30 +87,30 @@ describe('XDSCommandPalette', () => {
);
});
- it('renders input and footer slots', () => {
+ it('renders default input and footer when not provided', () => {
render(
<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('footer-slot')).toBeInTheDocument();
+ expect(screen.getByRole('combobox')).toBeInTheDocument();
+ expect(screen.getByText(/Navigate/)).toBeInTheDocument();
});
- it('renders without footer slot', () => {
+ it('renders custom input and footer slots', () => {
render(
<XDSCommandPalette
isOpen={true}
onOpenChange={() => {}}
searchSource={simpleSource}
- input={<div>Input</div>}
+ input={<div data-testid="input-slot">Custom Input</div>}
+ footer={<div data-testid="footer-slot">Custom Footer</div>}
/>,
);
- expect(screen.getByRole('dialog')).toBeInTheDocument();
+ expect(screen.getByTestId('input-slot')).toBeInTheDocument();
+ expect(screen.getByTestId('footer-slot')).toBeInTheDocument();
});
it('default renders items from searchSource bootstrap', async () => {
@@ -121,7 +119,6 @@ describe('XDSCommandPalette', () => {
isOpen={true}
onOpenChange={() => {}}
searchSource={simpleSource}
- input={<div>Input</div>}
/>,
);
await waitFor(() => {
@@ -136,7 +133,6 @@ describe('XDSCommandPalette', () => {
isOpen={true}
onOpenChange={() => {}}
searchSource={groupedSource}
- input={<div>Input</div>}
/>,
);
await waitFor(() => {
@@ -147,29 +143,66 @@ describe('XDSCommandPalette', () => {
});
});
- it('uses render function children when provided', async () => {
+ it('uses renderItem for custom item content', 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>,
+ renderItem={item => <span>{item.label.toUpperCase()}</span>}
+ />,
);
await waitFor(() => {
- expect(screen.getByTestId('custom-render')).toBeInTheDocument();
expect(screen.getByText('HOME')).toBeInTheDocument();
expect(screen.getByText('SETTINGS')).toBeInTheDocument();
});
});
+ it('passes isSelected=true to renderItem for the selected value', async () => {
+ render(
+ <XDSCommandPalette
+ isOpen={true}
+ onOpenChange={() => {}}
+ searchSource={simpleSource}
+ value="home"
+ renderItem={(item, isSelected) => (
+ <span>{isSelected ? `checked-${item.label}` : item.label}</span>
+ )}
+ />,
+ );
+ await waitFor(() => {
+ expect(screen.getByText('checked-Home')).toBeInTheDocument();
+ expect(screen.getByText('Settings')).toBeInTheDocument();
+ });
+ });
+
+ it('shows emptyBootstrapText when bootstrap returns nothing', async () => {
+ render(
+ <XDSCommandPalette
+ isOpen={true}
+ onOpenChange={() => {}}
+ searchSource={emptySource}
+ emptyBootstrapText="Nothing to show"
+ />,
+ );
+ await waitFor(() => {
+ expect(screen.getByText('Nothing to show')).toBeInTheDocument();
+ });
+ });
+
+ it('shows default emptyBootstrapText when not provided', async () => {
+ render(
+ <XDSCommandPalette
+ isOpen={true}
+ onOpenChange={() => {}}
+ searchSource={emptySource}
+ />,
+ );
+ await waitFor(() => {
+ expect(screen.getByText('Type to search')).toBeInTheDocument();
+ });
+ });
+
it('calls onOpenChange(false) when Escape is pressed', () => {
const handleOpenChange = vi.fn();
render(
@@ -177,7 +210,6 @@ describe('XDSCommandPalette', () => {
isOpen={true}
onOpenChange={handleOpenChange}
searchSource={simpleSource}
- input={<div>Input</div>}
/>,
);
const dialog = screen.getByRole('dialog');
diff --git a/packages/lab/src/CommandPalette/XDSCommandPalette.tsx b/packages/lab/src/CommandPalette/XDSCommandPalette.tsx
index c9f2c34f4c..737512c492 100644
--- a/packages/lab/src/CommandPalette/XDSCommandPalette.tsx
+++ b/packages/lab/src/CommandPalette/XDSCommandPalette.tsx
@@ -16,8 +16,10 @@ import {
useEffect,
useId,
useMemo,
+ useOptimistic,
useRef,
useState,
+ useTransition,
type ReactNode,
} from 'react';
import {XDSDialog} from '@xds/core/Dialog';
@@ -34,6 +36,9 @@ import {CommandPaletteContext} from './CommandPaletteContext';
import {XDSCommandPaletteList} from './XDSCommandPaletteList';
import {XDSCommandPaletteItem} from './XDSCommandPaletteItem';
import {XDSCommandPaletteGroup} from './XDSCommandPaletteGroup';
+import {XDSCommandPaletteInput} from './XDSCommandPaletteInput';
+import {XDSCommandPaletteFooter} from './XDSCommandPaletteFooter';
+import {XDSCommandPaletteEmpty} from './XDSCommandPaletteEmpty';
export interface XDSCommandPaletteProps<
T extends XDSSearchableItem = XDSSearchableItem,
@@ -52,22 +57,35 @@ export interface XDSCommandPaletteProps<
searchSource: XDSSearchSource<T>;
/**
- * The search input slot. Pass XDSCommandPaletteInput here.
+ * The search input slot.
+ * @default <XDSCommandPaletteInput />
*/
input?: ReactNode;
/**
- * The footer slot. Pass XDSCommandPaletteFooter here.
+ * The footer slot.
+ * @default <XDSCommandPaletteFooter />
*/
footer?: ReactNode;
/**
- * 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
+ * Per-item render function. Receives the item and whether it is currently selected.
+ * Auto-grouping by `auxiliaryData.group` is preserved.
+ * When omitted, renders each item's `label` text.
*/
- children?: (items: T[]) => ReactNode;
+ renderItem?: (item: T, isSelected: boolean) => ReactNode;
+
+ /**
+ * Content shown when a search query returns no results.
+ * @default 'No results'
+ */
+ emptySearchText?: ReactNode;
+
+ /**
+ * Content shown when there is no search query and bootstrap() returns nothing.
+ * @default 'Type to search'
+ */
+ emptyBootstrapText?: ReactNode;
/** Controlled selected value (for picker mode). */
value?: string;
@@ -146,30 +164,37 @@ function buildSelectableItems(
return result;
}
+interface RendererProps<T extends XDSSearchableItem> {
+ items: T[];
+ value: string;
+ renderItem?: (item: T, isSelected: boolean) => ReactNode;
+}
+
/**
- * Default renderer for search results.
- * Renders items as XDSCommandPaletteItem with label text.
- * Auto-groups items by auxiliaryData.group when present.
+ * Renders items with optional per-item customization.
+ * Auto-groups by auxiliaryData.group when present.
+ * Passes `isSelected` so renderItem can handle picker-mode visuals.
*/
-function DefaultRenderer({items}: {items: XDSSearchableItem[]}) {
+function ItemRenderer<T extends XDSSearchableItem>({
+ items,
+ value,
+ renderItem,
+}: RendererProps<T>) {
+ const renderOne = (item: T) => (
+ <XDSCommandPaletteItem key={item.id} value={item.id}>
+ {renderItem ? renderItem(item, item.id === value) : item.label}
+ </XDSCommandPaletteItem>
+ );
+
const hasGroups = items.some(item => getGroup(item) != null);
if (!hasGroups) {
- return (
- <>
- {items.map(item => (
- <XDSCommandPaletteItem key={item.id} value={item.id}>
- {item.label}
- </XDSCommandPaletteItem>
- ))}
- </>
- );
+ return <>{items.map(renderOne)}</>;
}
- // Group items preserving insertion order of groups
const groupOrder: string[] = [];
- const groups = new Map<string, XDSSearchableItem[]>();
- const ungrouped: XDSSearchableItem[] = [];
+ const groups = new Map<string, T[]>();
+ const ungrouped: T[] = [];
for (const item of items) {
const group = getGroup(item);
@@ -188,18 +213,10 @@ function DefaultRenderer({items}: {items: XDSSearchableItem[]}) {
<>
{groupOrder.map(heading => (
<XDSCommandPaletteGroup key={heading} heading={heading}>
- {groups.get(heading)!.map(item => (
- <XDSCommandPaletteItem key={item.id} value={item.id}>
- {item.label}
- </XDSCommandPaletteItem>
- ))}
+ {groups.get(heading)!.map(renderOne)}
</XDSCommandPaletteGroup>
))}
- {ungrouped.map(item => (
- <XDSCommandPaletteItem key={item.id} value={item.id}>
- {item.label}
- </XDSCommandPaletteItem>
- ))}
+ {ungrouped.map(renderOne)}
</>
);
}
@@ -214,38 +231,34 @@ function DefaultRenderer({items}: {items: XDSSearchableItem[]}) {
* ensuring consistent arrow key, Home/End, Enter, and Escape behavior
* across all combobox-pattern components.
*
- * Progressive disclosure:
- * - No children: default rendering (label text, auto-groups by auxiliaryData.group)
- * - Children render function: full control over item layout and grouping
+ * Input and footer are rendered by default — only pass them to replace the defaults.
*
* @compositionHint
- * - `input` slot: XDSCommandPaletteInput
- * - `children`: optional render function `(items) => ReactNode`
- * - `footer` slot: XDSCommandPaletteFooter
+ * - `input` slot: XDSCommandPaletteInput (default)
+ * - `footer` slot: XDSCommandPaletteFooter (default)
+ * - `renderItem(item, isSelected)`: custom per-item content (grouping preserved)
*
* @example
- * ```
- * // Simplest — no children, default rendering
+ * ```tsx
+ * // Simplest — zero config beyond open state and source
* <XDSCommandPalette
* isOpen={isOpen}
* onOpenChange={setIsOpen}
* searchSource={createStaticSource(commands)}
- * input={<XDSCommandPaletteInput placeholder="Search..." />}
- * footer={<XDSCommandPaletteFooter />}
* />
*
- * // Custom rendering
+ * // Custom item rendering (grouping still automatic)
* <XDSCommandPalette
* isOpen={isOpen}
* onOpenChange={setIsOpen}
* searchSource={source}
- * input={<XDSCommandPaletteInput placeholder="Search..." />}>
- * {(items) => items.map(item => (
- * <XDSCommandPaletteItem key={item.id} value={item.id}>
+ * renderItem={(item, isSelected) => (
+ * <>
+ * <XDSIcon icon={item.auxiliaryData.icon} size="sm" />
* {item.label}
- * </XDSCommandPaletteItem>
- * ))}
- * </XDSCommandPalette>
+ * </>
+ * )}
+ * />
* ```
*/
export function XDSCommandPalette<
@@ -255,8 +268,10 @@ export function XDSCommandPalette<
onOpenChange,
searchSource,
input,
- children,
footer,
+ renderItem,
+ emptySearchText = 'No results',
+ emptyBootstrapText = 'Type to search',
value: controlledValue,
onValueChange,
label = 'Command palette',
@@ -264,10 +279,18 @@ export function XDSCommandPalette<
maxHeight = 480,
}: XDSCommandPaletteProps<T>) {
const listId = useId();
+ // search: the committed query — only advances when async results arrive.
+ // optimisticSearch: updates immediately on keystroke, drives input + empty state.
+ // This way optimisticSearch is always what the user sees, and search is what
+ // the current results actually correspond to.
const [search, setSearch] = useState('');
const [internalValue, setInternalValue] = useState('');
const [searchResults, setSearchResults] = useState<T[]>([]);
- const [isBusy, setIsBusy] = useState(false);
+ const [isPending, startTransition] = useTransition();
+ const [optimisticSearch, setOptimisticSearch] = useOptimistic(search);
+ const [optimisticResults, setOptimisticResults] =
+ useOptimistic(searchResults);
+ const isBusy = isPending;
const searchVersionRef = useRef(0);
const value = controlledValue ?? internalValue;
@@ -283,14 +306,16 @@ export function XDSCommandPalette<
);
// Build flat selectable items in DOM order from search results.
- // This must match the order that DefaultRenderer (or custom children) renders.
+ // Must match the render order of ItemRenderer.
const selectableItems = useMemo(
- () => buildSelectableItems(searchResults),
- [searchResults],
+ () => buildSelectableItems(optimisticResults),
+ [optimisticResults],
);
const handleClose = useCallback(() => {
+ // Reset both committed and optimistic search on close
setSearch('');
+ setSearchResults([]);
if (controlledValue === undefined) {
setInternalValue('');
}
@@ -332,35 +357,49 @@ export function XDSCommandPalette<
}
}, [isOpen, selectableItems, value, combobox]);
- // Unified search effect: bootstrap on open or empty query, search otherwise
- useEffect(() => {
- if (!isOpen) return;
+ // Run a search for the given query and commit results.
+ // Called directly when the user types — no effect needed.
+ const runSearch = useCallback(
+ (query: string) => {
+ searchSource.cancel?.();
+ const version = ++searchVersionRef.current;
+
+ startTransition(async () => {
+ const isBootstrap = query === '';
+
+ // Client-filter previous results for instant narrowing while fetch is in flight
+ if (!isBootstrap && searchResults.length > 0) {
+ const lower = query.toLowerCase().trim();
+ setOptimisticResults(
+ searchResults.filter(item =>
+ item.label.toLowerCase().includes(lower),
+ ),
+ );
+ }
- 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);
+ const result = isBootstrap
+ ? searchSource.bootstrap()
+ : searchSource.search(query);
+
+ const items = await Promise.resolve(result);
+
+ if (searchVersionRef.current === version) {
+ // Commit query and results together
+ setSearch(query);
+ setOptimisticResults(items);
+ setSearchResults(items);
+ }
+ });
+ },
+ [searchSource, searchResults, startTransition],
+ );
+
+ // Bootstrap on open — the only remaining effect.
+ useEffect(() => {
+ if (isOpen) {
+ runSearch('');
}
- }, [search, isOpen, searchSource]);
+ }, [isOpen]);
// Wrap combobox's onKeyDown to intercept Escape (close palette) and
// Enter on highlight (select + close), since we're not using combobox's
@@ -395,8 +434,14 @@ export function XDSCommandPalette<
const contextValue = useMemo(
() => ({
- search,
- setSearch,
+ // Input uses optimisticSearch — reflects keystrokes immediately.
+ // setSearch calls setOptimisticSearch for instant feedback then
+ // triggers the async search directly (no effect indirection).
+ search: optimisticSearch,
+ setSearch: (query: string) => {
+ setOptimisticSearch(query);
+ runSearch(query);
+ },
value,
setValue,
listId,
@@ -404,7 +449,7 @@ export function XDSCommandPalette<
setHighlightedIndex: combobox.setHighlightedIndex,
getItemId: combobox.getItemId,
selectableItems,
- searchResults,
+ searchResults: optimisticResults,
selectItem,
onKeyDown: handleKeyDown,
onClose: handleClose,
@@ -412,7 +457,9 @@ export function XDSCommandPalette<
isBusy,
}),
[
- search,
+ optimisticSearch,
+ setOptimisticSearch,
+ runSearch,
value,
setValue,
listId,
@@ -420,7 +467,7 @@ export function XDSCommandPalette<
combobox.setHighlightedIndex,
combobox.getItemId,
selectableItems,
- searchResults,
+ optimisticResults,
selectItem,
handleKeyDown,
handleClose,
@@ -429,11 +476,32 @@ export function XDSCommandPalette<
],
);
- const listContent = children ? (
- children(searchResults)
- ) : (
- <DefaultRenderer items={searchResults} />
- );
+ // Empty state uses committed search (= what current results correspond to),
+ // not optimisticSearch (= what the user typed).
+ // While the transition is pending, search stays at '' so showEmptyBootstrap
+ // remains true even after the user has started typing.
+ const showEmptyBootstrap = search === '' && optimisticResults.length === 0;
+ const showEmptySearch =
+ !isPending && search !== '' && optimisticResults.length === 0;
+
+ let listContent: ReactNode;
+ if (showEmptyBootstrap) {
+ listContent = (
+ <XDSCommandPaletteEmpty>{emptyBootstrapText}</XDSCommandPaletteEmpty>
+ );
+ } else if (showEmptySearch) {
+ listContent = (
+ <XDSCommandPaletteEmpty>{emptySearchText}</XDSCommandPaletteEmpty>
+ );
+ } else {
+ listContent = (
+ <ItemRenderer
+ items={optimisticResults}
+ value={value}
+ renderItem={renderItem}
+ />
+ );
+ }
return (
<XDSDialog
@@ -450,11 +518,9 @@ export function XDSCommandPalette<
<XDSLayout
defaultHasDividers
header={
- input != null ? (
- <XDSLayoutHeader hasDivider padding={0}>
- {input}
- </XDSLayoutHeader>
- ) : undefined
+ <XDSLayoutHeader hasDivider padding={0}>
+ {input ?? <XDSCommandPaletteInput />}
+ </XDSLayoutHeader>
}
content={
<XDSLayoutContent padding={0}>
@@ -462,11 +528,9 @@ export function XDSCommandPalette<
</XDSLayoutContent>
}
footer={
- footer != null ? (
- <XDSLayoutFooter hasDivider padding={0}>
- {footer}
- </XDSLayoutFooter>
- ) : undefined
+ <XDSLayoutFooter hasDivider padding={0}>
+ {footer ?? <XDSCommandPaletteFooter />}
+ </XDSLayoutFooter>
}
/>
</CommandPaletteContext.Provider>
diff --git a/packages/lab/src/CommandPalette/XDSCommandPaletteEmpty.tsx b/packages/lab/src/CommandPalette/XDSCommandPaletteEmpty.tsx
new file mode 100644
index 0000000000..d7b1156576
--- /dev/null
+++ b/packages/lab/src/CommandPalette/XDSCommandPaletteEmpty.tsx
@@ -0,0 +1,57 @@
+/**
+ * @file XDSCommandPaletteEmpty.tsx
+ * @input Uses React, StyleX
+ * @output Exports XDSCommandPaletteEmpty component
+ * @position Sub-component; empty state shown when there are no items to display
+ *
+ * SYNC: When modified, update:
+ * - /packages/lab/src/CommandPalette/README.md
+ */
+
+'use client';
+
+import type {ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ spacingVars,
+ typeScaleVars,
+ typographyVars,
+} from '@xds/core/theme/tokens.stylex';
+
+const styles = stylex.create({
+ empty: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ paddingBlock: spacingVars['--spacing-8'],
+ paddingInline: spacingVars['--spacing-4'],
+ fontFamily: typographyVars['--font-family-body'],
+ fontSize: typeScaleVars['--text-supporting-size'],
+ lineHeight: typeScaleVars['--text-supporting-leading'],
+ color: colorVars['--color-text-secondary'],
+ textAlign: 'center' as const,
+ },
+});
+
+export interface XDSCommandPaletteEmptyProps {
+ /** The message or content to display. */
+ children: ReactNode;
+}
+
+/**
+ * Empty state for the command palette list area.
+ *
+ * Rendered automatically by XDSCommandPalette in two situations:
+ * - `emptyBootstrapText`: no search term and bootstrap() returns nothing
+ * - `emptySearchText`: a search query returned no results
+ *
+ * Can also be composed manually inside a custom render function.
+ */
+export function XDSCommandPaletteEmpty({
+ children,
+}: XDSCommandPaletteEmptyProps) {
+ return <div {...stylex.props(styles.empty)}>{children}</div>;
+}
+
+XDSCommandPaletteEmpty.displayName = 'XDSCommandPaletteEmpty';
diff --git a/packages/lab/src/CommandPalette/XDSCommandPaletteInput.tsx b/packages/lab/src/CommandPalette/XDSCommandPaletteInput.tsx
index 085d1a79c5..46185b135e 100644
--- a/packages/lab/src/CommandPalette/XDSCommandPaletteInput.tsx
+++ b/packages/lab/src/CommandPalette/XDSCommandPaletteInput.tsx
@@ -11,7 +11,13 @@
'use client';
-import {useCallback, useEffect, useRef, type InputHTMLAttributes} from 'react';
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ type InputHTMLAttributes,
+ type ReactNode,
+} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {XDSIcon} from '@xds/core/Icon';
@@ -42,6 +48,25 @@ const styles = stylex.create({
flexShrink: 0,
color: colorVars['--color-text-secondary'],
},
+ // Groups spinner + endContent on the right with a consistent gap
+ end: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-1'],
+ flexShrink: 0,
+ },
+ // Delay spinner appearance to avoid flickering on near-instant searches.
+ // Uses @starting-style + transition-delay so the spinner only appears
+ // if the search is still pending after 150ms.
+ spinner: {
+ opacity: 1,
+ transitionProperty: 'opacity',
+ transitionDuration: '1ms',
+ transitionDelay: '150ms',
+ '@starting-style': {
+ opacity: 0,
+ },
+ },
input: {
flex: 1,
minWidth: 0,
@@ -90,6 +115,13 @@ export interface XDSCommandPaletteInputProps extends Omit<
*/
hasAutoFocus?: boolean;
+ /**
+ * Content rendered at the trailing end of the input, after the spinner.
+ * Use for clear buttons, keyboard shortcuts, or other trailing actions.
+ * The spinner (when busy) appears immediately before this content with a 4px gap.
+ */
+ endContent?: ReactNode;
+
/** StyleX styles for the wrapper element. */
xstyle?: StyleXStyles;
}
@@ -118,6 +150,7 @@ export function XDSCommandPaletteInput({
onValueChange,
placeholder = 'Search...',
hasAutoFocus = true,
+ endContent,
onChange,
onKeyDown,
ref,
@@ -170,11 +203,7 @@ export function XDSCommandPaletteInput({
stylex.props(styles.wrapper, xstyle),
)}>
<span {...stylex.props(styles.icon)}>
- {ctx?.isBusy ? (
- <XDSSpinner size="sm" />
- ) : (
- <XDSIcon icon="search" size="sm" color="inherit" />
- )}
+ <XDSIcon icon="search" size="sm" color="inherit" />
</span>
<input
ref={setRefs}
@@ -198,6 +227,16 @@ export function XDSCommandPaletteInput({
{...stylex.props(styles.input)}
{...props}
/>
+ {(ctx?.isBusy || endContent) && (
+ <span {...stylex.props(styles.end)}>
+ {ctx?.isBusy && (
+ <span {...stylex.props(styles.icon, styles.spinner)}>
+ <XDSSpinner size="sm" />
+ </span>
+ )}
+ {endContent}
+ </span>
+ )}{' '}
</div>
);
}
diff --git a/packages/lab/src/CommandPalette/index.ts b/packages/lab/src/CommandPalette/index.ts
index 66297c169d..05edae7951 100644
--- a/packages/lab/src/CommandPalette/index.ts
+++ b/packages/lab/src/CommandPalette/index.ts
@@ -25,5 +25,8 @@ export type {XDSCommandPaletteGroupProps} from './XDSCommandPaletteGroup';
export {XDSCommandPaletteFooter} from './XDSCommandPaletteFooter';
export type {XDSCommandPaletteFooterProps} from './XDSCommandPaletteFooter';
+export {XDSCommandPaletteEmpty} from './XDSCommandPaletteEmpty';
+export type {XDSCommandPaletteEmptyProps} from './XDSCommandPaletteEmpty';
+
export {useCommandPaletteContext} from './CommandPaletteContext';
export type {CommandPaletteContextValue} from './CommandPaletteContext';