Command
SaveA command palette with a search field, grouped results that filter word by word, full keyboard navigation, an empty state, a loading row for slower results, and a Cmd+K dialog variant, built on Base UI Autocomplete and Dialog.
- Category
- Overlays
- Version
- 0.1.0
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
Command preview
Start a run⌘R
Review pending approvals2 waiting
Open trace for run 482
RunsGR
Tools and integrationsGT
Workspace settingsGS
Revoke API key
Installation
npx @shakenui/cli add commandReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add command --dry-runUsage
command-example.tsx
"use client";
import { type ReactNode, useEffect, useState } from "react";
import {
Command,
CommandDialog,
CommandDialogTrigger,
CommandEmpty,
CommandFooter,
CommandGroup,
type CommandGroupData,
CommandInput,
CommandItem,
type CommandItemData,
CommandItemMeta,
CommandList,
CommandLoading,
CommandShortcut,
} from "@/components/shaken/ui/command";
interface Action extends CommandItemData {
icon: ReactNode;
meta?: string;
keys?: string[];
destructive?: boolean;
}
const stroke = { stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" } as const;
const svg = (path: ReactNode) => (
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none">
{path}
</svg>
);
const play = svg(<path d="M5 3.5v9l7-4.5-7-4.5Z" {...stroke} />);
const check = svg(<><circle cx="8" cy="8" r="5.75" {...stroke} /><path d="m5.75 8.25 1.5 1.5 3-3.25" {...stroke} /></>);
const trace = svg(<path d="M2.5 12.5h11M4.5 10V7M8 10V4M11.5 10V8.5" {...stroke} />);
const arrow = svg(<path d="M3.5 8h9M9 4.5 12.5 8 9 11.5" {...stroke} />);
const key = svg(<><circle cx="5.5" cy="10.5" r="2.5" {...stroke} /><path d="m7.25 8.75 5.25-5.25M10.5 5.5l1.5 1.5" {...stroke} /></>);
const run = svg(<><circle cx="8" cy="8" r="5.75" {...stroke} /><path d="M8 5v3l2 1.25" {...stroke} /></>);
const groups: CommandGroupData<Action>[] = [
{
label: "Suggested",
items: [
{ value: "start-run", label: "Start a run", icon: play, keys: ["⌘", "R"], keywords: ["agent", "new", "task"] },
{ value: "approvals", label: "Review pending approvals", icon: check, meta: "2 waiting", keywords: ["approve", "gate"] },
{ value: "trace", label: "Open trace for run 482", icon: trace, keywords: ["debug", "timeline", "spans"] },
],
},
{
label: "Go to",
items: [
{ value: "go-runs", label: "Runs", icon: arrow, keys: ["G", "R"], keywords: ["history"] },
{ value: "go-tools", label: "Tools and integrations", icon: arrow, keys: ["G", "T"], keywords: ["mcp", "connectors"] },
{ value: "go-settings", label: "Workspace settings", icon: arrow, keys: ["G", "S"], keywords: ["preferences", "config"] },
],
},
{
label: "Danger zone",
items: [{ value: "revoke", label: "Revoke API key", icon: key, destructive: true, keywords: ["token", "secret", "delete"] }],
},
];
const pastRuns: Action[] = [
{ value: "run-482", label: "Run 482: rate limits per plan", icon: run, meta: "Merged" },
{ value: "run-479", label: "Run 479: retry flaky webhook tests", icon: run, meta: "Failed" },
{ value: "run-471", label: "Run 471: migrate billing to v2 API", icon: run, meta: "Merged" },
];
function Results() {
return (
<>
<CommandEmpty />
<CommandList>
{(group: CommandGroupData<Action>) => (
<CommandGroup key={group.label} heading={group.label} items={group.items}>
{(item: Action) => (
<CommandItem key={item.value} value={item} destructive={item.destructive}>
{item.icon}
<span className="truncate">{item.label}</span>
{item.meta ? <CommandItemMeta>{item.meta}</CommandItemMeta> : null}
{item.keys ? <CommandShortcut>{item.keys}</CommandShortcut> : null}
</CommandItem>
)}
</CommandGroup>
)}
</CommandList>
</>
);
}
/** The dialog body: searching past runs takes a moment, so a quiet loading row shows meanwhile. */
function Palette() {
const [query, setQuery] = useState("");
const [loaded, setLoaded] = useState("");
const searching = query.trim().length >= 2 && loaded !== query;
useEffect(() => {
if (query.trim().length < 2) return;
const timer = setTimeout(() => setLoaded(query), 700);
return () => clearTimeout(timer);
}, [query]);
const items = loaded && loaded === query ? [...groups, { label: "Past runs", items: pastRuns }] : groups;
return (
<Command items={items} value={query} onValueChange={setQuery}>
<CommandInput placeholder="Search commands and runs" end={<CommandShortcut>Esc</CommandShortcut>} />
<CommandLoading loading={searching} label="Searching past runs" className="px-1.5 pt-1.5" />
<Results />
<CommandFooter>
<span className="flex items-center gap-1.5">
<kbd>↑</kbd>
<kbd>↓</kbd>
Move
</span>
<span className="flex items-center gap-1.5">
<kbd>↵</kbd>
Run
</span>
<span className="ml-auto max-sm:hidden">Results update as you type</span>
</CommandFooter>
</Command>
);
}
// A search-field look for the trigger, on the Button secondary recipe.
const searchButton =
"flex h-9 w-64 items-center gap-2 rounded-lg border border-zinc-950/12 bg-white pr-1.5 pl-3 text-sm text-zinc-500 select-none " +
"transition-[background-color,border-color] duration-150 ease-out motion-reduce:transition-none " +
"hover:border-zinc-950/20 hover:bg-zinc-950/[0.03] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500 " +
"dark:border-white/15 dark:bg-black dark:text-zinc-400 dark:hover:border-white/25 dark:hover:bg-white/[0.06]";
export default function CommandExample() {
return (
<div className="grid w-full max-w-xl justify-items-center gap-6">
{/* This docs site already uses Cmd+K for its own search, so the example listens for Cmd+J. */}
<CommandDialog
shortcut="j"
trigger={
<CommandDialogTrigger className={searchButton}>
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="size-4 shrink-0">
<circle cx="7.25" cy="7.25" r="4.5" {...stroke} />
<path d="m10.75 10.75 2.75 2.75" {...stroke} />
</svg>
Search commands
<CommandShortcut>{["⌘", "J"]}</CommandShortcut>
</CommandDialogTrigger>
}
>
<Palette />
</CommandDialog>
<Command items={groups}>
<CommandInput />
<Results />
</Command>
</div>
);
}API
| Prop | Type | Default | Description |
|---|---|---|---|
| Command items | Item[] | { label, items }[] | — | The commands, flat or grouped. Items shaped { value, label, keywords? } work with the default filter; extra fields are passed to your render function. |
| Command filter | (item, query, itemToString) => boolean | null | defaultCommandFilter | Replaces the default filter, which needs every query word in the label or keywords and ignores case and accents. null leaves filtering to you. |
| Command value / defaultValue / onValueChange | string / string / (value) => void | — | The query. |
| Command loopFocus | boolean | true | Wraps the highlight from the last command to the first. |
| CommandInput placeholder / end | string / ReactNode | "Search commands" | Placeholder, also used as the accessible name, and content at the end of the field such as an Esc hint. |
| CommandList children | (itemOrGroup) => ReactNode | — | Renders each matching item, or each group when items are grouped. |
| CommandGroup heading / items | ReactNode / Item[] | — | A titled section; pass a function child to render each of its matching items. Empty groups are left out. |
| CommandItem value / onSelect / destructive / disabled | Item / (event) => void / boolean / boolean | — | One command. onSelect runs on click or Enter; inside CommandDialog the dialog then closes unless the event is prevented. |
| CommandShortcut / CommandItemMeta | ComponentProps<"span"> | — | Key caps at the end of a row (one cap per array entry) and secondary text after the label. |
| CommandEmpty children | ReactNode | (query) => ReactNode | — | Shown only when nothing matches. Defaults to a message naming the query. |
| CommandLoading loading / label | boolean / ReactNode | true / "Searching" | A row with the agent searching mark while slower results arrive, announced politely. |
| CommandDialog open / defaultOpen / onOpenChange | boolean / boolean / (open) => void | — | Dialog state. |
| CommandDialog shortcut | string | null | "k" | Key that toggles the palette with Cmd or Ctrl. null registers none. |
| CommandDialog trigger / title | ReactNode / string | - / "Command palette" | A CommandDialogTrigger to render inside the root, and the dialog's accessible name. |
Accessibility
- The field is a combobox (role="combobox") with aria-controls pointing at the listbox and aria-activedescendant on the highlighted option, so focus stays in the field while the arrow keys move.
- The first match is always highlighted, so Enter runs it; Up, Down, Home, and End move the highlight and wrap at the ends.
- Group headings label their groups; the empty message and the loading row are polite live regions.
- CommandDialog opens with Cmd+K or Ctrl+K, traps focus with the field focused, and closes on Escape, a click outside, or after a command runs, returning focus to where it was.
- Opening with the shortcut and closing from the keyboard appear instantly; pointer opens use the dialog entrance, and reduced motion removes all transitions.
- The field uses a 16px font on small screens so iOS does not zoom when it is focused.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/ui/command.tsxcommand- Also installs agent-state@0.1.0registry dependency
- npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/command/0.1.0.json.
ui/command.tsxShowHide
ui/command.tsx
"use client";
import { Autocomplete as BaseAutocomplete } from "@base-ui/react/autocomplete";
import { Dialog as BaseDialog } from "@base-ui/react/dialog";
import {
type ComponentProps,
type MouseEvent,
type ReactNode,
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from "react";
import { AgentState } from "../agent/agent-state";
type ClassName<State> = string | ((state: State) => string | undefined) | undefined;
function cx(...classes: (string | false | null | undefined)[]) {
return classes.filter(Boolean).join(" ");
}
/** Prepends base classes while keeping Base UI's state-function form of className working. */
function withBase<State>(base: string, className: ClassName<State>) {
return typeof className === "function" ? (state: State) => cx(base, className(state)) : cx(base, className);
}
/** The shape the default filter understands. Any extra fields ride along to your render function. */
export interface CommandItemData {
/** Stable id for the command. */
value: string;
/** Text shown and matched. */
label: string;
/** Extra words that should also find this command, such as synonyms. */
keywords?: readonly string[];
}
/** A titled group of commands. Pass an array of these to `items` for a grouped list. */
export interface CommandGroupData<Item = CommandItemData> {
/** Heading shown above the group. */
label: string;
items: readonly Item[];
}
/**
* Matches when every word of the query appears in the label or keywords, ignoring case and
* accents, so "dep prod" finds "Deploy to production".
*/
export function defaultCommandFilter(item: unknown, query: string, itemToString?: (item: unknown) => string) {
const words = normalize(query).split(/\s+/).filter(Boolean);
if (words.length === 0) return true;
const record = (item ?? {}) as Partial<CommandItemData>;
const haystack = normalize(
[itemToString ? itemToString(item) : (record.label ?? String(item)), ...(record.keywords ?? [])].join(" "),
);
return words.every((word) => haystack.includes(word));
}
function normalize(text: string) {
return text.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
}
interface DialogBridge {
close: (instant: boolean) => void;
}
const DialogBridgeContext = createContext<DialogBridge | null>(null);
export interface CommandProps<Item = CommandItemData>
extends Omit<ComponentProps<"div">, "children" | "defaultValue" | "onChange"> {
/** The commands: a flat array, or an array of `{ label, items }` groups. */
items: readonly Item[] | readonly CommandGroupData<Item>[];
/** Replaces the default word-by-word filter. Pass `null` to filter outside, for example on a server. */
filter?: ((item: Item, query: string, itemToString?: (item: Item) => string) => boolean) | null;
/** The query. Pass with `onValueChange` to control it. */
value?: string;
/** The initial query when uncontrolled. */
defaultValue?: string;
/** Called on every keystroke with the new query. */
onValueChange?: (value: string) => void;
/** Wrap arrow-key movement from the last command to the first. */
loopFocus?: boolean;
children?: ReactNode;
}
/**
* The palette itself: a search field over a list of commands that filters as you type. The first
* match is always highlighted, so Enter runs it; arrow keys, Home, and End move the highlight.
* Use it inline (for example in a sidebar) or inside CommandDialog.
*/
export function Command<Item = CommandItemData>({
items,
filter = defaultCommandFilter as NonNullable<CommandProps<Item>["filter"]>,
value,
defaultValue,
onValueChange,
loopFocus = true,
className,
children,
...props
}: CommandProps<Item>) {
return (
<BaseAutocomplete.Root
open
inline
items={items as readonly Item[]}
filter={filter as never}
autoHighlight="always"
keepHighlight
loopFocus={loopFocus}
{...(value !== undefined ? { value } : null)}
defaultValue={defaultValue}
onValueChange={(next) => onValueChange?.(next)}
>
<div
data-slot="command"
className={cx(
"flex min-h-0 w-full flex-col overflow-hidden text-zinc-950 dark:text-white",
"rounded-xl border border-zinc-950/10 bg-white shadow-[0_1px_2px_rgb(0_0_0/0.04)] dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
// Inside CommandDialog the dialog draws the surface.
"in-data-[slot=command-dialog]:rounded-none in-data-[slot=command-dialog]:border-0 in-data-[slot=command-dialog]:bg-transparent in-data-[slot=command-dialog]:shadow-none",
className,
)}
{...props}
>
{children}
</div>
</BaseAutocomplete.Root>
);
}
export interface CommandInputProps extends Omit<BaseAutocomplete.Input.Props, "size"> {
/** Content at the end of the field, such as a CommandShortcut hint. */
end?: ReactNode;
}
/** The search field. Typing filters the list; the field keeps focus while the arrow keys move the highlight. */
export function CommandInput({ className, end, placeholder = "Search commands", ...props }: CommandInputProps) {
return (
<div className="flex h-12 shrink-0 items-center gap-2.5 border-b border-zinc-950/[0.07] px-4 dark:border-white/[0.08]">
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="size-4 shrink-0 text-zinc-500">
<circle cx="7.25" cy="7.25" r="4.5" stroke="currentColor" strokeWidth="1.5" />
<path d="m10.75 10.75 2.75 2.75" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
<BaseAutocomplete.Input
placeholder={placeholder}
aria-label={props["aria-label"] ?? placeholder}
className={withBase(
cx(
// 16px on touch screens so iOS does not zoom into the field.
"h-full min-w-0 flex-1 bg-transparent text-base text-zinc-950 outline-none placeholder:text-zinc-400 sm:text-sm",
"dark:text-white dark:placeholder:text-zinc-500",
"[&::-webkit-search-cancel-button]:hidden",
),
className,
)}
{...props}
/>
{end}
</div>
);
}
export interface CommandListProps extends BaseAutocomplete.List.Props {
/** Classes for the scrolling wrapper around the list. */
viewportClassName?: string;
}
/**
* The scrolling list of results. Pass a function child to render each item (or each group when
* `items` is grouped); it receives only the items that match the query.
*/
export function CommandList({ className, viewportClassName, ...props }: CommandListProps) {
return (
<div
className={cx(
"max-h-[min(22rem,calc(100dvh-14rem))] min-h-0 flex-1 overflow-y-auto overscroll-contain scroll-py-1.5",
viewportClassName,
)}
>
<BaseAutocomplete.List className={withBase("p-1.5 outline-none data-[empty]:p-0", className)} {...props} />
</div>
);
}
export interface CommandGroupProps extends Omit<BaseAutocomplete.Group.Props, "children"> {
/** Heading shown above the group and used as its accessible name. */
heading?: ReactNode;
/** The group's matching items. With these, pass a function child to render each one. */
items?: readonly unknown[];
children?: ReactNode | ((item: any, index: number) => ReactNode);
}
/** A titled section of results. Groups with no matches are left out. */
export function CommandGroup({ heading, items, className, children, ...props }: CommandGroupProps) {
return (
<BaseAutocomplete.Group items={items} className={withBase("not-first:mt-1.5", className)} {...props}>
{heading ? (
<BaseAutocomplete.GroupLabel className="flex h-7 items-center px-2.5 text-xs font-medium text-zinc-500 select-none">
{heading}
</BaseAutocomplete.GroupLabel>
) : null}
{typeof children === "function" ? <BaseAutocomplete.Collection>{children}</BaseAutocomplete.Collection> : children}
</BaseAutocomplete.Group>
);
}
export interface CommandItemProps extends Omit<BaseAutocomplete.Item.Props, "onSelect"> {
/**
* Runs the command, on click or Enter. Inside CommandDialog the dialog then closes; call
* `event.preventDefault()` to keep it open, for example to show a nested page of commands.
*/
onSelect?: (event: MouseEvent<HTMLDivElement>) => void;
/** Styles the command for actions that delete or cannot be undone. */
destructive?: boolean;
}
/**
* One command. Put an icon first and a CommandShortcut last. The highlight follows the pointer
* and the arrow keys instantly, with no animation, so fast keyboard use never lags.
*/
export function CommandItem({ onSelect, onClick, destructive = false, className, ...props }: CommandItemProps) {
const bridge = useContext(DialogBridgeContext);
return (
<BaseAutocomplete.Item
data-destructive={destructive || undefined}
onClick={(event) => {
onClick?.(event);
onSelect?.(event);
// A click with no pointer behind it (detail 0) came from the keyboard: close without motion.
if (!event.defaultPrevented) bridge?.close(event.detail === 0);
}}
className={withBase(
cx(
"flex min-h-9 cursor-default scroll-my-1.5 items-center gap-3 rounded-lg px-2.5 py-1.5 text-sm outline-none select-none",
"[&_svg]:size-4 [&_svg]:shrink-0",
"data-[disabled]:pointer-events-none data-[disabled]:opacity-45",
destructive
? cx(
"text-red-600 [&_svg]:text-red-600/80 data-[highlighted]:bg-red-500/[0.08] data-[highlighted]:text-red-700",
"dark:text-red-400 dark:[&_svg]:text-red-400/80 dark:data-[highlighted]:bg-red-500/[0.12] dark:data-[highlighted]:text-red-300",
)
: cx(
"text-zinc-700 [&_svg]:text-zinc-500 data-[highlighted]:bg-zinc-950/[0.05] data-[highlighted]:text-zinc-950 data-[highlighted]:[&_svg]:text-zinc-950",
"dark:text-zinc-300 dark:[&_svg]:text-zinc-500 dark:data-[highlighted]:bg-white/[0.08] dark:data-[highlighted]:text-white dark:data-[highlighted]:[&_svg]:text-white",
),
),
className,
)}
{...props}
/>
);
}
/** Secondary text after the label, such as where a command lives. Pushes shortcuts to the end. */
export function CommandItemMeta({ className, ...props }: ComponentProps<"span">) {
return <span className={cx("min-w-0 truncate text-xs text-zinc-500", className)} {...props} />;
}
/** Keyboard keys shown at the end of an item or the field. Pass one key per child for separate caps. */
export function CommandShortcut({ className, children, ...props }: ComponentProps<"span">) {
const keys = Array.isArray(children) ? children : [children];
return (
<span className={cx("ml-auto flex shrink-0 items-center gap-1 pl-3", className)} {...props}>
{keys.map((key, index) => (
<kbd
key={index}
className={cx(
"inline-flex h-5 min-w-5 items-center justify-center rounded-md border border-zinc-950/10 px-1 font-sans text-[11px] leading-none font-medium text-zinc-500",
"dark:border-white/15 dark:text-zinc-400",
)}
>
{key}
</kbd>
))}
</span>
);
}
/** A divider between groups of results. */
export function CommandSeparator({ className, ...props }: BaseAutocomplete.Separator.Props) {
return (
<BaseAutocomplete.Separator
className={withBase("-mx-1.5 my-1.5 h-px bg-zinc-950/[0.07] dark:bg-white/[0.08]", className)}
{...props}
/>
);
}
export interface CommandEmptyProps extends Omit<BaseAutocomplete.Empty.Props, "children"> {
/** Replaces the message. Receives the query that found nothing. */
children?: ReactNode | ((query: string) => ReactNode);
}
/** Shown only when nothing matches, and announced to screen readers when it appears. */
export function CommandEmpty({ className, children, ...props }: CommandEmptyProps) {
return (
<BaseAutocomplete.Empty className={withBase("empty:hidden", className)} {...props}>
<div className="grid justify-items-center gap-1 px-6 py-10 text-center text-sm">
<BaseAutocomplete.Value>
{(query) =>
typeof children === "function" ? (
children(query)
) : (
children ?? (
<>
<span className="font-medium text-zinc-950 dark:text-white">No commands match “{query}”</span>
<span className="text-zinc-500">Try fewer words, or search by what the command does.</span>
</>
)
)
}
</BaseAutocomplete.Value>
</div>
</BaseAutocomplete.Empty>
);
}
export interface CommandLoadingProps extends Omit<BaseAutocomplete.Status.Props, "children"> {
/** Whether results are still arriving. The row disappears when false. */
loading?: boolean;
/** What is being searched, as a verb phrase. */
label?: ReactNode;
}
/**
* A quiet row for results that arrive later, such as a server search or an agent looking
* something up. Uses the shared agent mark and is announced politely to screen readers.
*/
export function CommandLoading({ loading = true, label = "Searching", className, ...props }: CommandLoadingProps) {
return (
<BaseAutocomplete.Status className={withBase("empty:hidden", className)} {...props}>
{loading ? (
<div className="flex h-9 items-center px-2.5">
<AgentState activity="searching" label={label} variant="plain" size="sm" />
</div>
) : null}
</BaseAutocomplete.Status>
);
}
/** A strip under the list for key hints or a status line. */
export function CommandFooter({ className, ...props }: ComponentProps<"div">) {
return (
<div
className={cx(
"flex h-10 shrink-0 items-center gap-4 border-t border-zinc-950/[0.07] px-4 text-xs text-zinc-500 dark:border-white/[0.08]",
"[&_kbd]:inline-flex [&_kbd]:h-5 [&_kbd]:min-w-5 [&_kbd]:items-center [&_kbd]:justify-center [&_kbd]:rounded-md [&_kbd]:border [&_kbd]:border-zinc-950/10 [&_kbd]:px-1 [&_kbd]:font-sans [&_kbd]:text-[11px] [&_kbd]:font-medium",
"dark:[&_kbd]:border-white/15 dark:[&_kbd]:text-zinc-400",
className,
)}
{...props}
/>
);
}
export interface CommandDialogProps extends Omit<BaseDialog.Root.Props, "children" | "onOpenChange"> {
/** Called whenever the dialog opens or closes, from the shortcut, a trigger, Escape, or a command. */
onOpenChange?: (open: boolean) => void;
/**
* Key that toggles the dialog together with Cmd on macOS or Ctrl elsewhere. Defaults to "k".
* Pass `null` to register no shortcut.
*/
shortcut?: string | null;
/** Rendered inside the dialog root, so a CommandDialogTrigger placed here opens the palette. */
trigger?: ReactNode;
/** Accessible name of the dialog. Not shown. */
title?: string;
/** Element to portal into. Defaults to `document.body`. */
container?: BaseDialog.Portal.Props["container"];
/** Classes for the panel. */
className?: string;
/** A Command. It is mounted fresh on every open, so the query starts empty. */
children?: ReactNode;
}
/**
* A modal palette near the top of the screen. Opens with Cmd+K or Ctrl+K and closes after a
* command runs. Opening with the shortcut and closing from the keyboard skip the animation, since
* a keyboard user wants the palette now; pointer opens get the 220ms dialog entrance.
*/
export function CommandDialog({
shortcut = "k",
trigger,
title = "Command palette",
open: openProp,
defaultOpen = false,
onOpenChange,
container,
className,
children,
...props
}: CommandDialogProps) {
const [uncontrolled, setUncontrolled] = useState(defaultOpen);
const open = openProp ?? uncontrolled;
const [instant, setInstant] = useState(false);
const setOpen = useCallback(
(next: boolean, fromKeyboard: boolean) => {
setInstant(fromKeyboard);
if (openProp === undefined) setUncontrolled(next);
onOpenChange?.(next);
},
[onOpenChange, openProp],
);
useEffect(() => {
if (!shortcut) return;
function onKeyDown(event: KeyboardEvent) {
if (event.defaultPrevented || event.repeat) return;
if (event.key.toLowerCase() !== shortcut?.toLowerCase() || !(event.metaKey || event.ctrlKey) || event.altKey) return;
event.preventDefault();
setOpen(!open, true);
}
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [shortcut, open, setOpen]);
const bridge = useMemo<DialogBridge>(() => ({ close: (fromKeyboard) => setOpen(false, fromKeyboard) }), [setOpen]);
return (
<BaseDialog.Root
open={open}
onOpenChange={(next, details) => setOpen(next, details.reason === "escape-key")}
{...props}
>
{trigger}
<BaseDialog.Portal container={container}>
<BaseDialog.Backdrop
data-instant={instant || undefined}
className={cx(
"fixed inset-0 z-50 bg-black/40 dark:bg-black/70",
"transition-opacity duration-220 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
"data-[starting-style]:opacity-0 data-[ending-style]:opacity-0 data-[ending-style]:duration-150 data-[instant]:transition-none",
)}
/>
<BaseDialog.Viewport className="fixed inset-0 z-50 flex items-start justify-center px-4 pt-[min(14dvh,8rem)] pb-4">
<BaseDialog.Popup
data-slot="command-dialog"
data-instant={instant || undefined}
aria-label={title}
className={cx(
"flex max-h-full w-full max-w-xl flex-col overflow-hidden outline-none",
"rounded-2xl border border-zinc-950/10 bg-white shadow-[0_24px_64px_-16px_rgb(0_0_0/0.28),0_2px_6px_rgb(0_0_0/0.04)]",
"dark:border-white/15 dark:bg-black dark:shadow-[0_24px_64px_-12px_rgb(0_0_0/1),inset_0_1px_0_rgb(255_255_255/0.08)]",
// Pointer opens: 220ms quint ease-out from 96% and 8px low; exits 150ms. Keyboard: instant.
"transition-[opacity,scale,translate] duration-220 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none data-[instant]:transition-none",
"data-[starting-style]:opacity-0 motion-safe:data-[starting-style]:translate-y-2 motion-safe:data-[starting-style]:scale-96",
"data-[ending-style]:opacity-0 data-[ending-style]:duration-150 motion-safe:data-[ending-style]:translate-y-1 motion-safe:data-[ending-style]:scale-98",
className,
)}
>
<DialogBridgeContext.Provider value={bridge}>{children}</DialogBridgeContext.Provider>
</BaseDialog.Popup>
</BaseDialog.Viewport>
</BaseDialog.Portal>
</BaseDialog.Root>
);
}
/** A button that opens the palette. Pass it to CommandDialog's `trigger`. Unstyled; pass `className` or `render`. */
export const CommandDialogTrigger = BaseDialog.Trigger;