A search box over a grouped list of actions, with arrow-key highlight and Enter to run, inline or as a dialog.
use gpui::{div, prelude::*, px, App, Context, SharedString, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::command::{Command, CommandDialog, CommandGroup, CommandItem};
use crate::icons::{CALCULATOR, CALENDAR, CREDIT_CARD, SETTINGS, SMILE, USER};
#[derive(Default)]
pub struct CommandDemo {
dialog_open: bool,
last_run: Option<SharedString>,
}
impl CommandDemo {
fn run(cx: &mut Context<Self>) -> impl Fn(&SharedString, &mut Window, &mut App) + 'static {
cx.listener(|this, value: &SharedString, _, cx| {
this.last_run = Some(value.clone());
this.dialog_open = false;
cx.notify();
})
}
/// Builds the same list for the inline palette and the dialog; each needs its own id.
fn palette(&self, id: &'static str, cx: &mut Context<Self>) -> Command {
Command::new(id)
.group(
CommandGroup::new("Suggestions")
.item(CommandItem::new("Calendar").icon(CALENDAR).on_select(Self::run(cx)))
.item(
CommandItem::new("Search Emoji")
.icon(SMILE)
.keywords(["smiley", "reaction"])
.on_select(Self::run(cx)),
)
.item(CommandItem::new("Calculator").icon(CALCULATOR).disabled(true)),
)
.group(
CommandGroup::new("Settings")
.item(CommandItem::new("Profile").icon(USER).shortcut("Ctrl+P").on_select(Self::run(cx)))
.item(
CommandItem::new("Billing")
.icon(CREDIT_CARD)
.shortcut("Ctrl+B")
.on_select(Self::run(cx)),
)
.item(
CommandItem::new("Settings")
.icon(SETTINGS)
.shortcut("Ctrl+S")
.keywords(["preferences"])
.on_select(Self::run(cx)),
),
)
}
}
impl Render for CommandDemo {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let (border, muted_fg, background, radius) =
(theme.border, theme.muted_foreground, theme.background, theme.radius);
let status: SharedString = match &self.last_run {
Some(value) => format!("Ran \"{value}\"").into(),
None => "Use the mouse, or Up, Down and Enter.".into(),
};
// A fixed height with the palette last keeps the button still while the list filters.
div()
.w(px(450.0))
.h(px(300.0))
.flex()
.flex_col()
.gap_3()
.child(
div()
.flex()
.items_center()
.justify_between()
.gap_3()
.child(div().flex_1().truncate().text_sm().text_color(muted_fg).child(status))
.child(
CommandDialog::new("command-dialog", self.dialog_open, self.palette("command-in-dialog", cx))
.trigger(
Button::new("command-dialog-trigger", "Open as dialog")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Sm),
)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.dialog_open = *open;
cx.notify();
})),
),
)
.child(
div()
.rounded(radius)
.border_1()
.border_color(border)
.bg(background)
.shadow_md()
.child(self.palette("command-inline", cx).max_height(px(212.0))),
)
}
}Installation
Copies src/ui/command.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Install the icons
This component draws icons from
crate::icons. Copy src/icons.rs into your project and declaremod icons;next tomod theme;.Copy the source
Paste the code below into
src/ui/command.rs.src/ui/command.rs //! A searchable list of actions, like shadcn/ui's `Command` (cmdk). Typing filters the groups, //! Up/Down move the highlight, Enter runs the highlighted item. //! //! Inline: `Command::new("palette").placeholder("Type a command...").group(...)`. //! As a palette over the page, wrap it in [`CommandDialog`]: //! //! ```ignore //! CommandDialog::new("palette-dialog", self.open, Command::new("palette").group(...)) //! .on_open_change(cx.listener(|this, open: &bool, _, cx| { //! this.open = *open; //! cx.notify(); //! })) //! ``` use std::rc::Rc; use gpui::{ div, prelude::*, px, svg, AnyElement, App, ElementId, Entity, EntityInputHandler, Focusable, FontWeight, Pixels, ScrollHandle, SharedString, Subscription, Window, }; use crate::theme::ActiveTheme; use crate::ui::dialog::Modal; use crate::ui::input::{InputEvent, TextInput}; use crate::icons::{CHECK, SEARCH}; type SelectHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App) + 'static>; type OpenChangeHandler = Rc<dyn Fn(&bool, &mut Window, &mut App) + 'static>; /// One row. Enter or a click runs `on_select` with the item's value. pub struct CommandItem { value: SharedString, label: SharedString, keywords: Vec<SharedString>, icon: Option<&'static [u8]>, shortcut: Option<SharedString>, checked: bool, disabled: bool, on_select: Option<SelectHandler>, } impl CommandItem { pub fn new(label: impl Into<SharedString>) -> Self { let label = label.into(); Self { value: label.clone(), label, keywords: Vec::new(), icon: None, shortcut: None, checked: false, disabled: false, on_select: None, } } /// What `on_select` receives. Defaults to the label. pub fn value(mut self, value: impl Into<SharedString>) -> Self { self.value = value.into(); self } /// Extra words the search matches, e.g. "preferences" for "Settings". pub fn keywords(mut self, keywords: impl IntoIterator<Item = impl Into<SharedString>>) -> Self { self.keywords.extend(keywords.into_iter().map(Into::into)); self } /// A 24x24 SVG (for example a Lucide icon), drawn at 16px before the label. pub fn icon(mut self, svg: &'static [u8]) -> Self { self.icon = Some(svg); self } /// Right-aligned hint such as "Ctrl+P". Display only: bind the keys in your app. pub fn shortcut(mut self, shortcut: impl Into<SharedString>) -> Self { self.shortcut = Some(shortcut.into()); self } /// Draws a check mark on the right, for lists that show the current choice. pub fn checked(mut self, checked: bool) -> Self { self.checked = checked; self } pub fn disabled(mut self, disabled: bool) -> Self { self.disabled = disabled; self } pub fn on_select( mut self, handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static, ) -> Self { self.on_select = Some(Rc::new(handler)); self } fn matches(&self, query: &str) -> bool { query.is_empty() || self.label.to_lowercase().contains(query) || self.keywords.iter().any(|k| k.to_lowercase().contains(query)) } } /// Items under an optional heading. Groups with no matches are hidden, and a separator is /// drawn between the visible ones. pub struct CommandGroup { heading: Option<SharedString>, items: Vec<CommandItem>, } impl CommandGroup { pub fn new(heading: impl Into<SharedString>) -> Self { Self { heading: Some(heading.into()), items: Vec::new(), } } pub fn untitled() -> Self { Self { heading: None, items: Vec::new(), } } pub fn item(mut self, item: CommandItem) -> Self { self.items.push(item); self } pub fn items(mut self, items: impl IntoIterator<Item = CommandItem>) -> Self { self.items.extend(items); self } } /// The search box and filtered list. #[derive(IntoElement)] pub struct Command { id: ElementId, placeholder: SharedString, empty: SharedString, groups: Vec<CommandGroup>, max_height: Pixels, auto_focus: bool, } /// Not controlled, unlike most hyuskui components: the search box has to be a `TextInput` /// entity, and the highlight is transient. Both live as long as the command is rendered, so a /// command inside a closed popover or dialog starts fresh next time, as cmdk does on unmount. struct CommandState { input: Entity<TextInput>, query: SharedString, /// Index into the visible items. highlighted: Option<usize>, scroll: ScrollHandle, _input_changes: Subscription, } enum Row { Heading(SharedString), Separator, Item(CommandItem), } impl Command { pub fn new(id: impl Into<ElementId>) -> Self { Self { id: id.into(), placeholder: "Type a command or search...".into(), empty: "No results found.".into(), groups: Vec::new(), max_height: px(300.0), auto_focus: false, } } pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self { self.placeholder = placeholder.into(); self } /// Shown when nothing matches the search. pub fn empty(mut self, empty: impl Into<SharedString>) -> Self { self.empty = empty.into(); self } pub fn group(mut self, group: CommandGroup) -> Self { self.groups.push(group); self } /// The list scrolls past this height. pub fn max_height(mut self, height: impl Into<Pixels>) -> Self { self.max_height = height.into(); self } /// Focus the search box when the command appears. Popovers and modals focus their own /// panel two frames after opening (deferred content joins the dispatch tree late), so this /// waits one frame longer to win. pub fn auto_focus(mut self, auto_focus: bool) -> Self { self.auto_focus = auto_focus; self } } impl RenderOnce for Command { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let (placeholder, auto_focus) = (self.placeholder, self.auto_focus); let state = window.use_keyed_state(self.id.clone(), cx, |window, cx| { let input = cx.new(|cx| TextInput::new(cx).bare().placeholder(placeholder)); let input_changes = cx.subscribe(&input, |_, _, event: &InputEvent, cx| { if matches!(event, InputEvent::Change(_)) { cx.notify(); } }); if auto_focus { let focus = input.focus_handle(cx); window.on_next_frame(move |window, _| { window.on_next_frame(move |window, _| { window.on_next_frame(move |window, cx| window.focus(&focus, cx)); }); }); } CommandState { input, query: SharedString::default(), highlighted: None, scroll: ScrollHandle::new(), _input_changes: input_changes, } }); let input = state.read(cx).input.clone(); let query = input.read(cx).text(); let needle = query.trim().to_lowercase(); let mut rows = Vec::new(); for group in self.groups { let items: Vec<_> = group.items.into_iter().filter(|item| item.matches(&needle)).collect(); if items.is_empty() { continue; } if !rows.is_empty() { rows.push(Row::Separator); } if let Some(heading) = group.heading { rows.push(Row::Heading(heading)); } rows.extend(items.into_iter().map(Row::Item)); } // Per visible item: its child index in the list (for scrolling), whether the keyboard // can land on it, its value and its handler. let items: Vec<(usize, bool, SharedString, Option<SelectHandler>)> = rows .iter() .enumerate() .filter_map(|(child, row)| match row { Row::Item(item) => { Some((child, !item.disabled, item.value.clone(), item.on_select.clone())) } _ => None, }) .collect(); let first_enabled = items.iter().position(|(_, enabled, _, _)| *enabled); let (highlighted, scroll) = state.update(cx, |state, _| { // Like cmdk, a new search highlights the first match. if state.query != query { state.query = query.clone(); state.highlighted = first_enabled; state.scroll.scroll_to_item(0); } if state.highlighted.is_none_or(|ix| ix >= items.len()) { state.highlighted = first_enabled; } (state.highlighted, state.scroll.clone()) }); let items = Rc::new(items); let on_key = { let (state, input, items) = (state.clone(), input.clone(), items.clone()); move |event: &gpui::KeyDownEvent, window: &mut Window, cx: &mut App| { // Keys typed mid-composition belong to the IME: Enter commits Korean or Japanese text. if input.update(cx, |input, cx| input.marked_text_range(window, cx)).is_some() { return; } let current = state.read(cx).highlighted; match event.keystroke.key.as_str() { "up" | "down" => { let enabled = items.iter().enumerate().filter(|(_, (_, on, _, _))| *on).map(|(ix, _)| ix); let next = if event.keystroke.key == "down" { enabled.clone().find(|ix| current.is_none_or(|c| *ix > c)) } else { enabled.clone().rev().find(|ix| current.is_none_or(|c| *ix < c)) }; if let Some(next) = next { let child = items[next].0; state.update(cx, |state, cx| { state.highlighted = Some(next); state.scroll.scroll_to_item(child); cx.notify(); }); } } "enter" => { let target = current .and_then(|ix| items.get(ix)) .filter(|(_, enabled, _, _)| *enabled) .and_then(|(_, _, value, handler)| Some((value.clone(), handler.clone()?))); if let Some((value, handler)) = target { handler(&value, window, cx); } } _ => return, } // The search box would otherwise move its cursor or emit Submit. cx.stop_propagation(); } }; let theme = cx.theme(); let (accent, accent_fg, muted_fg, border) = (theme.accent, theme.accent_foreground, theme.muted_foreground, theme.border); let has_rows = !rows.is_empty(); let mut item_ix = 0; let children = rows.into_iter().map(|row| match row { Row::Heading(heading) => div() .px_2() .py(px(6.0)) .text_xs() .font_weight(FontWeight::MEDIUM) .text_color(muted_fg) .child(heading) .into_any_element(), Row::Separator => div().mx(px(-4.0)).my_1().h(px(1.0)).bg(border).into_any_element(), Row::Item(item) => { let ix = item_ix; item_ix += 1; let active = highlighted == Some(ix); let disabled = item.disabled; let hover_state = state.clone(); div() .id(("command-item", ix)) .flex() .items_center() .gap_2() .h(px(32.0)) .px_2() .rounded(px(4.0)) .text_sm() .when(active && !disabled, |this| this.bg(accent).text_color(accent_fg)) .when(disabled, |this| this.opacity(0.5).cursor_not_allowed()) .when(!disabled, |this| { let (on_select, value) = (item.on_select.clone(), item.value.clone()); this.cursor_pointer() // The pointer and the arrow keys share one highlight, as in cmdk. .on_mouse_move(move |_, _, cx| { if hover_state.read(cx).highlighted != Some(ix) { hover_state.update(cx, |state, cx| { state.highlighted = Some(ix); cx.notify(); }); } }) .on_click(move |_, window, cx| { if let Some(on_select) = &on_select { on_select(&value, window, cx); } }) }) .when_some(item.icon, |this, icon| { this.child(svg().data(icon).flex_none().size(px(16.0)).text_color(muted_fg)) }) .child(div().flex_1().truncate().child(item.label)) .when_some(item.shortcut, |this, shortcut| { this.child(div().text_xs().text_color(muted_fg).child(shortcut)) }) .when(item.checked, |this| { this.child(svg().data(CHECK).flex_none().size(px(16.0)).text_color(if active { accent_fg } else { theme.foreground })) }) .into_any_element() } }); let children: Vec<AnyElement> = children.collect(); div() .flex() .flex_col() .w_full() .overflow_hidden() .rounded(theme.radius) .bg(theme.background) .text_color(theme.foreground) .capture_key_down(on_key) .child( div() .flex() .items_center() .gap_2() .h(px(40.0)) .px_3() .border_b_1() .border_color(border) .child(svg().data(SEARCH).flex_none().size(px(16.0)).text_color(muted_fg)) .child(input), ) .child( div() .id(self.id) .max_h(self.max_height) .overflow_y_scroll() .track_scroll(&scroll) .p_1() .when(!has_rows, |this| { this.child(div().py_6().text_center().text_sm().text_color(muted_fg).child(self.empty)) }) .children(children), ) } } /// A [`Command`] in a modal over the page, like shadcn/ui's `CommandDialog`. The parent owns /// `open`; Escape or a click outside asks to close. The search box is focused on open. #[derive(IntoElement)] pub struct CommandDialog { id: ElementId, open: bool, command: Command, trigger: Option<AnyElement>, on_open_change: Option<OpenChangeHandler>, } impl CommandDialog { pub fn new(id: impl Into<ElementId>, open: bool, command: Command) -> Self { Self { id: id.into(), open, command, trigger: None, on_open_change: None, } } /// Clicking this element asks the parent to open the dialog. pub fn trigger(mut self, trigger: impl IntoElement) -> Self { self.trigger = Some(trigger.into_any_element()); self } /// Receives the *next* open value. pub fn on_open_change( mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static, ) -> Self { self.on_open_change = Some(Rc::new(handler)); self } } impl RenderOnce for CommandDialog { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let panel = div() .w(px(512.0)) .rounded(theme.radius) .border_1() .border_color(theme.border) .bg(theme.background) .shadow_lg() .child(self.command.auto_focus(true)); Modal::new(self.id, self.open) .when_some(self.trigger, |this, trigger| this.trigger(trigger)) .when_some(self.on_open_change, |this, handler| { this.on_open_change(move |open, window, cx| handler(open, window, cx)) }) .panel(panel) } }Register the module
// src/ui/mod.rs pub mod command;
Usage
use crate::ui::command::*;API Reference
CommandItem
One row. Enter or a click runs on_select with the item's value.
CommandItem::new(label: impl Into<SharedString>) -> Self.value(value: impl Into<SharedString>)What on_select receives. Defaults to the label.
.keywords(keywords: impl IntoIterator<Item = impl Into<SharedString>>)Extra words the search matches, e.g. "preferences" for "Settings".
.icon(svg: &'static [u8])A 24x24 SVG (for example a Lucide icon), drawn at 16px before the label.
.shortcut(shortcut: impl Into<SharedString>)Right-aligned hint such as "Ctrl+P". Display only: bind the keys in your app.
.checked(checked: bool)Draws a check mark on the right, for lists that show the current choice.
.disabled(disabled: bool).on_select(handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static)CommandGroup
Items under an optional heading. Groups with no matches are hidden, and a separator is drawn between the visible ones.
CommandGroup::new(heading: impl Into<SharedString>) -> SelfCommandGroup::untitled() -> Self.item(item: CommandItem).items(items: impl IntoIterator<Item = CommandItem>)Command
The search box and filtered list.
Command::new(id: impl Into<ElementId>) -> Self.placeholder(placeholder: impl Into<SharedString>).empty(empty: impl Into<SharedString>)Shown when nothing matches the search.
.group(group: CommandGroup).max_height(height: impl Into<Pixels>)The list scrolls past this height.
.auto_focus(auto_focus: bool)Focus the search box when the command appears. Popovers and modals focus their own panel two frames after opening (deferred content joins the dispatch tree late), so this waits one frame longer to win.
CommandDialog
A [Command] in a modal over the page, like shadcn/ui's CommandDialog. The parent owns open; Escape or a click outside asks to close. The search box is focused on open.
CommandDialog::new(id: impl Into<ElementId>, open: bool, command: Command) -> Self.trigger(trigger: impl IntoElement)Clicking this element asks the parent to open the dialog.
.on_open_change(handler: impl Fn(&bool, &mut Window, &mut App) + 'static)Receives the *next* open value.