Command
A command palette: a search field over a list that filters as you type, with arrow keys, Enter and a dialog version for ⌘K.
import { InkIcon } from "@/components/ui/ink-icons";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut } from "@/components/ui/command";
export default function CommandDemo() {
return (
<Command framed seed="command-demo" className="w-full max-w-sm bg-popover">
<CommandInput placeholder="Type a command or search…" />
<CommandList>
<CommandEmpty>No results found.</CommandEmpty>
<CommandGroup heading="Suggestions">
<CommandItem>
<InkIcon name="calendar" /> Calendar
</CommandItem>
<CommandItem>
<InkIcon name="smile" /> Search emoji
</CommandItem>
<CommandItem disabled>
<InkIcon name="percent" /> Calculator
</CommandItem>
</CommandGroup>
<CommandSeparator />
<CommandGroup heading="Settings">
<CommandItem>
<InkIcon name="user" /> Profile <CommandShortcut>⌘P</CommandShortcut>
</CommandItem>
<CommandItem>
<InkIcon name="credit-card" /> Billing <CommandShortcut>⌘B</CommandShortcut>
</CommandItem>
<CommandItem>
<InkIcon name="settings" /> Settings <CommandShortcut>⌘S</CommandShortcut>
</CommandItem>
</CommandGroup>
</CommandList>
</Command>
);
}Installation
pnpm dlx shadcn@latest add @ballpoint/ command"use client";
import {
Children,
createContext,
isValidElement,
useCallback,
useContext,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
type ComponentProps,
type KeyboardEvent,
type ReactNode,
} from "react";
import { cn } from "@/lib/utils";
import { usePen, type Pen } from "@/hooks/use-ink-box";
import { inkWash } from "@/lib/ink";
import { InkOutline } from "@/lib/ink-outline";
import { InkIcon } from "@/components/ui/ink-icons";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Separator } from "@/components/ui/separator";
// A command palette in the cmdk mould, without the library: a search field
// above a list that filters as you type, arrow keys to move, Enter to run.
// The list is a listbox and the field a combobox that names the active item
// with aria-activedescendant, so focus never leaves the field.
/** How well `search` matches an item, 0 (hidden) to 1: text that starts with it first, then contains it, then has its letters in order. */
export function commandScore(value: string, search: string, keywords: string[] = []) {
const needle = search.trim().toLowerCase();
if (!needle) return 1;
const hay = [value, ...keywords].join(" ").toLowerCase();
const at = hay.indexOf(needle);
if (at === 0) return 1;
if (at > 0) return 0.9 - Math.min(at, 40) / 100;
let i = 0;
for (const ch of hay) if (ch === needle[i]) i++;
return i === needle.length ? 0.1 : 0;
}
type Filter = (value: string, search: string, keywords?: string[]) => number;
type CommandContextValue = {
search: string;
setSearch: (search: string) => void;
/** Makes an item the active one. */
activate: (item: HTMLElement | undefined) => void;
shouldFilter: boolean;
filter: Filter;
listId: string;
count: number | null;
register: (id: string) => () => void;
};
const CommandContext = createContext<CommandContextValue | null>(null);
function useCommand() {
const context = useContext(CommandContext);
if (!context) throw new Error("Command parts must be used inside <Command>.");
return context;
}
const itemSelector = "[data-slot=command-item]:not([aria-disabled=true])";
/**
* The palette. Items that don't match the search are left out; the first that
* does is active. `shouldFilter={false}` leaves filtering to you (a search
* that asks a server, say).
*/
function Command({
className,
children,
filter = commandScore,
shouldFilter = true,
loop = false,
framed = false,
seed,
roughness,
passes,
radius,
corners,
draw,
weight,
speed,
onKeyDown,
style,
...props
}: ComponentProps<"div"> &
Pick<Pen, "roughness" | "passes" | "radius" | "corners" | "draw" | "weight" | "speed"> & {
filter?: Filter;
shouldFilter?: boolean;
loop?: boolean;
/** Pencil a box round the palette, for one set on the page rather than in a dialog. */
framed?: boolean;
seed?: string | number;
}) {
const pen = usePen({ roughness, passes, radius, corners, draw, weight, speed });
const root = useRef<HTMLDivElement>(null);
const listId = useId();
const [search, setSearch] = useState("");
const [count, setCount] = useState<number | null>(null);
const ids = useRef(new Set<string>());
const register = useCallback((id: string) => {
ids.current.add(id);
setCount(ids.current.size);
return () => {
ids.current.delete(id);
setCount(ids.current.size);
};
}, []);
const items = useCallback(() => Array.from(root.current?.querySelectorAll<HTMLElement>(itemSelector) ?? []), []);
// Which item is active lives on the items themselves (data-selected), and
// on the field (aria-activedescendant): it is the DOM's to know, since the
// DOM is where the order of the items is.
const activate = useCallback((item: HTMLElement | undefined) => {
for (const el of root.current?.querySelectorAll<HTMLElement>("[data-slot=command-item][data-selected=true]") ?? []) {
el.removeAttribute("data-selected");
el.setAttribute("aria-selected", "false");
}
item?.setAttribute("data-selected", "true");
item?.setAttribute("aria-selected", "true");
const field = root.current?.querySelector<HTMLElement>("[data-slot=command-input]");
if (item) field?.setAttribute("aria-activedescendant", item.id);
else field?.removeAttribute("aria-activedescendant");
}, []);
// Searching starts again at the first item that matches; otherwise something
// stays active, the first item when the active one has gone.
const searched = useRef<string | null>(null);
useLayoutEffect(() => {
const all = items();
if (searched.current !== search || !all.some((el) => el.dataset.selected === "true")) {
searched.current = search;
activate(all[0]);
}
if (count === null) setCount(ids.current.size);
}, [search, count, items, activate]);
const current = () => items().findIndex((el) => el.dataset.selected === "true");
const move = (to: number) => {
const all = items();
if (!all.length) return;
const target = all[loop ? (to + all.length) % all.length : Math.min(all.length - 1, Math.max(0, to))];
activate(target);
target.scrollIntoView({ block: "nearest" });
};
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
onKeyDown?.(event);
if (event.defaultPrevented) return;
const at = current();
if (event.key === "ArrowDown") {
event.preventDefault();
move(event.metaKey ? items().length - 1 : at + 1);
} else if (event.key === "ArrowUp") {
event.preventDefault();
move(event.metaKey ? 0 : at - 1);
} else if (event.key === "Home") {
event.preventDefault();
move(0);
} else if (event.key === "End") {
event.preventDefault();
move(items().length - 1);
} else if (event.key === "Enter" && !event.nativeEvent.isComposing) {
event.preventDefault();
items()[at]?.click();
}
};
const value = useMemo(() => ({ search, setSearch, activate, shouldFilter, filter, listId, count, register }), [search, activate, shouldFilter, filter, listId, count, register]);
return (
<CommandContext value={value}>
<div
ref={root}
data-slot="command"
className={cn("flex h-full w-full flex-col text-base text-popover-foreground", framed ? "relative isolate" : "overflow-hidden", className)}
style={{ ...inkWash, ...style }}
onKeyDown={handleKeyDown}
{...props}
>
{framed && <InkOutline pen={pen} seed={seed} estimate={[384, 300]} maxRadius={14} className="-z-10 text-ink-line" />}
{children}
</div>
</CommandContext>
);
}
/** The palette in a dialog: open it from a shortcut such as ⌘K. */
function CommandDialog({
title = "Command palette",
description = "Search for a command to run.",
children,
className,
...props
}: Omit<ComponentProps<typeof Dialog>, "children"> & { title?: string; description?: string; className?: string; children?: ReactNode }) {
return (
<Dialog {...props}>
<DialogContent showCloseButton={false} className={cn("gap-0 overflow-hidden p-0", className)}>
<DialogHeader className="sr-only">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<Command className="[&_[data-slot=command-input-wrapper]]:h-12">{children}</Command>
</DialogContent>
</Dialog>
);
}
/** The search field, ruled off from the list with a pen line. */
function CommandInput({ className, onChange, ...props }: Omit<ComponentProps<"input">, "value" | "type">) {
const { search, setSearch, listId } = useCommand();
return (
<div data-slot="command-input-wrapper" className="relative flex h-11 shrink-0 items-center gap-2 px-3">
<InkIcon name="search" className="size-4 shrink-0 text-ink-3" />
<input
data-slot="command-input"
role="combobox"
aria-expanded="true"
aria-controls={listId}
aria-autocomplete="list"
autoComplete="off"
autoCorrect="off"
spellCheck={false}
value={search}
onChange={(event) => {
setSearch(event.target.value);
onChange?.(event);
}}
className={cn("h-full w-full bg-transparent text-base outline-none placeholder:text-ink-3 disabled:cursor-not-allowed disabled:opacity-50", className)}
{...props}
/>
<Separator className="absolute inset-x-3 bottom-0" />
</div>
);
}
function CommandList({ className, ...props }: ComponentProps<"div">) {
const { listId } = useCommand();
return <div id={listId} role="listbox" data-slot="command-list" className={cn("max-h-72 scroll-py-1.5 overflow-x-hidden overflow-y-auto overscroll-contain p-1.5", className)} {...props} />;
}
/** Shown when nothing matches. */
function CommandEmpty({ className, ...props }: ComponentProps<"div">) {
const { count } = useCommand();
if (count !== 0) return null;
return <div data-slot="command-empty" role="presentation" className={cn("py-6 text-center text-base text-ink-3", className)} {...props} />;
}
/** A heading over a run of items. The group goes when none of its items match. */
function CommandGroup({ className, heading, children, ...props }: Omit<ComponentProps<"div">, "heading"> & { heading?: ReactNode }) {
const headingId = useId();
return (
<div data-slot="command-group" role="group" aria-labelledby={heading ? headingId : undefined} className={cn("hidden overflow-hidden has-[[data-slot=command-item]]:block", className)} {...props}>
{heading && (
<div id={headingId} aria-hidden="true" data-slot="command-group-heading" className="px-2.5 pt-1.5 pb-1 text-sm text-ink-3">
{heading}
</div>
)}
{children}
</div>
);
}
function CommandSeparator({ className, ...props }: ComponentProps<typeof Separator>) {
return <Separator data-slot="command-separator" role="presentation" aria-hidden="true" className={cn("my-1.5", className)} {...props} />;
}
/** The text of some children, for items that don't give a `value`. */
function textOf(node: ReactNode): string {
let text = "";
Children.forEach(node, (child) => {
if (typeof child === "string" || typeof child === "number") text += child;
else if (isValidElement<{ children?: ReactNode }>(child)) text += textOf(child.props.children);
});
return text;
}
/**
* One thing to run. Its `value` (by default its text) and `keywords` are what
* the search looks at; `onSelect` is called when it is chosen by Enter or a click.
*/
function CommandItem({
className,
value: valueProp,
keywords,
onSelect,
disabled,
children,
onClick,
onPointerMove,
...props
}: Omit<ComponentProps<"div">, "onSelect"> & { value?: string; keywords?: string[]; onSelect?: (value: string) => void; disabled?: boolean }) {
const { search, shouldFilter, filter, activate, register } = useCommand();
const id = useId();
const value = (valueProp ?? textOf(children)).trim();
const shown = !shouldFilter || filter(value, search, keywords) > 0;
useLayoutEffect(() => (shown ? register(id) : undefined), [shown, register, id]);
if (!shown) return null;
return (
<div
id={id}
role="option"
data-slot="command-item"
data-value={value}
data-disabled={disabled ? "true" : undefined}
aria-selected="false"
aria-disabled={disabled ? true : undefined}
className={cn(
"relative isolate flex cursor-default items-center gap-2 px-2.5 py-1 text-base outline-none select-none",
"before:pointer-events-none before:absolute before:inset-x-0.5 before:inset-y-0 before:-z-10 before:bg-current before:opacity-0 before:transition-opacity before:duration-(--dur-press)",
"before:[mask-image:var(--ink-wash-1)] before:[mask-size:100%_100%] before:[mask-repeat:no-repeat]",
"data-[selected=true]:before:opacity-13 data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50",
"[&_svg:not(.ink-sketch)]:pointer-events-none [&_svg:not(.ink-sketch)]:shrink-0 [&_svg:not(.ink-sketch):not([class*='size-'])]:size-4",
className,
)}
onPointerMove={(event) => {
onPointerMove?.(event);
if (!disabled && event.currentTarget.dataset.selected !== "true") activate(event.currentTarget);
}}
onClick={(event) => {
onClick?.(event);
if (!disabled) onSelect?.(value);
}}
{...props}
>
{children}
</div>
);
}
function CommandShortcut({ className, ...props }: ComponentProps<"span">) {
return <span data-slot="command-shortcut" className={cn("ml-auto text-sm tracking-wide text-ink-3", className)} {...props} />;
}
export { Command, CommandDialog, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem, CommandShortcut, CommandSeparator };Usage
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command"
<Command>
<CommandInput placeholder="Type a command or search…" />
<CommandList>
<CommandEmpty>No results found.</CommandEmpty>
<CommandGroup heading="Suggestions">
<CommandItem onSelect={() => …}>Calendar</CommandItem>
</CommandGroup>
</CommandList>
</Command>Examples
In a dialog
Open the palette from anywhere with ⌘K.
"use client";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandShortcut } from "@/components/ui/command";
import { InkIcon } from "@/components/ui/ink-icons";
import { Kbd } from "@/components/ui/kbd";
export default function CommandDialogExample() {
const [open, setOpen] = useState(false);
useEffect(() => {
const down = (event: KeyboardEvent) => {
if (event.key === "k" && (event.metaKey || event.ctrlKey)) {
event.preventDefault();
setOpen((o) => !o);
}
};
document.addEventListener("keydown", down);
return () => document.removeEventListener("keydown", down);
}, []);
return (
<>
<Button variant="outline" onClick={() => setOpen(true)} seed="cd-open">
Search <Kbd>⌘K</Kbd>
</Button>
<CommandDialog open={open} onOpenChange={setOpen} className="max-w-lg">
<CommandInput placeholder="Search the notebook…" />
<CommandList>
<CommandEmpty>Nothing found.</CommandEmpty>
<CommandGroup heading="Pages">
<CommandItem onSelect={() => setOpen(false)}>
<InkIcon name="file-text" /> Letter to Ada
</CommandItem>
<CommandItem onSelect={() => setOpen(false)}>
<InkIcon name="map" /> Route home
</CommandItem>
<CommandItem onSelect={() => setOpen(false)}>
<InkIcon name="list" /> Shopping list
</CommandItem>
</CommandGroup>
<CommandGroup heading="Actions">
<CommandItem onSelect={() => setOpen(false)}>
<InkIcon name="plus" /> New page <CommandShortcut>⌘N</CommandShortcut>
</CommandItem>
<CommandItem onSelect={() => setOpen(false)}>
<InkIcon name="settings" /> Open settings <CommandShortcut>⌘,</CommandShortcut>
</CommandItem>
</CommandGroup>
</CommandList>
</CommandDialog>
</>
);
}As a picker
Keywords help a search find an item by what it is, not only by its name.
Writing on cream. Try "yellow" or "scrap".
"use client";
import { useState } from "react";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { InkGlyph } from "@/lib/ink-glyphs";
const papers = [
{ value: "cream", label: "Cream", keywords: ["warm", "default"] },
{ value: "legal", label: "Legal pad", keywords: ["yellow", "ruled"] },
{ value: "white", label: "White", keywords: ["plain"] },
{ value: "slip", label: "Torn slip", keywords: ["scrap", "ragged"] },
];
export default function CommandSelect() {
const [paper, setPaper] = useState("cream");
return (
<div className="flex w-full max-w-sm flex-col gap-4">
<Command framed seed="command-select" className="bg-popover">
<CommandInput placeholder="Find a paper…" />
<CommandList>
<CommandEmpty>No paper like that.</CommandEmpty>
<CommandGroup heading="Papers">
{papers.map((p) => (
<CommandItem key={p.value} value={p.label} keywords={p.keywords} onSelect={() => setPaper(p.value)}>
{p.label}
{paper === p.value && <InkGlyph name="check" className="ml-auto" />}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
<p className="text-ink-2" aria-live="polite">
Writing on {papers.find((p) => p.value === paper)?.label.toLowerCase()}. Try "yellow" or "scrap".
</p>
</div>
);
}API reference
- shouldFilterdefault
true booleanSet false to filter the list yourself, e.g. with results from a server.
- filter
(value, search, keywords?) => numberScores an item against the search, 0 to 1; 0 hides it. The default prefers text that starts with the search, then text that contains it.
- loopdefault
false booleanWrap from the last item to the first with the arrow keys.
- frameddefault
false booleanPencils a box round the palette, for one set on the page. In a CommandDialog the dialog is the box.
- CommandItem value / keywords
string / string[]What the search looks at. The value defaults to the item's text.
- CommandItem onSelect
(value: string) => voidCalled when the item is chosen with Enter or a click.
- CommandDialog
Dialog propsThe palette in a dialog; open and onOpenChange work as on Dialog.