# Command

A searchable list of actions, on the page or in a dialog.

```tsx
import { Fragment } from "react"
import * as stylex from "@stylexjs/stylex"
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator,
  CommandShortcut,
} from "@/components/ui/command"
import { radius, width } from "@/theme/tokens.stylex"
import { BellIcon } from "@phosphor-icons/react/dist/csr/Bell"
import { FilePlusIcon } from "@phosphor-icons/react/dist/csr/FilePlus"
import { GearIcon } from "@phosphor-icons/react/dist/csr/Gear"
import { MagnifyingGlassIcon } from "@phosphor-icons/react/dist/csr/MagnifyingGlass"
import { MoonIcon } from "@phosphor-icons/react/dist/csr/Moon"
import { UsersIcon } from "@phosphor-icons/react/dist/csr/Users"
import type { Icon as PhosphorIcon } from "@phosphor-icons/react"

type Action = {
  value: string
  label: string
  icon: PhosphorIcon
  shortcut?: string
  disabled?: boolean
}
type Group = { value: string; items: Action[] }

const groups: Group[] = [
  {
    value: "Suggestions",
    items: [
      { value: "new-document", label: "New Document", icon: FilePlusIcon },
      { value: "search-files", label: "Search Files", icon: MagnifyingGlassIcon },
      { value: "toggle-theme", label: "Toggle Theme", icon: MoonIcon, disabled: true },
    ],
  },
  {
    value: "Settings",
    items: [
      { value: "members", label: "Members", icon: UsersIcon, shortcut: "⌘M" },
      { value: "notifications", label: "Notifications", icon: BellIcon, shortcut: "⇧⌘N" },
      { value: "preferences", label: "Preferences", icon: GearIcon, shortcut: "⌘," },
    ],
  },
]

const styles = stylex.create({
  command: { maxWidth: width.sm, borderRadius: radius.lg, borderWidth: 1, borderStyle: "solid" },
})

export default function CommandDemo() {
  return (
    <Command items={groups} xstyle={styles.command}>
      <CommandInput placeholder="Type a command or search..." aria-label="Search commands" />
      <CommandEmpty>No results found.</CommandEmpty>
      <CommandList>
        {(group: Group, index: number) => (
          <Fragment key={group.value}>
            {index > 0 && <CommandSeparator />}
            <CommandGroup heading={group.value} items={group.items}>
              {(item: Action) => (
                <CommandItem key={item.value} value={item} disabled={item.disabled}>
                  <item.icon />
                  <span>{item.label}</span>
                  {item.shortcut && <CommandShortcut>{item.shortcut}</CommandShortcut>}
                </CommandItem>
              )}
            </CommandGroup>
          </Fragment>
        )}
      </CommandList>
    </Command>
  )
}
```

## About

`Command` is Base UI's `Autocomplete` rendered inline, not the `cmdk` package
that shadcn's Command is built on. The list is always open, the input filters
it, and an item runs its `onClick` when clicked or when Enter is pressed while
it is highlighted. The trade-off is the data shape. Options go through `items`
and render from a function child, the way a `Combobox` does.

## Installation

**Command**

```bash
npx shadcn@latest add @arene/command
```

Needs the [arene setup](https://www.arene.style/docs/installation) first. Also adds [Button](https://www.arene.style/docs/components/button), [Dialog](https://www.arene.style/docs/components/dialog), [Input](https://www.arene.style/docs/components/input) and [Input Group](https://www.arene.style/docs/components/input-group).

**Manual**

1. Install the packages it imports:

   ```bash
   npm install @base-ui/react @stylexjs/stylex clsx @phosphor-icons/react
   ```

2. Set up the token layer and the StyleX compiler, if you have not already. See
   [Installation](https://www.arene.style/docs/installation), and paste `states.ts` and `state-styles.ts`
   from the same page. `states.ts` holds the dimmed item style, and an item reads
   its highlight and disabled state through `state-styles.ts`. The list needs `interop.css`
   for its hidden scrollbar and for the icons it does not render.

3. Add [Input](https://www.arene.style/docs/components/input), [Input Group](https://www.arene.style/docs/components/input-group)
   and [Dialog](https://www.arene.style/docs/components/dialog). The search field is an `InputGroup`, and
   `CommandDialog` is a `Dialog`.

4. Paste this source into the file named in its title.

   ```tsx title="components/ui/command.tsx"
   "use client"

   import { useEffect, useState } from "react"
   import type { ComponentProps, CSSProperties, ReactNode } from "react"
   import { useRender } from "@base-ui/react/use-render"
   import { Autocomplete as AutocompletePrimitive } from "@base-ui/react/autocomplete"
   import * as stylex from "@stylexjs/stylex"
   import type { StyleXStyles } from "@stylexjs/stylex"
   import { clsx } from "clsx"
   import { MagnifyingGlassIcon } from "@phosphor-icons/react/dist/csr/MagnifyingGlass"

   import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog"
   import { Input } from "@/components/ui/input"
   import { InputGroup, InputGroupAddon } from "@/components/ui/input-group"
   import { stateStyles } from "@/lib/state-styles"
   import { breakpoints } from "@/theme/breakpoints.stylex"
   import { states } from "@/theme/states"
   import {
     color,
     leading,
     radius,
     shadow,
     space,
     text,
     tracking,
     width,
   } from "@/theme/tokens.stylex"

   const panelRadius = `calc(var(--arene-command-radius, ${radius.xl}) - ${space.s1})`

   const styles = stylex.create({
     root: {
       display: "flex",
       width: "100%",
       height: "100%",
       flexDirection: "column",
       overflow: "hidden",
       "--arene-command-radius": radius.xl,
       borderRadius: "var(--arene-command-radius)",
       padding: space.s1,
       backgroundColor: color.tray,
       color: color.popoverForeground,
     },
     inputWrapper: {
       paddingInline: space.s1,
     },
     inputFrame: {
       minHeight: space.s10,
       borderColor: color.transparent,
       backgroundColor: color.transparent,
       boxShadow: "none",
     },
     list: {
       flexGrow: 1,
       minHeight: 0,
       maxHeight: "var(--arene-command-list-height, 18rem)",
       overflowX: "hidden",
       overflowY: "auto",
       overscrollBehavior: "contain",
       borderRadius: panelRadius,
       backgroundColor: { default: color.popover, ":empty": color.transparent },
       boxShadow: { default: shadow.raised, ":empty": "none" },
       scrollPaddingTop: space.s1,
       scrollPaddingBottom: space.s1,
       outlineStyle: "none",
     },
     empty: {
       paddingBlock: { default: space.s8, ":empty": 0 },
       textAlign: "center",
       fontSize: text.sm,
       lineHeight: leading.sm,
       color: color.mutedForeground,
     },
     group: { overflow: "hidden", padding: space.s1, color: color.foreground },
     heading: {
       paddingInline: space.s2,
       paddingBlockStart: space.s2,
       paddingBlockEnd: space.s1,
       fontSize: text.xs,
       lineHeight: leading.xs,
       fontWeight: 500,
       color: color.mutedForeground,
     },
     separator: {
       height: 1,
       backgroundColor: color.border,
     },
     item: {
       position: "relative",
       display: "flex",
       alignItems: "center",
       gap: space.s2,
       cursor: "default",
       userSelect: "none",
       borderRadius: `max(0px, calc(var(--arene-command-radius, ${radius.xl}) - 2 * ${space.s1}))`,
       paddingInline: space.s2,
       paddingBlock: space.s1_5,
       fontSize: text.sm,
       lineHeight: leading.sm,
       outlineStyle: "none",
       "--arene-icon-size": space.s4,
     },
     shortcut: {
       marginInlineStart: "auto",
       fontSize: text.xs,
       lineHeight: leading.xs,
       letterSpacing: tracking.widest,
       color: color.mutedForeground,
     },
     footer: {
       display: "flex",
       alignItems: "center",
       gap: space.s4,
       paddingInline: space.s2,
       paddingBlockStart: space.s2,
       paddingBlockEnd: space.s1,
       fontSize: text.xs,
       lineHeight: leading.xs,
       color: color.mutedForeground,
     },
     dialogContent: {
       overflow: "hidden",
       maxWidth: { default: "none", [breakpoints.md]: width.sm },
       height: { default: null, [breakpoints.maxMd]: "var(--arene-visual-viewport-height, 100dvh)" },
       insetBlockStart: {
         default: null,
         [breakpoints.maxMd]: "var(--arene-visual-viewport-top, 0px)",
       },
       padding: 0,
       borderRadius: { default: 0, [breakpoints.md]: radius.xl },
       boxShadow: { default: "none", [breakpoints.md]: shadow.popupLifted },
       "--arene-command-list-height": { default: null, [breakpoints.maxMd]: "none" },
     },
     dialogViewport: {
       alignItems: "start",
       padding: { default: 0, [breakpoints.md]: space.s4 },
       paddingBlockStart: { default: 0, [breakpoints.md]: "33vh" },
     },
   })

   const commandStyles = {
     root: styles.root,
     list: styles.list,
     empty: styles.empty,
     group: styles.group,
     heading: styles.heading,
     separator: styles.separator,
     item: styles.item,
     itemHighlighted: states.itemHighlight,
     itemDisabled: states.disabled,
     shortcut: styles.shortcut,
     footer: styles.footer,
   }

   type Overrides = { xstyle?: StyleXStyles; className?: string }

   type StateOverrides = Overrides & { style?: CSSProperties }

   type CommandProps<Item> = Omit<
     AutocompletePrimitive.Root.Props<Item>,
     | "inline"
     | "open"
     | "defaultOpen"
     | "onOpenChange"
     | "onOpenChangeComplete"
     | "openOnInputClick"
     | "modal"
     | "items"
   > &
     Overrides & {
       render?: useRender.ComponentProps<"div">["render"]
       items: NonNullable<AutocompletePrimitive.Root.Props<Item>["items"]>
     }

   function Command<Item>({
     render,
     xstyle,
     className,
     children,
     items,
     autoHighlight = "always",
     keepHighlight = true,
     ...props
   }: CommandProps<Item>) {
     const sx = stylex.props(styles.root, xstyle)

     return useRender({
       defaultTagName: "div",
       render,
       props: {
         "data-slot": "command",
         ...sx,
         className: clsx(sx.className, className),
         children: (
           <AutocompletePrimitive.Root
             inline
             open
             autoHighlight={autoHighlight}
             keepHighlight={keepHighlight}
             {...props}
             items={items as readonly Item[]}
           >
             {children}
           </AutocompletePrimitive.Root>
         ),
       },
     })
   }

   type CommandDialogProps = Omit<ComponentProps<typeof Dialog>, "children"> &
     Overrides & {
       title?: string
       description?: string
       showCloseButton?: boolean
       children: ReactNode
     }

   type VisualViewportBox = { height: number; top: number }

   function useVisualViewport(active: boolean) {
     const [box, setBox] = useState<VisualViewportBox>()

     useEffect(() => {
       const viewport = window.visualViewport
       if (!active || !viewport) return
       const update = () => setBox({ height: viewport.height, top: viewport.offsetTop })
       update()
       viewport.addEventListener("resize", update)
       viewport.addEventListener("scroll", update)
       return () => {
         viewport.removeEventListener("resize", update)
         viewport.removeEventListener("scroll", update)
         setBox(undefined)
       }
     }, [active])

     return box
   }

   function CommandDialog({
     title = "Command Palette",
     description = "Search for a command to run...",
     children,
     xstyle,
     className,
     showCloseButton = false,
     open,
     defaultOpen = false,
     onOpenChange,
     ...props
   }: CommandDialogProps) {
     const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen)
     const box = useVisualViewport(open ?? uncontrolledOpen)

     const viewportStyle:
       | (CSSProperties & {
           "--arene-visual-viewport-height": string
           "--arene-visual-viewport-top": string
         })
       | undefined = box
       ? {
           "--arene-visual-viewport-height": `${box.height}px`,
           "--arene-visual-viewport-top": `${box.top}px`,
         }
       : undefined

     return (
       <Dialog
         open={open}
         defaultOpen={defaultOpen}
         onOpenChange={(next, details) => {
           setUncontrolledOpen(next)
           onOpenChange?.(next, details)
         }}
         {...props}
       >
         <DialogContent
           xstyle={[styles.dialogContent, states.instant, xstyle]}
           className={className}
           style={viewportStyle}
           showCloseButton={showCloseButton}
           overlayProps={{ xstyle: states.instant }}
           viewportProps={{ xstyle: styles.dialogViewport }}
         >
           <DialogTitle xstyle={states.srOnly}>{title}</DialogTitle>
           <DialogDescription xstyle={states.srOnly}>{description}</DialogDescription>
           {children}
         </DialogContent>
       </Dialog>
     )
   }

   type CommandInputProps = Omit<AutocompletePrimitive.Input.Props, "className" | "children"> &
     Overrides & { children?: ReactNode }

   function CommandInput({ xstyle, className, children, ...props }: CommandInputProps) {
     return (
       <div data-slot="command-input-wrapper" {...stylex.props(styles.inputWrapper)}>
         <InputGroup xstyle={[styles.inputFrame, xstyle]} className={className}>
           <AutocompletePrimitive.Input render={<Input />} {...props} />
           <InputGroupAddon>
             <MagnifyingGlassIcon aria-hidden="true" />
           </InputGroupAddon>
           {children}
         </InputGroup>
       </div>
     )
   }

   type CommandListProps = Omit<AutocompletePrimitive.List.Props, "className"> & Overrides

   function CommandList({ xstyle, className, ...props }: CommandListProps) {
     const sx = stylex.props(styles.list, xstyle)
     return (
       <AutocompletePrimitive.List
         data-slot="command-list"
         {...sx}
         {...props}
         className={clsx("no-scrollbar", sx.className, className)}
       />
     )
   }

   type CommandEmptyProps = Omit<AutocompletePrimitive.Empty.Props, "className"> & Overrides

   function CommandEmpty({ xstyle, className, ...props }: CommandEmptyProps) {
     const sx = stylex.props(styles.empty, xstyle)
     return (
       <AutocompletePrimitive.Empty
         data-slot="command-empty"
         {...sx}
         {...props}
         className={clsx(sx.className, className)}
       />
     )
   }

   type CommandGroupProps<Item> = Omit<
     AutocompletePrimitive.Group.Props,
     "className" | "children" | "items"
   > &
     Overrides & {
       heading?: ReactNode
       items?: readonly Item[]
       children?: ReactNode | ((item: Item, index: number) => ReactNode)
     }

   function CommandGroup<Item>({
     heading,
     items,
     xstyle,
     className,
     children,
     ...props
   }: CommandGroupProps<Item>) {
     const sx = stylex.props(styles.group, xstyle)
     return (
       <AutocompletePrimitive.Group
         data-slot="command-group"
         items={items}
         {...sx}
         {...props}
         className={clsx(sx.className, className)}
       >
         {heading != null && (
           <AutocompletePrimitive.GroupLabel
             data-slot="command-group-heading"
             {...stylex.props(styles.heading)}
           >
             {heading}
           </AutocompletePrimitive.GroupLabel>
         )}
         {typeof children === "function" ? (
           <AutocompletePrimitive.Collection>{children}</AutocompletePrimitive.Collection>
         ) : (
           children
         )}
       </AutocompletePrimitive.Group>
     )
   }

   type CommandSeparatorProps = Omit<AutocompletePrimitive.Separator.Props, "className"> & Overrides

   function CommandSeparator({ xstyle, className, ...props }: CommandSeparatorProps) {
     const sx = stylex.props(styles.separator, xstyle)
     return (
       <AutocompletePrimitive.Separator
         data-slot="command-separator"
         {...sx}
         {...props}
         className={clsx(sx.className, className)}
       />
     )
   }

   type CommandItemProps = Omit<AutocompletePrimitive.Item.Props, "className" | "style"> &
     StateOverrides

   function CommandItem({ xstyle, style, className, ...props }: CommandItemProps) {
     return (
       <AutocompletePrimitive.Item
         data-slot="command-item"
         {...props}
         {...stateStyles(
           (state) => [
             styles.item,
             state.highlighted && states.itemHighlight,
             state.disabled && states.disabled,
             xstyle,
           ],
           { className, style, hook: "arene-icons" },
         )}
       />
     )
   }

   function CommandShortcut({
     render,
     ref,
     style,
     xstyle,
     className,
     ...props
   }: useRender.ComponentProps<"span"> & Overrides) {
     const sx = stylex.props(styles.shortcut, xstyle)
     return useRender({
       defaultTagName: "span",
       render,
       ref,
       props: {
         "data-slot": "command-shortcut",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
   }

   function CommandFooter({
     render,
     ref,
     style,
     xstyle,
     className,
     ...props
   }: useRender.ComponentProps<"div"> & Overrides) {
     const sx = stylex.props(styles.footer, xstyle)
     return useRender({
       defaultTagName: "div",
       render,
       ref,
       props: {
         "data-slot": "command-footer",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
   }

   export {
     Command,
     CommandDialog,
     CommandEmpty,
     CommandFooter,
     CommandGroup,
     CommandInput,
     CommandItem,
     CommandList,
     CommandSeparator,
     CommandShortcut,
     commandStyles,
   }
   ```

5. Change the `@/` imports if your project uses different aliases.

## Usage

```tsx
import {
  Command,
  CommandDialog,
  CommandEmpty,
  CommandFooter,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator,
  CommandShortcut,
} from "@/components/ui/command"
```

```tsx
const actions = [
  { value: "new-document", label: "New Document" },
  { value: "search-files", label: "Search Files" },
  { value: "toggle-theme", label: "Toggle Theme" },
]

export function Example() {
  return (
    <Command items={actions}>
      <CommandInput placeholder="Type a command or search..." aria-label="Search commands" />
      <CommandEmpty>No results found.</CommandEmpty>
      <CommandList>
        <CommandGroup heading="Suggestions" items={actions}>
          {(item: (typeof actions)[number]) => (
            <CommandItem key={item.value} value={item} onClick={() => run(item)}>
              {item.label}
            </CommandItem>
          )}
        </CommandGroup>
      </CommandList>
    </Command>
  )
}
```

Items shaped `{ value, label }` filter on `label`. For any other shape, pass
`itemToStringValue` to `Command`.

## Composition

```text
Command
├── CommandInput
├── CommandEmpty
└── CommandList
    ├── CommandGroup
    │   └── CommandItem
    ├── CommandSeparator
    └── CommandGroup
        └── CommandItem
└── CommandFooter
```

`CommandEmpty` sits before `CommandList`, not inside it. The list is a
listbox, and a status message is not one of its options.

`Command` is a tray, and `CommandList` is the raised panel inside it. The
input and `CommandFooter` sit on the tray. When nothing matches, the list
drops its panel and the empty message shows on the tray.

## Groups

Pass groups shaped `{ value, items }` to `items`. `CommandList` takes a
function child that receives each group; render a `CommandGroup` with the
group's `items` and a function child that receives each item.

```tsx
"use client"

import { Fragment, useState } from "react"
import { Button } from "@/components/ui/button"
import {
  Command,
  CommandDialog,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator,
  CommandShortcut,
} from "@/components/ui/command"
import { BellIcon } from "@phosphor-icons/react/dist/csr/Bell"
import { FilePlusIcon } from "@phosphor-icons/react/dist/csr/FilePlus"
import { GearIcon } from "@phosphor-icons/react/dist/csr/Gear"
import { MagnifyingGlassIcon } from "@phosphor-icons/react/dist/csr/MagnifyingGlass"
import { MoonIcon } from "@phosphor-icons/react/dist/csr/Moon"
import { UsersIcon } from "@phosphor-icons/react/dist/csr/Users"
import type { Icon as PhosphorIcon } from "@phosphor-icons/react"

type Action = { value: string; label: string; icon: PhosphorIcon; shortcut?: string }
type Group = { value: string; items: Action[] }

const groups: Group[] = [
  {
    value: "Suggestions",
    items: [
      { value: "new-document", label: "New Document", icon: FilePlusIcon },
      { value: "search-files", label: "Search Files", icon: MagnifyingGlassIcon },
      { value: "toggle-theme", label: "Toggle Theme", icon: MoonIcon },
    ],
  },
  {
    value: "Settings",
    items: [
      { value: "members", label: "Members", icon: UsersIcon, shortcut: "⌘M" },
      { value: "notifications", label: "Notifications", icon: BellIcon, shortcut: "⇧⌘N" },
      { value: "preferences", label: "Preferences", icon: GearIcon, shortcut: "⌘," },
    ],
  },
]

export default function CommandGroups() {
  const [open, setOpen] = useState(false)

  return (
    <>
      <Button variant="outline" onClick={() => setOpen(true)}>
        Open palette
      </Button>
      <CommandDialog open={open} onOpenChange={setOpen}>
        <Command items={groups}>
          <CommandInput placeholder="Type a command or search..." aria-label="Search commands" />
          <CommandEmpty>No results found.</CommandEmpty>
          <CommandList>
            {(group: Group, index: number) => (
              <Fragment key={group.value}>
                {index > 0 && <CommandSeparator />}
                <CommandGroup heading={group.value} items={group.items}>
                  {(item: Action) => (
                    <CommandItem key={item.value} value={item} onClick={() => setOpen(false)}>
                      <item.icon />
                      <span>{item.label}</span>
                      {item.shortcut && <CommandShortcut>{item.shortcut}</CommandShortcut>}
                    </CommandItem>
                  )}
                </CommandGroup>
              </Fragment>
            )}
          </CommandList>
        </Command>
      </CommandDialog>
    </>
  )
}
```

Filtering drops a group with no match left, so put the `CommandSeparator`
before every group but the first rather than between groups.

## Basic

Put the `Command` inside a `CommandDialog` and control it with `open` and
`onOpenChange`. Close it from an item's `onClick`.

```tsx
"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import {
  Command,
  CommandDialog,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command"

type Action = { value: string; label: string }

const suggestions: Action[] = [
  { value: "new-document", label: "New Document" },
  { value: "search-files", label: "Search Files" },
  { value: "toggle-theme", label: "Toggle Theme" },
]

export default function CommandBasic() {
  const [open, setOpen] = useState(false)

  return (
    <>
      <Button variant="outline" onClick={() => setOpen(true)}>
        Open palette
      </Button>
      <CommandDialog open={open} onOpenChange={setOpen}>
        <Command items={suggestions}>
          <CommandInput placeholder="Type a command or search..." aria-label="Search commands" />
          <CommandEmpty>No results found.</CommandEmpty>
          <CommandList>
            <CommandGroup heading="Suggestions" items={suggestions}>
              {(item: Action) => (
                <CommandItem key={item.value} value={item} onClick={() => setOpen(false)}>
                  {item.label}
                </CommandItem>
              )}
            </CommandGroup>
          </CommandList>
        </Command>
      </CommandDialog>
    </>
  )
}
```

## Dialog

Toggle the dialog from a keyboard shortcut. Nothing in the component binds one.

```tsx
"use client"

import { Fragment, useEffect, useState } from "react"
import {
  Command,
  CommandDialog,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator,
  CommandShortcut,
} from "@/components/ui/command"
import { Kbd, KbdGroup } from "@/components/ui/kbd"
import { BellIcon } from "@phosphor-icons/react/dist/csr/Bell"
import { FilePlusIcon } from "@phosphor-icons/react/dist/csr/FilePlus"
import { GearIcon } from "@phosphor-icons/react/dist/csr/Gear"
import { MagnifyingGlassIcon } from "@phosphor-icons/react/dist/csr/MagnifyingGlass"
import { MoonIcon } from "@phosphor-icons/react/dist/csr/Moon"
import { UsersIcon } from "@phosphor-icons/react/dist/csr/Users"
import type { Icon as PhosphorIcon } from "@phosphor-icons/react"
import { Text } from "@/components/ui/text"

type Action = { value: string; label: string; icon: PhosphorIcon; shortcut?: string }
type Group = { value: string; items: Action[] }

const groups: Group[] = [
  {
    value: "Suggestions",
    items: [
      { value: "new-document", label: "New Document", icon: FilePlusIcon },
      { value: "search-files", label: "Search Files", icon: MagnifyingGlassIcon },
      { value: "toggle-theme", label: "Toggle Theme", icon: MoonIcon },
    ],
  },
  {
    value: "Settings",
    items: [
      { value: "members", label: "Members", icon: UsersIcon, shortcut: "⌘M" },
      { value: "notifications", label: "Notifications", icon: BellIcon, shortcut: "⇧⌘N" },
      { value: "preferences", label: "Preferences", icon: GearIcon, shortcut: "⌘," },
    ],
  },
]

export default function CommandDialogDemo() {
  const [open, setOpen] = useState(false)

  useEffect(() => {
    const down = (event: KeyboardEvent) => {
      if (event.key === "j" && (event.metaKey || event.ctrlKey)) {
        event.preventDefault()
        setOpen((open) => !open)
      }
    }

    document.addEventListener("keydown", down)
    return () => document.removeEventListener("keydown", down)
  }, [])

  return (
    <>
      <Text render={<p />} size="sm" tone="muted">
        Press{" "}
        <KbdGroup>
          <Kbd>⌘</Kbd>
          <Kbd>J</Kbd>
        </KbdGroup>
      </Text>
      <CommandDialog open={open} onOpenChange={setOpen}>
        <Command items={groups}>
          <CommandInput placeholder="Type a command or search..." aria-label="Search commands" />
          <CommandEmpty>No results found.</CommandEmpty>
          <CommandList>
            {(group: Group, index: number) => (
              <Fragment key={group.value}>
                {index > 0 && <CommandSeparator />}
                <CommandGroup heading={group.value} items={group.items}>
                  {(item: Action) => (
                    <CommandItem key={item.value} value={item} onClick={() => setOpen(false)}>
                      <item.icon />
                      <span>{item.label}</span>
                      {item.shortcut && <CommandShortcut>{item.shortcut}</CommandShortcut>}
                    </CommandItem>
                  )}
                </CommandGroup>
              </Fragment>
            )}
          </CommandList>
        </Command>
      </CommandDialog>
    </>
  )
}
```

## Shortcuts

Use `CommandShortcut` to show a key combination at the trailing edge of an
item. It displays the key only.

```tsx
"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import {
  Command,
  CommandDialog,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandShortcut,
} from "@/components/ui/command"
import { BellIcon } from "@phosphor-icons/react/dist/csr/Bell"
import { GearIcon } from "@phosphor-icons/react/dist/csr/Gear"
import { UsersIcon } from "@phosphor-icons/react/dist/csr/Users"
import type { Icon as PhosphorIcon } from "@phosphor-icons/react"

type Action = { value: string; label: string; icon: PhosphorIcon; shortcut: string }

const settings: Action[] = [
  { value: "members", label: "Members", icon: UsersIcon, shortcut: "⌘M" },
  { value: "notifications", label: "Notifications", icon: BellIcon, shortcut: "⇧⌘N" },
  { value: "preferences", label: "Preferences", icon: GearIcon, shortcut: "⌘," },
]

export default function CommandShortcuts() {
  const [open, setOpen] = useState(false)

  return (
    <>
      <Button variant="outline" onClick={() => setOpen(true)}>
        Open palette
      </Button>
      <CommandDialog open={open} onOpenChange={setOpen}>
        <Command items={settings}>
          <CommandInput placeholder="Type a command or search..." aria-label="Search commands" />
          <CommandEmpty>No results found.</CommandEmpty>
          <CommandList>
            <CommandGroup heading="Settings" items={settings}>
              {(item: Action) => (
                <CommandItem key={item.value} value={item} onClick={() => setOpen(false)}>
                  <item.icon />
                  <span>{item.label}</span>
                  <CommandShortcut>{item.shortcut}</CommandShortcut>
                </CommandItem>
              )}
            </CommandGroup>
          </CommandList>
        </Command>
      </CommandDialog>
    </>
  )
}
```

## Scrollable

The list stops at `18rem` and scrolls. The highlighted item scrolls into view.

```tsx
"use client"

import { Fragment, useState } from "react"
import { Button } from "@/components/ui/button"
import {
  Command,
  CommandDialog,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator,
  CommandShortcut,
} from "@/components/ui/command"
import { ArchiveIcon } from "@phosphor-icons/react/dist/csr/Archive"
import { BellIcon } from "@phosphor-icons/react/dist/csr/Bell"
import { CalendarBlankIcon } from "@phosphor-icons/react/dist/csr/CalendarBlank"
import { ChartBarIcon } from "@phosphor-icons/react/dist/csr/ChartBar"
import { ClockIcon } from "@phosphor-icons/react/dist/csr/Clock"
import { CodeIcon } from "@phosphor-icons/react/dist/csr/Code"
import { CopyIcon } from "@phosphor-icons/react/dist/csr/Copy"
import { FilePlusIcon } from "@phosphor-icons/react/dist/csr/FilePlus"
import { FolderPlusIcon } from "@phosphor-icons/react/dist/csr/FolderPlus"
import { GearIcon } from "@phosphor-icons/react/dist/csr/Gear"
import { ImageIcon } from "@phosphor-icons/react/dist/csr/Image"
import { MathOperationsIcon } from "@phosphor-icons/react/dist/csr/MathOperations"
import { MinusIcon } from "@phosphor-icons/react/dist/csr/Minus"
import { QuestionIcon } from "@phosphor-icons/react/dist/csr/Question"
import { StarIcon } from "@phosphor-icons/react/dist/csr/Star"
import { TableIcon } from "@phosphor-icons/react/dist/csr/Table"
import { TextBIcon } from "@phosphor-icons/react/dist/csr/TextB"
import { TextHIcon } from "@phosphor-icons/react/dist/csr/TextH"
import { TextItalicIcon } from "@phosphor-icons/react/dist/csr/TextItalic"
import { TrashIcon } from "@phosphor-icons/react/dist/csr/Trash"
import { UploadSimpleIcon } from "@phosphor-icons/react/dist/csr/UploadSimple"
import { UsersIcon } from "@phosphor-icons/react/dist/csr/Users"
import { UsersThreeIcon } from "@phosphor-icons/react/dist/csr/UsersThree"
import type { Icon as PhosphorIcon } from "@phosphor-icons/react"

type Action = { value: string; label: string; icon: PhosphorIcon; shortcut?: string }
type Group = { value: string; items: Action[] }

const groups: Group[] = [
  {
    value: "Go to",
    items: [
      { value: "recent", label: "Recent", icon: ClockIcon, shortcut: "⌘1" },
      { value: "starred", label: "Starred", icon: StarIcon, shortcut: "⌘2" },
      { value: "shared", label: "Shared with Me", icon: UsersIcon, shortcut: "⌘3" },
      { value: "archive", label: "Archive", icon: ArchiveIcon, shortcut: "⌘4" },
    ],
  },
  {
    value: "Create",
    items: [
      { value: "new-document", label: "New Document", icon: FilePlusIcon, shortcut: "⌘N" },
      { value: "new-folder", label: "New Folder", icon: FolderPlusIcon, shortcut: "⇧⌘N" },
      { value: "new-table", label: "New Table", icon: TableIcon },
      { value: "upload", label: "Upload File", icon: UploadSimpleIcon, shortcut: "⌘U" },
      { value: "duplicate", label: "Duplicate", icon: CopyIcon, shortcut: "⌘D" },
      { value: "delete", label: "Delete", icon: TrashIcon, shortcut: "⌫" },
    ],
  },
  {
    value: "Format",
    items: [
      { value: "bold", label: "Bold", icon: TextBIcon, shortcut: "⌘B" },
      { value: "italic", label: "Italic", icon: TextItalicIcon, shortcut: "⌘I" },
      { value: "heading", label: "Heading", icon: TextHIcon, shortcut: "⌥⌘1" },
      { value: "code-block", label: "Code Block", icon: CodeIcon, shortcut: "⌥⌘C" },
    ],
  },
  {
    value: "Workspace",
    items: [
      { value: "members", label: "Members", icon: UsersThreeIcon },
      { value: "notifications", label: "Notifications", icon: BellIcon },
      { value: "preferences", label: "Preferences", icon: GearIcon, shortcut: "⌘," },
      { value: "usage", label: "Usage", icon: ChartBarIcon },
      { value: "help", label: "Help", icon: QuestionIcon },
    ],
  },
  {
    value: "Insert",
    items: [
      { value: "image", label: "Image", icon: ImageIcon },
      { value: "date", label: "Date", icon: CalendarBlankIcon },
      { value: "equation", label: "Equation", icon: MathOperationsIcon },
      { value: "divider", label: "Divider", icon: MinusIcon },
    ],
  },
]

export default function CommandScrollable() {
  const [open, setOpen] = useState(false)

  return (
    <>
      <Button variant="outline" onClick={() => setOpen(true)}>
        Open palette
      </Button>
      <CommandDialog open={open} onOpenChange={setOpen}>
        <Command items={groups}>
          <CommandInput placeholder="Type a command or search..." aria-label="Search commands" />
          <CommandEmpty>No results found.</CommandEmpty>
          <CommandList>
            {(group: Group, index: number) => (
              <Fragment key={group.value}>
                {index > 0 && <CommandSeparator />}
                <CommandGroup heading={group.value} items={group.items}>
                  {(item: Action) => (
                    <CommandItem key={item.value} value={item} onClick={() => setOpen(false)}>
                      <item.icon />
                      <span>{item.label}</span>
                      {item.shortcut && <CommandShortcut>{item.shortcut}</CommandShortcut>}
                    </CommandItem>
                  )}
                </CommandGroup>
              </Fragment>
            )}
          </CommandList>
        </Command>
      </CommandDialog>
    </>
  )
}
```

## API reference

Pass `render` to replace a part's element or compose it with another component.

Every part wraps the Base UI `Autocomplete` part of the same name and accepts
its props. See the [Base UI reference](https://base-ui.com/react/components/autocomplete)
for the full list. Each styled part also takes `xstyle` and `className`.
`CommandItem` also takes `style`, which is real inline CSS merged over the style
its Base UI state resolves to.

### Command

| Prop                | Type                                  | Default    |
| ------------------- | ------------------------------------- | ---------- |
| `items`             | `readonly Item[] \| readonly Group[]` | —          |
| `autoHighlight`     | `boolean \| "always"`                 | `"always"` |
| `keepHighlight`     | `boolean`                             | `true`     |
| `itemToStringValue` | `(item: Item) => string`              | —          |
| `filter`            | `(item, query, toString) => boolean`  | —          |
| `value`             | `string`                              | —          |
| `onValueChange`     | `(value: string, details) => void`    | —          |

`value` is the input's text. `inline` and `open` are set and cannot be
changed.

### CommandDialog

| Prop              | Type                               | Default                            |
| ----------------- | ---------------------------------- | ---------------------------------- |
| `open`            | `boolean`                          | —                                  |
| `onOpenChange`    | `(open: boolean, details) => void` | —                                  |
| `title`           | `string`                           | `"Command Palette"`                |
| `description`     | `string`                           | `"Search for a command to run..."` |
| `showCloseButton` | `boolean`                          | `false`                            |

`title` and `description` are read to screen readers and not shown. From `md`
up, the popup sits a third of the way down the viewport and stays put as the
list changes height. Below `md` it fills the screen and the list takes the
height above the on-screen keyboard. A full-screen panel has no outside to tap,
so give it a way out, such as a Cancel button in `CommandInput`.

### CommandInput

| Prop       | Type        | Default |
| ---------- | ----------- | ------- |
| `children` | `ReactNode` | —       |

`children` render inside the field after the search icon. Pass an
`InputGroupAddon` with `align="inline-end"` to put a button at the field's end:

```tsx
<CommandInput placeholder="Search…">
  <InputGroupAddon align="inline-end">
    <DialogClose render={<InputGroupButton size="sm" />}>Cancel</DialogClose>
  </InputGroupAddon>
</CommandInput>
```

### CommandGroup

| Prop       | Type                                                    | Default |
| ---------- | ------------------------------------------------------- | ------- |
| `heading`  | `ReactNode`                                             | —       |
| `items`    | `readonly Item[]`                                       | —       |
| `children` | `ReactNode \| (item: Item, index: number) => ReactNode` | —       |

### CommandItem

| Prop       | Type              | Default |
| ---------- | ----------------- | ------- |
| `value`    | `Item`            | —       |
| `onClick`  | `(event) => void` | —       |
| `disabled` | `boolean`         | `false` |

### commandStyles

The style maps behind the component. Spread them onto any element.

| Key               | What it is                          |
| ----------------- | ----------------------------------- |
| `root`            | The tray: surface, radius, padding  |
| `list`            | The raised, scrolling results panel |
| `empty`           | The empty message                   |
| `group`           | A group's padding                   |
| `heading`         | A group heading                     |
| `separator`       | The hairline between groups         |
| `item`            | An item's row and type              |
| `itemHighlighted` | The highlight fill and inset ring   |
| `itemDisabled`    | The dimmed, inert item              |
| `shortcut`        | `CommandShortcut`                   |
| `footer`          | `CommandFooter`, a row on the tray  |

`itemDisabled` is `disabled` from `states` in `theme/states.ts`, the same dim
every other control uses. `root` keeps its own fill. The tray is inline, so it
takes no popup ring or shadow.

### Data attributes

| Attribute                           | On         | Effect                            |
| ----------------------------------- | ---------- | --------------------------------- |
| `data-slot="command"`               | the panel  | Targets the panel from a parent   |
| `data-slot="input-group"`           | the field  | The frame `CommandInput` renders  |
| `data-slot="command-list"`          | the list   | Targets the list from a parent    |
| `data-slot="command-group"`         | a group    | Targets a group from a parent     |
| `data-slot="command-group-heading"` | a heading  | Targets a heading from a parent   |
| `data-slot="command-item"`          | an item    | Targets items from a parent       |
| `data-slot="command-footer"`        | the footer | Targets the footer from a parent  |
| `data-highlighted`, `data-disabled` | an item    | Base UI writes them               |
| `data-slot="dialog-content"`        | the dialog | Targets the animated dialog panel |
