use std::{cell::RefCell, rc::Rc, time::Duration};
use arc_motion::{
ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, arc_spring, arc_spring_with_options,
arc_transition, is_reduced_motion, motion_now, spring::SpringOptions,
};
use arc_tokens::{
ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, Typography, oklab_mix,
};
use gpui_kit::{
App, Bounds, ElementId, Entity, Focusable as _, Hsla, IntoElement, KeyDownEvent, MouseButton,
MouseDownEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
TestSupportExt as _, Window,
assets::IconName,
base::{Button as BaseButton, StyledExt as _},
canvas,
component::{
Icon,
input::{Input as KitInput, InputState},
},
deferred, div, point,
prelude::*,
px,
};
type ComboboxChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
pub const COMBOBOX_TEXT_EM_PX: f32 = 14.0;
pub const COMBOBOX_OPTION_HEIGHT_PX: f32 = 32.0;
pub const COMBOBOX_EMPTY_HEIGHT_PX: f32 = 38.0;
pub const COMBOBOX_MAX_LISTBOX_HEIGHT_PX: f32 = 260.0;
pub fn filter_combobox_options(options: &[ComboboxOption], query: &str) -> Vec<usize> {
let norm = query.trim().to_lowercase();
if norm.is_empty() {
return (0..options.len()).collect();
}
options
.iter()
.enumerate()
.filter_map(|(idx, opt)| {
let label_match = opt.label.to_lowercase().contains(&norm);
let kw_match = opt
.keywords
.iter()
.any(|kw| kw.to_lowercase().contains(&norm));
if label_match || kw_match {
Some(idx)
} else {
None
}
})
.collect()
}
pub fn combobox_target_height(filtered_count: usize) -> f32 {
if filtered_count == 0 {
COMBOBOX_EMPTY_HEIGHT_PX
} else {
(filtered_count as f32 * COMBOBOX_OPTION_HEIGHT_PX).min(COMBOBOX_MAX_LISTBOX_HEIGHT_PX)
}
}
pub fn combobox_settle_sample(elapsed: f64, has_value: bool, reduced: bool) -> (f32, f32) {
if reduced {
return (1.0, 0.0);
}
if has_value {
let t = (elapsed / 0.24).clamp(0.0, 1.0) as f32;
let e = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t);
let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), false);
let op = (e * blur.opacity_multiplier).clamp(0.0, 1.0);
let y = 0.35 * COMBOBOX_TEXT_EM_PX * (1.0 - e);
(op, y)
} else {
let t = (elapsed / 0.16).clamp(0.0, 1.0) as f32;
let e = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t);
(e.clamp(0.0, 1.0), 0.0)
}
}
pub fn combobox_empty_sample(elapsed: f64, reduced: bool) -> (f32, f32) {
if reduced {
return (1.0, 0.0);
}
let t = (elapsed / 0.24).clamp(0.0, 1.0) as f32;
let e = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t);
let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), false);
(
(e * blur.opacity_multiplier).clamp(0.0, 1.0),
4.0 * (1.0 - e),
)
}
pub fn next_enabled_combobox_match(
options: &[ComboboxOption],
filtered: &[usize],
current_filtered_pos: Option<usize>,
step: isize,
) -> Option<usize> {
let enabled_positions: Vec<usize> = filtered
.iter()
.enumerate()
.filter_map(|(pos, &opt_idx)| (!options[opt_idx].disabled).then_some(pos))
.collect();
if enabled_positions.is_empty() {
return None;
}
let len = enabled_positions.len() as isize;
let cur_slot =
current_filtered_pos.and_then(|p| enabled_positions.iter().position(|&ep| ep == p));
let next_slot = match cur_slot {
Some(slot) => (slot as isize + step).rem_euclid(len) as usize,
None => {
if step >= 0 {
0
} else {
(len - 1) as usize
}
}
};
Some(enabled_positions[next_slot])
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ComboboxOption {
pub value: SharedString,
pub label: SharedString,
pub disabled: bool,
pub keywords: Vec<SharedString>,
}
impl ComboboxOption {
pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
value: value.into(),
label: label.into(),
disabled: false,
keywords: Vec::new(),
}
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn keyword(mut self, keyword: impl Into<SharedString>) -> Self {
self.keywords.push(keyword.into());
self
}
pub fn keywords<I, S>(mut self, keywords: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<SharedString>,
{
self.keywords.extend(keywords.into_iter().map(Into::into));
self
}
}
#[derive(Clone)]
struct ComboboxInternal {
open: bool,
opened_at_secs: f64,
uncontrolled_value: SharedString,
settled_value: SharedString,
settle_started_at_secs: f64,
empty_entered_at_secs: Option<f64>,
last_query: SharedString,
active_filtered_pos: Option<usize>,
control_hovered: bool,
clear_pressed: bool,
query_input: Entity<InputState>,
control_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
popover_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
}
impl ComboboxInternal {
fn new(
default_value: SharedString,
placeholder: SharedString,
now: f64,
window: &mut Window,
cx: &mut App,
) -> Self {
let query_input = cx.new(|cx| InputState::new(window, cx).placeholder(placeholder));
Self {
open: false,
opened_at_secs: now - 10.0,
uncontrolled_value: default_value.clone(),
settled_value: default_value,
settle_started_at_secs: now - 10.0,
empty_entered_at_secs: None,
last_query: "".into(),
active_filtered_pos: None,
control_hovered: false,
clear_pressed: false,
query_input,
control_bounds: Rc::new(RefCell::new(None)),
popover_bounds: Rc::new(RefCell::new(None)),
}
}
}
fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
let rad = angle_deg.to_radians();
let cos_a = rad.cos();
let sin_a = rad.sin();
let pts = [(-4.0_f32, -2.0_f32), (0.0, 2.0), (4.0, -2.0)];
let mut builder = PathBuilder::stroke(px(1.75));
for (i, (lx, ly)) in pts.iter().enumerate() {
let rx = cx + lx * cos_a - ly * sin_a;
let ry = cy + lx * sin_a + ly * cos_a;
let p = point(px(rx), px(ry));
if i == 0 {
builder.move_to(p);
} else {
builder.line_to(p);
}
}
if let Ok(path) = builder.build() {
window.paint_path(path, color);
}
}
fn paint_check(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
let pts = [(-4.5_f32, 0.2_f32), (-1.4, 3.3), (4.8, -3.2)];
let mut builder = PathBuilder::stroke(px(1.75));
for (i, (lx, ly)) in pts.iter().enumerate() {
let p = point(px(cx + lx), px(cy + ly));
if i == 0 {
builder.move_to(p);
} else {
builder.line_to(p);
}
}
if let Ok(path) = builder.build() {
window.paint_path(path, color);
}
}
#[derive(IntoElement)]
pub struct Combobox {
id: ElementId,
label: SharedString,
options: Vec<ComboboxOption>,
value: Option<SharedString>,
default_value: Option<SharedString>,
description: Option<SharedString>,
placeholder: SharedString,
empty_message: SharedString,
disabled: bool,
width: Option<Pixels>,
on_value_change: Option<ComboboxChangeHandler>,
}
impl Combobox {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
options: Vec::new(),
value: None,
default_value: None,
description: None,
placeholder: "Search or select…".into(),
empty_message: "No matches found".into(),
disabled: false,
width: None,
on_value_change: None,
}
}
pub fn option(mut self, option: ComboboxOption) -> Self {
self.options.push(option);
self
}
pub fn options(mut self, options: impl IntoIterator<Item = ComboboxOption>) -> Self {
self.options.extend(options);
self
}
pub fn value(mut self, value: impl Into<SharedString>) -> Self {
self.value = Some(value.into());
self
}
pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
self.default_value = Some(value.into());
self
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
self.placeholder = placeholder.into();
self
}
pub fn empty_message(mut self, message: impl Into<SharedString>) -> Self {
self.empty_message = message.into();
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn width(mut self, width: impl Into<Pixels>) -> Self {
self.width = Some(width.into());
self
}
pub fn on_value_change(
mut self,
handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_value_change = Some(Rc::new(handler));
self
}
}
impl RenderOnce for Combobox {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let motion = theme.motion;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let initial_val = self
.value
.clone()
.or_else(|| self.default_value.clone())
.unwrap_or_default();
let placeholder_init = self.placeholder.clone();
let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-combobox-state".into());
let internal = window.use_keyed_state(state_id, cx, |window, cx| {
ComboboxInternal::new(initial_val.clone(), placeholder_init, now, window, cx)
});
let selected_value = self
.value
.clone()
.unwrap_or_else(|| internal.read(cx).uncontrolled_value.clone());
let selected_option = self
.options
.iter()
.find(|opt| opt.value == selected_value)
.cloned();
let has_selected = selected_option.is_some();
let effective_placeholder = selected_option
.as_ref()
.map(|opt| opt.label.clone())
.unwrap_or_else(|| self.placeholder.clone());
{
let q_entity = internal.read(cx).query_input.clone();
q_entity.update(cx, |s, cx| {
s.set_placeholder(effective_placeholder.clone(), window, cx);
});
}
{
let prev_settled = internal.read(cx).settled_value.clone();
if prev_settled != selected_value {
internal.update(cx, |s, _| {
s.settled_value = selected_value.clone();
s.settle_started_at_secs = now;
});
}
}
{
let q_entity = internal.read(cx).query_input.clone();
let q_val: SharedString = q_entity.read(cx).value().clone();
let is_input_focused = q_entity.read(cx).focus_handle(cx).is_focused(window);
let last_q = internal.read(cx).last_query.clone();
let was_open = internal.read(cx).open;
if !self.disabled
&& (q_val != last_q || (is_input_focused && !was_open && !q_val.is_empty()))
{
internal.update(cx, |s, _| {
if q_val != last_q {
s.last_query = q_val.clone();
s.active_filtered_pos = None;
if !q_val.is_empty() && !s.open {
s.open = true;
s.opened_at_secs = now;
}
}
});
}
}
let snap = internal.read(cx).clone();
let is_open = snap.open && !self.disabled;
let query_str = if is_open {
snap.query_input.read(cx).value().to_string()
} else {
String::new()
};
let filtered_indices = filter_combobox_options(&self.options, &query_str);
{
let is_empty = is_open && filtered_indices.is_empty();
let cur_empty_at = internal.read(cx).empty_entered_at_secs;
if is_empty && cur_empty_at.is_none() {
internal.update(cx, |s, _| {
s.empty_entered_at_secs = Some(now);
});
} else if !is_empty && cur_empty_at.is_some() {
internal.update(cx, |s, _| {
s.empty_entered_at_secs = None;
});
}
}
let empty_started_at = internal.read(cx).empty_entered_at_secs.unwrap_or(now);
let is_input_focused = snap
.query_input
.read(cx)
.focus_handle(cx)
.is_focused(window);
let settle_elapsed = (now - snap.settle_started_at_secs).max(0.0);
let settle_dur = if has_selected { 0.24 } else { 0.16 };
let (settle_op, settle_y) = if !is_open && settle_elapsed < settle_dur {
window.request_animation_frame();
combobox_settle_sample(settle_elapsed, has_selected, reduced)
} else {
(1.0, 0.0)
};
let chevron_deg = if reduced {
if is_open { 180.0 } else { 0.0 }
} else {
arc_spring(
(self.id.clone(), "chevron-deg"),
if is_open { 180.0 } else { 0.0 },
motion.spring.snappy,
window,
cx,
)
};
let show_clear_target = has_selected && !self.disabled;
let clear_target_scale = if !show_clear_target {
0.6
} else if snap.clear_pressed && !reduced {
0.96
} else {
1.0
};
let clear_scale = if reduced {
if show_clear_target { 1.0 } else { 0.6 }
} else {
arc_spring(
(self.id.clone(), "clear-scale"),
clear_target_scale,
motion.spring.snappy,
window,
cx,
)
};
let clear_op = arc_transition(
(self.id.clone(), "clear-op"),
if show_clear_target { 1.0 } else { 0.0 },
if reduced {
motion.duration.instant
} else if show_clear_target {
motion.duration.fast
} else {
motion.duration.instant
},
motion.ease.standard,
window,
cx,
);
let clear_blur = BlurFallback::evaluate(motion.blur.subtle * (1.0 - clear_op), reduced);
let render_clear = show_clear_target || clear_op > 0.02;
let hover_p = arc_transition(
(self.id.clone(), "control-hover"),
if !self.disabled && (is_open || snap.control_hovered) {
1.0
} else {
0.0
},
if reduced {
Duration::ZERO
} else {
motion.duration.fast
},
motion.ease.standard,
window,
cx,
);
let control_bg = oklab_mix(colors.surface_muted, colors.surface, hover_p);
let control_border = if !self.disabled && is_input_focused {
colors.accent
} else {
oklab_mix(colors.border_strong, colors.border, hover_p)
};
let popover_presence = ArcPresence::new((self.id.clone(), "popover-presence"), is_open)
.animate_initial(false)
.config(ArcPresenceConfig {
enter_duration: motion.duration.fast,
exit_duration: motion.duration.instant,
enter_ease: motion.ease.enter,
exit_ease: motion.ease.standard,
fade_on_reduced_motion: true,
})
.sample(window, cx);
let popover_y = if reduced {
0.0
} else {
arc_spring(
(self.id.clone(), "popover-y"),
if is_open { 0.0 } else { -6.0 },
motion.spring.snappy,
window,
cx,
)
};
let target_h = combobox_target_height(filtered_indices.len());
let auto_h = if reduced {
target_h
} else {
arc_spring_with_options(
(self.id.clone(), "auto-height"),
target_h,
SpringOptions::new(motion.spring.smooth),
window,
cx,
)
.value
.max(24.0)
};
let control_bounds_ref = snap.control_bounds.clone();
let control_bounds_outside = snap.control_bounds.clone();
let popover_bounds_outside = snap.popover_bounds.clone();
let internal_outside = internal.clone();
let control_probe = canvas(
move |rect, _, _| {
*control_bounds_ref.borrow_mut() = Some(rect);
},
move |_, _, window, _| {
if is_open {
let c_ref = control_bounds_outside.clone();
let p_ref = popover_bounds_outside.clone();
let st = internal_outside.clone();
window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
if !phase.bubble() {
return;
}
let in_control =
c_ref.borrow().is_some_and(|b| b.contains(&event.position));
let in_popover =
p_ref.borrow().is_some_and(|b| b.contains(&event.position));
if !in_control && !in_popover {
let q_in = st.read(cx).query_input.clone();
q_in.update(cx, |s, cx| s.set_value("", window, cx));
st.update(cx, |s, _| {
s.open = false;
s.last_query = "".into();
s.active_filtered_pos = None;
});
window.refresh();
}
});
}
},
)
.absolute()
.inset_0();
let disabled = self.disabled;
let int_hover = internal.clone();
let int_open = internal.clone();
let int_key = internal.clone();
let options_for_key = self.options.clone();
let filtered_for_key = filtered_indices.clone();
let on_change_key = self.on_value_change.clone();
let int_clear_click = internal.clone();
let int_clear_down = internal.clone();
let int_clear_up = internal.clone();
let int_clear_out = internal.clone();
let on_change_clear = self.on_value_change.clone();
let clear_hover_bg = colors.surface_muted;
let clear_hover_fg = colors.foreground;
let clear_el = if render_clear {
let btn_sz = (22.0 * clear_scale).clamp(13.0, 24.0);
let icon_sz = (14.0 * clear_scale).clamp(9.0, 16.0);
Some(
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"clear".into(),
))
.accessibility_label("Clear selection")
.on_click(move |_, window, cx| {
let t_now = motion_now(cx);
let q_in = int_clear_click.read(cx).query_input.clone();
q_in.update(cx, |s, cx| {
s.set_value("", window, cx);
s.focus(window, cx);
});
int_clear_click.update(cx, |s, _| {
s.uncontrolled_value = "".into();
s.settled_value = "".into();
s.settle_started_at_secs = t_now;
s.last_query = "".into();
s.open = true;
s.opened_at_secs = t_now;
s.active_filtered_pos = None;
s.clear_pressed = false;
});
if let Some(cb) = &on_change_clear {
let empty: SharedString = "".into();
cb(&empty, window, cx);
}
window.refresh();
})
.w(px(btn_sz))
.h(px(btn_sz))
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded(Radii::CONTROL)
.opacity((clear_op * clear_blur.opacity_multiplier).clamp(0.0, 1.0))
.text_color(colors.text_muted)
.cursor_pointer()
.hover(move |s| s.bg(clear_hover_bg).text_color(clear_hover_fg))
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
int_clear_down.update(cx, |s, _| s.clear_pressed = true);
window.refresh();
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
int_clear_up.update(cx, |s, _| s.clear_pressed = false);
window.refresh();
})
.on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
int_clear_out.update(cx, |s, _| s.clear_pressed = false);
window.refresh();
})
.child(Icon::new(IconName::X).text_size(px(icon_sz))),
)
} else {
None
};
let middle_slot = if is_open {
div()
.flex_1()
.min_w_0()
.text_size(Typography::TEXT_SM)
.text_color(colors.foreground)
.child(
KitInput::new(&snap.query_input)
.appearance(false)
.disabled(disabled)
.w_full(),
)
.into_any_element()
} else {
let display_text = selected_option
.as_ref()
.map(|opt| opt.label.clone())
.unwrap_or_else(|| self.placeholder.clone());
let text_fg = if has_selected {
colors.foreground
} else {
colors.text_muted
};
div()
.flex_1()
.min_w_0()
.h(px(20.0))
.overflow_hidden()
.flex()
.items_center()
.child(
div()
.w_full()
.mt(px(settle_y))
.opacity(settle_op)
.text_size(Typography::TEXT_SM)
.text_color(text_fg)
.truncate()
.child(display_text),
)
.into_any_element()
};
let chevron_color = colors.text_muted;
let control_id = ElementId::NamedChild(self.id.clone().into(), "control".into());
let int_chevron_toggle = internal.clone();
let control = div()
.id(control_id)
.test_support()
.role(Role::ComboBox)
.aria_label(self.label.clone())
.relative()
.w_full()
.min_h(ControlHeights::MD)
.px(Spacing::S3)
.flex()
.flex_row()
.items_center()
.gap(Spacing::S2)
.rounded(Radii::CONTROL)
.border_1()
.border_color(control_border)
.bg(control_bg)
.opacity(if disabled { 0.5 } else { 1.0 })
.when(!disabled, |this| this.cursor_pointer())
.on_hover(move |hovered, window, cx| {
int_hover.update(cx, |s, _| {
s.control_hovered = *hovered;
});
window.refresh();
})
.on_click(move |_, window, cx| {
if disabled {
return;
}
let t_now = motion_now(cx);
let q_in = int_open.read(cx).query_input.clone();
let already_open = int_open.read(cx).open;
if !already_open {
q_in.update(cx, |s, cx| {
s.set_value("", window, cx);
s.focus(window, cx);
});
int_open.update(cx, |s, _| {
s.open = true;
s.opened_at_secs = t_now;
s.last_query = "".into();
s.active_filtered_pos = None;
});
} else {
q_in.update(cx, |s, cx| s.set_value("", window, cx));
int_open.update(cx, |s, _| {
s.open = false;
s.last_query = "".into();
s.active_filtered_pos = None;
});
}
window.refresh();
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if disabled {
return;
}
match event.keystroke.key.as_str() {
"down" | "arrowdown" => {
let currently_open = int_key.read(cx).open;
if !currently_open {
let t_now = motion_now(cx);
let q_in = int_key.read(cx).query_input.clone();
q_in.update(cx, |s, cx| s.set_value("", window, cx));
int_key.update(cx, |s, _| {
s.open = true;
s.opened_at_secs = t_now;
s.last_query = "".into();
s.active_filtered_pos = None;
});
} else {
let cur = int_key.read(cx).active_filtered_pos;
if let Some(next_pos) = next_enabled_combobox_match(
&options_for_key,
&filtered_for_key,
cur,
1,
) {
int_key.update(cx, |s, _| {
s.active_filtered_pos = Some(next_pos);
});
}
}
window.refresh();
}
"up" | "arrowup" => {
let currently_open = int_key.read(cx).open;
if !currently_open {
let t_now = motion_now(cx);
let q_in = int_key.read(cx).query_input.clone();
q_in.update(cx, |s, cx| s.set_value("", window, cx));
int_key.update(cx, |s, _| {
s.open = true;
s.opened_at_secs = t_now;
s.last_query = "".into();
s.active_filtered_pos = None;
});
} else {
let cur = int_key.read(cx).active_filtered_pos;
if let Some(prev_pos) = next_enabled_combobox_match(
&options_for_key,
&filtered_for_key,
cur,
-1,
) {
int_key.update(cx, |s, _| {
s.active_filtered_pos = Some(prev_pos);
});
}
}
window.refresh();
}
"enter" => {
let (currently_open, active_pos) = {
let s = int_key.read(cx);
(s.open, s.active_filtered_pos)
};
if currently_open
&& let Some(pos) = active_pos
&& let Some(&opt_idx) = filtered_for_key.get(pos)
&& let Some(opt) = options_for_key.get(opt_idx)
&& !opt.disabled
{
let chosen_val = opt.value.clone();
let t_now = motion_now(cx);
let q_in = int_key.read(cx).query_input.clone();
q_in.update(cx, |s, cx| s.set_value("", window, cx));
int_key.update(cx, |s, _| {
s.uncontrolled_value = chosen_val.clone();
s.settled_value = chosen_val.clone();
s.settle_started_at_secs = t_now;
s.last_query = "".into();
s.open = false;
s.active_filtered_pos = None;
});
if let Some(cb) = &on_change_key {
cb(&chosen_val, window, cx);
}
window.refresh();
}
}
"escape" => {
let currently_open = int_key.read(cx).open;
if currently_open {
let q_in = int_key.read(cx).query_input.clone();
q_in.update(cx, |s, cx| s.set_value("", window, cx));
int_key.update(cx, |s, _| {
s.open = false;
s.last_query = "".into();
s.active_filtered_pos = None;
});
window.refresh();
}
}
_ => {}
}
})
.child(control_probe)
.child(
Icon::new(IconName::Search)
.text_size(px(16.0))
.text_color(colors.text_muted),
)
.child(middle_slot)
.when_some(clear_el, |this, btn| this.child(btn))
.child(
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"chevron-toggle".into(),
))
.accessibility_label("Toggle options")
.disabled(disabled)
.on_click(move |_, window, cx| {
if disabled {
return;
}
let t_now = motion_now(cx);
let q_in = int_chevron_toggle.read(cx).query_input.clone();
let next_open = !int_chevron_toggle.read(cx).open;
q_in.update(cx, |s, cx| {
s.set_value("", window, cx);
if next_open {
s.focus(window, cx);
}
});
int_chevron_toggle.update(cx, |s, _| {
s.open = next_open;
if next_open {
s.opened_at_secs = t_now;
}
s.last_query = "".into();
s.active_filtered_pos = None;
});
window.refresh();
})
.size(px(22.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded(Radii::CONTROL)
.cursor_pointer()
.child(
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
paint_rotated_chevron(cx_pt, cy_pt, chevron_deg, chevron_color, window);
},
)
.size(px(16.0))
.flex_none(),
),
);
let popover_el = if popover_presence.should_render() {
let p = popover_presence.progress.clamp(0.0, 1.0);
let popover_bounds_ref = snap.popover_bounds.clone();
let popover_probe = canvas(
move |rect, _, _| {
*popover_bounds_ref.borrow_mut() = Some(rect);
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let listbox_content = if filtered_indices.is_empty() {
let empty_elapsed = (now - empty_started_at).max(0.0);
let (emp_op, emp_y) = combobox_empty_sample(empty_elapsed, reduced);
if is_open && !reduced && empty_elapsed < 0.24 {
window.request_animation_frame();
}
div()
.w_full()
.p(Spacing::S3)
.mt(px(emp_y))
.opacity(emp_op)
.text_size(Typography::TEXT_SM)
.text_color(colors.text_muted)
.child(self.empty_message)
.into_any_element()
} else {
let option_rows = filtered_indices
.iter()
.copied()
.enumerate()
.map(|(pos, opt_idx)| {
let option = &self.options[opt_idx];
let item_id = ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("option-{}", option.value)),
);
let is_active = snap.active_filtered_pos == Some(pos) && !option.disabled;
let is_selected = option.value == selected_value;
let row_bg = if is_active {
colors.surface_muted
} else {
Hsla::transparent_black()
};
let int_hi = internal.clone();
let int_choose = internal.clone();
let on_change = self.on_value_change.clone();
let opt_val = option.value.clone();
let opt_label = option.label.clone();
let opt_disabled = option.disabled;
let check_color = colors.foreground;
div()
.id(item_id)
.test_support()
.role(Role::ListBoxOption)
.aria_label(opt_label.clone())
.w_full()
.min_h(px(COMBOBOX_OPTION_HEIGHT_PX))
.px(px(12.0))
.flex()
.flex_row()
.items_center()
.justify_between()
.gap(Spacing::S3)
.rounded((Radii::PANEL - px(4.0)).max(px(4.0)))
.bg(row_bg)
.text_size(Typography::TEXT_SM)
.text_color(colors.foreground)
.opacity(if opt_disabled { 0.42 } else { 1.0 })
.when(!opt_disabled, |this| this.cursor_pointer())
.on_hover(move |hovered, window, cx| {
if opt_disabled {
return;
}
int_hi.update(cx, |s, _| {
if *hovered {
s.active_filtered_pos = Some(pos);
}
});
window.refresh();
})
.on_click(move |_, window, cx| {
if opt_disabled {
return;
}
let t_now = motion_now(cx);
let q_in = int_choose.read(cx).query_input.clone();
q_in.update(cx, |s, cx| s.set_value("", window, cx));
int_choose.update(cx, |s, _| {
s.uncontrolled_value = opt_val.clone();
s.settled_value = opt_val.clone();
s.settle_started_at_secs = t_now;
s.last_query = "".into();
s.open = false;
s.active_filtered_pos = None;
});
if let Some(cb) = &on_change {
cb(&opt_val, window, cx);
}
window.refresh();
})
.child(div().flex_1().min_w_0().truncate().child(opt_label))
.when(is_selected, |this| {
this.child(
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let cx_pt =
f32::from(rect.origin.x + rect.size.width * 0.5);
let cy_pt =
f32::from(rect.origin.y + rect.size.height * 0.5);
paint_check(cx_pt, cy_pt, check_color, window);
},
)
.size(px(16.0))
.flex_none(),
)
})
.into_any_element()
})
.collect::<Vec<_>>();
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"listbox".into(),
))
.role(Role::ListBox)
.w_full()
.max_h(px(COMBOBOX_MAX_LISTBOX_HEIGHT_PX))
.overflow_y_scroll()
.flex()
.flex_col()
.children(option_rows)
.into_any_element()
};
Some(
deferred(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"popover".into(),
))
.test_support()
.absolute()
.top_full()
.left_0()
.right_0()
.mt(px(8.0 + popover_y))
.p(px(5.0))
.rounded(Radii::PANEL)
.border_1()
.border_color(colors.border)
.bg(colors.surface_raised)
.shadow(Shadows::floating(theme.mode))
.opacity(p)
.overflow_hidden()
.child(popover_probe)
.child(
div()
.w_full()
.h(px(auto_h))
.overflow_hidden()
.child(listbox_content),
),
)
.with_priority(20),
)
} else {
None
};
div()
.id(self.id)
.test_support()
.when_some(self.width, |this, w| this.w(w))
.when(self.width.is_none(), |this| this.w_full())
.flex()
.flex_col()
.gap(Spacing::S2)
.child(
div()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.child(self.label),
)
.child(
div()
.relative()
.w_full()
.child(control)
.when_some(popover_el, |this, pop| this.child(pop)),
)
.when_some(self.description, |this, desc| {
this.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(desc),
)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn filter_combobox_options_matches_labels_and_keywords_case_insensitively() {
let options = vec![
ComboboxOption::new("rust", "Rust").keywords(["cargo", "systems"]),
ComboboxOption::new("ts", "TypeScript").keywords(["node", "web"]),
ComboboxOption::new("py", "Python").keywords(["ml", "data"]),
];
assert_eq!(filter_combobox_options(&options, " "), vec![0, 1, 2]);
assert_eq!(filter_combobox_options(&options, "CARGO"), vec![0]);
assert_eq!(filter_combobox_options(&options, "script"), vec![1]);
assert!(filter_combobox_options(&options, "kotlin").is_empty());
}
#[test]
fn combobox_settle_and_empty_samples_progress_cleanly() {
let (op0, y0) = combobox_settle_sample(0.0, true, false);
assert!(op0 < 0.01);
assert!(y0 > 4.5);
let (op1, y1) = combobox_settle_sample(0.26, true, false);
assert!((op1 - 1.0).abs() < 1e-4);
assert!(y1.abs() < 1e-4);
let (emp_op0, emp_y0) = combobox_empty_sample(0.0, false);
assert!(emp_op0 < 0.01);
assert!((emp_y0 - 4.0).abs() < 1e-4);
let (emp_op_red, emp_y_red) = combobox_empty_sample(0.01, true);
assert!((emp_op_red - 1.0).abs() < 1e-4);
assert!(emp_y_red.abs() < 1e-4);
}
#[test]
fn next_enabled_combobox_match_skips_disabled_items() {
let options = vec![
ComboboxOption::new("a", "Alpha"),
ComboboxOption::new("b", "Beta").disabled(true),
ComboboxOption::new("c", "Gamma"),
];
let filtered = vec![0, 1, 2];
assert_eq!(
next_enabled_combobox_match(&options, &filtered, None, 1),
Some(0)
);
assert_eq!(
next_enabled_combobox_match(&options, &filtered, Some(0), 1),
Some(2)
);
assert_eq!(
next_enabled_combobox_match(&options, &filtered, Some(2), 1),
Some(0)
);
}
}