RendyUI 中文

Components / Command palette

Command palette

Overlays · React / TypeScript Free

Recorded demo

Command palette preview

Source

command-palette.tsx
"use client";

/**
 * Command palette — replica of the public UI Stacks spec.
 * Original implementation written from the public API docs.
 */
import * as React from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { CornerDownLeft, Loader2, Search, Sparkles } from "lucide-react";
import { cn, useControllable, useFocusTrap } from "../internal";

export type CommandItem = {
  id: string;
  label: string;
  icon?: React.ReactNode;
  shortcut?: string;
  keywords?: string[];
  disabled?: boolean;
  onRun?: () => void;
};

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

export interface CommandPaletteProps {
  groups: CommandGroup[];
  hotkey?: boolean;
  triggerLabel?: string;
  open?: boolean;
  defaultOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
  onQueryChange?: (query: string) => void;
  loading?: boolean;
  onAsk?: (query: string) => void;
  askLabel?: string;
  askHint?: string;
  placeholder?: string;
  emptyHint?: string;
  size?: "md" | "lg";
}

/**
 * Command palette: one keyboard-first box to jump to records and run
 * actions. Cmd/Ctrl + K opens it; the highlight slides with the arrow keys.
 */
export function CommandPalette({
  groups,
  hotkey = true,
  triggerLabel = "Search…",
  open,
  defaultOpen = false,
  onOpenChange,
  onQueryChange,
  loading = false,
  onAsk,
  askLabel = "Ask AI",
  askHint = "Tab to send the query",
  placeholder = "Type a command or search…",
  emptyHint = "No results yet",
  size = "md",
}: CommandPaletteProps) {
  const reduce = useReducedMotion();
  const [isOpen, setOpen] = useControllable(open, defaultOpen, onOpenChange);
  const [query, setQuery] = React.useState("");
  const [activeIndex, setActiveIndex] = React.useState(0);
  const panelRef = React.useRef<HTMLDivElement>(null);
  const inputRef = React.useRef<HTMLInputElement>(null);

  useFocusTrap(panelRef, isOpen, { initialFocus: inputRef });

  React.useEffect(() => {
    if (!hotkey) return;
    const onKeyDown = (event: KeyboardEvent) => {
      if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
        event.preventDefault();
        setOpen(!isOpen);
      }
    };
    document.addEventListener("keydown", onKeyDown);
    return () => document.removeEventListener("keydown", onKeyDown);
  }, [hotkey, isOpen, setOpen]);

  React.useEffect(() => {
    if (!isOpen) {
      setQuery("");
      setActiveIndex(0);
    }
  }, [isOpen]);

  const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean);

  const filtered = React.useMemo(() => {
    if (!terms.length) return groups;
    return groups
      .map((group) => ({
        ...group,
        items: group.items.filter((item) => {
          const haystack = [item.label, ...(item.keywords ?? [])].join(" ").toLowerCase();
          return terms.every((term) => haystack.includes(term));
        }),
      }))
      .filter((group) => group.items.length > 0);
  }, [groups, query]);

  const flat = filtered.flatMap((group) => group.items).filter((item) => !item.disabled);
  const showAsk = Boolean(onAsk) && query.trim().length > 0;

  React.useEffect(() => {
    setActiveIndex(0);
  }, [query]);

  React.useEffect(() => {
    if (!isOpen) return;
    const node = panelRef.current?.querySelector<HTMLElement>(`[data-cmd-index="${activeIndex}"]`);
    node?.scrollIntoView({ block: "nearest" });
  }, [isOpen, activeIndex]);

  const run = (item: CommandItem) => {
    if (item.disabled) return;
    item.onRun?.();
    setOpen(false);
  };

  const onKeyDown = (event: React.KeyboardEvent) => {
    if (event.key === "Escape") {
      event.preventDefault();
      setOpen(false);
      return;
    }
    if (event.key === "Tab" && showAsk && onAsk) {
      event.preventDefault();
      onAsk(query);
      setOpen(false);
      return;
    }
    if (event.key === "ArrowDown") {
      event.preventDefault();
      setActiveIndex((index) => (flat.length ? (index + 1) % flat.length : 0));
      return;
    }
    if (event.key === "ArrowUp") {
      event.preventDefault();
      setActiveIndex((index) => (flat.length ? (index - 1 + flat.length) % flat.length : 0));
      return;
    }
    if (event.key === "Enter") {
      event.preventDefault();
      const item = flat[activeIndex];
      if (item) run(item);
    }
  };

  const width = size === "lg" ? "max-w-[640px]" : "max-w-[560px]";

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        className="inline-flex h-9 w-full max-w-[280px] items-center gap-2 rounded-[9px] border border-border bg-surface px-3 text-[13px] text-fg-subtle shadow-[var(--shadow-btn-secondary)] transition-colors hover:bg-subtle"
      >
        <Search className="size-3.5" aria-hidden />
        <span className="flex-1 text-left">{triggerLabel}</span>
        {hotkey ? (
          <kbd className="rounded-[5px] border border-border bg-subtle px-1.5 py-0.5 font-mono text-[10.5px]">
            ⌘K
          </kbd>
        ) : null}
      </button>

      <AnimatePresence>
        {isOpen ? (
          <div className="fixed inset-0 z-[120] flex items-start justify-center px-4 pt-[12vh]">
            <motion.div
              initial={reduce ? false : { opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={reduce ? undefined : { opacity: 0 }}
              transition={{ duration: 0.15 }}
              onClick={() => setOpen(false)}
              className="absolute inset-0 bg-[var(--scrim)] backdrop-blur-[2px]"
              aria-hidden
            />
            <motion.div
              ref={panelRef}
              role="dialog"
              aria-modal="true"
              aria-label="Command palette"
              initial={reduce ? false : { opacity: 0, scale: 0.97, y: -8 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={reduce ? undefined : { opacity: 0, scale: 0.98, y: -6 }}
              transition={{ duration: 0.18, ease: [0.2, 0, 0, 1] }}
              onKeyDown={onKeyDown}
              className={cn(
                "relative w-full overflow-hidden rounded-[16px] bg-surface shadow-[var(--shadow-overlay)]",
                width,
              )}
            >
              <div className="flex items-center gap-2.5 border-b border-border px-4">
                <Search className="size-4 shrink-0 text-fg-subtle" aria-hidden />
                <input
                  ref={inputRef}
                  value={query}
                  onChange={(event) => {
                    setQuery(event.target.value);
                    onQueryChange?.(event.target.value);
                  }}
                  placeholder={placeholder}
                  aria-label="Command search"
                  className={cn(
                    "h-12 w-full bg-transparent text-[14px] text-fg outline-none placeholder:text-fg-subtle",
                    size === "lg" && "h-14 text-[15px]",
                  )}
                />
                {loading ? <Loader2 className="size-4 animate-spin text-fg-subtle" aria-hidden /> : null}
              </div>

              <div className="max-h-[380px] overflow-auto p-2">
                {loading && !flat.length ? (
                  <div className="flex flex-col gap-2 p-2">
                    {[0, 1, 2, 3].map((row) => (
                      <div
                        key={row}
                        className="h-9 animate-pulse rounded-[8px] bg-subtle"
                        style={{ opacity: 1 - row * 0.18 }}
                      />
                    ))}
                  </div>
                ) : null}

                {!loading && !flat.length ? (
                  <div className="px-3 py-8 text-center">
                    <p className="text-[13.5px] font-medium text-fg">No matches</p>
                    <p className="mt-1 text-[12.5px] text-fg-subtle">{emptyHint}</p>
                  </div>
                ) : null}

                {filtered.map((group) => (
                  <div key={group.label} className="mb-1">
                    <div className="px-2.5 pb-1 pt-2 text-[11px] font-semibold uppercase tracking-wide text-fg-subtle">
                      {group.label}
                    </div>
                    {group.items.map((item) => {
                      const index = flat.indexOf(item);
                      const active = index === activeIndex;
                      return (
                        <div
                          key={item.id}
                          role="option"
                          aria-selected={active}
                          aria-disabled={item.disabled || undefined}
                          data-cmd-index={index}
                          tabIndex={-1}
                          onMouseEnter={() => !item.disabled && setActiveIndex(index)}
                          onClick={() => run(item)}
                          className={cn(
                            "flex cursor-pointer items-center gap-2.5 rounded-[9px] px-2.5 py-2 text-[13.5px]",
                            active && "bg-subtle",
                            item.disabled && "cursor-not-allowed opacity-40",
                          )}
                        >
                          {item.icon ? (
                            <span className="grid size-4 shrink-0 place-items-center text-fg-subtle">
                              {item.icon}
                            </span>
                          ) : null}
                          <span className="min-w-0 flex-1 truncate text-fg">{item.label}</span>
                          {item.shortcut ? (
                            <span className="shrink-0 font-mono text-[11px] text-fg-subtle">
                              {item.shortcut}
                            </span>
                          ) : null}
                        </div>
                      );
                    })}
                  </div>
                ))}

                {showAsk ? (
                  <div
                    role="option"
                    aria-selected={false}
                    tabIndex={-1}
                    onClick={() => {
                      onAsk?.(query);
                      setOpen(false);
                    }}
                    className="mt-1 flex cursor-pointer items-center gap-2.5 rounded-[9px] px-2.5 py-2 text-[13.5px] hover:bg-subtle"
                  >
                    <Sparkles className="size-4 shrink-0 text-[var(--select)]" aria-hidden />
                    <span className="flex-1 truncate text-fg">{askLabel}</span>
                    <span className="shrink-0 text-[11.5px] text-fg-subtle">{askHint}</span>
                    <CornerDownLeft className="size-3 shrink-0 text-fg-subtle" aria-hidden />
                  </div>
                ) : null}
              </div>
            </motion.div>
          </div>
        ) : null}
      </AnimatePresence>
    </>
  );
}

export default CommandPalette;

Usage

Add the TSX to your React project and install the required dependencies. Styles use Tailwind CSS and theme tokens。

Package dependencies · lucide-react、motion、react

Shared source · internal.ts

Props

NameTypeDescription
`groups``{ label; items: { id; label; icon?; shortcut?; keywords?; disabled?; onRun? }[] }[]`Every typed word must match the label or the keywords.
`hotkey``boolean`Opens and closes with ⌘K or Ctrl+K anywhere on the page.
`triggerLabel``string`Shows a search-field trigger with this text.
`open / defaultOpen / onOpenChange``boolean / boolean / (open) => void`Controlled or uncontrolled.
`onQueryChange / loading``(query) => void / boolean`Fetch records as people type; skeleton rows and a spinner meanwhile.
`onAsk / askLabel / askHint``(query) => void / string / string`Adds the Ask AI row; Tab sends the query.
`placeholder / emptyHint``string`Field text and the second line of the empty state.
`size``"md" \| "lg"`560 or 640 wide; lg has a larger field.