A select whose list has a search box to filter the options.
use gpui::{div, prelude::*, px, Context, SharedString, Window};
use crate::ui::combobox::Combobox;
#[derive(Default)]
pub struct FrameworkPicker {
framework: Option<SharedString>,
open: bool,
}
impl Render for FrameworkPicker {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// Top-aligned so the list has room to open downward in the preview.
div().h(px(300.0)).child(
Combobox::new("framework", self.framework.clone(), self.open)
.placeholder("Select framework...")
.search_placeholder("Search framework...")
.empty("No framework found.")
.option("next.js", "Next.js")
.option("sveltekit", "SvelteKit")
.option("nuxt.js", "Nuxt.js")
.option("remix", "Remix")
.option("astro", "Astro")
.on_change(cx.listener(|this, value: &SharedString, _, cx| {
this.framework = Some(value.clone());
cx.notify();
}))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
})),
)
}
}Installation
Copies src/ui/combobox.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/combobox.rs.src/ui/combobox.rs use std::{rc::Rc, sync::Arc}; use gpui::{ div, point, prelude::*, px, svg, App, BoxShadow, ElementId, FocusHandle, FontWeight, KeyDownEvent, Pixels, SharedString, Window, }; use crate::theme::{focus_visible, ActiveTheme, FocusRing}; use crate::ui::command::{Command, CommandGroup, CommandItem}; use crate::ui::popover::{return_focus, Align, Popover, Side}; use crate::icons::CHEVRONS_UP_DOWN; type ChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App) + 'static>; type OpenChangeHandler = Rc<dyn Fn(&bool, &mut Window, &mut App) + 'static>; /// A select whose list has a search box: a [`Popover`] holding a [`Command`]. /// The parent owns both `value` and `open`. The trigger is a tab stop; Enter, Space or the /// down arrow open the list, and picking an option hands focus back to the trigger. #[derive(IntoElement)] pub struct Combobox { id: ElementId, value: Option<SharedString>, open: bool, options: Vec<(SharedString, SharedString)>, placeholder: SharedString, search_placeholder: SharedString, empty: SharedString, width: Pixels, disabled: bool, invalid: bool, focus_handle: Option<FocusHandle>, on_change: Option<ChangeHandler>, on_open_change: Option<OpenChangeHandler>, } impl Combobox { pub fn new(id: impl Into<ElementId>, value: Option<SharedString>, open: bool) -> Self { Self { id: id.into(), value, open, options: Vec::new(), placeholder: "Select an option...".into(), search_placeholder: "Search...".into(), empty: "No results found.".into(), width: px(200.0), disabled: false, invalid: false, focus_handle: None, on_change: None, on_open_change: None, } } /// `value` is what `on_change` receives; `label` is what the user sees and searches. pub fn option(mut self, value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self { self.options.push((value.into(), label.into())); self } /// Shown on the trigger while nothing is chosen. pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self { self.placeholder = placeholder.into(); self } pub fn search_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self { self.search_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 } /// Width of both the trigger and the list. pub fn width(mut self, width: impl Into<Pixels>) -> Self { self.width = width.into(); self } pub fn disabled(mut self, disabled: bool) -> Self { self.disabled = disabled; self } /// Draws a destructive border and ring, like `aria-invalid` on shadcn/ui's trigger. pub fn invalid(mut self, invalid: bool) -> Self { self.invalid = invalid; self } /// Focus the trigger through this handle, such as `form.focus_handle(..)` or one from /// `cx.focus_handle()`, to move focus to it from code. Without one it keeps its own. pub fn focus_handle(mut self, handle: FocusHandle) -> Self { self.focus_handle = Some(handle); self } /// Receives the chosen option's value. pub fn on_change( mut self, handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static, ) -> Self { self.on_change = Some(Rc::new(handler)); 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 Combobox { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let disabled = self.disabled; let open = self.open && !disabled; // A RenderOnce combobox is rebuilt every frame, but focus has to stay on the same // handle, so it keeps its own under its id unless the caller passes one. let focus = self .focus_handle .unwrap_or_else(|| { let key = ElementId::NamedChild(Arc::new(self.id.clone()), "focus".into()); window.use_keyed_state(key, cx, |_, cx| cx.focus_handle()).read(cx).clone() }) .tab_stop(!disabled); // Like CSS `:focus-visible`: the ring shows for keyboard use and after the form moves focus // here, not after a click. let focus_visible = focus_visible(&focus, window, cx); let theme = cx.theme(); let current = self .value .as_ref() .and_then(|value| self.options.iter().find(|(v, _)| v == value)) .map(|(_, label)| label.clone()); let (on_change, on_open_change) = (self.on_change, self.on_open_change); let ring = if self.invalid { Some(theme.destructive.opacity(0.2)) } else { focus_visible.then(|| theme.ring.opacity(0.5)) }; let trigger = div() .id("combobox-trigger") .flex() .items_center() .justify_between() .gap_2() .w(self.width) .h(px(36.0)) .px_3() .rounded(theme.radius) .border_1() .border_color(match (self.invalid, focus_visible) { (true, _) => theme.destructive, (false, true) => theme.ring, (false, false) => theme.input, }) .bg(theme.background) // GPUI shadows fill the element's whole shape; the opaque background keeps the // focus ring to the outside of the border. .map(|this| match ring { Some(color) => this.shadow(vec![BoxShadow { color, offset: point(px(0.), px(0.)), blur_radius: px(0.), spread_radius: px(3.), inset: false, }]), None => this.shadow_xs(), }) .text_sm() .font_weight(FontWeight::MEDIUM) .text_color(theme.foreground) .when(disabled, |this| this.opacity(0.5).cursor_not_allowed()) .when(!disabled, |this| { let hover_bg = theme.accent; this.cursor_pointer().hover(move |style| style.bg(hover_bg)) }) .child(div().truncate().child(current.unwrap_or(self.placeholder))) .child( svg() .data(CHEVRONS_UP_DOWN) .flex_none() .size(px(16.0)) .text_color(theme.foreground) .opacity(0.5), ); let items = self.options.into_iter().map(|(value, label)| { let (on_change, on_open_change, focus) = (on_change.clone(), on_open_change.clone(), focus.clone()); CommandItem::new(label) .checked(self.value.as_ref() == Some(&value)) .value(value) .on_select(move |value, window, cx| { if let Some(on_change) = &on_change { on_change(value, window, cx); } if let Some(on_open_change) = &on_open_change { on_open_change(&false, window, cx); } // Back to the trigger, so the keyboard can reopen the list. window.focus(&focus, cx); }) }); let command = Command::new("combobox-command") .placeholder(self.search_placeholder) .empty(self.empty) .auto_focus(true) .group(CommandGroup::untitled().items(items)); let popover = Popover::new(self.id, open) .side(Side::Bottom) .align(Align::Start) .width(self.width) .padded(false) .trigger(trigger) .when_some(on_open_change.clone().filter(|_| !disabled), |this, handler| { let focus = focus.clone(); this.on_open_change(move |open, window, cx| { handler(open, window, cx); return_focus(*open, &focus, window, cx); }) }) .child(command); // The trigger's focus is tracked around the whole popover, which the list renders inside // even though it floats elsewhere: typing in the search box still counts as being in the // combobox, so a form doesn't see it blur when it opens. div() .flex() .when(!disabled, |this| { this.track_focus(&focus) .end_visible_focus_on_press(&focus, cx) .on_key_down(move |event: &KeyDownEvent, window, cx| { // Opening moves focus into the search box, so the key's release can't // also click the trigger and close the list again. if !open && matches!(event.keystroke.key.as_str(), "down" | "enter" | "space") { if let Some(handler) = &on_open_change { handler(&true, window, cx); } cx.stop_propagation(); } }) }) .child(popover) } }Register the module
// src/ui/mod.rs pub mod combobox;
Usage
use crate::ui::combobox::*;API Reference
Combobox
A select whose list has a search box: a [Popover] holding a [Command]. The parent owns both value and open. The trigger is a tab stop; Enter, Space or the down arrow open the list, and picking an option hands focus back to the trigger.
Combobox::new(id: impl Into<ElementId>, value: Option<SharedString>, open: bool) -> Self.option(value: impl Into<SharedString>, label: impl Into<SharedString>)value is what on_change receives; label is what the user sees and searches.
.placeholder(placeholder: impl Into<SharedString>)Shown on the trigger while nothing is chosen.
.search_placeholder(placeholder: impl Into<SharedString>).empty(empty: impl Into<SharedString>)Shown when nothing matches the search.
.width(width: impl Into<Pixels>)Width of both the trigger and the list.
.disabled(disabled: bool).invalid(invalid: bool)Draws a destructive border and ring, like aria-invalid on shadcn/ui's trigger.
.focus_handle(handle: FocusHandle)Focus the trigger through this handle, such as form.focus_handle(..) or one from cx.focus_handle(), to move focus to it from code. Without one it keeps its own.
.on_change(handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static)Receives the chosen option's value.
.on_open_change(handler: impl Fn(&bool, &mut Window, &mut App) + 'static)Receives the *next* open value.