CommandMenu
@codeui/solid v0.3.0
A searchable palette of commands opened from the keyboard.
When to use
Use CommandMenu to let people find any action, setting, or option by name and run it from the keyboard. An app has one command menu. It lists every visible action and setting, read from the same data as the controls that own them. The highlight previews a choice on the content, Enter applies it, and Escape restores what was there before.
When to choose another component
- Choose
Comboboxto pick a value for one field in a form. It stays in place and keeps a selected value.CommandMenufloats over the app and keeps no value. - Choose
DropdownMenufor a short list of actions anchored to a button, where search adds nothing. - Choose
Dialogfor settings or a decision that blocks.CommandMenuhas no scrim and no buttons.
Live demo
import { createMemo, createSignal } from "solid-js";
import { Button, type CommandItem, CommandMenu } from "@codeui/solid";
type Theme = { id: string; name: string; background: string; text: string; accent: string };
const themes: Theme[] = [
{ id: "vercel", name: "Vercel", background: "#0a0a0a", text: "#ededed", accent: "#52a8ff" },
{ id: "dracula", name: "Dracula", background: "#282a36", text: "#f8f8f2", accent: "#ff79c6" },
{ id: "nord", name: "Nord", background: "#2e3440", text: "#d8dee9", accent: "#88c0d0" },
{ id: "solarized", name: "Solarized light", background: "#fdf6e3", text: "#586e75", accent: "#b58900" },
];
type ThemeItem = CommandItem & { theme: Theme };
function Swatch(props: { theme: Theme }) {
return (
<span
style={{
width: "16px",
height: "16px",
"border-radius": "50%",
background: `linear-gradient(135deg, ${props.theme.background} 50%, ${props.theme.accent} 50%)`,
"box-shadow": "inset 0 0 0 1px rgb(127 127 127 / 35%)",
}}
/>
);
}
export default function ThemePicker() {
const [open, setOpen] = createSignal(false);
const [applied, setApplied] = createSignal(themes[0]);
const [preview, setPreview] = createSignal<Theme>();
const [status, setStatus] = createSignal("");
const shown = () => preview() ?? applied();
const items = createMemo<ThemeItem[]>(() =>
themes.map(theme => ({
id: theme.id,
textValue: theme.name,
label: theme.name,
group: "Themes",
leading: <Swatch theme={theme} />,
current: theme.id === applied().id,
theme,
})),
);
return (
<div style={{ display: "grid", gap: "var(--cui-space-3)", "justify-items": "start" }}>
<pre
style={{
margin: 0,
padding: "var(--cui-space-4)",
"border-radius": "var(--cui-radius-lg)",
background: shown().background,
color: shown().text,
"font-size": "13px",
}}
>
<span style={{ color: shown().accent }}>export function</span> greet(name) {"{"}
{"\n"}
{" "}
<span style={{ color: shown().accent }}>return</span> `Hello, ${"{"}name{"}"}`;{"\n"}
{"}"}
</pre>
<Button variant="secondary" onClick={() => setOpen(true)}>
Change theme
</Button>
<p aria-live="polite" style={{ margin: 0, color: "var(--cui-text-hint)" }}>
{status()}
</p>
<CommandMenu
open={open()}
onOpenChange={setOpen}
items={items()}
title="Search themes"
placeholder="Search themes"
hint="↑↓ preview · ↵ apply · esc cancel"
emptyContent="No theme matches"
onHighlightChange={item => setPreview(item?.theme)}
onBeforeClose={() => setPreview(undefined)}
onCancel={() => setStatus(`Kept ${applied().name}`)}
onSelect={item => {
setApplied(item.theme);
setStatus(`Applied ${item.theme.name}`);
}}
/>
</div>
);
}The demo is a theme picker. Move the highlight with the arrow keys or the pointer and the snippet above previews that theme. Press Enter or click to apply it. Press Escape or click outside to close the menu and get the applied theme back.
Three callbacks make the preview work:
onHighlightChangeruns each time the highlight moves, with the item under it. The demo shows that theme.onBeforeCloseruns first on every close. The demo ends the preview there.onSelectruns only on Enter or a click, after the menu has closed. The demo applies the theme there.
onCancel runs after onBeforeClose when the menu closes without a selection. That covers Escape, a click outside, and the app setting open to false. Use it to revert work that onBeforeClose does not cover, or to report that nothing changed.
Anatomy
Tap a part to outline it in the demo.
- 01Trigger
commandmenu-triggerclasses.trigger - 02Overlay
commandmenu-overlayclasses.overlay - 03Content
commandmenu-contentclasses.content - 04Title
commandmenu-titleclasses.title - 05Search
commandmenu-searchclasses.search - 06SearchInput
commandmenu-search-inputclasses.searchInput - 07Hint
commandmenu-hintclasses.hint - 08Listbox
commandmenu-listboxclasses.listbox - 09Group
commandmenu-groupclasses.group - 10GroupLabel
commandmenu-group-labelclasses.groupLabel - 11Item
commandmenu-itemclasses.item - 12Leading
commandmenu-leadingclasses.leading - 13ItemLabel
commandmenu-item-labelclasses.itemLabel - 14ItemDescription
commandmenu-item-descriptionclasses.itemDescription - 15ItemIndicator
commandmenu-item-indicatorclasses.itemIndicator - 16Shortcut
commandmenu-shortcutclasses.shortcut - 17Empty
commandmenu-emptyclasses.empty
| Export | Renders | classes key | data-cui | Role |
|---|---|---|---|---|
Root | No DOM | none | none | none |
Trigger | button | trigger | commandmenu-trigger | button |
Portal | No DOM | none | none | none |
Overlay | div | overlay | commandmenu-overlay | none |
Content | div | content | commandmenu-content | dialog |
Title | h2, visually hidden | title | commandmenu-title | none |
Search | div | search | commandmenu-search | none |
SearchInput | input | searchInput | commandmenu-search-input | combobox |
Hint | span | hint | commandmenu-hint | aria-hidden |
Listbox | ul | listbox | commandmenu-listbox | listbox |
Group | li | group | commandmenu-group | presentation |
GroupLabel | span | groupLabel | commandmenu-group-label | none |
Item | li | item | commandmenu-item | option |
Leading | span | leading | commandmenu-leading | aria-hidden |
ItemLabel | div | itemLabel | commandmenu-item-label | none |
ItemDescription | div | itemDescription | commandmenu-item-description | none |
ItemIndicator | div | itemIndicator | commandmenu-item-indicator | aria-hidden |
Shortcut | span | shortcut | commandmenu-shortcut | none |
Empty | div | empty | commandmenu-empty | status |
The ready CommandMenu renders every part except Trigger and Overlay. The app opens the menu from its own shortcut, and the menu has no scrim so the content behind it stays visible as the preview.
Variants
Groups, leading visuals, and row details
import { createSignal } from "solid-js";
import { Button, type CommandItem, CommandMenu } from "@codeui/solid";
function Swatch(props: { colors: [string, string] }) {
return (
<span
style={{
width: "16px",
height: "16px",
"border-radius": "50%",
background: `linear-gradient(135deg, ${props.colors[0]} 50%, ${props.colors[1]} 50%)`,
"box-shadow": "inset 0 0 0 1px rgb(127 127 127 / 35%)",
}}
/>
);
}
// Consecutive items with the same group and section share one heading.
const items: CommandItem[] = [
{ id: "export-png", textValue: "Export as PNG", label: "Export as PNG", group: "Export", shortcut: "⌘ E" },
{ id: "export-svg", textValue: "Export as SVG", label: "Export as SVG", group: "Export" },
{ id: "copy-link", textValue: "Copy share link", label: "Copy share link", group: "Export", shortcut: "⌘ ⇧ C" },
{
id: "vercel",
textValue: "Vercel",
label: "Vercel",
group: "Themes",
leading: <Swatch colors={["#0a0a0a", "#52a8ff"]} />,
current: true,
},
{ id: "dracula", textValue: "Dracula", label: "Dracula", group: "Themes", leading: <Swatch colors={["#282a36", "#ff79c6"]} /> },
{
id: "legacy",
textValue: "Legacy light",
label: "Legacy light",
group: "Themes",
leading: <Swatch colors={["#ffffff", "#999999"]} />,
disabled: true,
},
{
id: "jetbrains",
textValue: "JetBrains Mono",
label: "JetBrains Mono",
description: "Monospace with ligatures",
group: "Font",
section: "Editor",
current: true,
},
{
id: "fira",
textValue: "Fira Code",
label: "Fira Code",
description: "Monospace with ligatures",
group: "Font",
section: "Editor",
},
];
export default function GroupsDemo() {
const [open, setOpen] = createSignal(false);
const [last, setLast] = createSignal("");
return (
<div style={{ display: "grid", gap: "var(--cui-space-3)", "justify-items": "start" }}>
<Button variant="secondary" onClick={() => setOpen(true)}>
Open commands
</Button>
<p aria-live="polite" style={{ margin: 0, color: "var(--cui-text-hint)" }}>
{last()}
</p>
<CommandMenu
open={open()}
onOpenChange={setOpen}
items={items}
title="Search commands"
placeholder="Search commands, themes and fonts"
hint="↑↓ preview · ↵ apply · esc cancel"
emptyContent="No command matches"
onSelect={item => setLast(`Ran ${item.textValue}`)}
/>
</div>
);
}Each item can carry a group, a section, a leading visual, a description, a shortcut, and the current and disabled flags.
- Consecutive items with the same
groupandsectionshare one heading. Keep the items of a group next to each other initems, or the heading repeats. - A
sectionprefixes the heading, as in "Editor / Font". leadingsits in a 20px box before the label. When one item in a group has a leading visual, every row in that group gets the box, so the labels line up.descriptionshows after the label in the hint color. The default filter searches it when it is a string.shortcutis a key label at the end of the row. It is display text only. The app binds the keys.currentshows a check to mark the value in use, such as the applied theme.disabledrows are dimmed, skipped by the arrow keys, and cannot be selected.
States
Open and closed
open is required and controlled. onOpenChange reports every request to open or close. Every open starts with an empty query and the highlight on the first enabled item. The menu opens and closes without animation, and moving the highlight from the keyboard has no animation either. A menu that opens many times a session from the keyboard should not make people wait.
Empty
import { createSignal } from "solid-js";
import { Button, type CommandItem, CommandMenu } from "@codeui/solid";
const snippets: CommandItem[] = [
{ id: "hello", textValue: "hello-world.ts", label: "hello-world.ts", group: "Recent snippets" },
{ id: "fetch", textValue: "fetch-user.ts", label: "fetch-user.ts", group: "Recent snippets" },
{ id: "styles", textValue: "button.css.ts", label: "button.css.ts", group: "Recent snippets" },
];
export default function EmptyDemo() {
const [open, setOpen] = createSignal(false);
return (
<>
<Button variant="secondary" onClick={() => setOpen(true)}>
Open snippet
</Button>
<CommandMenu
open={open()}
onOpenChange={setOpen}
items={snippets}
title="Search snippets"
placeholder="Type a name, such as kiwi"
emptyContent="No snippet matches. Clear the search to see recent snippets."
onSelect={() => {}}
/>
</>
);
}Type a name that matches nothing, such as "kiwi". emptyContent renders while no item matches. When emptyContent is unset, the list is blank. Say what is missing and how to get results back.
Highlighted
The highlighted row gets the field fill and primary text. It is neutral, never an accent fill. Item carries data-highlighted while it has the highlight, and onHighlightChange reports it. The pointer moves the highlight the same way as the arrow keys, so a preview follows both.
Disabled item
A disabled item carries data-disabled and aria-disabled="true". It shows at 40% opacity.
Controlled query
Pass query and onQueryChange to own the search text, for example to fetch results from a server. On close, the menu calls onQueryChange("") so the next open starts empty. The run commands pattern shows a full example.
Ready API
CommandMenu
Renders the whole menu in a portal: the dialog, the search field, the list, and the empty state. It is generic over the item type, so onSelect and onHighlightChange receive your own item type with any extra fields you add.
Prop
Type
Each entry in items is a CommandItem.
Prop
Type
filterCommandItems(items, query) is the default filter, exported from @codeui/solid. It keeps the items whose textValue, group, section, or string description contain every word of the query, ignoring case. Call it from your own filter to extend it.
CommandMenu passes nothing through to Kobalte. Every prop is listed above.
Styled parts API
Import the parts from @codeui/solid/command-menu/parts. Use them when the ready component cannot express your layout, such as a footer row or a custom item.
import { createSignal, Show } from "solid-js";
import { Button, icons } from "@codeui/solid";
import * as M from "@codeui/solid/command-menu/parts";
type Command = { id: string; label: string; shortcut?: string; current?: boolean; disabled?: boolean };
type Group = { name: string; commands: Command[] };
const groups: Group[] = [
{
name: "Export",
commands: [
{ id: "png", label: "Export as PNG", shortcut: "⌘ E" },
{ id: "svg", label: "Export as SVG" },
],
},
{
name: "Background",
commands: [
{ id: "gradient", label: "Gradient", current: true },
{ id: "solid", label: "Solid color" },
{ id: "image", label: "Image", disabled: true },
],
},
];
export default function PartsDemo() {
const [open, setOpen] = createSignal(false);
return (
<M.Root open={open()} onOpenChange={setOpen}>
<M.Trigger as={Button} variant="secondary">
Open commands
</M.Trigger>
<M.Portal>
<M.Content<Command, Group>
options={groups}
optionValue="id"
optionTextValue="label"
optionDisabled="disabled"
optionGroupChildren="commands"
onSelect={() => setOpen(false)}
sectionComponent={section => (
<M.Group>
<M.GroupLabel>{section.section.rawValue.name}</M.GroupLabel>
</M.Group>
)}
itemComponent={item => (
<M.Item item={item.item}>
<M.ItemLabel>{item.item.rawValue.label}</M.ItemLabel>
<Show when={item.item.rawValue.current}>
<M.ItemIndicator forceMount>
<icons.CheckIcon />
</M.ItemIndicator>
</Show>
<Show when={item.item.rawValue.shortcut}>
{shortcut => <M.Shortcut>{shortcut()}</M.Shortcut>}
</Show>
</M.Item>
)}
>
<M.Title>Commands</M.Title>
<M.Search>
<M.SearchInput aria-label="Search commands" placeholder="Search commands" />
<M.Hint>↑↓ preview · ↵ apply · esc cancel</M.Hint>
</M.Search>
<M.Listbox aria-label="Commands" />
<M.Empty>No command matches</M.Empty>
</M.Content>
</M.Portal>
</M.Root>
);
}The parts wrap two Kobalte primitives. The dialog parts (Root, Trigger, Portal, Overlay, Content, Title) wrap Kobalte Dialog. The list parts wrap Kobalte Combobox. Content hosts the combobox engine, so the search input and the list inside it share one highlight. The engine keeps the list open and never keeps a selected value.
When you compose the parts, the close lifecycle is yours. Content calls onSelect but does not close the menu, and it does not clear the query. The ready component adds onBeforeClose, onCancel, and the empty query per open.
The parts are also available as one object, CommandMenuParts, exported from @codeui/solid.
Content
Renders the dialog panel and the combobox engine. The highlight starts on the first enabled option and moves back to it each time the query changes.
Prop
Type
Kobalte dialog content props pass through. These change behavior:
Prop
Type
Without a Trigger, focus returns on close to the element that had it when the menu opened.
Empty
Renders a div with role="status" only while no option matches the query. It takes the props of a div.
Group
Renders the heading row that starts a group, as a Kobalte combobox section. Render it from sectionComponent. It takes the props of an li.
GroupLabel
Renders the text of a group heading, in a span. It takes the props of a span.
Hint
Renders key hints such as "↑↓ preview · ↵ apply · esc cancel" in a span with aria-hidden="true". Place it inside Search, after the input. It is hidden on phones. It takes the props of a span.
Item
Renders one option as a Kobalte combobox item. Render it from itemComponent and pass it the node.
Prop
Type
ItemDescription
Renders secondary text after the label, linked to the option as its description. It wraps Kobalte's combobox item description.
ItemIndicator
Renders the check slot. The menu never keeps a selection, so the indicator shows only with forceMount. Render it only for the current item.
Prop
Type
ItemLabel
Renders the option label, linked to the option as its accessible name. It wraps Kobalte's combobox item label.
Leading
Renders a fixed 20px box before the label, with aria-hidden="true". Put an icon or a swatch in it. Render it on every row of a group, empty or not, so the labels line up. It takes the props of a span.
Listbox
Renders the list of options as a Kobalte combobox listbox. It shows six rows, then scrolls. Give it an aria-label or aria-labelledby.
Prop
Type
Overlay
Renders a fixed, full-screen layer behind the panel, as a Kobalte dialog overlay. It has no fill. The design has no scrim for the command menu, so the ready component does not render it.
Portal
Moves the content to the end of document.body, or to mount. It renders no element of its own.
Prop
Type
Root
Holds the open state of the dialog. It renders no element.
Prop
Type
Search
Renders the field row around the search icon, the input, and the hint. It takes the props of a div.
SearchInput
Renders the search input as a Kobalte combobox input, with autocomplete="off" and spellcheck={false}. Give it an aria-label or aria-labelledby. It takes the props of an input.
Shortcut
Renders a key label at the end of a row in a span. It is display text only. It takes the props of a span.
Title
Renders the accessible name of the dialog, visually hidden. Use its id as aria-labelledby on Content, SearchInput, and Listbox, as the ready component does.
Trigger
Renders a button that opens the menu, as a Kobalte dialog trigger. Pass as to render a kit Button. With a trigger, focus returns to it on close. Most apps open the menu from a shortcut and need no trigger.
useCommandMenuContext
Returns the Kobalte combobox context of the nearest Content. It is Kobalte's useComboboxContext. Use it inside Content to read or set the query, for example context.inputValue() and context.setInputValue("").
Styles export
commandMenuStyles
import { commandMenuStyles } from "@codeui/solid/command-menu/parts";
const rowClass = commandMenuStyles.item();commandMenuStyles has one function per part key from the anatomy table. Each function takes no arguments and returns the class string of that part. None of the parts has variants. Call a function when you render your own element and want it to look like a part, for example a footer row styled as hint. The function returns the class only. It does not add data-cui, roles, or behavior.
Accessibility
Keyboard
| Key | Action |
|---|---|
| The app's shortcut, such as Cmd+K | Opens the menu. The app binds it. |
| ↓ | Moves the highlight to the next enabled item. Wraps from the last to the first. |
| ↑ | Moves the highlight to the previous enabled item. Wraps from the first to the last. |
| Home, End | Move the highlight to the first or the last enabled item. |
| PageUp, PageDown | Move the highlight by one page of the list. |
| ←, → | Move the text cursor and clear the highlight. onHighlightChange receives undefined. |
| Enter | Closes the menu, then calls onSelect with the highlighted item. |
| Escape | Closes the menu without a selection. Calls onBeforeClose, then onCancel. |
| Tab | Stays inside the menu. Focus is trapped. |
| Any other key | Edits the query. The highlight moves to the first match. |
A click on an item works like Enter. A click outside works like Escape.
ARIA
Contenthasrole="dialog", named by the hiddenTitle. It is modal, so the rest of the page is hidden from assistive technology while it is open.SearchInputhasrole="combobox",aria-expanded="true",aria-controlspointing at the list, andaria-activedescendantpointing at the highlighted option.Listboxhasrole="listbox". EachItemhasrole="option", witharia-disabledwhen it is disabled.Grouprows haverole="presentation", so screen readers read the group label as text in the list, not as a group name.Hint,Leading, andItemIndicatorare hidden from assistive technology. Put the meaning of a leading visual in the label.Emptyhasrole="status", so the empty message is announced when it appears.
Focus
- On open, focus moves to the search field.
- Focus stays on the search field while the highlight moves. The highlight is
aria-activedescendant, not DOM focus. - On close, focus returns to the
Triggerwhen there is one. Without a trigger, it returns to the element that had focus when the menu opened. PassonCloseAutoFocusand callpreventDefault()to move focus yourself.
SSR notes
An open or force-mounted menu includes the panel, list and hidden title in server HTML at the Portal declaration. Hydration adopts those nodes and moves them to the portal target. Closed content stays absent unless force-mounted. Trigger renders on the server as a normal button. IDs come from Solid's createUniqueId, so they match between the server and the client. Bind the open shortcut in onMount, which runs only on the client.
Theming hooks
The menu reads these custom properties. See tokens for the defaults.
| Property | Used for |
|---|---|
--cui-surface-dialog | Panel background, through the dialog panel |
--cui-shadow-dialog | Panel shadow, through the dialog panel |
--cui-text-dialog | Item text |
--cui-radius-command | Panel corners |
--cui-radius-lg | Search field corners |
--cui-radius-nav | Item corners |
--cui-surface-input | Search field fill and the highlighted row |
--cui-text-input | Query text |
--cui-text-hint | Placeholder, search icon, hint, group labels, leading visuals, descriptions, shortcuts, and the empty message |
--cui-action-brand-base | The check of the current item |
--cui-surface-scroll-thumb | List scrollbar |
--cui-space-1 to --cui-space-5 | Padding, gaps, and the leading box |
--cui-font-size-xs, --cui-font-size-sm, --cui-font-size-caption, --cui-font-size-md | Text sizes. md applies to the query on phones, so the page does not zoom. |
--cui-font-weight-semibold | Group labels |
Composition examples
- Run commands binds Cmd+K, builds grouped items from the app's actions, and loads results from a server.
- The styled parts demo above builds the menu from parts, with a trigger.
Related
Comboboxpicks and keeps one value for a form field.DropdownMenulists a few actions anchored to a button, without search.Dialogblocks the app behind a scrim for settings and decisions.Kbdshows a key in text, such as the shortcut that opens the menu.