CommandPalette
Search pages and actions in one place, with grouped results, keywords, keyboard navigation and custom content. Usually keep one instance in the application layout.
Import
import { HuiCommandPalette } from '@nscode/handy-ui'
import type {
CommandPaletteItem,
CommandPaletteProps,
CommandPaletteEmits,
CommandPaletteExpose
} from '@nscode/handy-ui'
Examples
Basic usage
Click the button or press mod+k. mod means ⌘ on Apple platforms and Ctrl elsewhere. Use ↑ and ↓ to navigate, Enter to execute, and Esc to close. select is emitted before the item's action. By default, execution waits until the panel closes and restores focus, then runs on the next frame.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiCommandPalette, HuiKbd, HuiMessage, HuiSpace } from '@nscode/handy-ui'
import type { CommandPaletteItem } from '@nscode/handy-ui'
const palette = ref<InstanceType<typeof HuiCommandPalette>>()
const selected = ref('None')
const items: CommandPaletteItem[] = [
{
id: 'users',
label: 'Users',
group: 'Pages',
icon: 'user',
action: () => HuiMessage.success('Opening users')
},
{
id: 'settings',
label: 'Settings',
group: 'Pages',
icon: 'search',
action: () => HuiMessage.success('Opening settings')
},
{
id: 'save',
label: 'Save changes',
group: 'Actions',
icon: 'check',
action: () => HuiMessage.success('Saved')
}
]
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace align="center"
><HuiButton @click="palette?.open()">Open command palette</HuiButton><span>or press</span
><HuiKbd keys="mod+k"
/></HuiSpace>
<span>Last selected: {{ selected }}</span>
<HuiCommandPalette ref="palette" :items="items" @select="selected = $event.label" />
</HuiSpace>
</template>
Pinyin and aliases
Queries are split at whitespace. Every term must appear in the label or a keyword, ignoring case. Pinyin and initial matching are not built in; add those aliases to keywords.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiCommandPalette, HuiMessage } from '@nscode/handy-ui'
const palette = ref<InstanceType<typeof HuiCommandPalette>>()
const items = [
{ label: '用户管理', keywords: ['yonghu', 'yh', 'users'] },
{ label: '角色管理', keywords: ['juese', 'js', 'roles'] },
{ label: '系统设置', keywords: ['xitong', 'xt', 'settings'] }
]
</script>
<template>
<HuiButton @click="palette?.open()">Search yh, juese or settings</HuiButton>
<HuiCommandPalette
ref="palette"
:items="items"
:hotkey="false"
@select="HuiMessage.success($event.label)"
/>
</template>
Descriptions, shortcut labels and disabled items
description is displayed but not searched. shortcut only displays a key combination and registers no listener. Disabled commands stay visible but cannot be selected with the mouse or keyboard. Changing another item's disabled state preserves the current selection. Selection resets to the first enabled item only when the current item becomes disabled or the result key sequence changes.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiCommandPalette, HuiMessage } from '@nscode/handy-ui'
const palette = ref<InstanceType<typeof HuiCommandPalette>>()
const items = [
{ label: 'Save', description: 'Save current changes', shortcut: 'mod+s', icon: 'check' },
{ label: 'Search', description: 'Find on the current page', shortcut: 'mod+f', icon: 'search' },
{
label: 'Archive',
description: 'You do not have permission to archive this record',
disabled: true
}
]
</script>
<template>
<HuiButton @click="palette?.open()">View command details</HuiButton>
<HuiCommandPalette
ref="palette"
:items="items"
:hotkey="false"
@select="HuiMessage.success($event.label)"
/>
</template>
Custom hotkeys
Ctrl, ⌘ and Alt combinations also work inside inputs. A plain character such as / remains available for typing there. Pass false to open only through a button or instance method.
<script setup lang="ts">
import { ref } from 'vue'
import {
HuiButton,
HuiCommandPalette,
HuiInput,
HuiKbd,
HuiMessage,
HuiSpace
} from '@nscode/handy-ui'
const print = ref<InstanceType<typeof HuiCommandPalette>>()
const slash = ref<InstanceType<typeof HuiCommandPalette>>()
const text = ref('')
const items = [{ label: 'Print preview' }, { label: 'Export file' }]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap align="center">
<HuiButton @click="print?.open()">Modifier hotkey</HuiButton><HuiKbd keys="mod+p" />
<HuiButton @click="slash?.open()">Single-key hotkey</HuiButton><HuiKbd keys="/" />
</HuiSpace>
<HuiInput v-model="text" placeholder="Type / here; mod+p still opens the palette" />
<HuiCommandPalette
ref="print"
:items="items"
hotkey="mod+p"
@select="HuiMessage.success($event.label)"
/>
<HuiCommandPalette
ref="slash"
:items="items"
hotkey="/"
@select="HuiMessage.success($event.label)"
/>
</HuiSpace>
</template>
Remote search
Control the query with v-model:query and replace items with the response. Return true from filter to keep server order without local filtering. Input is debounced for 300ms before a simulated request; the footer shows request count. New input invalidates older responses immediately. Loading hides old commands and empty results and blocks command execution.
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { HuiButton, HuiCommandPalette, HuiMessage } from '@nscode/handy-ui'
import type { CommandPaletteItem } from '@nscode/handy-ui'
const palette = ref<InstanceType<typeof HuiCommandPalette>>()
const query = ref('')
const source = [{ label: 'East orders' }, { label: 'South orders' }, { label: 'North orders' }]
const items = ref<CommandPaletteItem[]>(source)
const loading = ref(false)
const requests = ref(0)
let timer: ReturnType<typeof setTimeout> | undefined
let revision = 0
const search = (value: string) => {
const current = ++revision
clearTimeout(timer)
loading.value = true
timer = setTimeout(async () => {
requests.value++
const result = await new Promise<CommandPaletteItem[]>((resolve) => {
setTimeout(
() =>
resolve(
source.filter((item) => item.label.toLowerCase().includes(value.trim().toLowerCase()))
),
500
)
})
if (current !== revision) return
items.value = result
loading.value = false
}, 300)
}
onBeforeUnmount(() => {
revision++
clearTimeout(timer)
})
</script>
<template>
<HuiButton @click="palette?.open()">Search orders</HuiButton>
<HuiCommandPalette
ref="palette"
v-model:query="query"
:items="items"
:loading="loading"
:hotkey="false"
:filter="() => true"
@update:query="search"
@select="HuiMessage.success($event.label)"
>
<template #loading="{ query }">Searching for “{{ query }}”…</template>
<template #footer
>Requests: {{ requests }};
{{ loading ? 'Searching…' : `${items.length} results returned` }}</template
>
</HuiCommandPalette>
</template>
Custom items, empty content and footer
The item slot receives item, active and query. The outer option keeps keyboard, mouse and ARIA behavior. The empty slot receives the current query.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAvatar, HuiButton, HuiCommandPalette, HuiMessage, HuiSpace } from '@nscode/handy-ui'
const palette = ref<InstanceType<typeof HuiCommandPalette>>()
const items = [
{ label: 'Alice', description: 'alice@example.com', keywords: ['alice', 'a'] },
{ label: 'Bob', description: 'bob@example.com', keywords: ['bob', 'b'] }
]
</script>
<template>
<HuiButton @click="palette?.open()">Search contacts</HuiButton>
<HuiCommandPalette
ref="palette"
:items="items"
:hotkey="false"
@select="HuiMessage.success(`Selected ${$event.label}`)"
>
<template #item="{ item, active, query }">
<HuiAvatar :label="item.label.slice(0, 1)" size="small" />
<HuiSpace direction="vertical" :size="0"
><strong>{{ item.label }}</strong
><span>{{ item.description }}</span></HuiSpace
>
<span v-if="active">{{ query ? `Match: ${query}` : 'Selected' }}</span>
</template>
<template #empty="{ query }">No contacts for “{{ query }}”. Try another name.</template>
<template #footer
><HuiButton size="small" @click="palette?.close()">Close contact search</HuiButton></template
>
</HuiCommandPalette>
</template>
Controlled state, result limits and staying open
Controlled state depends on whether visible or query is passed. Explicit undefined means closed or empty text; an update listener alone keeps internal state. Parents may accept, normalize or reject requests. Removing a prop restores its previous internal value. For controlled visibility, selecting a command requests closing and waits for the parent to supply false before execution. If closing is still refused on the next animation frame, that selection is cancelled and another command can be selected; closing later does not execute the expired command. With closeOnSelect=false, execution is immediate and the panel stays open.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiCommandPalette, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
const visible = ref(false)
const query = ref('')
const closeOnSelect = ref(false)
const selected = ref('None')
const items = Array.from({ length: 12 }, (_, index) => ({
id: index,
label: `Command ${index + 1}`
}))
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace align="center"
><HuiSwitch v-model="closeOnSelect" /><span>Close after selecting</span></HuiSpace
>
<HuiButton @click="visible = true">Open a 420px palette with at most 5 results</HuiButton>
<span>Last selected: {{ selected }}; query: {{ query }}</span>
<HuiCommandPalette
v-model:visible="visible"
v-model:query="query"
:items="items"
:hotkey="false"
:limit="5"
:width="420"
:close-on-select="closeOnSelect"
@select="selected = $event.label"
/>
</HuiSpace>
</template>
Custom scoring, text and methods
Default scoring prefers prefix matches over word-boundary matches, then substring matches. Label matches have twice the keyword weight. A custom filter returns a positive score to rank an item, or false / 0 to exclude it. Empty queries keep the original order without calling the filter.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiCommandPalette, HuiMessage, HuiSpace } from '@nscode/handy-ui'
import type { CommandPaletteItem } from '@nscode/handy-ui'
const palette = ref<InstanceType<typeof HuiCommandPalette>>()
const state = ref('Closed')
const items = [{ label: 'View report' }, { label: 'Create report' }, { label: 'Create order' }]
const filter = (item: CommandPaletteItem, query: string) => {
if (!item.label.toLowerCase().includes(query.toLowerCase())) return false
return item.label.startsWith('Create') ? 10 : 1
}
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace align="center"
><HuiButton @click="palette?.open()">open()</HuiButton
><HuiButton @click="palette?.toggle()">toggle()</HuiButton></HuiSpace
>
<span>Palette: {{ state }}</span>
<HuiCommandPalette
ref="palette"
:items="items"
:hotkey="false"
width="70vw"
:filter="filter"
placeholder="Search reports or create"
empty-text="Try another keyword"
@update:visible="state = $event ? 'Open' : 'Closed'"
@select="HuiMessage.success($event.label)"
>
<template #footer
><HuiButton size="small" @click="palette?.close()">close()</HuiButton></template
>
</HuiCommandPalette>
</HuiSpace>
</template>
Recreating commands on every parent render
createItems() returns new objects on every parent render. The active item stays selected while unique IDs, order and disabled states remain unchanged. After closing, the palette finds the latest object by key and uses it for both select and action. This example increments the version when closing, so the result shows which version ran. Press ↓ to select the second command, then refresh using the footer button; the active item stays on the second command.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiCommandPalette, HuiSpace } from '@nscode/handy-ui'
import type { CommandPaletteItem } from '@nscode/handy-ui'
const visible = ref(false)
const version = ref(1)
const selected = ref('None')
const executed = ref('Not executed')
const createItems = (): CommandPaletteItem[] => {
const currentVersion = version.value
return [
{ id: 'report', label: 'View report' },
{ id: 'settings', label: 'Save settings' }
].map((item) => ({
...item,
description: `Version ${currentVersion}`,
action: () => {
executed.value = `${item.label}, version ${currentVersion}`
}
}))
}
const updateVisible = (value: boolean) => {
visible.value = value
if (!value) version.value++
}
const onSelect = (item: CommandPaletteItem) => {
selected.value = `${item.label}, ${item.description}`
}
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiButton @click="visible = true">Open dynamic commands</HuiButton>
<span>Version: {{ version }}; select: {{ selected }}; action: {{ executed }}</span>
<HuiCommandPalette
:visible="visible"
:items="createItems()"
:hotkey="false"
@update:visible="updateVisible"
@select="onSelect"
>
<template #footer>
<HuiButton size="small" @mousedown.prevent @click="version++"
>Refresh and keep active item</HuiButton
>
</template>
</HuiCommandPalette>
</HuiSpace>
</template>
Props
| Prop | Description | Type | Default |
|---|---|---|---|
| items | Command list | CommandPaletteItem[] | Required |
| visible | Open state; supports v-model:visible; managed internally when omitted | boolean | — |
| hotkey | Shortcut to open/close; false disables registration | string | false | 'mod+k' |
| query | Search text; supports v-model:query; managed internally when omitted | string | — |
| placeholder | Input placeholder; an explicit empty string is respected | string | Locale |
| emptyText | Empty result text; an explicit empty string is respected | string | Locale |
| loading | Hide old results and empty state while searching; block execution | boolean | false |
| limit | Maximum results; 0 displays none; non-finite values fall back to 100 | number | 100 |
| closeOnSelect | Close before execution; false executes immediately and stays open | boolean | true |
| filter | Custom matching and scoring; not called for empty queries | (item, query) => number | boolean | — |
| width | Panel width; numbers use px | number | string | 640 |
Events
| Event | Description | Parameters |
|---|---|---|
| update:visible | Request opening or closing | visible: boolean |
| update:query | Search input changed | query: string |
| select | Command selected, before its action runs | item: CommandPaletteItem |
Slots
| Slot | Description | Parameters |
|---|---|---|
| item | Custom result content | { item, active, query } |
| empty | Content when no results match | { query } |
| loading | Searching content; defaults to localized loading text | { query } |
| footer | Replace keyboard hints | — |
Methods
| Method | Description | Parameters |
|---|---|---|
| open | Request opening | — |
| close | Request closing | — |
| toggle | Request toggling the open state | — |
Types
interface CommandPaletteItem {
id?: string | number
label: string
description?: string
group?: string
icon?: string
keywords?: string[]
shortcut?: string
disabled?: boolean
action?: () => void
}
interface CommandPaletteExpose {
open: () => void
close: () => void
toggle: () => void
}