implementing-command-palettes
Use when building Cmd+K command palettes in React - covers keyboard navigation with arrow keys, keeping selected items in view with scrollIntoView, filtering with shortcut matching, and preventing infinite re-renders from reference instability
What this skill does
# Implementing Command Palettes
## Overview
Command palettes (Cmd+K / Ctrl+K) need precise keyboard navigation, scroll behavior, and stable references to avoid re-render loops. This skill covers the mechanical patterns that make command palettes feel responsive.
## When to Use
- Building a Cmd+K command palette in React
- Implementing arrow key navigation with visual selection
- Keeping selected items visible during keyboard navigation
- Filtering commands by label text AND keyboard shortcuts
- Experiencing infinite re-renders when commands update
## Quick Reference
| Feature | Implementation |
|---------|----------------|
| Arrow navigation | Track `selectedIndex`, clamp with `Math.min/max` |
| Keep in view | `scrollIntoView({ block: 'nearest', behavior: 'smooth' })` |
| Shortcut matching | Strip spaces from shortcuts, match against query |
| Stable icons | Define icon elements outside component |
| Stable handlers | `useCallback` + `noop` constant for disabled states |
## Keyboard Navigation
### Critical: Wrapper Pattern for Conditional Rendering
**This is the most common source of bugs.** The keyboard effect must ONLY run when the palette is open. Use a wrapper component:
```tsx
// Wrapper ensures effects only run when open
export function CommandPalette(props: CommandPaletteProps) {
if (!props.isOpen) return null;
return <CommandPaletteContent {...props} />;
}
// Content component - effects run on mount/unmount
function CommandPaletteContent({ onClose, ... }: CommandPaletteProps) {
// Effects here only run when palette is visible
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => { ... };
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [deps]);
return <div>...</div>;
}
```
**Why this matters:**
- If you put `if (!isOpen) return null` AFTER useEffect hooks, the effects still run when closed
- This causes keyboard listeners to be registered even when palette is invisible
- The wrapper pattern ensures effects only run when the component actually renders
### Input Focus + Window Listener Pattern
The input MUST be focused (for typing to work), and keyboard navigation MUST use `window.addEventListener`. This works because:
- The window listener receives keydown events for ALL keys
- Arrow keys don't insert text into inputs, so `e.preventDefault()` just stops page scrolling
- Regular character keys still reach the input for typing
```tsx
// Input with autoFocus - NOT setTimeout focus
<input
autoFocus
type="text"
value={query}
onChange={e => {
setQuery(e.target.value);
setSelectedIndex(0); // Reset to first item when query changes
}}
/>
```
### Index Management
```tsx
const [selectedIndex, setSelectedIndex] = useState(0);
useEffect(() => {
if (!isOpen) return;
const handleKeyDown = (e: KeyboardEvent) => {
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
// Clamp to last item
setSelectedIndex(prev => Math.min(prev + 1, filteredItems.length - 1));
break;
case 'ArrowUp':
e.preventDefault();
// Clamp to first item
setSelectedIndex(prev => Math.max(prev - 1, 0));
break;
case 'Enter':
e.preventDefault();
if (filteredItems[selectedIndex]) {
executeCommand(filteredItems[selectedIndex]);
close();
}
break;
case 'Escape':
e.preventDefault();
close();
break;
}
};
// NO capture phase needed - simple window listener works with focused input
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [isOpen, filteredItems, selectedIndex, close]);
```
**Key patterns:**
- `e.preventDefault()` stops arrow keys from scrolling the page
- `Math.min/max` prevents index going out of bounds
- Effect depends on `filteredItems` so navigation updates when filter changes
- Use `autoFocus` on input, NOT `setTimeout(() => ref.current?.focus(), 0)`
## Keeping Selected Item in View
### Using Refs Array
```tsx
const itemRefs = useRef<(HTMLButtonElement | null)[]>([]);
// Scroll effect - runs when selection changes
useEffect(() => {
const selectedItem = itemRefs.current[selectedIndex];
if (selectedItem) {
selectedItem.scrollIntoView({
block: 'nearest', // Minimal scroll - only scroll if needed
behavior: 'smooth' // Smooth animation
});
}
}, [selectedIndex]);
// Assign refs in render
{filteredItems.map((item, index) => (
<button
key={index}
ref={el => { itemRefs.current[index] = el; }}
className={index === selectedIndex ? 'bg-blue-100' : ''}
>
{item.label}
</button>
))}
```
### Alternative: Single Ref for Selected Item
```tsx
const selectedItemRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
if (isOpen && selectedItemRef.current) {
selectedItemRef.current.scrollIntoView({
block: 'nearest',
behavior: 'smooth',
});
}
}, [isOpen, selectedIndex]);
// Only assign ref to selected item
<button
ref={index === selectedIndex ? selectedItemRef : null}
>
```
**Why `block: 'nearest'`?**
- `'nearest'` only scrolls if the element is outside the visible area
- `'center'` would scroll even when item is already visible, causing jarring movement
- `'start'` or `'end'` would always align to top/bottom
## Filtering with Shortcut Matching
```tsx
const filteredCommands = commands.filter(command => {
const q = query.toLowerCase().trim();
if (!q) return true;
// Standard label matching
if (command.label.toLowerCase().includes(q)) return true;
// Shortcut matching: "gd" matches "g d", "gb" matches "g b"
if (command.shortcut) {
const shortcutNoSpaces = command.shortcut.toLowerCase().replace(/\s+/g, '');
if (shortcutNoSpaces.startsWith(q) || shortcutNoSpaces.includes(q)) {
return true;
}
}
// For numbered items (PRs, issues), match by number
if (command.type === 'pr') {
const numberMatch = q.match(/^#?(\d+)$/);
if (numberMatch) {
return String(command.pr.number).startsWith(numberMatch[1]);
}
}
return false;
});
```
**Why strip spaces from shortcuts?**
Users type continuously without spaces. Shortcut `"g d"` should match when user types `"gd"`.
## Preventing Re-Render Loops
Command palettes often suffer from infinite re-renders when command objects are recreated every render.
### Problem: Unstable References
```tsx
// BAD: Icons recreated every render
function usePageCommands() {
const commands = useMemo(() => [{
label: 'Sync',
icon: <RefreshCw size={16} />, // New element every render!
action: () => onSync(), // New function every render!
}], [onSync]); // Even with deps, icon is new
useRegisterCommands(commands); // Triggers re-registration → re-render loop
}
```
### Solution: Stable References
```tsx
// GOOD: Icons defined OUTSIDE component
const refreshIcon = <RefreshCw size={16} />;
const refreshSpinIcon = <RefreshCw size={16} className="animate-spin" />;
const noop = () => {};
function usePageCommands({ onSync, isSyncing }: Props) {
// Memoize handlers
const handleSync = useCallback(() => onSync?.(), [onSync]);
const commands = useMemo(() => [{
label: isSyncing ? 'Syncing...' : 'Sync',
icon: isSyncing ? refreshSpinIcon : refreshIcon, // Stable references
action: isSyncing ? noop : handleSync, // noop, not undefined
}], [isSyncing, handleSync]);
useRegisterCommands(commands);
}
```
### Label-Based Change Detection
Instead of comparing object references, compare by labels:
```tsx
export function useRegisterCommands(commands: CommandItem[]) {
const { registerCommands, unregisterCommands } = useCommandPalette();
// Create stable ID based on LABELS, not object references
const commandIds = useMemo(
() => commands.map(c => {
if (c.type === 'nav') return `nav:${c.path}`Related in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.