Skip to Content
CodeUI

Run commands

@codeui/solid v0.3.0

Wire a command menu to your app's actions and shortcuts.

This guide connects a CommandMenu to your app. You bind the shortcut that opens it, build its items from your actions, preview a choice while it is highlighted, and load results from a server.

Bind Cmd+K

Click here, then press ⌘ K or Ctrl K to open the menu.

run-commands/shortcut.tsx
import { createSignal, onSettled } from "solid-js";
import { type CommandItem, CommandMenu, Kbd } from "@codeui/solid";

const commands: CommandItem[] = [
	{ id: "export-png", textValue: "Export as PNG", label: "Export as PNG", group: "Export" },
	{ id: "copy-link", textValue: "Copy share link", label: "Copy share link", group: "Export" },
	{ id: "new-snippet", textValue: "New snippet", label: "New snippet", group: "Snippet" },
];

export default function ShortcutDemo() {
	const [open, setOpen] = createSignal(false);
	const [last, setLast] = createSignal("");

	// An app binds the shortcut once, on `window`. This page already uses Cmd+K for its search, so
	// the demo acts only while the menu is open or focus is in the demo, and listens in the capture
	// phase to stop the event before the search sees it.
	let root!: HTMLDivElement;
	onSettled(() => {
		const onKeyDown = (event: KeyboardEvent) => {
			if (event.isComposing || event.repeat) return;
			if (!(event.metaKey || event.ctrlKey) || event.key.toLowerCase() !== "k") return;
			if (!open() && !root.contains(document.activeElement)) return;
			event.preventDefault();
			event.stopPropagation();
			setOpen(value => !value);
		};
		window.addEventListener("keydown", onKeyDown, true);
		return () => window.removeEventListener("keydown", onKeyDown, true);
	});

	return (
		<div
			ref={root}
			tabindex={-1}
			style={{ display: "grid", gap: "var(--cui-space-3)", "justify-items": "start" }}
		>
			<p style={{ margin: 0 }}>
				Click here, then press <Kbd>⌘</Kbd> <Kbd>K</Kbd> or <Kbd>Ctrl</Kbd> <Kbd>K</Kbd> to open the menu.
			</p>
			<p aria-live="polite" style={{ margin: 0, color: "var(--cui-text-hint)" }}>
				{last()}
			</p>
			<CommandMenu
				open={open()}
				onOpenChange={setOpen}
				items={commands}
				title="Search commands"
				placeholder="Search commands"
				hint="↑↓ preview · ↵ apply · esc cancel"
				emptyContent="No command matches"
				onSelect={item => setLast(`Ran ${item.textValue}`)}
			/>
		</div>
	);
}

The menu does not listen for a shortcut. Your app binds one, once, at its root.

This page already uses Cmd+K for search. The demo answers the shortcut only while its menu is open or focus is in the demo, and it stops the event before the search sees it. Your app owns the shortcut, so it needs neither check.

  1. Add a keydown listener on window in onMount, so it runs only on the client.
  2. Match Cmd+K on macOS and Ctrl+K elsewhere with event.metaKey || event.ctrlKey.
  3. Call event.preventDefault(). Browsers use Ctrl+K to focus the address bar.
  4. Toggle open. Pressing the shortcut again while the menu is open closes it, the same as Escape.
  5. Remove the listener in onCleanup.

Skip events where event.isComposing is true, so the shortcut does not fire while someone types with an input method editor. Skip event.repeat, so holding the keys does not open and close the menu in a loop.

Mount one command menu for the whole app. Two listeners for the same shortcut open two menus.

Build items from your actions

run-commands/grouped.tsx
import { createSignal } from "solid-js";
import { Button, type CommandItem, CommandMenu } from "@codeui/solid";

type Action = { id: string; name: string; shortcut?: string };
type AppCommand = CommandItem & { run: () => void };

export default function GroupedDemo() {
	const [open, setOpen] = createSignal(false);
	const [log, setLog] = createSignal("");

	// One list of actions. The toolbar, the menus and the command menu read it.
	const actions: Record<"export" | "snippet" | "view", Action[]> = {
		export: [
			{ id: "export-png", name: "Export as PNG", shortcut: "⌘ E" },
			{ id: "export-svg", name: "Export as SVG" },
		],
		snippet: [
			{ id: "duplicate", name: "Duplicate snippet", shortcut: "⌘ D" },
			{ id: "rename", name: "Rename snippet" },
		],
		view: [{ id: "line-numbers", name: "Toggle line numbers" }],
	};

	// Items with the same group must be next to each other to share a heading.
	const items: AppCommand[] = [
		...actions.export.map(action => ({ ...action, group: "Export" })),
		...actions.snippet.map(action => ({ ...action, group: "Snippet" })),
		...actions.view.map(action => ({ ...action, group: "View" })),
	].map(action => ({
		id: action.id,
		textValue: action.name,
		label: action.name,
		group: action.group,
		shortcut: action.shortcut,
		run: () => setLog(`Ran ${action.name}`),
	}));

	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)" }}>
				{log()}
			</p>
			<CommandMenu
				open={open()}
				onOpenChange={setOpen}
				items={items}
				title="Search commands"
				placeholder="Search commands"
				hint="↑↓ preview · ↵ apply · esc cancel"
				emptyContent="No command matches"
				onSelect={item => item.run()}
			/>
		</div>
	);
}

Keep one list of actions and read it from the toolbar, the menus, and the command menu. The command menu then lists every action the app has, and a renamed action changes everywhere.

  • Map each action to a CommandItem. Set textValue to the plain text that search matches, and label to what the row shows.
  • Add your own fields to the item type, such as run. onSelect receives your type, so it can call item.run() with no lookup.
  • Set group to put a heading over related items. Items share a heading only when they are next to each other in items, so build the list group by group.
  • Set shortcut to show the key label of an action that has one. It is display text. Bind the keys yourself.
  • Set disabled on an action that cannot run now, instead of removing it. People still find it and see why it is dim.

onSelect runs after the menu has closed. An action that opens a dialog works as it would from a button, because the command menu is no longer in the way.

Preview a choice before you apply it

export function greet(name) {
  return `Hello, ${name}`;
}

command-menu/basic.tsx
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>
	);
}

For settings such as a theme or a font, show the highlighted choice on the content and apply it only on Enter.

<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}`);
	}}
/>
  1. Keep the applied value and the previewed value in two signals. Render preview() ?? applied().
  2. In onHighlightChange, set the preview. It runs for the arrow keys and the pointer, and with undefined when nothing is highlighted.
  3. In onBeforeClose, clear the preview. It runs first on every close, so the content never keeps a preview after the menu is gone.
  4. In onSelect, set the applied value. Enter and a click are the only ways to apply.
  5. In onCancel, handle a close without a selection, such as Escape, a click outside, or your shortcut. The preview is already cleared, so the applied value shows again.

Set current: true on the item that matches the applied value, so its row shows a check. Pass the hint text "↑↓ preview · ↵ apply · esc cancel" so people know that the highlight is only a preview.

Keep previews cheap. The highlight moves on every arrow key, and the menu does not animate it. A preview that waits on the network makes the list feel stuck.

The CommandMenu live demo explains the order of the callbacks.

Load results from a server

run-commands/async.tsx
import { createEffect, createSignal } from "solid-js";
import { Button, type CommandItem, CommandMenu } from "@codeui/solid";

const library = [
	"hello-world.ts",
	"fetch-user.ts",
	"button.css.ts",
	"use-debounce.ts",
	"router.tsx",
	"schema.sql",
	"deploy.yml",
];

// Stands in for a request to your server.
function searchSnippets(query: string): Promise<CommandItem[]> {
	const words = query.toLowerCase().split(/\s+/).filter(Boolean);
	const names = library.filter(name => words.every(word => name.includes(word)));
	return new Promise(resolve =>
		setTimeout(
			() =>
				resolve(
					names.map(name => ({
						id: name,
						textValue: name,
						label: name,
						group: query ? "Results" : "Recent snippets",
					})),
				),
			400,
		),
	);
}

export default function AsyncDemo() {
	const [open, setOpen] = createSignal(false);
	const [query, setQuery] = createSignal("");
	const [results, setResults] = createSignal<CommandItem[]>([]);
	const [loading, setLoading] = createSignal(false);
	const [opened, setOpened] = createSignal("");

	createEffect(() => open() ? query() : undefined, current => {
		if (current === undefined) return;
		let stale = false;
		setLoading(true);
		// Wait for a pause in typing before the request.
		const timer = setTimeout(() => {
			searchSnippets(current).then(items => {
				if (stale) return;
				setResults(items);
				setLoading(false);
			});
		}, 150);
		return () => {
			stale = true;
			clearTimeout(timer);
		};
	});

	return (
		<div style={{ display: "grid", gap: "var(--cui-space-3)", "justify-items": "start" }}>
			<Button variant="secondary" onClick={() => setOpen(true)}>
				Open snippet
			</Button>
			<p aria-live="polite" style={{ margin: 0, color: "var(--cui-text-hint)" }}>
				{opened()}
			</p>
			<CommandMenu
				open={open()}
				onOpenChange={setOpen}
				items={results()}
				// The server already matched the query. Keep its order.
				filter={items => items}
				query={query()}
				onQueryChange={setQuery}
				title="Search snippets"
				placeholder="Search snippets"
				emptyContent={loading() ? "Searching…" : "No snippet matches"}
				onSelect={item => setOpened(`Opened ${item.textValue}`)}
			/>
		</div>
	);
}

When the items come from a request, own the query and filter on the server.

  1. Pass query and onQueryChange to control the search text.
  2. Run the request in an effect that reads query() and open(). Skip it while the menu is closed.
  3. Wait for a short pause in typing before the request, and ignore a response that arrives after a newer query.
  4. Pass filter={items => items}. The server already matched the query, and the default filter would drop results that match on a field it does not search.
  5. Set emptyContent to "Searching…" while the request runs, and to a no-match message after it. Keep the previous results in items while the next request runs, so the list does not flash empty.

On close, the menu calls onQueryChange(""), so the next open starts with an empty query and your effect loads the default results again.

Filter on more fields

The default filter, filterCommandItems, matches every word of the query against textValue, group, section, and a string description. To search other fields, such as aliases, pass your own filter.

run-commands/aliases.tsx
import { createSignal } from "solid-js";
import { Button, type CommandItem, CommandMenu, filterCommandItems } from "@codeui/solid";

type AppCommand = CommandItem & { aliases: string[] };

const commands: AppCommand[] = [
	{ id: "export-png", textValue: "Export as PNG", label: "Export as PNG", group: "Export", aliases: ["image", "download", "save"] },
	{ id: "copy-link", textValue: "Copy share link", label: "Copy share link", group: "Export", aliases: ["url", "share"] },
	{ id: "line-numbers", textValue: "Toggle line numbers", label: "Toggle line numbers", group: "View", aliases: ["gutter"] },
];

// The default filter, plus a match on any alias.
const filter = (items: readonly AppCommand[], query: string) => {
	const matched = new Set(filterCommandItems(items, query));
	const words = query.toLowerCase().split(/\s+/).filter(Boolean);
	return items.filter(
		item => matched.has(item) || words.every(word => item.aliases.some(alias => alias.includes(word))),
	);
};

export default function AliasesDemo() {
	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={commands}
				filter={filter}
				title="Search commands"
				placeholder="Try download or gutter"
				emptyContent="No command matches"
				onSelect={item => setLast(`Ran ${item.textValue}`)}
			/>
		</div>
	);
}

Call filterCommandItems from your filter to keep the default matches, then add your own. Type "download" or "gutter" in the demo to match an alias. Return the items in the order to show them. The highlight moves to the first enabled result each time the query changes.

  • CommandMenu documents every prop, part, and key.
  • Kbd shows the shortcut in your app's text.

On this page