Skip to content

ComponentsActions

SourceSource

Command Palette

A searchable quick switcher of grouped destinations and actions, driven from the keyboard.

A search field over a list of destinations and actions. Its dialog shell is built on Radix Dialog in React and Reka UI Dialog in Vue. The search field and the list are newt/ui’s own.

Use it to give keyboard users one place to jump anywhere or run anything: switch channel, open settings, mention a member. It complements the visible navigation and never replaces it, because nothing on screen says the palette exists. Bind it to a shortcut and offer a button too.

Typing narrows the list to the rows whose label, description or keywords contain the query. The palette filters the rows it is given; for results from a server, pass new groups as the query changes.

Root class newt-command-palette
"use client"

import * as React from "react"

import { Button } from "@/registry/bases/newt/ui/button"
import {
  CommandPalette,
  type CommandGroup,
} from "@/registry/bases/newt/ui/command-palette"

const GROUPS: readonly CommandGroup[] = [
  {
    label: "Channels",
    items: [
      {
        id: "general",
        label: "general",
        prefix: "#",
        description: "Community",
      },
      {
        id: "release-notes",
        label: "release-notes",
        prefix: "#",
        description: "Announcements",
      },
      { id: "help", label: "help", prefix: "#", description: "Support" },
    ],
  },
  {
    label: "Actions",
    items: [
      {
        id: "settings",
        label: "Server settings",
        prefix: "⚙",
        shortcut: "Ctrl ,",
        keywords: ["preferences", "config"],
      },
      { id: "mention", label: "Mention a member", prefix: "@" },
    ],
  },
]

export default function CommandPaletteDemo() {
  const [open, setOpen] = React.useState(false)
  const [last, setLast] = React.useState("Nothing chosen yet")

  return (
    <div className="flex flex-col items-center gap-3">
      <Button variant="secondary" onClick={() => setOpen(true)}>
        Open quick switcher
      </Button>
      <p className="m-0 text-xs text-newt-text-muted" aria-live="polite">
        {last}
      </p>
      <CommandPalette
        label="Quick switcher"
        open={open}
        onOpenChange={setOpen}
        groups={GROUPS}
        onSelect={(item) => setLast(`Went to ${item.label}`)}
      />
    </div>
  )
}
<script setup lang="ts">
import { ref } from "vue"
import { Button } from "~~/registry/bases/newt/ui/button"
import {
  CommandPalette,
  type CommandGroup,
} from "~~/registry/bases/newt/ui/command-palette"

const GROUPS: readonly CommandGroup[] = [
  {
    label: "Channels",
    items: [
      {
        id: "general",
        label: "general",
        prefix: "#",
        description: "Community",
      },
      {
        id: "release-notes",
        label: "release-notes",
        prefix: "#",
        description: "Announcements",
      },
      { id: "help", label: "help", prefix: "#", description: "Support" },
    ],
  },
  {
    label: "Actions",
    items: [
      {
        id: "settings",
        label: "Server settings",
        prefix: "⚙",
        shortcut: "Ctrl ,",
        keywords: ["preferences", "config"],
      },
      { id: "mention", label: "Mention a member", prefix: "@" },
    ],
  },
]

const open = ref(false)
const last = ref("Nothing chosen yet")
</script>

<template>
  <div class="flex flex-col items-center gap-3">
    <Button variant="secondary" @click="open = true">
      Open quick switcher
    </Button>
    <p class="m-0 text-xs text-newt-text-muted" aria-live="polite">
      {{ last }}
    </p>
    <CommandPalette
      v-model:open="open"
      label="Quick switcher"
      :groups="GROUPS"
      @select="last = `Went to ${$event.label}`"
    />
  </div>
</template>

Installation

npx newtui@latest add command-palettenpx shadcn@latest add @newtui/command-palettenpx shadcn-vue@latest add @newtui/command-palettepnpm dlx newtui@latest add command-palettepnpm dlx shadcn@latest add @newtui/command-palettepnpm dlx shadcn-vue@latest add @newtui/command-paletteyarn dlx newtui@latest add command-paletteyarn dlx shadcn@latest add @newtui/command-paletteyarn dlx shadcn-vue@latest add @newtui/command-palettebunx newtui@latest add command-palettebunx shadcn@latest add @newtui/command-palettebunx shadcn-vue@latest add @newtui/command-palettedeno run -A npm:newtui@latest add command-palettedeno run -A npm:shadcn@latest add @newtui/command-palettedeno run -A npm:shadcn-vue@latest add @newtui/command-palettevlx newtui@latest add command-palettevlx shadcn@latest add @newtui/command-palettevlx shadcn-vue@latest add @newtui/command-palettevp dlx newtui@latest add command-palettevp dlx shadcn@latest add @newtui/command-palettevp dlx shadcn-vue@latest add @newtui/command-palettenubx newtui@latest add command-palettenubx shadcn@latest add @newtui/command-palettenubx shadcn-vue@latest add @newtui/command-palettenlx newtui@latest add command-palettenlx shadcn@latest add @newtui/command-palettenlx shadcn-vue@latest add @newtui/command-paletteupx newtui@latest add command-paletteupx shadcn@latest add @newtui/command-paletteupx shadcn-vue@latest add @newtui/command-palette

The shadcn CLI needs the @newtui registry in your components.json. Set it up.

Install the dependencies

npm install radix-uipnpm add radix-uiyarn add radix-uibun add radix-uideno add npm:radix-uivlt install radix-uivp add radix-uinub add radix-uini radix-uiupm add radix-ui
npm install reka-uipnpm add reka-uiyarn add reka-uibun add reka-uideno add npm:reka-uivlt install reka-uivp add reka-uinub add reka-uini reka-uiupm add reka-ui

Copy the source into your project

"use client"

import { Dialog as DialogPrimitive } from "radix-ui"
import * as React from "react"

import { cn } from "@/lib/utils"

/** One row of the palette. */
export interface CommandItem {
  /** Unique across the whole palette; handed back by `onSelect`. */
  id: string
  label: string
  /** The quieter text beside the label. */
  description?: string
  /** A one-character sign before the label, such as `#` or `@`. */
  prefix?: string
  /** A key combination shown at the end of the row. */
  shortcut?: string
  /** Extra words the search should match that the row does not show. */
  keywords?: readonly string[]
}

export interface CommandGroup {
  label: string
  items: readonly CommandItem[]
}

/** The three lines of the footer. */
export interface CommandPaletteHints {
  move: string
  select: string
  close: string
}

export interface CommandPaletteProps extends Omit<
  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>,
  "onSelect" | "children"
> {
  /** Whether the palette is shown. */
  open?: boolean
  /** Called with `false` on Escape, a press of the overlay or a selection. */
  onOpenChange?: (open: boolean) => void
  groups: readonly CommandGroup[]
  /** Called with the chosen row; the palette then closes itself. */
  onSelect?: (item: CommandItem) => void
  /** Accessible name of the dialog. */
  label?: string
  placeholder?: string
  /** Shown when the query matches nothing. */
  emptyText?: string
  /** The footer's wording. Pass `false` to leave the footer out. */
  hints?: CommandPaletteHints | false
  /**
   * The element the overlay and panel are portalled into. Defaults to
   * `document.body`. A palette opened below a `DirectionProvider` or a themed
   * wrapper passes that element, so it keeps the direction and the palette.
   */
  container?: React.ComponentProps<typeof DialogPrimitive.Portal>["container"]
}

const defaultHints: CommandPaletteHints = {
  move: "to move",
  select: "to select",
  close: "to close",
}

const kbdClassName =
  "inline-flex h-5 min-w-5 items-center justify-center rounded-[var(--newt-radius-sm)] border border-newt-border bg-newt-bg-base px-1.5 font-[family-name:var(--newt-font-mono)] text-[11px] font-semibold text-newt-text-secondary"

function matches(item: CommandItem, query: string): boolean {
  if (query === "") return true
  return [item.label, item.description ?? "", ...(item.keywords ?? [])].some(
    (text) => text.toLowerCase().includes(query)
  )
}

/*
 * A search box over a list of places to go and things to do. The shell is a
 * Radix Dialog, which owns the focus trap, Escape and outside press, scroll
 * lock, and hiding the page from screen readers. Focus never leaves the
 * input: the arrow keys move a highlight through the list, and
 * `aria-activedescendant` tells a screen reader which row that is.
 */
const CommandPalette = React.forwardRef<
  React.ComponentRef<typeof DialogPrimitive.Content>,
  CommandPaletteProps
>(
  (
    {
      className,
      open = false,
      onOpenChange,
      groups,
      onSelect,
      label = "Command palette",
      placeholder = "Where would you like to go?",
      emptyText = "Nothing matches that.",
      hints = defaultHints,
      container,
      onOpenAutoFocus,
      onCloseAutoFocus,
      onEscapeKeyDown,
      ...props
    },
    ref
  ) => {
    const id = React.useId()
    const [query, setQuery] = React.useState("")
    const [active, setActive] = React.useState(0)
    const close = React.useCallback(() => onOpenChange?.(false), [onOpenChange])
    /* The element that had focus before the palette opened. */
    const previousFocus = React.useRef<Element | null>(null)

    /* Every opening starts from an empty query. */
    const [wasOpen, setWasOpen] = React.useState(open)
    if (open !== wasOpen) {
      setWasOpen(open)
      if (open) {
        setQuery("")
        setActive(0)
      }
    }

    const needle = query.trim().toLowerCase()
    const shown = groups
      .map((group) => ({
        label: group.label,
        items: group.items.filter((item) => matches(item, needle)),
      }))
      .filter((group) => group.items.length > 0)
    const flat = shown.flatMap((group) => group.items)
    const current = flat[Math.min(active, flat.length - 1)]
    const optionId = (item: CommandItem) => `${id}-${item.id}`

    /*
     * The highlighted row is scrolled into view only when the keyboard moved
     * it. The pointer moves the highlight too, and scrolling then would slide
     * the list under the pointer and make it jitter.
     */
    const scrollToCurrent = React.useRef(false)
    React.useEffect(() => {
      if (!scrollToCurrent.current || current === undefined) return
      scrollToCurrent.current = false
      document
        .getElementById(`${id}-${current.id}`)
        ?.scrollIntoView({ block: "nearest" })
    }, [current, id])

    const choose = (item: CommandItem) => {
      onSelect?.(item)
      close()
    }

    return (
      <DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>
        <DialogPrimitive.Portal container={container}>
          <DialogPrimitive.Overlay className="fixed inset-0 z-[100] bg-newt-overlay" />
          <DialogPrimitive.Content
            ref={ref}
            aria-describedby={undefined}
            className={cn(
              "fixed inset-x-0 top-[15vh] z-[100] mx-auto flex max-h-[70vh] w-[560px] max-w-[92vw] flex-col overflow-hidden rounded-[var(--newt-radius-lg)] border border-newt-border bg-newt-bg-elevated text-newt-text-primary shadow-elevation-high outline-none",
              className
            )}
            onOpenAutoFocus={(event) => {
              // Save it first: the handler can move focus into the palette.
              previousFocus.current = document.activeElement
              onOpenAutoFocus?.(event)
            }}
            onCloseAutoFocus={(event) => {
              onCloseAutoFocus?.(event)
              if (event.defaultPrevented) return
              /*
               * The palette has no trigger for Radix to give focus back to,
               * so it returns to the element that had it.
               */
              event.preventDefault()
              if (previousFocus.current instanceof HTMLElement) {
                previousFocus.current.focus()
              }
            }}
            onEscapeKeyDown={(event) => {
              onEscapeKeyDown?.(event)
              /* While an input method composes, Escape cancels its candidate. */
              if (event.isComposing) event.preventDefault()
            }}
            {...props}
          >
            <DialogPrimitive.Title className="sr-only">
              {label}
            </DialogPrimitive.Title>
            <input
              type="text"
              role="combobox"
              aria-expanded="true"
              aria-controls={`${id}-list`}
              aria-activedescendant={
                current === undefined ? undefined : optionId(current)
              }
              aria-autocomplete="list"
              aria-label={placeholder}
              placeholder={placeholder}
              autoComplete="off"
              spellCheck={false}
              value={query}
              onChange={(event) => {
                setQuery(event.target.value)
                setActive(0)
              }}
              onKeyDown={(event) => {
                /* While an input method composes, Enter confirms a candidate. */
                if (event.nativeEvent.isComposing) return
                if (event.key === "Enter") {
                  event.preventDefault()
                  if (current !== undefined) choose(current)
                } else if (event.key === "ArrowDown" && flat.length > 0) {
                  event.preventDefault()
                  scrollToCurrent.current = true
                  setActive(
                    (flat.indexOf(current ?? flat[0]) + 1) % flat.length
                  )
                } else if (event.key === "ArrowUp" && flat.length > 0) {
                  event.preventDefault()
                  scrollToCurrent.current = true
                  setActive(
                    (flat.indexOf(current ?? flat[0]) - 1 + flat.length) %
                      flat.length
                  )
                }
              }}
              className="mx-3 mt-3 rounded-[var(--newt-radius-sm)] border border-newt-border bg-newt-bg-input px-3.5 py-3 font-[family-name:var(--newt-font-sans)] text-base text-newt-text-primary placeholder:text-newt-text-muted focus:border-newt-brand focus:outline-none"
            />
            <div
              id={`${id}-list`}
              role="listbox"
              aria-label={label}
              className="flex-1 overflow-y-auto px-3 pb-3 pt-2"
            >
              {shown.map((group) => (
                <div key={group.label} role="group" aria-label={group.label}>
                  <div
                    aria-hidden="true"
                    className="px-2 pb-1 pt-2.5 text-xs font-bold uppercase tracking-[0.02em] text-newt-text-muted"
                  >
                    {group.label}
                  </div>
                  {group.items.map((item) => {
                    const selected = item === current
                    return (
                      // oxlint-disable-next-line jsx-a11y/click-events-have-key-events -- options are driven from the input through aria-activedescendant; Enter there selects the highlighted one
                      <div
                        key={item.id}
                        id={optionId(item)}
                        role="option"
                        tabIndex={-1}
                        aria-selected={selected}
                        onClick={() => choose(item)}
                        onPointerMove={() => setActive(flat.indexOf(item))}
                        className={cn(
                          "flex cursor-pointer items-center gap-2 rounded-[var(--newt-radius-sm)] p-2 text-[15px] leading-5",
                          selected
                            ? "bg-newt-bg-active text-newt-text-primary"
                            : "text-newt-text-secondary"
                        )}
                      >
                        <span
                          aria-hidden="true"
                          className="w-5 shrink-0 text-center font-semibold text-newt-text-muted"
                        >
                          {item.prefix}
                        </span>
                        <span className="truncate font-medium">
                          {item.label}
                        </span>
                        {item.description === undefined ? null : (
                          <span className="truncate text-[13px] text-newt-text-muted">
                            {item.description}
                          </span>
                        )}
                        {item.shortcut === undefined ? null : (
                          <kbd className={cn(kbdClassName, "ms-auto shrink-0")}>
                            {item.shortcut}
                          </kbd>
                        )}
                      </div>
                    )
                  })}
                </div>
              ))}
              {flat.length === 0 ? (
                <p className="m-0 px-2 py-6 text-center text-sm text-newt-text-muted">
                  {emptyText}
                </p>
              ) : null}
            </div>
            {hints === false ? null : (
              <footer
                aria-hidden="true"
                className="flex flex-wrap gap-x-4 gap-y-1 border-t border-newt-border bg-newt-bg-surface px-4 py-2.5 text-xs text-newt-text-muted"
              >
                <span className="inline-flex items-center gap-1">
                  <kbd className={kbdClassName}>↑</kbd>
                  <kbd className={kbdClassName}>↓</kbd>
                  {hints.move}
                </span>
                <span className="inline-flex items-center gap-1">
                  <kbd className={kbdClassName}>Enter</kbd>
                  {hints.select}
                </span>
                <span className="inline-flex items-center gap-1">
                  <kbd className={kbdClassName}>Esc</kbd>
                  {hints.close}
                </span>
              </footer>
            )}
          </DialogPrimitive.Content>
        </DialogPrimitive.Portal>
      </DialogPrimitive.Root>
    )
  }
)
CommandPalette.displayName = "CommandPalette"

export { CommandPalette }
<script setup lang="ts">
import {
  DialogContent,
  DialogOverlay,
  DialogPortal,
  DialogRoot,
  DialogTitle,
} from "reka-ui"
import { computed, nextTick, ref, useId, watch, type HTMLAttributes } from "vue"

import { cn } from "@/lib/utils"

import type { CommandGroup, CommandItem, CommandPaletteHints } from "."

defineOptions({ inheritAttrs: false })

/*
 * A search box over a list of places to go and things to do. The shell is a
 * Reka Dialog, which owns the focus trap, Escape and outside press, scroll
 * lock, and hiding the page from screen readers. Focus never leaves the
 * input: the arrow keys move a highlight through the list, and
 * `aria-activedescendant` tells a screen reader which row that is.
 */
const props = withDefaults(
  defineProps<{
    class?: HTMLAttributes["class"]
    /**
     * The element the overlay and panel are portalled into. Defaults to
     * `body`. A palette opened below a `DirectionProvider` or a themed
     * wrapper passes that element, so it keeps the direction and the palette.
     */
    container?: string | HTMLElement
    groups: readonly CommandGroup[]
    /** Accessible name of the dialog. */
    label?: string
    placeholder?: string
    /** Shown when the query matches nothing. */
    emptyText?: string
    /** The footer's wording. Pass `false` to leave the footer out. */
    hints?: CommandPaletteHints | false
  }>(),
  {
    label: "Command palette",
    placeholder: "Where would you like to go?",
    emptyText: "Nothing matches that.",
    hints: () => ({ move: "to move", select: "to select", close: "to close" }),
  }
)

const emit = defineEmits<{
  /** Fired with the chosen row; the palette then closes itself. */
  (e: "select", item: CommandItem): void
}>()

/** Use `v-model:open` to control visibility. */
const open = defineModel<boolean>("open", { default: false })

/* The element that had focus before the palette opened. */
let previousFocus: Element | null = null
const id = useId()
const query = ref("")
const active = ref(0)

const kbdClassName =
  "inline-flex h-5 min-w-5 items-center justify-center rounded-[var(--newt-radius-sm)] border border-newt-border bg-newt-bg-base px-1.5 font-[family-name:var(--newt-font-mono)] text-[11px] font-semibold text-newt-text-secondary"

function matches(item: CommandItem, needle: string): boolean {
  if (needle === "") return true
  return [item.label, item.description ?? "", ...(item.keywords ?? [])].some(
    (text) => text.toLowerCase().includes(needle)
  )
}

const shown = computed(() => {
  const needle = query.value.trim().toLowerCase()
  return props.groups
    .map((group) => ({
      label: group.label,
      items: group.items.filter((item) => matches(item, needle)),
    }))
    .filter((group) => group.items.length > 0)
})
const flat = computed(() => shown.value.flatMap((group) => group.items))
const current = computed(
  () => flat.value[Math.min(active.value, flat.value.length - 1)]
)

function optionId(item: CommandItem): string {
  return `${id}-${item.id}`
}

function close() {
  open.value = false
}

function choose(item: CommandItem) {
  emit("select", item)
  close()
}

/*
 * The highlighted row is scrolled into view only when the keyboard moved it.
 * The pointer moves the highlight too, and scrolling then would slide the
 * list under the pointer and make it jitter.
 */
async function move(direction: 1 | -1) {
  const count = flat.value.length
  if (count === 0) return
  const from =
    current.value === undefined ? 0 : flat.value.indexOf(current.value)
  active.value = (from + direction + count) % count
  await nextTick()
  if (current.value !== undefined) {
    document
      .getElementById(optionId(current.value))
      ?.scrollIntoView({ block: "nearest" })
  }
}

function onKeydown(event: KeyboardEvent) {
  /* While an input method is composing, Enter confirms a candidate. */
  if (event.isComposing) return
  if (event.key === "Enter") {
    event.preventDefault()
    if (current.value !== undefined) choose(current.value)
  } else if (event.key === "ArrowDown") {
    event.preventDefault()
    void move(1)
  } else if (event.key === "ArrowUp") {
    event.preventDefault()
    void move(-1)
  }
}

function onInput() {
  active.value = 0
}

function onOpenAutoFocus() {
  previousFocus = document.activeElement
}

/*
 * The palette has no trigger for Reka to give focus back to, so it returns to
 * the element that had it.
 */
function onCloseAutoFocus(event: Event) {
  if (event.defaultPrevented) return
  event.preventDefault()
  if (previousFocus instanceof HTMLElement) previousFocus.focus()
}

/* While an input method composes, Escape cancels its candidate. */
function onEscapeKeyDown(event: KeyboardEvent) {
  if (event.isComposing) event.preventDefault()
}

/* Every opening starts from an empty query. */
watch(open, (isOpen) => {
  if (!isOpen) return
  query.value = ""
  active.value = 0
})
</script>

<template>
  <DialogRoot v-model:open="open">
    <DialogPortal :to="props.container">
      <DialogOverlay class="fixed inset-0 z-[100] bg-newt-overlay" />
      <DialogContent
        :aria-describedby="undefined"
        v-bind="$attrs"
        :class="
          cn(
            'fixed inset-x-0 top-[15vh] z-[100] mx-auto flex max-h-[70vh] w-[560px] max-w-[92vw] flex-col overflow-hidden rounded-[var(--newt-radius-lg)] border border-newt-border bg-newt-bg-elevated text-newt-text-primary shadow-elevation-high outline-none',
            props.class
          )
        "
        @open-auto-focus="onOpenAutoFocus"
        @close-auto-focus="onCloseAutoFocus"
        @escape-key-down="onEscapeKeyDown"
      >
        <DialogTitle class="sr-only">{{ props.label }}</DialogTitle>
        <input
          v-model="query"
          type="text"
          role="combobox"
          aria-expanded="true"
          :aria-controls="`${id}-list`"
          :aria-activedescendant="
            current === undefined ? undefined : optionId(current)
          "
          aria-autocomplete="list"
          :aria-label="props.placeholder"
          :placeholder="props.placeholder"
          autocomplete="off"
          spellcheck="false"
          class="mx-3 mt-3 rounded-[var(--newt-radius-sm)] border border-newt-border bg-newt-bg-input px-3.5 py-3 font-[family-name:var(--newt-font-sans)] text-base text-newt-text-primary placeholder:text-newt-text-muted focus:border-newt-brand focus:outline-none"
          @input="onInput"
          @keydown="onKeydown"
        />
        <div
          :id="`${id}-list`"
          role="listbox"
          :aria-label="props.label"
          class="flex-1 overflow-y-auto px-3 pb-3 pt-2"
        >
          <div
            v-for="group in shown"
            :key="group.label"
            role="group"
            :aria-label="group.label"
          >
            <div
              aria-hidden="true"
              class="px-2 pb-1 pt-2.5 text-xs font-bold uppercase tracking-[0.02em] text-newt-text-muted"
            >
              {{ group.label }}
            </div>
            <!--
              Options are driven from the input through aria-activedescendant;
              Enter there selects the highlighted one.
            -->
            <div
              v-for="item in group.items"
              :id="optionId(item)"
              :key="item.id"
              role="option"
              tabindex="-1"
              :aria-selected="item === current"
              :class="
                cn(
                  'flex cursor-pointer items-center gap-2 rounded-[var(--newt-radius-sm)] p-2 text-[15px] leading-5',
                  item === current
                    ? 'bg-newt-bg-active text-newt-text-primary'
                    : 'text-newt-text-secondary'
                )
              "
              @click="choose(item)"
              @pointermove="active = flat.indexOf(item)"
            >
              <span
                aria-hidden="true"
                class="w-5 shrink-0 text-center font-semibold text-newt-text-muted"
              >
                {{ item.prefix }}
              </span>
              <span class="truncate font-medium">{{ item.label }}</span>
              <span
                v-if="item.description !== undefined"
                class="truncate text-[13px] text-newt-text-muted"
              >
                {{ item.description }}
              </span>
              <kbd
                v-if="item.shortcut !== undefined"
                :class="cn(kbdClassName, 'ms-auto shrink-0')"
              >
                {{ item.shortcut }}
              </kbd>
            </div>
          </div>
          <p
            v-if="flat.length === 0"
            class="m-0 px-2 py-6 text-center text-sm text-newt-text-muted"
          >
            {{ props.emptyText }}
          </p>
        </div>
        <footer
          v-if="props.hints !== false"
          aria-hidden="true"
          class="flex flex-wrap gap-x-4 gap-y-1 border-t border-newt-border bg-newt-bg-surface px-4 py-2.5 text-xs text-newt-text-muted"
        >
          <span class="inline-flex items-center gap-1">
            <kbd :class="kbdClassName">↑</kbd>
            <kbd :class="kbdClassName">↓</kbd>
            {{ props.hints.move }}
          </span>
          <span class="inline-flex items-center gap-1">
            <kbd :class="kbdClassName">Enter</kbd>
            {{ props.hints.select }}
          </span>
          <span class="inline-flex items-center gap-1">
            <kbd :class="kbdClassName">Esc</kbd>
            {{ props.hints.close }}
          </span>
        </footer>
      </DialogContent>
    </DialogPortal>
  </DialogRoot>
</template>
export { default as CommandPalette } from "./CommandPalette.vue"

/** One row of the palette. */
export interface CommandItem {
  /** Unique across the whole palette; handed back by the `select` event. */
  id: string
  label: string
  /** The quieter text beside the label. */
  description?: string
  /** A one-character sign before the label, such as `#` or `@`. */
  prefix?: string
  /** A key combination shown at the end of the row. */
  shortcut?: string
  /** Extra words the search should match that the row does not show. */
  keywords?: readonly string[]
}

export interface CommandGroup {
  label: string
  items: readonly CommandItem[]
}

/** The three lines of the footer. */
export interface CommandPaletteHints {
  move: string
  select: string
  close: string
}

Update the import paths

The files import @/lib/utils and sibling components through the aliases in your components.json. Point them at wherever those live in your project.

No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds Command Palette to your React project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.

No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds Command Palette to your Vue project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.

Usage

import { CommandPalette } from "@/components/ui/command-palette"

export function Example() {
  return <CommandPalette />
}
<script setup lang="ts">
import { CommandPalette } from "@/components/ui/command-palette"
</script>

<template>
  <CommandPalette />
</template>

API reference

CommandPalette

PropType
open / v-model:open?boolean

Whether the palette is shown.

Typeboolean
Defaultfalse
onOpenChange?(open: boolean) => void

React only. Called with `false` on Escape, a press of the overlay or a selection; Vue emits `update:open`.

Type(open: boolean) => void
groups?{ label: string; items: CommandItem[] }[]

The rows, under their headings. A group with no matching row is hidden.

Type{ label: string; items: CommandItem[] }[]
onSelect / @select?(item: CommandItem) => void

Called with the chosen row. The palette then closes itself.

Type(item: CommandItem) => void
label?string

Accessible name of the dialog and of the list.

Typestring
Default"Command palette"
placeholder?string

Placeholder and accessible name of the search field.

Typestring
Default"Where would you like to go?"
emptyText?string

Shown when the query matches nothing.

Typestring
Default"Nothing matches that."
hints?{ move: string; select: string; close: string } | false

The wording of the footer's key hints. `false` leaves the footer out.

Type{ move: string; select: string; close: string } | false
container?HTMLElement

Element the overlay and panel are portalled into. A palette below a `DirectionProvider` or a themed wrapper passes that element to keep the direction and the palette.

TypeHTMLElement
Defaultdocument.body

CommandItem

PropType
id?string

Unique across the whole palette.

Typestring
label?string

The row's main text.

Typestring
description?string

Quieter text beside the label.

Typestring
prefix?string

A one-character sign before the label, such as `#` or `@`.

Typestring
shortcut?string

A key combination shown at the end of the row.

Typestring
keywords?string[]

Extra words the search matches that the row does not show.

Typestring[]

Opening the palette always starts from an empty query with the first row highlighted.

Accessibility

The shell carries role="dialog" and aria-modal="true", and takes its accessible name from label. The primitive holds focus inside it and hides the page behind from screen readers. Escape closes it, and so does a press on the dimmed page. While an input method composes text, Escape cancels the candidate and the palette stays open. When the palette closes, focus goes back to the element that had it before. The search field is a role="combobox" that keeps focus the whole time: Up and Down move the highlight, wrapping at the ends, and aria-activedescendant tells a screen reader which row is highlighted. Enter chooses it. Rows are role="option" inside a role="listbox", grouped under their headings. The footer hints repeat what the keys do for sighted users and are hidden from assistive technology.

label, placeholder, emptyText and hints default to English. Translating labels lists every English default.

Tokens

Command Palette reads its colours, radii and motion from the --newt-* tokens installed with the library. Override a token and every component that reads it follows, including this one — see the token layer. In the plain HTML and CSS distribution the same component is newt-command-palette.

  • --newt-border
  • --newt-radius-lg
  • --newt-bg-elevated
  • --newt-shadow-elevation-high
  • --newt-text-primary
  • --newt-radius-sm
  • --newt-bg-input
  • --newt-font-sans
  • --newt-brand
  • --newt-text-muted
  • --newt-text-secondary
  • --newt-bg-active
  • --newt-bg-base
  • --newt-font-mono
  • --newt-bg-surface