A trigger showing the chosen value that opens a list of options, with groups, separators and keyboard navigation.
use gpui::{div, prelude::*, px, Context, SharedString, Window};
use crate::ui::select::{Select, SelectOption};
#[derive(Default)]
pub struct FruitSelect {
fruit: Option<SharedString>,
open: bool,
}
impl Render for FruitSelect {
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(310.0)).child(
Select::new("fruit", self.fruit.clone(), self.open)
.placeholder("Select a fruit")
.label("Fruits")
.option(SelectOption::new("apple", "Apple"))
.option(SelectOption::new("banana", "Banana"))
.option(SelectOption::new("blueberry", "Blueberry"))
.option(SelectOption::new("grapes", "Grapes"))
.separator()
.label("Vegetables")
.option(SelectOption::new("carrot", "Carrot"))
.option(SelectOption::new("potato", "Potato").disabled(true))
.on_change(cx.listener(|this, value: &SharedString, _, cx| {
this.fruit = Some(value.clone());
cx.notify();
}))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
})),
)
}
}Installation
Copies src/ui/select.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/select.rs.src/ui/select.rs use std::rc::Rc; use gpui::{ div, point, prelude::*, px, svg, App, BoxShadow, ElementId, FocusHandle, FontWeight, Pixels, ScrollHandle, SharedString, Window, }; use crate::theme::{focus_visible, ActiveTheme, FocusRing}; use crate::ui::popover::{focus_when_mounted, return_focus, Align, Popover, Side}; use crate::icons::{CHECK, CHEVRON_DOWN}; type ChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App) + 'static>; type OpenChangeHandler = Rc<dyn Fn(&bool, &mut Window, &mut App) + 'static>; /// One choice. `value` is what `on_change` receives; `label` is what the user sees. pub struct SelectOption { value: SharedString, label: SharedString, disabled: bool, } impl SelectOption { pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self { Self { value: value.into(), label: label.into(), disabled: false, } } pub fn disabled(mut self, disabled: bool) -> Self { self.disabled = disabled; self } } enum SelectEntry { Option(SelectOption), Label(SharedString), Separator, } /// A trigger showing the chosen value and a list to pick from. The parent owns `value` and `open`. /// The trigger is a tab stop; Enter, Space or the arrow keys open the list. #[derive(IntoElement)] pub struct Select { id: ElementId, value: Option<SharedString>, open: bool, entries: Vec<SelectEntry>, placeholder: SharedString, width: Pixels, disabled: bool, invalid: bool, focus_handle: Option<FocusHandle>, on_change: Option<ChangeHandler>, on_open_change: Option<OpenChangeHandler>, } /// The highlighted row is transient keyboard/pointer state, and both focus handles have to /// outlive a frame for keys to reach them, so they live here rather than with the parent. struct SelectState { trigger_focus: FocusHandle, list_focus: FocusHandle, /// Index into the entries. highlighted: Option<usize>, scroll: ScrollHandle, was_open: bool, } impl Select { pub fn new(id: impl Into<ElementId>, value: Option<SharedString>, open: bool) -> Self { Self { id: id.into(), value, open, entries: Vec::new(), placeholder: "Select an option".into(), width: px(180.0), disabled: false, invalid: false, focus_handle: None, on_change: None, on_open_change: None, } } pub fn option(mut self, option: SelectOption) -> Self { self.entries.push(SelectEntry::Option(option)); self } /// A heading for the options that follow it. pub fn label(mut self, label: impl Into<SharedString>) -> Self { self.entries.push(SelectEntry::Label(label.into())); self } pub fn separator(mut self) -> Self { self.entries.push(SelectEntry::Separator); self } /// Shown on the trigger while nothing is chosen. pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self { self.placeholder = placeholder.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 Select { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let disabled = self.disabled; let open = self.open && !disabled; let selected = self.entries.iter().position(|entry| { matches!(entry, SelectEntry::Option(option) if Some(&option.value) == self.value.as_ref()) }); // Entry index and value of each option the keyboard can land on. let enabled: Rc<Vec<(usize, SharedString)>> = Rc::new( self.entries .iter() .enumerate() .filter_map(|(ix, entry)| match entry { SelectEntry::Option(option) if !option.disabled => Some((ix, option.value.clone())), _ => None, }) .collect(), ); let state = window.use_keyed_state(self.id.clone(), cx, |_, cx| SelectState { trigger_focus: cx.focus_handle(), list_focus: cx.focus_handle(), highlighted: None, scroll: ScrollHandle::new(), was_open: false, }); let (trigger_focus, list_focus, highlighted, scroll, just_opened) = state.update(cx, |state, _| { let just_opened = open && !state.was_open; state.was_open = open; if just_opened { // Opening lands on the current choice, as Radix does. state.highlighted = selected.or(enabled.first().map(|(ix, _)| *ix)); if let Some(ix) = state.highlighted { state.scroll.scroll_to_item(ix); } } ( state.trigger_focus.clone(), state.list_focus.clone(), state.highlighted, state.scroll.clone(), just_opened, ) }); let trigger_focus = self.focus_handle.unwrap_or(trigger_focus).tab_stop(!disabled); if just_opened { // The popover focuses its own panel once mounted; the list waits one frame longer // so the arrow keys reach it. let list_focus = list_focus.clone(); window.on_next_frame(move |window, _| focus_when_mounted(list_focus, window)); } // Like CSS `:focus-visible`: the ring shows for keyboard use and after the form moves focus // here, not after a click. let trigger_focused = focus_visible(&trigger_focus, window, cx); let theme = cx.theme(); let (accent, accent_fg, muted_fg, border, foreground) = (theme.accent, theme.accent_foreground, theme.muted_foreground, theme.border, theme.foreground); let (on_change, on_open_change) = (self.on_change, self.on_open_change); // Picking an option hands focus back to the trigger, so the keyboard can reopen it. let choose: Rc<dyn Fn(&SharedString, &mut Window, &mut App)> = { let (on_change, on_open_change, trigger_focus) = (on_change.clone(), on_open_change.clone(), trigger_focus.clone()); Rc::new(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); } window.focus(&trigger_focus, cx); }) }; let current = selected.and_then(|ix| match &self.entries[ix] { SelectEntry::Option(option) => Some(option.label.clone()), _ => None, }); let trigger = div() .id("select-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, trigger_focused) { (true, _) => theme.destructive, (false, true) => theme.ring, (false, false) => theme.input, }) .bg(theme.background) .text_sm() .map(|this| { // GPUI shadows fill the element's whole shape; the opaque background keeps // the focus ring to the outside of the border. if trigger_focused { let ring = if self.invalid { theme.destructive.opacity(0.2) } else { theme.ring.opacity(0.5) }; this.shadow(vec![BoxShadow { color: ring, offset: point(px(0.), px(0.)), blur_radius: px(0.), spread_radius: px(3.), inset: false, }]) } else { this.shadow_xs() } }) .when(disabled, |this| this.opacity(0.5).cursor_not_allowed()) .when(!disabled, |this| this.cursor_pointer().hover(move |style| style.bg(accent))) .child(match current { Some(label) => div().truncate().child(label), None => div().truncate().text_color(muted_fg).child(self.placeholder), }) .child(svg().data(CHEVRON_DOWN).flex_none().size(px(16.0)).text_color(muted_fg).opacity(0.5)); let rows = self.entries.into_iter().enumerate().map(|(ix, entry)| match entry { SelectEntry::Label(label) => div() .px_2() .py(px(6.0)) .text_xs() .text_color(muted_fg) .child(label) .into_any_element(), SelectEntry::Separator => div().mx(px(-4.0)).my_1().h(px(1.0)).bg(border).into_any_element(), SelectEntry::Option(option) => { let active = highlighted == Some(ix) && !option.disabled; let is_selected = selected == Some(ix); let hover_state = state.clone(); let choose = choose.clone(); let value = option.value.clone(); div() .id(("select-option", ix)) .relative() .flex() .items_center() .h(px(32.0)) .pl_2() .pr(px(32.0)) .rounded(px(4.0)) .text_sm() .when(active, |this| this.bg(accent).text_color(accent_fg)) .when(option.disabled, |this| this.opacity(0.5).cursor_not_allowed()) .when(!option.disabled, |this| { this.cursor_pointer() // The pointer and the arrow keys share one highlight, as in Radix. .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| choose(&value, window, cx)) }) .child(div().truncate().child(option.label)) .when(is_selected, |this| { this.child( svg() .data(CHECK) .absolute() .right_2() .size(px(16.0)) .text_color(if active { accent_fg } else { foreground }), ) }) .into_any_element() } }); let rows: Vec<_> = rows.collect(); let list = { let (state, enabled, choose) = (state.clone(), enabled.clone(), choose.clone()); div() .id("select-list") .track_focus(&list_focus) .max_h(px(300.0)) .overflow_y_scroll() .track_scroll(&scroll) .p_1() .font_weight(FontWeight::NORMAL) .on_key_down(move |event, window, cx| { let current = state.read(cx).highlighted; match event.keystroke.key.as_str() { "up" | "down" => { let next = if event.keystroke.key == "down" { enabled.iter().map(|(ix, _)| *ix).find(|ix| current.is_none_or(|c| *ix > c)) } else { enabled.iter().map(|(ix, _)| *ix).rev().find(|ix| current.is_none_or(|c| *ix < c)) }; if let Some(next) = next { state.update(cx, |state, cx| { state.highlighted = Some(next); state.scroll.scroll_to_item(next); cx.notify(); }); } } "enter" | "space" => { let value = enabled.iter().find(|(ix, _)| Some(*ix) == current).map(|(_, v)| v.clone()); if let Some(value) = value { choose(&value, window, cx); } } _ => return, } cx.stop_propagation(); }) .children(rows) }; 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 = trigger_focus.clone(); this.on_open_change(move |open, window, cx| { handler(open, window, cx); return_focus(*open, &focus, window, cx); }) }) .child(list); // The trigger's focus is tracked around the whole popover, which the list renders inside // even though it floats elsewhere: focus in the list still counts as in the select, so // a form doesn't see the select blur when it opens. div() .flex() .when(!disabled, |this| { let open_handler = on_open_change; this.track_focus(&trigger_focus) .end_visible_focus_on_press(&trigger_focus, cx) .on_key_down(move |event, window, cx| { if !open && matches!(event.keystroke.key.as_str(), "down" | "up" | "enter" | "space") { if let Some(handler) = &open_handler { handler(&true, window, cx); } cx.stop_propagation(); } }) }) .child(popover) } }Register the module
// src/ui/mod.rs pub mod select;
Usage
use crate::ui::select::*;API Reference
SelectOption
One choice. value is what on_change receives; label is what the user sees.
SelectOption::new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self.disabled(disabled: bool)Select
A trigger showing the chosen value and a list to pick from. The parent owns value and open. The trigger is a tab stop; Enter, Space or the arrow keys open the list.
Select::new(id: impl Into<ElementId>, value: Option<SharedString>, open: bool) -> Self.option(option: SelectOption).label(label: impl Into<SharedString>)A heading for the options that follow it.
.separator().placeholder(placeholder: impl Into<SharedString>)Shown on the trigger while nothing is chosen.
.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.