add select component built on menu

This commit is contained in:
2026-11-01 12:06:21 +07:00
parent ac4a0f2add
commit bbb56fdda7
8 changed files with 654 additions and 12 deletions
+3
View File
@@ -18,6 +18,9 @@ pub mod switch;
#[cfg(feature = "radio")]
pub mod radio;
#[cfg(feature = "select")]
pub mod select;
#[cfg(feature = "toggle")]
pub mod toggle;
+18 -11
View File
@@ -7,7 +7,7 @@ use gpui::{
Entity, InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent,
ParentElement as _, Pixels, RenderOnce, Role, ScrollHandle, SharedString,
StatefulInteractiveElement as _, Styled as _, Window, anchored, canvas, deferred, div,
ease_out_quint, px, relative,
ease_out_quint, px,
};
use gpui_native_icons::{IconRole, icon as icon_glyph};
use gpui_native_theme::ActiveTheme as _;
@@ -144,6 +144,7 @@ struct MenuChrome {
pub struct Menu {
id: ElementId,
open: bool,
initial_selection: Option<usize>,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
trigger: Option<TriggerFn>,
@@ -159,6 +160,7 @@ impl Menu {
Self {
id: id.into(),
open: false,
initial_selection: None,
a11y_label: None,
on_change: None,
trigger: None,
@@ -166,6 +168,12 @@ impl Menu {
}
}
/// Sets the row keyboard-highlighted when the menu opens.
pub fn initial_selection(mut self, index: usize) -> Self {
self.initial_selection = Some(index);
self
}
/// Sets the current open state.
pub fn open(mut self, open: bool) -> Self {
self.open = open;
@@ -310,6 +318,8 @@ impl RenderOnce for Menu {
let selected = if *was_open.read(cx) {
*selection.read(cx)
} else if let Some(requested) = self.initial_selection {
requested.min(items.len().saturating_sub(1))
} else {
let first = items.iter().position(|item| item.selectable()).unwrap_or(0);
selection.update(cx, |selection, _| *selection = first);
@@ -339,7 +349,6 @@ impl RenderOnce for Menu {
.aria_label(label)
.mt_1()
.min_w_40()
.max_h(relative(0.75))
.p_1()
.bg(chrome.surface)
.text_color(chrome.foreground)
@@ -490,15 +499,6 @@ fn render_item(
}
}
})
.when_some(checked, |row, checked| {
row.child(div().flex_none().when(checked, |slot| {
slot.child(
icon_glyph(IconRole::Check)
.size(chrome.icon_size * 0.75)
.color(label_color),
)
}))
})
.when_some(icon_role, |row, role| {
row.child(icon_glyph(role).size(chrome.icon_size).color(label_color))
})
@@ -519,6 +519,13 @@ fn render_item(
.child(shortcut),
)
})
.when(checked == Some(true), |row| {
row.child(
icon_glyph(IconRole::Check)
.size(chrome.icon_size * 0.75)
.color(label_color),
)
})
.into_any_element()
}
}
+277
View File
@@ -0,0 +1,277 @@
use std::rc::Rc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window,
};
use gpui_native_icons::{IconRole, icon};
use gpui_native_theme::{ActiveTheme as _, Size};
use crate::common::{Sizable, StyledExt, h_flex};
use crate::menu::{Menu, MenuItem};
/// Reports the value the user chose. `None` means the select holds no value.
pub type SelectHandler<T> = Rc<dyn Fn(Option<T>, &mut Window, &mut App)>;
/// Select option for a [`Select`] control.
#[derive(Clone)]
pub struct SelectOption<T> {
value: T,
label: SharedString,
icon: Option<IconRole>,
}
impl<T> SelectOption<T> {
/// Creates a choice showing `label`; picking it reports `value`.
pub fn new<L>(value: T, label: L) -> Self
where
L: Into<SharedString>,
{
Self {
value,
label: label.into(),
icon: None,
}
}
/// Sets a leading icon for the option's row.
pub fn icon(mut self, role: IconRole) -> Self {
self.icon = Some(role);
self
}
}
impl<T, L> From<(T, L)> for SelectOption<T>
where
L: Into<SharedString>,
{
fn from((value, label): (T, L)) -> Self {
Self {
value,
label: label.into(),
icon: None,
}
}
}
/// A control that shows the chosen value and opens a menu of the choices.
#[derive(IntoElement)]
pub struct Select<T>
where
T: Clone + PartialEq + 'static,
{
id: ElementId,
options: Vec<SelectOption<T>>,
selected: Option<T>,
placeholder: SharedString,
a11y_label: Option<SharedString>,
size: Size,
style: StyleRefinement,
on_change: Option<SelectHandler<T>>,
}
impl<T> Select<T>
where
T: Clone + PartialEq + 'static,
{
/// Creates a closed select holding no value.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
options: Vec::new(),
selected: None,
placeholder: SharedString::from("Select..."),
a11y_label: None,
size: Size::default(),
style: StyleRefinement::default(),
on_change: None,
}
}
/// Sets the choice.
pub fn options<I>(mut self, options: I) -> Self
where
I: IntoIterator,
I::Item: Into<SelectOption<T>>,
{
self.options = options.into_iter().map(Into::into).collect();
self
}
/// Sets the current value. `None` shows the placeholder.
pub fn selected(mut self, selected: impl Into<Option<T>>) -> Self {
self.selected = selected.into();
self
}
/// Sets the text shown while no value is chosen.
pub fn placeholder<L>(mut self, placeholder: L) -> Self
where
L: Into<SharedString>,
{
self.placeholder = placeholder.into();
self
}
/// Reports the chosen value, when the user activates an option.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(Option<T>, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
/// Overrides the trigger's accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl<T> Sizable for Select<T>
where
T: Clone + PartialEq + 'static,
{
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl<T> gpui::Styled for Select<T>
where
T: Clone + PartialEq + 'static,
{
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl<T> RenderOnce for Select<T>
where
T: Clone + PartialEq + 'static,
{
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let metrics = theme.sizes.resolve(self.size);
let border = theme.colors.border;
let ring = theme.colors.ring;
let input = theme.colors.input;
let muted = theme.colors.muted;
let foreground = theme.colors.foreground;
let muted_foreground = theme.colors.muted_foreground;
let radius = theme.radius.control;
let icon_size = metrics.icon_size * 0.75;
let label = self
.a11y_label
.clone()
.unwrap_or_else(|| self.placeholder.clone());
let open = window.with_element_namespace(self.id.clone(), |window| {
window
.use_keyed_state("select-open", cx, |_, _| false)
.clone()
});
let is_open = *open.read(cx);
let selected_index = self.selected.as_ref().and_then(|value| {
self.options
.iter()
.position(|option| &option.value == value)
});
let trigger_options = self.options.clone();
let trigger_selected = self.selected.clone();
let trigger_placeholder = self.placeholder.clone();
let trigger_id = self.id.clone();
let trigger_label = label.clone();
let trigger_style = self.style;
let trigger = move |_window: &mut Window, _cx: &mut App| {
let text = trigger_selected
.as_ref()
.and_then(|value| {
trigger_options
.iter()
.find(|option| &option.value == value)
.map(|option| option.label.clone())
})
.unwrap_or_else(|| trigger_placeholder.clone());
h_flex()
.id((trigger_id.clone(), "select-trigger"))
.role(Role::ComboBox)
.aria_label(trigger_label.clone())
.cursor_pointer()
.justify_between()
.gap_2()
.w_full()
.h(metrics.input_height)
.px(metrics.padding_x / 2.0)
.rounded(radius)
.border_1()
.border_color(if is_open { ring } else { border })
.bg(input)
.text_size(metrics.text_size)
.text_color(if trigger_selected.is_some() {
foreground
} else {
muted_foreground
})
.hover(|style| style.bg(muted))
.child(text)
.child(
icon(IconRole::ChevronDown)
.size(icon_size)
.color(muted_foreground),
)
.refine_style(&trigger_style)
.into_any_element()
};
let open_for_items = open.clone();
let items = move |_window: &mut Window, _cx: &mut App| {
self.options
.iter()
.map(|option| {
let is_selected = self.selected.as_ref() == Some(&option.value);
let handler = {
let open = open_for_items.clone();
let value = option.value.clone();
let on_change = self.on_change.clone();
move |window: &mut Window, cx: &mut App| {
open.update(cx, |open, _| *open = false);
if let Some(on_change) = &on_change {
on_change(Some(value.clone()), window, cx);
}
}
};
let mut row = MenuItem::new(option.label.clone());
if let Some(role) = option.icon {
row = row.icon(role);
}
row.checked(is_selected).handler(handler)
})
.collect()
};
let menu = Menu::new(self.id)
.open(is_open)
.on_change(move |next, _window, cx| {
open.update(cx, |open, _| *open = next);
})
.trigger(trigger)
.items(items);
menu.when_some(selected_index, |menu, index| menu.initial_selection(index))
}
}