use std::{cell::RefCell, collections::HashMap, rc::Rc, time::Duration};
use arc_motion::{
ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, PathPoint, PolylinePath, arc_spring,
arc_transition, is_reduced_motion, motion_now,
};
use arc_tokens::{
ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, Typography, oklab_mix,
};
use gpui_kit::{
App, Bounds, ElementId, FocusHandle, 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,
deferred, div, point,
prelude::*,
px,
};
type MultiSelectChangeHandler = Rc<dyn Fn(&[SharedString], &mut Window, &mut App)>;
pub const MULTI_SELECT_CHIP_EM_PX: f32 = 12.0;
pub const MULTI_SELECT_CHIP_MAX_W_PX: f32 = 144.0;
pub const MULTI_SELECT_CHIP_GAP_PX: f32 = 5.0;
pub fn estimate_multi_select_slot_width(label: &str) -> f32 {
let text_w: f32 = label
.chars()
.map(|ch| if ch.is_ascii() { 6.8 } else { 12.2 })
.sum();
let chip_w = (text_w + 18.0).clamp(28.0, MULTI_SELECT_CHIP_MAX_W_PX);
chip_w + MULTI_SELECT_CHIP_GAP_PX
}
pub fn multi_select_count_roll_sample(
elapsed: f64,
direction: i8,
reduced: bool,
) -> (f32, f32, f32, f32) {
let dir = if direction >= 0 { 1.0_f32 } else { -1.0_f32 };
if reduced {
let t = (elapsed / 0.12).clamp(0.0, 1.0) as f32;
return (t, 0.0, 1.0 - t, 0.0);
}
let half_em = 0.5 * MULTI_SELECT_CHIP_EM_PX;
let t_in = (elapsed / 0.24).clamp(0.0, 1.0) as f32;
let e_in = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t_in);
let blur_in = BlurFallback::evaluate(px(2.0 * (1.0 - e_in)), false);
let enter_op = (e_in * blur_in.opacity_multiplier).clamp(0.0, 1.0);
let enter_y = dir * half_em * (1.0 - e_in);
let t_out = (elapsed / 0.12).clamp(0.0, 1.0) as f32;
let e_out = CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t_out);
let blur_out = BlurFallback::evaluate(px(2.0 * e_out), false);
let exit_op = ((1.0 - e_out) * blur_out.opacity_multiplier).clamp(0.0, 1.0);
let exit_y = -dir * half_em * e_out;
(enter_op, enter_y, exit_op, exit_y)
}
pub fn toggle_multi_select_value(
selected: &[SharedString],
target: &SharedString,
) -> Vec<SharedString> {
if selected.iter().any(|v| v == target) {
selected.iter().filter(|&v| v != target).cloned().collect()
} else {
let mut next = selected.to_vec();
next.push(target.clone());
next
}
}
pub fn next_enabled_multi_select_option(
options: &[MultiSelectOption],
current: Option<usize>,
step: isize,
) -> Option<usize> {
let enabled: Vec<usize> = options
.iter()
.enumerate()
.filter_map(|(idx, opt)| (!opt.disabled).then_some(idx))
.collect();
if enabled.is_empty() {
return None;
}
let len = enabled.len() as isize;
let cur_pos = current.and_then(|c| enabled.iter().position(|&e| e == c));
let next_pos = match cur_pos {
Some(pos) => (pos as isize + step).rem_euclid(len) as usize,
None => {
if step >= 0 {
0
} else {
(len - 1) as usize
}
}
};
Some(enabled[next_pos])
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MultiSelectOption {
pub value: SharedString,
pub label: SharedString,
pub disabled: bool,
}
impl MultiSelectOption {
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
}
}
#[derive(Clone)]
struct MultiSelectInternal {
open: bool,
uncontrolled_value: Vec<SharedString>,
slot_order: Vec<SharedString>,
measured_slot_widths: Rc<RefCell<HashMap<SharedString, f32>>>,
active_index: Option<usize>,
previous_remaining: usize,
previous_remaining_for_roll: Option<usize>,
count_direction: i8,
count_roll_started_at_secs: f64,
trigger_hovered: bool,
trigger_pressed: bool,
clear_pressed: bool,
trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
menu_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
focus_handle: FocusHandle,
}
impl MultiSelectInternal {
fn new(
default_value: Vec<SharedString>,
initial_remaining: usize,
now: f64,
focus_handle: FocusHandle,
) -> Self {
Self {
open: false,
slot_order: default_value.clone(),
uncontrolled_value: default_value,
measured_slot_widths: Rc::new(RefCell::new(HashMap::new())),
active_index: None,
previous_remaining: initial_remaining,
previous_remaining_for_roll: None,
count_direction: 1,
count_roll_started_at_secs: now - 10.0,
trigger_hovered: false,
trigger_pressed: false,
clear_pressed: false,
trigger_bounds: Rc::new(RefCell::new(None)),
menu_bounds: Rc::new(RefCell::new(None)),
focus_handle,
}
}
}
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_drawn_check(
origin_x: Pixels,
origin_y: Pixels,
path_length: f32,
opacity: f32,
color: Hsla,
window: &mut Window,
) {
let len = path_length.clamp(0.0, 1.0);
let alpha = opacity.clamp(0.0, 1.0);
if len <= 0.01 || alpha <= 0.01 {
return;
}
let s = 16.0 / 24.0;
let poly = PolylinePath::new(vec![
PathPoint::new(4.0 * s, 12.5 * s),
PathPoint::new(9.0 * s, 17.5 * s),
PathPoint::new(20.0 * s, 6.5 * s),
]);
let sliced = poly.slice(0.0, len);
let stroke_color = Hsla {
a: color.a * alpha,
..color
};
if let Some(b) = sliced.to_stroke_builder(origin_x, origin_y, px(1.75))
&& let Ok(path) = b.build()
{
window.paint_path(path, stroke_color);
}
}
#[derive(IntoElement)]
pub struct MultiSelect {
id: ElementId,
label: SharedString,
options: Vec<MultiSelectOption>,
value: Option<Vec<SharedString>>,
default_value: Vec<SharedString>,
placeholder: SharedString,
description: Option<SharedString>,
max_visible: usize,
disabled: bool,
width: Option<Pixels>,
on_value_change: Option<MultiSelectChangeHandler>,
}
impl MultiSelect {
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: Vec::new(),
placeholder: "Select options".into(),
description: None,
max_visible: 2,
disabled: false,
width: None,
on_value_change: None,
}
}
pub fn option(mut self, option: MultiSelectOption) -> Self {
self.options.push(option);
self
}
pub fn options(mut self, options: impl IntoIterator<Item = MultiSelectOption>) -> Self {
self.options.extend(options);
self
}
pub fn value<I, S>(mut self, value: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<SharedString>,
{
self.value = Some(value.into_iter().map(Into::into).collect());
self
}
pub fn default_value<I, S>(mut self, value: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<SharedString>,
{
self.default_value = value.into_iter().map(Into::into).collect();
self
}
pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
self.placeholder = placeholder.into();
self
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn max_visible(mut self, max_visible: usize) -> Self {
self.max_visible = max_visible.max(1);
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 MultiSelect {
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_vals = self
.value
.clone()
.unwrap_or_else(|| self.default_value.clone());
let initial_rem = initial_vals.len().saturating_sub(self.max_visible);
let state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-multi-select-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, cx| {
MultiSelectInternal::new(initial_vals.clone(), initial_rem, now, cx.focus_handle())
});
let selected: Vec<SharedString> = self
.value
.clone()
.unwrap_or_else(|| internal.read(cx).uncontrolled_value.clone());
let visible_slice: Vec<SharedString> =
selected.iter().take(self.max_visible).cloned().collect();
let remaining = selected.len().saturating_sub(visible_slice.len());
{
let mut order = internal.read(cx).slot_order.clone();
let mut changed = false;
for val in &visible_slice {
if !order.contains(val) {
order.push(val.clone());
changed = true;
}
}
if changed {
internal.update(cx, |s, _| {
s.slot_order = order;
});
}
}
{
let prev_rem = internal.read(cx).previous_remaining;
if prev_rem != remaining {
let dir = if remaining > prev_rem { 1 } else { -1 };
internal.update(cx, |s, _| {
if prev_rem > 0 && remaining > 0 {
s.previous_remaining_for_roll = Some(prev_rem);
s.count_roll_started_at_secs = now;
}
s.previous_remaining = remaining;
s.count_direction = dir;
});
}
}
let snap = internal.read(cx).clone();
let is_open = snap.open && !self.disabled;
let has_selections = !selected.is_empty();
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 placeholder_op = arc_transition(
(self.id.clone(), "placeholder-op"),
if has_selections { 0.0 } else { 1.0 },
motion.duration.instant,
motion.ease.standard,
window,
cx,
);
let trigger_active =
!self.disabled && (is_open || snap.trigger_hovered || snap.trigger_pressed);
let hover_p = arc_transition(
(self.id.clone(), "trigger-hover"),
if trigger_active { 1.0 } else { 0.0 },
if reduced {
Duration::ZERO
} else {
motion.duration.fast
},
motion.ease.standard,
window,
cx,
);
let trigger_bg = oklab_mix(colors.surface_muted, colors.surface, hover_p);
let trigger_border = oklab_mix(colors.border_strong, colors.border, hover_p);
let chip_bg = oklab_mix(colors.surface, colors.surface_muted, hover_p);
let show_clear_target = has_selections && !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 mut chip_slot_els = Vec::new();
for val in &snap.slot_order {
let is_vis = visible_slice.contains(val);
let label = self
.options
.iter()
.find(|opt| &opt.value == val)
.map(|opt| opt.label.clone())
.unwrap_or_else(|| val.clone());
let natural_w = snap
.measured_slot_widths
.borrow()
.get(val)
.copied()
.unwrap_or_else(|| estimate_multi_select_slot_width(&label));
let slot_w = if reduced {
if is_vis { natural_w } else { 0.0 }
} else {
arc_motion::arc_measured_spring(
(self.id.clone(), format!("slot-w-{val}")),
if is_vis {
snap.measured_slot_widths.borrow().get(val).copied()
} else {
Some(0.0)
},
natural_w,
motion.spring.smooth,
window,
cx,
)
};
let slot_op = arc_transition(
(self.id.clone(), format!("slot-op-{val}")),
if is_vis { 1.0 } else { 0.0 },
if reduced {
motion.duration.instant
} else if is_vis {
motion.duration.fast
} else {
motion.duration.instant
},
if is_vis {
motion.ease.enter
} else {
motion.ease.standard
},
window,
cx,
);
let blur_mult = BlurFallback::evaluate(
if is_vis {
motion.blur.soft * (1.0 - slot_op)
} else {
motion.blur.subtle * (1.0 - slot_op)
},
reduced,
)
.opacity_multiplier;
if is_vis || slot_w > 0.5 || slot_op > 0.01 {
let measured_map = snap.measured_slot_widths.clone();
let key_for_probe = val.clone();
let chip_probe = canvas(
move |rect, window, _| {
let w = f32::from(rect.size.width) + MULTI_SELECT_CHIP_GAP_PX;
if w > MULTI_SELECT_CHIP_GAP_PX {
let prev = measured_map.borrow().get(&key_for_probe).copied();
measured_map.borrow_mut().insert(key_for_probe.clone(), w);
if prev.is_none_or(|p| (p - w).abs() > 0.5) {
window.request_animation_frame();
}
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
chip_slot_els.push(
div()
.w(px(slot_w.max(0.0)))
.flex_none()
.flex()
.flex_row()
.items_center()
.overflow_hidden()
.opacity((slot_op * blur_mult).clamp(0.0, 1.0))
.child(
div()
.relative()
.flex_none()
.max_w(px(MULTI_SELECT_CHIP_MAX_W_PX))
.mr(px(MULTI_SELECT_CHIP_GAP_PX))
.px(px(8.0))
.py(px(4.0))
.rounded(Radii::PILL)
.border_1()
.border_color(colors.border_subtle)
.bg(chip_bg)
.text_size(Typography::TEXT_XS)
.text_color(colors.foreground)
.whitespace_nowrap()
.truncate()
.child(chip_probe)
.child(label),
)
.into_any_element(),
);
}
}
let show_more = remaining > 0;
let shown_rem_num = if show_more {
remaining
} else {
snap.previous_remaining.max(1)
};
let more_text = SharedString::from(format!("+{shown_rem_num}"));
let more_natural_w = estimate_multi_select_slot_width(&more_text);
let more_w = if reduced {
if show_more { more_natural_w } else { 0.0 }
} else {
arc_spring(
(self.id.clone(), "slot-w-__more__"),
if show_more { more_natural_w } else { 0.0 },
motion.spring.smooth,
window,
cx,
)
};
let more_op = arc_transition(
(self.id.clone(), "slot-op-__more__"),
if show_more { 1.0 } else { 0.0 },
if reduced {
motion.duration.instant
} else if show_more {
motion.duration.fast
} else {
motion.duration.instant
},
if show_more {
motion.ease.enter
} else {
motion.ease.standard
},
window,
cx,
);
let count_roll_elapsed = (now - snap.count_roll_started_at_secs).max(0.0);
let count_roll_dur = if reduced { 0.12 } else { 0.24 };
let (cnt_in_op, cnt_in_y, cnt_out_op, cnt_out_y) = if count_roll_elapsed < count_roll_dur {
window.request_animation_frame();
multi_select_count_roll_sample(count_roll_elapsed, snap.count_direction, reduced)
} else {
(1.0, 0.0, 0.0, 0.0)
};
if show_more || more_w > 0.5 || more_op > 0.01 {
let mut count_cell = div()
.relative()
.h(px(16.0))
.overflow_hidden()
.flex()
.items_center()
.child(
div()
.mt(px(cnt_in_y))
.opacity(cnt_in_op)
.child(SharedString::from(format!("{shown_rem_num}"))),
);
if cnt_out_op > 0.01
&& let Some(prev_num) = snap.previous_remaining_for_roll
{
count_cell = count_cell.child(
div()
.absolute()
.top_0()
.left_0()
.mt(px(cnt_out_y))
.opacity(cnt_out_op)
.child(SharedString::from(format!("{prev_num}"))),
);
}
chip_slot_els.push(
div()
.w(px(more_w.max(0.0)))
.flex_none()
.flex()
.flex_row()
.items_center()
.overflow_hidden()
.opacity(more_op.clamp(0.0, 1.0))
.child(
div()
.flex_none()
.mr(px(MULTI_SELECT_CHIP_GAP_PX))
.px(px(8.0))
.py(px(4.0))
.flex()
.flex_row()
.items_center()
.whitespace_nowrap()
.rounded(Radii::PILL)
.border_1()
.border_color(colors.border_subtle)
.bg(chip_bg)
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.child("+")
.child(count_cell),
)
.into_any_element(),
);
}
let menu_presence = ArcPresence::new((self.id.clone(), "menu-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 menu_y = if reduced {
0.0
} else {
arc_spring(
(self.id.clone(), "menu-y"),
if is_open { 0.0 } else { -6.0 },
motion.spring.snappy,
window,
cx,
)
};
let trigger_bounds_ref = snap.trigger_bounds.clone();
let trigger_bounds_outside = snap.trigger_bounds.clone();
let menu_bounds_outside = snap.menu_bounds.clone();
let internal_outside = internal.clone();
let trigger_probe = canvas(
move |rect, _, _| {
*trigger_bounds_ref.borrow_mut() = Some(rect);
},
move |_, _, window, _| {
if is_open {
let t_ref = trigger_bounds_outside.clone();
let m_ref = menu_bounds_outside.clone();
let st = internal_outside.clone();
window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
if !phase.bubble() {
return;
}
let in_trigger =
t_ref.borrow().is_some_and(|b| b.contains(&event.position));
let in_menu = m_ref.borrow().is_some_and(|b| b.contains(&event.position));
if !in_trigger && !in_menu {
st.update(cx, |s, _| {
s.open = false;
s.active_index = None;
});
window.refresh();
}
});
}
},
)
.absolute()
.inset_0();
let trigger_id = ElementId::NamedChild(self.id.clone().into(), "trigger".into());
let int_hover = internal.clone();
let int_down = internal.clone();
let int_up = internal.clone();
let int_out = internal.clone();
let int_click = internal.clone();
let focus_for_open = snap.focus_handle.clone();
let disabled = self.disabled;
let chevron_color = colors.text_muted;
let value_row = div()
.relative()
.flex_1()
.min_w_0()
.min_h(px(26.0))
.flex()
.flex_row()
.items_center()
.overflow_hidden()
.when(placeholder_op > 0.01, |this| {
this.child(
div()
.absolute()
.inset_0()
.flex()
.items_center()
.opacity(placeholder_op)
.text_size(Typography::TEXT_SM)
.text_color(colors.text_muted)
.truncate()
.child(self.placeholder.clone()),
)
})
.children(chip_slot_els);
let trigger = BaseButton::new(trigger_id)
.accessibility_label(self.label.clone())
.disabled(disabled)
.on_click(move |_, window, cx| {
if disabled {
return;
}
let mut became_open = false;
int_click.update(cx, |s, _| {
s.open = !s.open;
became_open = s.open;
if !s.open {
s.active_index = None;
}
});
if became_open {
window.focus(&focus_for_open, cx);
}
window.refresh();
})
.relative()
.w_full()
.min_h(ControlHeights::MD)
.pl(px(12.0))
.pr(px(11.0))
.py(px(5.0))
.flex()
.flex_row()
.items_center()
.gap(px(8.0))
.rounded(Radii::CONTROL)
.border_1()
.border_color(trigger_border)
.bg(trigger_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.trigger_hovered = *hovered;
if !*hovered {
s.trigger_pressed = false;
}
});
window.refresh();
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if !disabled {
int_down.update(cx, |s, _| s.trigger_pressed = true);
window.refresh();
}
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
int_up.update(cx, |s, _| s.trigger_pressed = false);
window.refresh();
})
.on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
int_out.update(cx, |s, _| s.trigger_pressed = false);
window.refresh();
})
.child(trigger_probe)
.child(value_row)
.child(
div()
.when(has_selections, |this| this.ml(px(26.0)))
.size(px(16.0))
.flex_none()
.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_full(),
),
);
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;
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, 15.0);
let top_offset = (44.0 - btn_sz) * 0.5;
Some(
div()
.absolute()
.top(px(top_offset))
.right(px(36.0 + (22.0 - btn_sz) * 0.5))
.child(
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"clear".into(),
))
.accessibility_label("Clear selections")
.on_click(move |_, window, cx| {
int_clear_click.update(cx, |s, _| {
s.uncontrolled_value.clear();
s.open = false;
s.active_index = None;
s.clear_pressed = false;
});
if let Some(cb) = &on_change_clear {
cb(&[], window, cx);
}
window.refresh();
})
.w(px(btn_sz))
.h(px(btn_sz))
.flex()
.items_center()
.justify_center()
.rounded(Radii::PILL)
.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 menu_el = if menu_presence.should_render() && !self.options.is_empty() {
let p = menu_presence.progress.clamp(0.0, 1.0);
let menu_bounds_ref = snap.menu_bounds.clone();
let menu_probe = canvas(
move |rect, _, _| {
*menu_bounds_ref.borrow_mut() = Some(rect);
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let int_key = internal.clone();
let options_for_key = self.options.clone();
let selected_for_key = selected.clone();
let on_change_key = self.on_value_change.clone();
let focus_handle = snap.focus_handle.clone();
let option_els = self
.options
.into_iter()
.enumerate()
.map(|(idx, option)| {
let is_checked = selected.iter().any(|v| v == &option.value);
let is_active = snap.active_index == Some(idx) && !option.disabled;
let check_len = arc_transition(
(self.id.clone(), format!("check-len-{}", option.value)),
if is_checked { 1.0 } else { 0.0 },
if reduced {
motion.duration.instant
} else if is_checked {
motion.duration.standard
} else {
motion.duration.instant
},
if is_checked {
motion.ease.enter
} else {
motion.ease.standard
},
window,
cx,
);
let check_op = arc_transition(
(self.id.clone(), format!("check-op-{}", option.value)),
if is_checked { 1.0 } else { 0.0 },
motion.duration.instant,
motion.ease.standard,
window,
cx,
);
let row_bg = if is_active {
colors.surface_muted
} else {
Hsla::transparent_black()
};
let int_hi = internal.clone();
let int_toggle = internal.clone();
let on_change = self.on_value_change.clone();
let cur_selected = selected.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(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("option-{}", option.value)),
))
.test_support()
.role(Role::ListBoxOption)
.aria_label(opt_label.clone())
.w_full()
.min_h(px(38.0))
.px(px(11.0))
.flex()
.flex_row()
.items_center()
.justify_between()
.gap(px(12.0))
.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_index = Some(idx);
}
});
window.refresh();
})
.on_click(move |_, window, cx| {
if opt_disabled {
return;
}
let next_vals = toggle_multi_select_value(&cur_selected, &opt_val);
int_toggle.update(cx, |s, _| {
s.uncontrolled_value = next_vals.clone();
s.active_index = Some(idx);
});
if let Some(cb) = &on_change {
cb(&next_vals, window, cx);
}
window.refresh();
})
.child(div().flex_1().min_w_0().truncate().child(opt_label))
.child(
div().size(px(16.0)).flex_none().child(
canvas(
|_, _, _| {},
move |rect, _, window, _| {
paint_drawn_check(
rect.origin.x,
rect.origin.y,
check_len,
check_op,
check_color,
window,
);
},
)
.size_full(),
),
)
.into_any_element()
})
.collect::<Vec<_>>();
Some(
deferred(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"listbox".into(),
))
.test_support()
.role(Role::ListBox)
.track_focus(&focus_handle)
.on_key_down(move |event: &KeyDownEvent, window, cx| {
match event.keystroke.key.as_str() {
"escape" => {
int_key.update(cx, |s, _| {
s.open = false;
s.active_index = None;
});
window.refresh();
}
"down" | "arrowdown" => {
let cur = int_key.read(cx).active_index;
if let Some(next_idx) =
next_enabled_multi_select_option(&options_for_key, cur, 1)
{
int_key.update(cx, |s, _| {
s.active_index = Some(next_idx);
});
window.refresh();
}
}
"up" | "arrowup" => {
let cur = int_key.read(cx).active_index;
if let Some(prev_idx) =
next_enabled_multi_select_option(&options_for_key, cur, -1)
{
int_key.update(cx, |s, _| {
s.active_index = Some(prev_idx);
});
window.refresh();
}
}
"enter" | " " | "space" => {
let active = int_key.read(cx).active_index;
if let Some(idx) = active
&& let Some(opt) = options_for_key.get(idx)
&& !opt.disabled
{
let next_vals = toggle_multi_select_value(
&selected_for_key,
&opt.value,
);
int_key.update(cx, |s, _| {
s.uncontrolled_value = next_vals.clone();
});
if let Some(cb) = &on_change_key {
cb(&next_vals, window, cx);
}
window.refresh();
}
}
_ => {}
}
})
.absolute()
.top_full()
.left_0()
.right_0()
.mt(px(8.0 + menu_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(menu_probe)
.child(div().w_full().flex().flex_col().children(option_els)),
)
.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(trigger)
.when_some(clear_el, |this, btn| this.child(btn))
.when_some(menu_el, |this, m| this.child(m)),
)
.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 toggle_multi_select_value_adds_and_removes_preserving_order() {
let initial: Vec<SharedString> = vec!["rust".into(), "gpui".into()];
let added = toggle_multi_select_value(&initial, &"metal".into());
assert_eq!(
added,
vec![
SharedString::from("rust"),
SharedString::from("gpui"),
SharedString::from("metal")
]
);
let removed = toggle_multi_select_value(&added, &"rust".into());
assert_eq!(
removed,
vec![SharedString::from("gpui"), SharedString::from("metal")]
);
}
#[test]
fn multi_select_count_roll_moves_directionally_and_settles() {
let (in_op0, in_y0, out_op0, _) = multi_select_count_roll_sample(0.0, 1, false);
assert!(in_op0 < 0.01);
assert!((in_y0 - 6.0).abs() < 1e-4);
assert!(out_op0 > 0.99);
let (_, in_y_neg, _, out_y_neg) = multi_select_count_roll_sample(0.06, -1, false);
assert!(in_y_neg < 0.0);
assert!(out_y_neg > 0.0);
let (in_op_done, in_y_done, out_op_done, _) =
multi_select_count_roll_sample(0.28, 1, false);
assert!((in_op_done - 1.0).abs() < 1e-4);
assert!(in_y_done.abs() < 1e-4);
assert!(out_op_done < 1e-4);
}
#[test]
fn next_enabled_multi_select_option_skips_disabled_and_wraps() {
let options = vec![
MultiSelectOption::new("a", "Alpha"),
MultiSelectOption::new("b", "Beta").disabled(true),
MultiSelectOption::new("c", "Gamma"),
];
assert_eq!(next_enabled_multi_select_option(&options, None, 1), Some(0));
assert_eq!(
next_enabled_multi_select_option(&options, Some(0), 1),
Some(2)
);
assert_eq!(
next_enabled_multi_select_option(&options, Some(2), 1),
Some(0)
);
}
}