Command palette

A ⌘K / Ctrl+K command palette in a modal dialog. Commands are grouped, filtered with a forgiving fuzzy match on labels and keywords (matched letters are highlighted), and run with the arrow keys and Enter or a click. Includes an empty state, keyboard shortcut hints, a footer legend, a result count for screen readers, focus restore on close, scroll lock and a useModKey helper for showing ⌘ or Ctrl.

Modals & overlaysComponentTailwind v4

Source

"use client";

import {
  Fragment, useEffect, useId, useLayoutEffect, useMemo, useRef, useState,
  type KeyboardEvent, type ReactNode,
} from "react";
import { createPortal } from "react-dom";
import { Search } from "lucide-react";
import { cn } from "@/lib/utils";

export interface CommandItem {
  id: string;
  label: string;
  icon?: ReactNode;
  /** Keys shown on the right, such as ["G", "D"] or ["⌘", "N"]. Display only. */
  shortcut?: string[];
  /** Extra words that should find this command. */
  keywords?: string[];
  disabled?: boolean;
  onSelect: () => void;
}

export interface CommandGroup {
  heading: string;
  items: CommandItem[];
}

export interface CommandPaletteProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  groups: CommandGroup[];
  placeholder?: string;
  /** Letter that toggles the palette with ⌘ (macOS) or Ctrl. Pass false to wire it yourself. */
  hotkey?: string | false;
  emptyMessage?: (query: string) => ReactNode;
  /** Accessible name of the dialog. */
  label?: string;
}

interface Match {
  score: number;
  indices: number[];
}

const BOUNDARY = /[\s\-_/.:]/;

// Substring matches rank highest (earlier and word-start better); otherwise every typed letter must appear in order.
function match(text: string, query: string): Match | null {
  const haystack = text.toLowerCase();
  const needle = query.toLowerCase().trim();
  if (!needle) return { score: 0, indices: [] };
  const at = haystack.indexOf(needle);
  if (at >= 0) {
    const wordStart = at === 0 || BOUNDARY.test(haystack[at - 1]);
    return { score: 1000 - at + (wordStart ? 200 : 0), indices: Array.from({ length: needle.length }, (_, i) => at + i) };
  }
  const indices: number[] = [];
  let from = 0;
  let gaps = 0;
  for (const char of needle.replace(/\s+/g, "")) {
    const found = haystack.indexOf(char, from);
    if (found < 0) return null;
    if (indices.length) gaps += found - indices[indices.length - 1] - 1;
    indices.push(found);
    from = found + 1;
  }
  const starts = indices.filter((i) => i === 0 || BOUNDARY.test(haystack[i - 1])).length;
  return { score: 500 - gaps * 4 + starts * 20, indices };
}

function Highlighted({ text, indices }: { text: string; indices: number[] }) {
  if (!indices.length) return <>{text}</>;
  const marked = new Set(indices);
  return (
    <>
      {Array.from(text).map((char, index) =>
        marked.has(index) ? <span key={index} className="font-semibold text-foreground">{char}</span> : <Fragment key={index}>{char}</Fragment>)}
    </>
  );
}

/** "⌘" on Apple platforms, "Ctrl" elsewhere. Starts as "Ctrl" on the server to avoid a hydration mismatch. */
export function useModKey() {
  const [key, setKey] = useState("Ctrl");
  useEffect(() => {
    if (/Mac|iPhone|iPad/i.test(navigator.platform || navigator.userAgent)) setKey("⌘");
  }, []);
  return key;
}

function Kbd({ children, className }: { children: ReactNode; className?: string }) {
  return (
    <kbd
      className={cn(
        "inline-flex h-5 min-w-5 items-center justify-center rounded border border-border bg-muted px-1 font-sans text-[11px] font-medium text-muted-foreground",
        className,
      )}
    >
      {children}
    </kbd>
  );
}

export function CommandPalette({
  open, onOpenChange, groups, placeholder = "Type a command or search…", hotkey = "k",
  emptyMessage = (query) => <>No commands match “{query}”</>, label = "Command palette",
}: CommandPaletteProps) {
  const id = useId();
  const listId = `${id}-list`;
  const [query, setQuery] = useState("");
  const [active, setActive] = useState(0);
  const [mounted, setMounted] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);
  const listRef = useRef<HTMLDivElement>(null);
  const returnFocus = useRef<HTMLElement | null>(null);

  useEffect(() => setMounted(true), []);

  // ⌘K / Ctrl+K toggles the palette from anywhere on the page.
  useEffect(() => {
    if (!hotkey) return;
    function handleKey(event: globalThis.KeyboardEvent) {
      if ((event.metaKey || event.ctrlKey) && !event.altKey && event.key.toLowerCase() === hotkey && !event.repeat) {
        event.preventDefault();
        onOpenChange(!open);
      }
    }
    window.addEventListener("keydown", handleKey);
    return () => window.removeEventListener("keydown", handleKey);
  }, [hotkey, open, onOpenChange]);

  // Each opening starts fresh: empty query, first command active, focus in the input, page scroll locked.
  useLayoutEffect(() => {
    if (!open || !mounted) return;
    returnFocus.current = document.activeElement as HTMLElement | null;
    setQuery("");
    setActive(0);
    inputRef.current?.focus({ preventScroll: true });
    const { overflow } = document.body.style;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = overflow;
      if (returnFocus.current?.isConnected) returnFocus.current.focus({ preventScroll: true });
    };
  }, [open, mounted]);

  const results = useMemo(() => {
    const sections = groups.map((group) => {
      const items = group.items
        .map((item) => {
          const byLabel = match(item.label, query);
          const byKeyword = byLabel ? null : (item.keywords ?? []).map((word) => match(word, query)).find(Boolean);
          const found = byLabel ?? (byKeyword ? { score: byKeyword.score - 300, indices: [] } : null);
          return found ? { item, ...found } : null;
        })
        .filter((entry): entry is NonNullable<typeof entry> => entry !== null);
      if (query.trim()) items.sort((a, b) => b.score - a.score);
      return { heading: group.heading, items };
    });
    return sections.filter((section) => section.items.length > 0);
  }, [groups, query]);

  const flat = useMemo(() => results.flatMap((section) => section.items), [results]);
  const selectable = flat.map((entry, index) => (entry.item.disabled ? -1 : index)).filter((index) => index >= 0);
  const optionId = (index: number) => `${id}-option-${index}`;

  // After filtering, start on the first command that can run.
  useEffect(() => {
    setActive((current) => (flat[current] && !flat[current].item.disabled ? current : Math.max(0, flat.findIndex((entry) => !entry.item.disabled))));
  }, [flat]);

  // Keep the active row in view inside the list, without scrolling the page.
  useEffect(() => {
    const list = listRef.current;
    const row = list?.querySelector<HTMLElement>(`[data-index="${active}"]`);
    if (!list || !row) return;
    if (row.offsetTop < list.scrollTop + 32) list.scrollTop = Math.max(0, row.offsetTop - 36);
    else if (row.offsetTop + row.offsetHeight > list.scrollTop + list.clientHeight)
      list.scrollTop = row.offsetTop + row.offsetHeight - list.clientHeight + 6;
  }, [active, results]);

  function run(index: number) {
    const entry = flat[index];
    if (!entry || entry.item.disabled) return;
    onOpenChange(false);
    entry.item.onSelect();
  }

  function step(direction: 1 | -1) {
    if (!selectable.length) return;
    const position = selectable.indexOf(active);
    const next = position < 0 ? (direction === 1 ? 0 : selectable.length - 1) : (position + direction + selectable.length) % selectable.length;
    setActive(selectable[next]);
  }

  function handleKeyDown(event: KeyboardEvent<HTMLDivElement>) {
    switch (event.key) {
      case "ArrowDown":
        event.preventDefault();
        step(1);
        break;
      case "ArrowUp":
        event.preventDefault();
        step(-1);
        break;
      case "PageDown":
        event.preventDefault();
        setActive(selectable[selectable.length - 1] ?? 0);
        break;
      case "PageUp":
        event.preventDefault();
        setActive(selectable[0] ?? 0);
        break;
      case "Enter":
        event.preventDefault();
        run(active);
        break;
      case "Escape":
        event.preventDefault();
        event.stopPropagation();
        onOpenChange(false);
        break;
      case "Tab":
        // The input is the only stop inside the palette; keep focus here.
        event.preventDefault();
        break;
    }
  }

  if (!mounted || !open) return null;

  let index = -1;
  return createPortal(
    <div className="fixed inset-0 z-50" onKeyDown={handleKeyDown}>
      <div aria-hidden="true" className="absolute inset-0 bg-black/40 transition-opacity duration-200 starting:opacity-0 dark:bg-black/60" />
      <div className="relative flex h-full justify-center px-3 pt-[12vh]" onMouseDown={(event) => event.target === event.currentTarget && onOpenChange(false)}>
        <div
          role="dialog"
          aria-modal="true"
          aria-label={label}
          // Clicks inside never take focus away from the input.
          onMouseDown={(event) => event.target !== inputRef.current && event.preventDefault()}
          className={cn(
            "flex h-fit max-h-[min(34rem,80vh)] w-full max-w-xl flex-col overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground",
            "shadow-[0_24px_64px_-16px_rgb(0_0_0/0.4)] transition-[opacity,scale,translate] duration-200 ease-[cubic-bezier(.2,.8,.2,1)]",
            "starting:opacity-0 motion-safe:starting:-translate-y-2 motion-safe:starting:scale-[0.98]",
          )}
        >
          <div className="flex items-center gap-3 border-b border-border px-4">
            <Search aria-hidden="true" className="size-[18px] shrink-0 text-muted-foreground" />
            <input
              ref={inputRef}
              role="combobox"
              aria-expanded="true"
              aria-controls={listId}
              aria-autocomplete="list"
              aria-activedescendant={flat[active] ? optionId(active) : undefined}
              aria-label={label}
              autoComplete="off"
              spellCheck={false}
              placeholder={placeholder}
              value={query}
              onChange={(event) => {
                setQuery(event.target.value);
                setActive(0);
              }}
              className="h-13 min-w-0 flex-1 bg-transparent text-[15px] text-foreground outline-hidden placeholder:text-muted-foreground/70"
            />
            <Kbd className="hidden sm:inline-flex">Esc</Kbd>
          </div>

          <div ref={listRef} id={listId} role="listbox" aria-label="Commands" className="relative min-h-0 flex-1 overflow-y-auto overscroll-contain p-1.5">
            {results.map((section, sectionIndex) => (
              <div key={section.heading} role="group" aria-labelledby={`${id}-group-${sectionIndex}`} className="pb-1">
                <div id={`${id}-group-${sectionIndex}`} className="px-2.5 pb-1.5 pt-2 text-xs font-medium text-muted-foreground">
                  {section.heading}
                </div>
                {section.items.map(({ item, indices }) => {
                  index += 1;
                  const rowIndex = index;
                  const isActive = rowIndex === active;
                  return (
                    <div
                      key={item.id}
                      id={optionId(rowIndex)}
                      role="option"
                      aria-selected={isActive}
                      aria-disabled={item.disabled || undefined}
                      data-index={rowIndex}
                      data-active={isActive || undefined}
                      onMouseDown={(event) => event.preventDefault()}
                      onMouseMove={() => !item.disabled && !isActive && setActive(rowIndex)}
                      onClick={() => run(rowIndex)}
                      className={cn(
                        "flex h-10 cursor-default select-none items-center gap-3 rounded-lg px-2.5 text-sm text-foreground/85",
                        "data-[active]:bg-accent data-[active]:text-accent-foreground aria-disabled:opacity-45",
                      )}
                    >
                      {item.icon && (
                        <span aria-hidden="true" className="flex shrink-0 text-muted-foreground [&_svg]:size-4">{item.icon}</span>
                      )}
                      <span className="min-w-0 flex-1 truncate"><Highlighted text={item.label} indices={indices} /></span>
                      {item.shortcut && (
                        <span aria-hidden="true" className="hidden shrink-0 items-center gap-1 sm:flex">
                          {item.shortcut.map((key, keyIndex) => <Kbd key={keyIndex}>{key}</Kbd>)}
                        </span>
                      )}
                    </div>
                  );
                })}
              </div>
            ))}
            {flat.length === 0 && (
              <p className="px-4 py-10 text-center text-sm text-muted-foreground">{emptyMessage(query.trim())}</p>
            )}
          </div>

          <div className="flex items-center gap-4 border-t border-border bg-muted/40 px-4 py-2.5 text-xs text-muted-foreground dark:bg-muted/20">
            <span className="flex items-center gap-1.5"><Kbd>↑</Kbd><Kbd>↓</Kbd> Navigate</span>
            <span className="flex items-center gap-1.5"><Kbd>↵</Kbd> Run</span>
            <span className="ml-auto flex items-center gap-1.5"><Kbd>Esc</Kbd> Close</span>
          </div>

          <span role="status" aria-live="polite" className="sr-only">
            {query.trim() ? `${flat.length} ${flat.length === 1 ? "command" : "commands"}` : ""}
          </span>
        </div>
      </div>
    </div>,
    document.body,
  );
}