Dialog command palettes
Five command palettes that live in a modal layer, the Cmd+K pattern: modal, overlay, center, top and fullscreen. Each renders a trigger button, moves focus into the input on open, and closes on Escape or a backdrop click. Self-contained (no cmdk, no radix, no portal), sized and token-driven.
Installation
The styled layer is free and installs like any other ai2 component.
Run the following command
npx shadcn@latest add @ai2/command-dialogDependencies, the @ai2/tokens theme and the component file are installed together.
Install dependencies
npm install motion lucide-reactCopy the source
components/ui/command-dialog.tsx"use client"
import * as React from "react"
import { AnimatePresence, motion, useReducedMotion } from "motion/react"
import {
Calculator,
Calendar,
CreditCard,
FileText,
Search,
Settings,
Smile,
User,
} from "lucide-react"
import { cn } from "@/lib/utils"
/* Dialog command family: 5 SELF-CONTAINED command palettes, all inside a modal
layer (the Cmd+K feel). NO cmdk, NO radix, NO portal - like dialog-styled it
builds its own fixed backdrop + panel. Each export renders a trigger button;
clicking it opens the palette, focus goes to the input, Escape and a backdrop
click close it, and clicking the panel does not (stopPropagation). The palette
is mounted only while open, so every opening starts with a clean query.
Color comes ONLY from tokens, via alpha color-mix. No transform under reduced
motion. */
export type StyledSize = "sm" | "md" | "lg" | "xl"
const paletteWidth: Record<StyledSize, string> = {
sm: "max-w-sm",
md: "max-w-md",
lg: "max-w-lg",
xl: "max-w-2xl",
}
export interface CommandItem {
label: React.ReactNode
group?: string
icon?: React.ReactNode
onSelect?: () => void
}
interface CommandDialogProps {
className?: string
size?: StyledSize
placeholder?: string
items?: CommandItem[]
trigger?: React.ReactNode
open?: boolean
defaultOpen?: boolean
onOpenChange?: (o: boolean) => void
}
/* The label can be a ReactNode; flatten it to plain text for filtering. */
function nodeText(node: React.ReactNode): string {
if (node === null || node === undefined || typeof node === "boolean") return ""
if (typeof node === "string" || typeof node === "number") return String(node)
if (Array.isArray(node)) return node.map(nodeText).join("")
if (React.isValidElement(node)) {
return nodeText((node.props as { children?: React.ReactNode }).children)
}
return ""
}
/* Varsayilan liste: prop'suz render eder. */
const defaultItems: CommandItem[] = [
{ label: "Calendar", group: "Suggestions", icon: <Calendar /> },
{ label: "Search Emoji", group: "Suggestions", icon: <Smile /> },
{ label: "Calculator", group: "Suggestions", icon: <Calculator /> },
{ label: "Profile", group: "Settings", icon: <User /> },
{ label: "Billing", group: "Settings", icon: <CreditCard /> },
{ label: "Settings", group: "Settings", icon: <Settings /> },
{ label: "New Document", group: "Actions", icon: <FileText /> },
]
/* The shared state + the combobox/listbox ids. Escape does NOT clear the query here:
the event bubbles up to the window and the dialog closes. */
function usePalette(source: CommandItem[]) {
const uid = React.useId()
const [query, setQuery] = React.useState("")
const [active, setActive] = React.useState(0)
const filtered = React.useMemo(() => {
const q = query.trim().toLowerCase()
if (q.length === 0) return source
return source.filter((item) => nodeText(item.label).toLowerCase().includes(q))
}, [query, source])
React.useEffect(() => {
setActive((prev) => (prev >= filtered.length ? 0 : prev))
}, [filtered.length])
const select = React.useCallback(
(index: number) => {
const item = filtered[index]
if (item) item.onSelect?.()
},
[filtered]
)
const onKeyDown = React.useCallback(
(e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "ArrowDown") {
e.preventDefault()
setActive((prev) => (filtered.length === 0 ? 0 : (prev + 1) % filtered.length))
} else if (e.key === "ArrowUp") {
e.preventDefault()
setActive((prev) =>
filtered.length === 0 ? 0 : (prev - 1 + filtered.length) % filtered.length
)
} else if (e.key === "Enter") {
e.preventDefault()
select(active)
}
},
[filtered.length, active, select]
)
const listId = `${uid}-list`
const optionId = React.useCallback((i: number) => `${uid}-option-${i}`, [uid])
return { query, setQuery, active, setActive, filtered, select, onKeyDown, listId, optionId }
}
const inputRowBase = "flex items-center gap-2 border-b border-border px-3"
const inputBase =
"h-11 w-full rounded-md bg-transparent py-3 text-sm text-popover-foreground outline-none placeholder:text-muted-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50"
const optionBase =
"flex cursor-pointer select-none items-center gap-2 rounded-lg px-2.5 py-2 text-sm outline-none transition-colors focus-visible:ring-[3px] focus-visible:ring-ring/50 [&_svg]:size-4 [&_svg]:shrink-0 [&_svg]:text-muted-foreground [&_i]:text-base [&_i]:leading-none [&_i]:text-muted-foreground"
const emptyBase = "py-6 text-center text-sm text-muted-foreground"
const triggerBtn =
"inline-flex h-9 shrink-0 select-none items-center justify-center gap-2 whitespace-nowrap rounded-lg border border-border bg-secondary px-4 text-sm font-medium text-secondary-foreground outline-none transition-colors hover:bg-[color-mix(in_oklab,var(--color-foreground)_6%,transparent)] focus-visible:ring-[3px] focus-visible:ring-ring/50 [&_svg]:size-4 [&_svg]:shrink-0 [&_i]:text-base [&_i]:leading-none"
const backdropBase = "fixed inset-0 z-50 flex p-4"
/* Palette body: focuses the input when it opens. */
function PaletteBody({
items,
placeholder,
listClassName,
}: {
items: CommandItem[]
placeholder: string
listClassName?: string
}) {
const p = usePalette(items)
const reduce = useReducedMotion() ?? false
const inputRef = React.useRef<HTMLInputElement>(null)
React.useEffect(() => {
const id = window.requestAnimationFrame(() => inputRef.current?.focus())
return () => window.cancelAnimationFrame(id)
}, [])
return (
<>
<div className={inputRowBase}>
<Search className="size-4 shrink-0 text-muted-foreground" />
<input
ref={inputRef}
role="combobox"
aria-expanded={true}
aria-controls={p.listId}
aria-autocomplete="list"
aria-activedescendant={p.filtered.length > 0 ? p.optionId(p.active) : undefined}
value={p.query}
placeholder={placeholder}
onChange={(e) => p.setQuery(e.target.value)}
onKeyDown={p.onKeyDown}
className={inputBase}
/>
</div>
<div
id={p.listId}
role="listbox"
aria-label="Command palette"
className={cn("max-h-72 overflow-y-auto p-1.5", listClassName)}
>
{p.filtered.length === 0 ? (
<p className={emptyBase}>No results found.</p>
) : (
p.filtered.map((item, i) => (
<motion.div
key={nodeText(item.label) || String(i)}
id={p.optionId(i)}
role="option"
aria-selected={i === p.active}
tabIndex={-1}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={reduce ? { duration: 0 } : { duration: 0.15, ease: "easeOut" }}
onMouseEnter={() => p.setActive(i)}
onClick={() => p.select(i)}
className={cn(optionBase, i === p.active && "bg-accent text-accent-foreground")}
>
{item.icon}
<span className="flex-1 truncate">{item.label}</span>
</motion.div>
))
)}
</div>
</>
)
}
/* Controlled/uncontrolled acik durum yonetimi. */
function useDialogState(props: CommandDialogProps) {
const { open, defaultOpen, onOpenChange } = props
const isControlled = open !== undefined
const [internal, setInternal] = React.useState(defaultOpen ?? false)
const isOpen = isControlled ? open : internal
const setOpen = React.useCallback(
(next: boolean) => {
if (!isControlled) setInternal(next)
onOpenChange?.(next)
},
[isControlled, onOpenChange]
)
return { isOpen, setOpen }
}
/* Shared shell: trigger plus backdrop plus panel. The variants differ only in the backdrop class, the alignment and the panel motion. */
function CommandDialogShell({
props,
backdropClassName,
alignClassName,
panelClassName,
panelMotion,
fullWidth,
}: {
props: CommandDialogProps
backdropClassName: string
alignClassName: string
panelClassName?: string
panelMotion: {
initial: Record<string, number>
animate: Record<string, number>
exit: Record<string, number>
}
fullWidth?: boolean
}) {
const {
className,
size = "md",
placeholder = "Type a command...",
items = defaultItems,
trigger,
} = props
const { isOpen, setOpen } = useDialogState(props)
const reduce = useReducedMotion() ?? false
React.useEffect(() => {
if (!isOpen) return
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") setOpen(false)
}
window.addEventListener("keydown", onKey)
return () => window.removeEventListener("keydown", onKey)
}, [isOpen, setOpen])
const fade = { initial: { opacity: 0 }, animate: { opacity: 1 }, exit: { opacity: 0 } }
const m = reduce ? fade : panelMotion
return (
<>
<span
data-slot="styled-command-trigger"
className="inline-flex"
onClick={() => setOpen(true)}
>
{trigger ?? (
<button type="button" className={triggerBtn}>
<Search />
Open command palette
</button>
)}
</span>
<AnimatePresence>
{isOpen ? (
<motion.div
className={cn(backdropBase, alignClassName, backdropClassName)}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2, ease: "easeOut" }}
onClick={() => setOpen(false)}
>
<motion.div
data-slot="styled-command"
role="dialog"
aria-modal="true"
aria-label="Command palette"
className={cn(
"flex w-full flex-col overflow-hidden border border-border bg-popover text-popover-foreground shadow-lg outline-none",
fullWidth ? "h-full rounded-none" : "rounded-xl",
!fullWidth && paletteWidth[size],
panelClassName,
className
)}
initial={m.initial}
animate={m.animate}
exit={m.exit}
transition={reduce ? { duration: 0.12 } : { duration: 0.22, ease: "easeOut" }}
onClick={(e) => e.stopPropagation()}
>
<PaletteBody
items={items}
placeholder={placeholder}
listClassName={fullWidth ? "max-h-none flex-1" : undefined}
/>
</motion.div>
</motion.div>
) : null}
</AnimatePresence>
</>
)
}
const scaleIn = {
initial: { opacity: 0, scale: 0.96 },
animate: { opacity: 1, scale: 1 },
exit: { opacity: 0, scale: 0.96 },
}
/* ModalCommand: klasik ortali modal, notr scrim. */
export function ModalCommand(props: CommandDialogProps) {
return (
<CommandDialogShell
props={props}
alignClassName="items-center justify-center"
backdropClassName="bg-[color-mix(in_oklab,var(--color-foreground)_45%,transparent)]"
panelMotion={scaleIn}
/>
)
}
/* OverlayCommand: guclu backdrop-blur ile sayfayi tamamen dagitan katman. */
export function OverlayCommand(props: CommandDialogProps) {
return (
<CommandDialogShell
props={props}
alignClassName="items-center justify-center"
backdropClassName="bg-[color-mix(in_oklab,var(--color-foreground)_30%,transparent)] supports-[backdrop-filter]:backdrop-blur-xl"
panelMotion={scaleIn}
/>
)
}
/* CenterCommand: primary tonlu scrim, ortadan asagi dogru buyuyen panel. */
export function CenterCommand(props: CommandDialogProps) {
return (
<CommandDialogShell
props={props}
alignClassName="items-center justify-center"
backdropClassName="bg-[color-mix(in_oklab,var(--color-primary)_30%,transparent)] supports-[backdrop-filter]:backdrop-blur-sm"
panelClassName="shadow-[0_0_0_1px_color-mix(in_oklab,var(--color-primary)_25%,transparent)]"
panelMotion={{
initial: { opacity: 0, scale: 0.9 },
animate: { opacity: 1, scale: 1 },
exit: { opacity: 0, scale: 0.9 },
}}
/>
)
}
/* TopCommand: the panel sits at the top and slides in downward. */
export function TopCommand(props: CommandDialogProps) {
return (
<CommandDialogShell
props={props}
alignClassName="items-start justify-center pt-[12vh]"
backdropClassName="bg-[color-mix(in_oklab,var(--color-foreground)_40%,transparent)] supports-[backdrop-filter]:backdrop-blur-sm"
panelMotion={{
initial: { opacity: 0, y: -16 },
animate: { opacity: 1, y: 0 },
exit: { opacity: 0, y: -16 },
}}
/>
)
}
/* FullscreenCommand: panel tum ekrani kaplar, kenar yuvarlamasi yok. */
export function FullscreenCommand(props: CommandDialogProps) {
return (
<CommandDialogShell
props={props}
alignClassName="items-stretch justify-stretch p-0"
backdropClassName="bg-[color-mix(in_oklab,var(--color-foreground)_20%,transparent)]"
fullWidth
panelMotion={{
initial: { opacity: 0, scale: 1.02 },
animate: { opacity: 1, scale: 1 },
exit: { opacity: 0, scale: 1.02 },
}}
/>
)
}Manual installs skip the @ai2/tokens theme, so add the token CSS from the theming guide or the tone colors will be missing.
Variations
5 takes on the same idea. Each is its own export, and every one accepts a size prop (sm, md, lg, xl) aligned to the base Button scale.
Modal
A classic centered modal with a neutral scrim.
import { ModalCommand } from "@/components/ui/command-dialog"
<ModalCommand />Overlay
A heavy backdrop blur that diffuses the page.
import { OverlayCommand } from "@/components/ui/command-dialog"
<OverlayCommand />Center
A primary tinted scrim with a scaling panel.
import { CenterCommand } from "@/components/ui/command-dialog"
<CenterCommand />Top
The panel sits near the top and slides down.
import { TopCommand } from "@/components/ui/command-dialog"
<TopCommand />Fullscreen
The palette takes the whole viewport.
import { FullscreenCommand } from "@/components/ui/command-dialog"
<FullscreenCommand />ai2 Dialog command palettes: 5 styled variations on the token system
The ai2 Dialog command palettes are a set of 5 decorative button variations from the styled layer of the @ai2 design system, built around command palettes inside a self-contained modal overlay. They are free and MIT licensed, and every color comes from a semantic token, so they theme with the rest of ai2 in light and dark.
Motion runs on framer-motion: framer-motion animates the backdrop and the panel on open and close. The styled layer is opt-in, so the dependency only lands if you use it; the base components stay lean. Under reduced motion, the transforms are skipped and the panel fades.
What is in the ai2 Dialog command palettes?
5 exports in one file: Modal, Overlay, Center, Top and Fullscreen. Each renders a native button and takes a size prop (sm, md, lg, xl) aligned to the base Button. They are separate from the base Button on purpose: the base keeps its clean variant, tone and size axes, while the styled layer carries the effects.
You own the file. Copy the one category file and you have all 5 variations, with no runtime dependency on ai2 itself.
Why use it
- On-system by construction: Every color resolves to an ai2 semantic token, so the buttons follow your theme in light and dark with no extra work.
- Effect without the sprawl: The decorations live in a dedicated styled file, so the base Button keeps its clean, predictable API.
- Accessible and honest: Each renders a real button element, keeps a visible focus ring, and respects prefers-reduced-motion.
Features
- Token-driven color: No hardcoded hex or oklch; the look recolors with your theme tokens.
- framer-motion: framer-motion animates the backdrop and the panel on open and close.
- Reduced-motion aware: Under prefers-reduced-motion, the transforms are skipped and the panel fades.
- Size aligned to the base: Every variation takes sm, md, lg and xl matching the base Button height scale, so styled and base buttons line up in a row.
Production tips
- Use it for emphasis, not everywhere: Styled buttons draw the eye. Reserve them for the one action you want people to take on a screen, and use the base Button for the rest.
- Keep labels as verbs: The decoration adds weight, so a clear action label keeps the button scannable.
- Pick one variation per surface: The variations share a family; using two different ones in the same view competes for attention.
Works with the rest of ai2
The Dialog command palettes sit alongside the base Button and the rest of the @ai2 registry. They share the same token file, so a styled action next to a base button or a badge stays visually consistent in both modes.