dxbh-uiGitHub

Command Palette

A grouped command list behind ⌘K and /. Keyboard opens are instant; a click gets a 150ms scale from 0.96. The panel is a translucent material over a dim scrim, with a focus trap, scroll lock and focus return.

Preview

Click for motion, press ⌘K or / for none.

Install

npx shadcn@latest add @dxbh-ui/command-palette

Add the @dxbh-ui registry to components.json once:

{
  "registries": {
    "@dxbh-ui": "https://ui.dxbh.dev/r/{name}.json"
  }
}

Usage

demo.tsx
"use client";

import { useState } from "react";
import { FilePlus, Folder, LayoutGrid, Moon, Search, Settings, Users } from "lucide-react";
import { CommandPalette, type CommandGroup } from "@/components/ui/command-palette/command-palette";

const groups: CommandGroup[] = [
  {
    heading: "Navigate",
    items: [
      { id: "overview", label: "Overview", icon: <LayoutGrid />, hint: "Home" },
      { id: "projects", label: "Projects", icon: <Folder /> },
      { id: "members", label: "Members", icon: <Users />, keywords: ["team", "people"] },
      { id: "settings", label: "Settings", icon: <Settings />, shortcut: "⌘," },
    ],
  },
  {
    heading: "Actions",
    items: [
      { id: "new", label: "New document", icon: <FilePlus />, shortcut: "⌘N" },
      { id: "theme", label: "Toggle dark mode", icon: <Moon />, keywords: ["theme", "appearance"] },
      { id: "archive", label: "Archive everything", disabled: true, hint: "Owner only" },
    ],
  },
];

export default function CommandPaletteDemo() {
  const [open, setOpen] = useState(false);
  const [last, setLast] = useState<string | null>(null);

  return (
    <div className="flex flex-col items-center gap-4">
      <button
        type="button"
        onClick={() => setOpen(true)}
        className="flex w-64 cursor-pointer items-center gap-2 rounded-lg border bg-background py-1.5 pr-1.5 pl-3 text-left text-sm text-muted-foreground outline-none transition-transform duration-(--duration-press,120ms) ease-out hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 active:scale-[0.97]"
      >
        <Search aria-hidden="true" className="size-4" />
        <span className="flex-1">Search…</span>
        <kbd className="rounded border px-1.5 py-0.5 font-mono text-[10px]">⌘K</kbd>
      </button>
      <p className="text-xs text-muted-foreground">
        Click for motion, press ⌘K or / for none.{" "}
        <span aria-live="polite" className="tabular-nums">
          {last ? `Ran “${last}”.` : ""}
        </span>
      </p>
      <CommandPalette
        groups={groups}
        open={open}
        onOpenChange={setOpen}
        onSelect={(item) => setLast(item.label)}
      />
    </div>
  );
}

Props

PropTypeDefault
groups*

Headings and their items. Empty groups hide while filtering.

CommandGroup[]—
onSelect

Called with the chosen item, after the item's own onSelect.

(item: CommandItem) => void—
renderItem

Replace a row's contents. The row keeps its role and highlight.

(item, { active, query }) => ReactNode—
open

Controlled open state.

boolean—
defaultOpen

Initial state when uncontrolled.

booleanfalse
onOpenChange

Called when the palette asks to open or close.

(open: boolean) => void—
filter

Custom matching. Defaults to every word in label, hint, keywords or heading.

(item, query, group) => boolean—
shortcut

Toggle with ⌘K / Ctrl+K.

booleantrue
slashShortcut

Open with / when focus is outside a text field.

booleantrue
closeOnSelect

Close after choosing an item.

booleantrue
label

Accessible name of the dialog.

string"Command palette"
placeholder

Search field placeholder.

string"Type a command or search…"
empty

Shown when nothing matches.

ReactNode | ((query: string) => ReactNode)"No results"
footer

Replaces the key legend. Pass null to hide it.

ReactNode—

Polish

  • cmdk, Radix Dialog, next/link, next/navigation and react-icons removed; one dependency-free file with lucide icons.
  • Commands, routes, easter eggs and contact details stripped; callers pass groups, onSelect and an optional renderItem.
  • Opens from the keyboard (⌘K, /, Enter on a trigger) skip motion entirely. Pointer opens scale 0.96 → 1 with opacity in 150ms; exits take 100ms.
  • Modal, so it stays centred: no transform-origin offset. Never scales from 0.
  • The active row highlight follows arrow keys and pointer with no transition.
  • Material panel paired with a dim scrim, the modal-task pairing from POLISH §7.
  • Focus trap, body scroll lock with scrollbar compensation, and focus returned to whatever opened it.
  • Combobox + listbox semantics with aria-activedescendant; result count announced politely.
  • Reduced motion keeps the fade and drops the scale.

Source

command-palette.tsx
"use client";

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

export type CommandItem = {
  /** Stable id, unique across every group. */
  id: string;
  label: string;
  /** Secondary text on the right of the row. Also searched. */
  hint?: string;
  /** Extra search terms that are never shown. */
  keywords?: string[];
  icon?: ReactNode;
  /** Display-only key hint, such as "⌘N". The palette does not bind it. */
  shortcut?: string;
  disabled?: boolean;
  /** Runs when the row is chosen, before the palette-level `onSelect`. */
  onSelect?: () => void;
};

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

export type CommandRenderState = {
  /** The row holds the keyboard highlight. */
  active: boolean;
  query: string;
};

export type CommandPaletteProps = {
  groups: CommandGroup[];
  /** Controlled open state. Leave undefined to let the palette own it. */
  open?: boolean;
  defaultOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
  /** Called with the chosen item. Route, copy or run anything here. */
  onSelect?: (item: CommandItem) => void;
  /** Replace the row's contents. The row itself (role, highlight, click) stays. */
  renderItem?: (item: CommandItem, state: CommandRenderState) => ReactNode;
  /** Return true to keep the item for this query. Defaults to a word match on label, hint, keywords and heading. */
  filter?: (item: CommandItem, query: string, group: CommandGroup) => boolean;
  /** Bind ⌘K / Ctrl+K to toggle. */
  shortcut?: boolean;
  /** Bind "/" to open when focus is not in a text field. */
  slashShortcut?: boolean;
  /** Close after an item is chosen. */
  closeOnSelect?: boolean;
  /** Accessible name of the dialog. */
  label?: string;
  placeholder?: string;
  /** Shown when nothing matches. Receives the query. */
  empty?: ReactNode | ((query: string) => ReactNode);
  /** Replaces the key legend at the bottom. Pass null to hide it. */
  footer?: ReactNode;
  className?: string;
};

/* ------------------------------------------------------------------------ */
/* Input modality. The palette opens hundreds of times a day from the       */
/* keyboard; those opens get no motion at all. A click still gets a short  */
/* scale so the panel reads as arriving.                                    */
/* ------------------------------------------------------------------------ */

let lastInput: "keyboard" | "pointer" = "pointer";
let modalityListeners = 0;
const onKeyInput = () => (lastInput = "keyboard");
const onPointerInput = () => (lastInput = "pointer");

function useInputModality() {
  useEffect(() => {
    if (modalityListeners++ === 0) {
      document.addEventListener("keydown", onKeyInput, true);
      document.addEventListener("pointerdown", onPointerInput, true);
    }
    return () => {
      if (--modalityListeners === 0) {
        document.removeEventListener("keydown", onKeyInput, true);
        document.removeEventListener("pointerdown", onPointerInput, true);
      }
    };
  }, []);
}

/** Enter 150ms, exit about a third faster. */
export const PALETTE_EXIT_MS = 100;

const TEXT_FIELD = "input, textarea, select, [contenteditable=''], [contenteditable='true']";
const isTyping = (target: EventTarget | null) => !!(target as Element | null)?.closest?.(TEXT_FIELD);

const normalise = (s: string) => s.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "");

export function defaultCommandFilter(item: CommandItem, query: string, group: CommandGroup): boolean {
  const haystack = normalise([item.label, item.hint, group.heading, ...(item.keywords ?? [])].join(" "));
  return normalise(query)
    .split(/\s+/)
    .filter(Boolean)
    .every((word) => haystack.includes(word));
}

const FOCUSABLE = 'input:not([disabled]), button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';

export function CommandPalette({
  groups,
  open: openProp,
  defaultOpen = false,
  onOpenChange,
  onSelect,
  renderItem,
  filter = defaultCommandFilter,
  shortcut = true,
  slashShortcut = true,
  closeOnSelect = true,
  label = "Command palette",
  placeholder = "Type a command or search…",
  empty = "No results",
  footer,
  className,
}: CommandPaletteProps) {
  const [openState, setOpenState] = useState(defaultOpen);
  const controlled = openProp !== undefined;
  const open = controlled ? openProp : openState;

  // Read by the global shortcut listener without re-binding it on every toggle.
  const openRef = useRef(open);
  useEffect(() => {
    openRef.current = open;
  }, [open]);
  const setOpen = useCallback(
    (next: boolean) => {
      if (next === openRef.current) return;
      if (!controlled) setOpenState(next);
      onOpenChange?.(next);
    },
    [controlled, onOpenChange],
  );

  useInputModality();

  // Mounted outlives `open` by the exit duration so the panel can fade out.
  const [mounted, setMounted] = useState(open);
  const [instant, setInstant] = useState(false);
  const [prevOpen, setPrevOpen] = useState(open);
  if (prevOpen !== open) {
    setPrevOpen(open);
    setInstant(lastInput === "keyboard");
    if (open) setMounted(true);
  }

  useEffect(() => {
    if (open || !mounted) return;
    const t = setTimeout(() => setMounted(false), instant ? 0 : PALETTE_EXIT_MS);
    return () => clearTimeout(t);
  }, [open, mounted, instant]);

  useEffect(() => {
    if (!shortcut && !slashShortcut) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.defaultPrevented || e.isComposing) return;
      lastInput = "keyboard";
      if (shortcut && (e.metaKey || e.ctrlKey) && !e.altKey && e.key.toLowerCase() === "k") {
        e.preventDefault();
        setOpen(!openRef.current);
      } else if (slashShortcut && e.key === "/" && !e.metaKey && !e.ctrlKey && !e.altKey && !isTyping(e.target)) {
        if (openRef.current) return;
        e.preventDefault();
        setOpen(true);
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [shortcut, slashShortcut, setOpen]);

  if (!mounted || typeof document === "undefined") return null;

  return createPortal(
    <PalettePanel
      groups={groups}
      open={open}
      instant={instant}
      onClose={() => setOpen(false)}
      onSelect={onSelect}
      renderItem={renderItem}
      filter={filter}
      closeOnSelect={closeOnSelect}
      label={label}
      placeholder={placeholder}
      empty={empty}
      footer={footer}
      className={className}
    />,
    document.body,
  );
}

type PanelProps = Required<Pick<CommandPaletteProps, "groups" | "filter" | "closeOnSelect" | "label" | "placeholder">> &
  Pick<CommandPaletteProps, "onSelect" | "renderItem" | "empty" | "footer" | "className"> & {
    open: boolean;
    instant: boolean;
    onClose: () => void;
  };

function PalettePanel({
  groups,
  open,
  instant,
  onClose,
  onSelect,
  renderItem,
  filter,
  closeOnSelect,
  label,
  placeholder,
  empty,
  footer,
  className,
}: PanelProps) {
  const id = useId();
  const panelRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const [query, setQuery] = useState("");
  const [activeId, setActiveId] = useState<string | null>(null);

  const visible = useMemo(() => {
    const q = query.trim();
    return groups
      .map((group) => ({ group, items: q ? group.items.filter((item) => filter(item, q, group)) : group.items }))
      .filter((g) => g.items.length > 0);
  }, [groups, query, filter]);

  const flat = useMemo(() => visible.flatMap((g) => g.items).filter((item) => !item.disabled), [visible]);
  // The highlight falls back to the first row whenever the current one is filtered out.
  const active = flat.find((item) => item.id === activeId) ?? flat[0] ?? null;
  const optionId = (item: CommandItem) => `${id}-option-${item.id}`;

  // Focus the field on open, scroll-lock the page, and hand focus back on close.
  useEffect(() => {
    const restore = document.activeElement as HTMLElement | null;
    inputRef.current?.focus({ preventScroll: true });
    const { overflow, paddingRight } = document.body.style;
    const gap = window.innerWidth - document.documentElement.clientWidth;
    document.body.style.overflow = "hidden";
    if (gap > 0) document.body.style.paddingRight = `${gap}px`;
    return () => {
      document.body.style.overflow = overflow;
      document.body.style.paddingRight = paddingRight;
      if (restore?.isConnected) restore.focus({ preventScroll: true });
    };
  }, []);

  useEffect(() => {
    if (!active) return;
    document.getElementById(optionId(active))?.scrollIntoView?.({ block: "nearest" });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [active?.id]);

  const choose = (item: CommandItem) => {
    if (item.disabled) return;
    item.onSelect?.();
    onSelect?.(item);
    if (closeOnSelect) onClose();
  };

  const move = (delta: number) => {
    if (!flat.length) return;
    const index = active ? flat.indexOf(active) : -1;
    setActiveId(flat[(index + delta + flat.length) % flat.length].id);
  };

  const onKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {
    if (e.nativeEvent.isComposing) return;
    switch (e.key) {
      case "ArrowDown":
        e.preventDefault();
        move(1);
        break;
      case "ArrowUp":
        e.preventDefault();
        move(-1);
        break;
      case "PageUp":
      case "PageDown":
        e.preventDefault();
        if (flat.length) setActiveId(flat[e.key === "PageUp" ? 0 : flat.length - 1].id);
        break;
      case "Enter":
        if (active) {
          e.preventDefault();
          choose(active);
        }
        break;
      case "Escape":
        e.preventDefault();
        e.stopPropagation();
        onClose();
        break;
      case "Tab": {
        // Keep Tab inside the dialog.
        const focusable = panelRef.current?.querySelectorAll<HTMLElement>(FOCUSABLE);
        if (!focusable?.length) return;
        const first = focusable[0];
        const last = focusable[focusable.length - 1];
        if (e.shiftKey && document.activeElement === first) {
          e.preventDefault();
          last.focus();
        } else if (!e.shiftKey && document.activeElement === last) {
          e.preventDefault();
          first.focus();
        }
        break;
      }
    }
  };

  const state = open ? "open" : "closed";
  const listId = `${id}-list`;
  const count = flat.length;

  return (
    <div
      className="fixed inset-0 z-50 flex items-start justify-center px-4 pt-[12vh] data-[state=closed]:pointer-events-none"
      data-state={state}
      data-instant={instant || undefined}
      onKeyDown={onKeyDown}
    >
      <div
        aria-hidden="true"
        data-slot="command-palette-scrim"
        onPointerDown={onClose}
        className={cn(
          "absolute inset-0 bg-black/40 transition-opacity duration-150 ease-out starting:opacity-0",
          "data-[state=closed]:opacity-0 data-[state=closed]:duration-100",
          "data-instant:transition-none",
        )}
        data-state={state}
        data-instant={instant || undefined}
      />
      <div
        ref={panelRef}
        role="dialog"
        aria-modal="true"
        aria-label={label}
        data-slot="command-palette"
        data-state={state}
        data-instant={instant || undefined}
        className={cn(
          "material-regular relative flex w-full max-w-xl flex-col overflow-hidden rounded-xl border border-border/60 text-foreground shadow-2xl outline-none",
          // Modals stay centred, so the default origin is right. Scale starts at 0.96, never 0.
          "transition-[opacity,transform] duration-150 ease-out starting:scale-[0.96] starting:opacity-0",
          "data-[state=closed]:scale-[0.96] data-[state=closed]:opacity-0 data-[state=closed]:duration-100",
          "motion-reduce:scale-100 motion-reduce:starting:scale-100 motion-reduce:data-[state=closed]:scale-100",
          "data-instant:transition-none",
          className,
        )}
      >
        <div className="flex items-center gap-2.5 border-b border-border/60 px-4">
          <Search aria-hidden="true" className="size-4 shrink-0 text-muted-foreground" />
          <input
            ref={inputRef}
            role="combobox"
            aria-expanded="true"
            aria-controls={listId}
            aria-autocomplete="list"
            aria-activedescendant={active ? optionId(active) : undefined}
            aria-label={label}
            value={query}
            onChange={(e) => {
              setQuery(e.target.value);
              setActiveId(null);
            }}
            placeholder={placeholder}
            autoComplete="off"
            autoCorrect="off"
            spellCheck={false}
            className="h-12 min-w-0 flex-1 bg-transparent text-[15px] outline-none placeholder:text-muted-foreground"
          />
          <kbd className="hidden rounded border border-border/80 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground sm:inline">
            Esc
          </kbd>
        </div>

        <div
          id={listId}
          role="listbox"
          aria-label={label}
          className="max-h-[min(60vh,420px)] scroll-py-2 overflow-y-auto overscroll-contain p-2"
        >
          {visible.length === 0 ? (
            <div className="px-3 py-10 text-center text-sm text-muted-foreground">
              {typeof empty === "function" ? empty(query.trim()) : empty}
            </div>
          ) : (
            visible.map(({ group, items }, g) => {
              const headingId = `${id}-group-${g}`;
              return (
                <div key={group.heading} role="group" aria-labelledby={headingId} className="not-first:mt-2">
                  <div
                    id={headingId}
                    className="px-3 pt-1.5 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase"
                  >
                    {group.heading}
                  </div>
                  {items.map((item) => {
                    const isActive = active?.id === item.id;
                    return (
                      <div
                        key={item.id}
                        id={optionId(item)}
                        role="option"
                        aria-selected={isActive}
                        aria-disabled={item.disabled || undefined}
                        data-active={isActive || undefined}
                        // Pointer moves the highlight; it does not steal focus from the field.
                        onPointerMove={() => !item.disabled && item.id !== activeId && setActiveId(item.id)}
                        onMouseDown={(e) => e.preventDefault()}
                        onClick={() => choose(item)}
                        className={cn(
                          // The highlight is instant: it follows the keyboard, so it never transitions.
                          "flex min-h-10 cursor-pointer items-center gap-3 rounded-lg px-3 py-2 text-sm select-none",
                          "data-active:bg-foreground/[0.07] aria-disabled:cursor-default aria-disabled:opacity-50",
                        )}
                      >
                        {renderItem ? (
                          renderItem(item, { active: isActive, query })
                        ) : (
                          <DefaultRow item={item} active={isActive} />
                        )}
                      </div>
                    );
                  })}
                </div>
              );
            })
          )}
        </div>

        {footer === undefined ? (
          <div className="flex items-center gap-4 border-t border-border/60 px-4 py-2 text-[11px] text-muted-foreground">
            <span>
              <Key>↑</Key>
              <Key>↓</Key> navigate
            </span>
            <span>
              <Key>↵</Key> select
            </span>
            <span>
              <Key>esc</Key> close
            </span>
          </div>
        ) : (
          footer
        )}

        <span role="status" aria-live="polite" className="sr-only">
          {query.trim() ? `${count} ${count === 1 ? "result" : "results"}` : ""}
        </span>
      </div>
    </div>
  );
}

function DefaultRow({ item, active }: { item: CommandItem; active: boolean }) {
  return (
    <Fragment>
      {item.icon ? (
        <span aria-hidden="true" className="grid size-4 shrink-0 place-items-center text-muted-foreground [&>svg]:size-4">
          {item.icon}
        </span>
      ) : null}
      <span className="min-w-0 flex-1 truncate">{item.label}</span>
      {item.hint ? <span className="truncate text-xs text-muted-foreground">{item.hint}</span> : null}
      {item.shortcut ? (
        <kbd className="font-mono text-[11px] tracking-widest text-muted-foreground">{item.shortcut}</kbd>
      ) : (
        <CornerDownLeft
          aria-hidden="true"
          className={cn("size-3.5 shrink-0 text-muted-foreground", active ? "opacity-100" : "opacity-0")}
        />
      )}
    </Fragment>
  );
}

function Key({ children }: { children: ReactNode }) {
  return (
    <kbd className="mr-1 inline-block min-w-[18px] rounded border border-border/80 px-1 text-center font-mono text-[10px]">
      {children}
    </kbd>
  );
}

Extracted from portfolio/src/components/CommandPalette.tsx at 466696b, anidub/apps/web/src/components/spotlight-search.tsx at a950c62, Vesrelle/components/layout/command-palette.tsx at 4619651.