Skip to main content

arc_ui/inputs/
multi_select.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/multi-select/multi-select.tsx` & `.module.css`
3//!
4//! P4 Component #3: `multi-select`
5//!
6//! - Trigger (`ControlHeights::MD` 44px, `Radii::CONTROL`, `1px border`, colour-only press feedback):
7//!   - Displays up to `max_visible` (default `2`) selected items as pill chips (`Radii::PILL`,
8//!     `surface_muted` background with `1px border_subtle` inset ring, inverting to `surface` on
9//!     trigger hover or open), plus a `+N` overflow pill when `selected.len() > max_visible`.
10//!   - Each chip sits inside a clipping slot whose width opens and collapses on
11//!     `motion.spring.smooth` while the chip itself springs between `scale(0.9)` and `1.0` on
12//!     `motion.spring.snappy` with `BlurFallback::soft`.
13//!   - The `+N` overflow count rolls vertically (`±0.5em` = `±6px`) in the direction the count
14//!     moved (`+1` when increasing, `-1` when decreasing).
15//!   - When `selected` is non-empty, the trailing chevron reserves `margin-left: 26px` for the
16//!     `22×22px` clear button (`right: 36px`), which springs between `scale(0.6)` and `1.0`
17//!     (`0.96` on press).
18//! - Floating menu (`top: calc(100% + 8px)`, `Radii::PANEL` 26px, `5px` padding):
19//!   - Enters from `y = -6px` on `motion.spring.snappy` with `duration.fast` opacity (`ease.enter`)
20//!     and exits over `duration.instant` (`120ms`).
21//!   - Closing the menu forgets `active_index` so the next open starts clean.
22//!   - Selected options draw a vector checkmark (`M4 12.5 9 17.5 20 6.5`) via `pathLength: 0 -> 1`
23//!     over `duration.standard` (`240ms`, `ease.enter`) and retract over `duration.instant` (`120ms`).
24
25use std::{cell::RefCell, collections::HashMap, rc::Rc, time::Duration};
26
27use arc_motion::{
28    ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, PathPoint, PolylinePath, arc_spring,
29    arc_transition, is_reduced_motion, motion_now,
30};
31use arc_tokens::{
32    ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, Typography, oklab_mix,
33};
34use gpui_kit::{
35    App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
36    MouseDownEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
37    TestSupportExt as _, Window,
38    assets::IconName,
39    base::{Button as BaseButton, StyledExt as _},
40    canvas,
41    component::Icon,
42    deferred, div, point,
43    prelude::*,
44    px,
45};
46
47type MultiSelectChangeHandler = Rc<dyn Fn(&[SharedString], &mut Window, &mut App)>;
48
49/// Base font size (`12px`, `--text-xs`) for the `+N` chip count roll (`0.5em` = `6px`).
50pub const MULTI_SELECT_CHIP_EM_PX: f32 = 12.0;
51/// Maximum width (`144px` = `9rem`) of an individual chip before ellipsis truncation.
52pub const MULTI_SELECT_CHIP_MAX_W_PX: f32 = 144.0;
53/// Trailing margin (`5px`) after each chip inside its slot.
54pub const MULTI_SELECT_CHIP_GAP_PX: f32 = 5.0;
55
56/// Estimates the natural slot width (chip width + `5px` trailing margin) of a chip label at
57/// `12px` (`--text-xs`) with `8px` horizontal padding on each side, clamped to
58/// `MULTI_SELECT_CHIP_MAX_W_PX + MULTI_SELECT_CHIP_GAP_PX`.
59pub fn estimate_multi_select_slot_width(label: &str) -> f32 {
60    let text_w: f32 = label
61        .chars()
62        .map(|ch| if ch.is_ascii() { 6.8 } else { 12.2 })
63        .sum();
64    let chip_w = (text_w + 18.0).clamp(28.0, MULTI_SELECT_CHIP_MAX_W_PX);
65    chip_w + MULTI_SELECT_CHIP_GAP_PX
66}
67
68/// Sampled `(enter_opacity, enter_y_px, exit_opacity, exit_y_px)` for the `+N` overflow count
69/// directional roll (`240ms` `ease.enter` in from `dir * 0.5em`, `120ms` `ease.standard` out to
70/// `-dir * 0.5em`, `blur.subtle 2px`).
71pub fn multi_select_count_roll_sample(
72    elapsed: f64,
73    direction: i8,
74    reduced: bool,
75) -> (f32, f32, f32, f32) {
76    let dir = if direction >= 0 { 1.0_f32 } else { -1.0_f32 };
77    if reduced {
78        let t = (elapsed / 0.12).clamp(0.0, 1.0) as f32;
79        return (t, 0.0, 1.0 - t, 0.0);
80    }
81
82    let half_em = 0.5 * MULTI_SELECT_CHIP_EM_PX;
83
84    let t_in = (elapsed / 0.24).clamp(0.0, 1.0) as f32;
85    let e_in = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t_in);
86    let blur_in = BlurFallback::evaluate(px(2.0 * (1.0 - e_in)), false);
87    let enter_op = (e_in * blur_in.opacity_multiplier).clamp(0.0, 1.0);
88    let enter_y = dir * half_em * (1.0 - e_in);
89
90    let t_out = (elapsed / 0.12).clamp(0.0, 1.0) as f32;
91    let e_out = CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t_out);
92    let blur_out = BlurFallback::evaluate(px(2.0 * e_out), false);
93    let exit_op = ((1.0 - e_out) * blur_out.opacity_multiplier).clamp(0.0, 1.0);
94    let exit_y = -dir * half_em * e_out;
95
96    (enter_op, enter_y, exit_op, exit_y)
97}
98
99/// Toggles `target` inside `selected`: removes it if present, or appends it at the end if absent.
100pub fn toggle_multi_select_value(
101    selected: &[SharedString],
102    target: &SharedString,
103) -> Vec<SharedString> {
104    if selected.iter().any(|v| v == target) {
105        selected.iter().filter(|&v| v != target).cloned().collect()
106    } else {
107        let mut next = selected.to_vec();
108        next.push(target.clone());
109        next
110    }
111}
112
113/// Loops forward (`step = 1`) or backward (`step = -1`) among enabled options.
114pub fn next_enabled_multi_select_option(
115    options: &[MultiSelectOption],
116    current: Option<usize>,
117    step: isize,
118) -> Option<usize> {
119    let enabled: Vec<usize> = options
120        .iter()
121        .enumerate()
122        .filter_map(|(idx, opt)| (!opt.disabled).then_some(idx))
123        .collect();
124    if enabled.is_empty() {
125        return None;
126    }
127    let len = enabled.len() as isize;
128    let cur_pos = current.and_then(|c| enabled.iter().position(|&e| e == c));
129    let next_pos = match cur_pos {
130        Some(pos) => (pos as isize + step).rem_euclid(len) as usize,
131        None => {
132            if step >= 0 {
133                0
134            } else {
135                (len - 1) as usize
136            }
137        }
138    };
139    Some(enabled[next_pos])
140}
141
142/// One option inside [`MultiSelect`].
143#[derive(Clone, Debug, PartialEq, Eq)]
144pub struct MultiSelectOption {
145    pub value: SharedString,
146    pub label: SharedString,
147    pub disabled: bool,
148}
149
150impl MultiSelectOption {
151    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
152        Self {
153            value: value.into(),
154            label: label.into(),
155            disabled: false,
156        }
157    }
158
159    pub fn disabled(mut self, disabled: bool) -> Self {
160        self.disabled = disabled;
161        self
162    }
163}
164
165#[derive(Clone)]
166struct MultiSelectInternal {
167    open: bool,
168    uncontrolled_value: Vec<SharedString>,
169    slot_order: Vec<SharedString>,
170    measured_slot_widths: Rc<RefCell<HashMap<SharedString, f32>>>,
171    active_index: Option<usize>,
172    previous_remaining: usize,
173    previous_remaining_for_roll: Option<usize>,
174    count_direction: i8,
175    count_roll_started_at_secs: f64,
176    trigger_hovered: bool,
177    trigger_pressed: bool,
178    clear_pressed: bool,
179    trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
180    menu_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
181    focus_handle: FocusHandle,
182}
183
184impl MultiSelectInternal {
185    fn new(
186        default_value: Vec<SharedString>,
187        initial_remaining: usize,
188        now: f64,
189        focus_handle: FocusHandle,
190    ) -> Self {
191        Self {
192            open: false,
193            slot_order: default_value.clone(),
194            uncontrolled_value: default_value,
195            measured_slot_widths: Rc::new(RefCell::new(HashMap::new())),
196            active_index: None,
197            previous_remaining: initial_remaining,
198            previous_remaining_for_roll: None,
199            count_direction: 1,
200            count_roll_started_at_secs: now - 10.0,
201            trigger_hovered: false,
202            trigger_pressed: false,
203            clear_pressed: false,
204            trigger_bounds: Rc::new(RefCell::new(None)),
205            menu_bounds: Rc::new(RefCell::new(None)),
206            focus_handle,
207        }
208    }
209}
210
211fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
212    let rad = angle_deg.to_radians();
213    let cos_a = rad.cos();
214    let sin_a = rad.sin();
215    let pts = [(-4.0_f32, -2.0_f32), (0.0, 2.0), (4.0, -2.0)];
216    let mut builder = PathBuilder::stroke(px(1.75));
217    for (i, (lx, ly)) in pts.iter().enumerate() {
218        let rx = cx + lx * cos_a - ly * sin_a;
219        let ry = cy + lx * sin_a + ly * cos_a;
220        let p = point(px(rx), px(ry));
221        if i == 0 {
222            builder.move_to(p);
223        } else {
224            builder.line_to(p);
225        }
226    }
227    if let Ok(path) = builder.build() {
228        window.paint_path(path, color);
229    }
230}
231
232fn paint_drawn_check(
233    origin_x: Pixels,
234    origin_y: Pixels,
235    path_length: f32,
236    opacity: f32,
237    color: Hsla,
238    window: &mut Window,
239) {
240    let len = path_length.clamp(0.0, 1.0);
241    let alpha = opacity.clamp(0.0, 1.0);
242    if len <= 0.01 || alpha <= 0.01 {
243        return;
244    }
245    // `M4 12.5 9 17.5 20 6.5` in 24×24 viewBox scaled into 16×16px.
246    let s = 16.0 / 24.0;
247    let poly = PolylinePath::new(vec![
248        PathPoint::new(4.0 * s, 12.5 * s),
249        PathPoint::new(9.0 * s, 17.5 * s),
250        PathPoint::new(20.0 * s, 6.5 * s),
251    ]);
252    let sliced = poly.slice(0.0, len);
253    let stroke_color = Hsla {
254        a: color.a * alpha,
255        ..color
256    };
257    if let Some(b) = sliced.to_stroke_builder(origin_x, origin_y, px(1.75))
258        && let Ok(path) = b.build()
259    {
260        window.paint_path(path, stroke_color);
261    }
262}
263
264/// Arc `MultiSelect` — multi-value selector with spring-expanding chip slots, directional `+N`
265/// overflow count roll, trailing clear button, and self-drawing option checkmarks.
266#[derive(IntoElement)]
267pub struct MultiSelect {
268    id: ElementId,
269    label: SharedString,
270    options: Vec<MultiSelectOption>,
271    value: Option<Vec<SharedString>>,
272    default_value: Vec<SharedString>,
273    placeholder: SharedString,
274    description: Option<SharedString>,
275    max_visible: usize,
276    disabled: bool,
277    width: Option<Pixels>,
278    on_value_change: Option<MultiSelectChangeHandler>,
279}
280
281impl MultiSelect {
282    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
283        Self {
284            id: id.into(),
285            label: label.into(),
286            options: Vec::new(),
287            value: None,
288            default_value: Vec::new(),
289            placeholder: "Select options".into(),
290            description: None,
291            max_visible: 2,
292            disabled: false,
293            width: None,
294            on_value_change: None,
295        }
296    }
297
298    pub fn option(mut self, option: MultiSelectOption) -> Self {
299        self.options.push(option);
300        self
301    }
302
303    pub fn options(mut self, options: impl IntoIterator<Item = MultiSelectOption>) -> Self {
304        self.options.extend(options);
305        self
306    }
307
308    pub fn value<I, S>(mut self, value: I) -> Self
309    where
310        I: IntoIterator<Item = S>,
311        S: Into<SharedString>,
312    {
313        self.value = Some(value.into_iter().map(Into::into).collect());
314        self
315    }
316
317    pub fn default_value<I, S>(mut self, value: I) -> Self
318    where
319        I: IntoIterator<Item = S>,
320        S: Into<SharedString>,
321    {
322        self.default_value = value.into_iter().map(Into::into).collect();
323        self
324    }
325
326    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
327        self.placeholder = placeholder.into();
328        self
329    }
330
331    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
332        self.description = Some(description.into());
333        self
334    }
335
336    pub fn max_visible(mut self, max_visible: usize) -> Self {
337        self.max_visible = max_visible.max(1);
338        self
339    }
340
341    pub fn disabled(mut self, disabled: bool) -> Self {
342        self.disabled = disabled;
343        self
344    }
345
346    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
347        self.width = Some(width.into());
348        self
349    }
350
351    pub fn on_value_change(
352        mut self,
353        handler: impl Fn(&[SharedString], &mut Window, &mut App) + 'static,
354    ) -> Self {
355        self.on_value_change = Some(Rc::new(handler));
356        self
357    }
358}
359
360impl RenderOnce for MultiSelect {
361    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
362        let theme = cx.arc_theme().clone();
363        let colors = theme.colors;
364        let motion = theme.motion;
365        let reduced = is_reduced_motion(cx);
366        let now = motion_now(cx);
367
368        let initial_vals = self
369            .value
370            .clone()
371            .unwrap_or_else(|| self.default_value.clone());
372        let initial_rem = initial_vals.len().saturating_sub(self.max_visible);
373
374        let state_id =
375            ElementId::NamedChild(self.id.clone().into(), "__arc-multi-select-state".into());
376        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
377            MultiSelectInternal::new(initial_vals.clone(), initial_rem, now, cx.focus_handle())
378        });
379
380        let selected: Vec<SharedString> = self
381            .value
382            .clone()
383            .unwrap_or_else(|| internal.read(cx).uncontrolled_value.clone());
384        let visible_slice: Vec<SharedString> =
385            selected.iter().take(self.max_visible).cloned().collect();
386        let remaining = selected.len().saturating_sub(visible_slice.len());
387
388        // Keep `slot_order` updated so newly visible chips are appended in selection order, while
389        // recently removed chips stay in place until their spring width collapses to 0.
390        {
391            let mut order = internal.read(cx).slot_order.clone();
392            let mut changed = false;
393            for val in &visible_slice {
394                if !order.contains(val) {
395                    order.push(val.clone());
396                    changed = true;
397                }
398            }
399            if changed {
400                internal.update(cx, |s, _| {
401                    s.slot_order = order;
402                });
403            }
404        }
405
406        // Detect `+N` remaining count change to trigger directional count roll.
407        {
408            let prev_rem = internal.read(cx).previous_remaining;
409            if prev_rem != remaining {
410                let dir = if remaining > prev_rem { 1 } else { -1 };
411                internal.update(cx, |s, _| {
412                    if prev_rem > 0 && remaining > 0 {
413                        s.previous_remaining_for_roll = Some(prev_rem);
414                        s.count_roll_started_at_secs = now;
415                    }
416                    s.previous_remaining = remaining;
417                    s.count_direction = dir;
418                });
419            }
420        }
421
422        let snap = internal.read(cx).clone();
423        let is_open = snap.open && !self.disabled;
424        let has_selections = !selected.is_empty();
425
426        // Chevron rotation `0 -> 180` on `motion.spring.snappy`.
427        let chevron_deg = if reduced {
428            if is_open { 180.0 } else { 0.0 }
429        } else {
430            arc_spring(
431                (self.id.clone(), "chevron-deg"),
432                if is_open { 180.0 } else { 0.0 },
433                motion.spring.snappy,
434                window,
435                cx,
436            )
437        };
438
439        // Placeholder opacity (`duration.instant` 120ms).
440        let placeholder_op = arc_transition(
441            (self.id.clone(), "placeholder-op"),
442            if has_selections { 0.0 } else { 1.0 },
443            motion.duration.instant,
444            motion.ease.standard,
445            window,
446            cx,
447        );
448
449        // Trigger surface & border transitions (`duration.fast` 160ms).
450        let trigger_active =
451            !self.disabled && (is_open || snap.trigger_hovered || snap.trigger_pressed);
452        let hover_p = arc_transition(
453            (self.id.clone(), "trigger-hover"),
454            if trigger_active { 1.0 } else { 0.0 },
455            if reduced {
456                Duration::ZERO
457            } else {
458                motion.duration.fast
459            },
460            motion.ease.standard,
461            window,
462            cx,
463        );
464        let trigger_bg = oklab_mix(colors.surface_muted, colors.surface, hover_p);
465        let trigger_border = oklab_mix(colors.border_strong, colors.border, hover_p);
466        // Chips invert from `surface_muted` to `surface` when the trigger is hovered or open.
467        let chip_bg = oklab_mix(colors.surface, colors.surface_muted, hover_p);
468
469        // Clear button (`22×22px`) presence, scale (`0.6 -> 1.0`, press `0.96`), and blur fallback.
470        let show_clear_target = has_selections && !self.disabled;
471        let clear_target_scale = if !show_clear_target {
472            0.6
473        } else if snap.clear_pressed && !reduced {
474            0.96
475        } else {
476            1.0
477        };
478        let clear_scale = if reduced {
479            if show_clear_target { 1.0 } else { 0.6 }
480        } else {
481            arc_spring(
482                (self.id.clone(), "clear-scale"),
483                clear_target_scale,
484                motion.spring.snappy,
485                window,
486                cx,
487            )
488        };
489        let clear_op = arc_transition(
490            (self.id.clone(), "clear-op"),
491            if show_clear_target { 1.0 } else { 0.0 },
492            if reduced {
493                motion.duration.instant
494            } else if show_clear_target {
495                motion.duration.fast
496            } else {
497                motion.duration.instant
498            },
499            motion.ease.standard,
500            window,
501            cx,
502        );
503        let clear_blur = BlurFallback::evaluate(motion.blur.subtle * (1.0 - clear_op), reduced);
504        let render_clear = show_clear_target || clear_op > 0.02;
505
506        // Build animated chip slots (`visible` + recently exited slots still collapsing).
507        let mut chip_slot_els = Vec::new();
508        for val in &snap.slot_order {
509            let is_vis = visible_slice.contains(val);
510            let label = self
511                .options
512                .iter()
513                .find(|opt| &opt.value == val)
514                .map(|opt| opt.label.clone())
515                .unwrap_or_else(|| val.clone());
516            let natural_w = snap
517                .measured_slot_widths
518                .borrow()
519                .get(val)
520                .copied()
521                .unwrap_or_else(|| estimate_multi_select_slot_width(&label));
522
523            let slot_w = if reduced {
524                if is_vis { natural_w } else { 0.0 }
525            } else {
526                arc_spring(
527                    (self.id.clone(), format!("slot-w-{val}")),
528                    if is_vis { natural_w } else { 0.0 },
529                    motion.spring.smooth,
530                    window,
531                    cx,
532                )
533            };
534            let slot_op = arc_transition(
535                (self.id.clone(), format!("slot-op-{val}")),
536                if is_vis { 1.0 } else { 0.0 },
537                if reduced {
538                    motion.duration.instant
539                } else if is_vis {
540                    motion.duration.fast
541                } else {
542                    motion.duration.instant
543                },
544                if is_vis {
545                    motion.ease.enter
546                } else {
547                    motion.ease.standard
548                },
549                window,
550                cx,
551            );
552            let blur_mult = BlurFallback::evaluate(
553                if is_vis {
554                    motion.blur.soft * (1.0 - slot_op)
555                } else {
556                    motion.blur.subtle * (1.0 - slot_op)
557                },
558                reduced,
559            )
560            .opacity_multiplier;
561
562            if is_vis || slot_w > 0.5 || slot_op > 0.01 {
563                let measured_map = snap.measured_slot_widths.clone();
564                let key_for_probe = val.clone();
565                let chip_probe = canvas(
566                    move |rect, window, _| {
567                        let w = f32::from(rect.size.width) + MULTI_SELECT_CHIP_GAP_PX;
568                        if w > MULTI_SELECT_CHIP_GAP_PX {
569                            let prev = measured_map.borrow().get(&key_for_probe).copied();
570                            measured_map.borrow_mut().insert(key_for_probe.clone(), w);
571                            if prev.is_some_and(|p| (p - w).abs() > 0.5) {
572                                window.request_animation_frame();
573                            }
574                        }
575                    },
576                    |_, _, _, _| {},
577                )
578                .absolute()
579                .inset_0();
580
581                chip_slot_els.push(
582                    div()
583                        .w(px(slot_w.max(0.0)))
584                        .flex_none()
585                        .flex()
586                        .flex_row()
587                        .items_center()
588                        .overflow_hidden()
589                        .opacity((slot_op * blur_mult).clamp(0.0, 1.0))
590                        .child(
591                            div()
592                                .relative()
593                                .flex_none()
594                                .max_w(px(MULTI_SELECT_CHIP_MAX_W_PX))
595                                .mr(px(MULTI_SELECT_CHIP_GAP_PX))
596                                .px(px(8.0))
597                                .py(px(4.0))
598                                .rounded(Radii::PILL)
599                                .border_1()
600                                .border_color(colors.border_subtle)
601                                .bg(chip_bg)
602                                .text_size(Typography::TEXT_XS)
603                                .text_color(colors.foreground)
604                                .whitespace_nowrap()
605                                .truncate()
606                                .child(chip_probe)
607                                .child(label),
608                        )
609                        .into_any_element(),
610                );
611            }
612        }
613
614        // `+N` overflow chip slot (`more`) with directional count roll.
615        let show_more = remaining > 0;
616        let shown_rem_num = if show_more {
617            remaining
618        } else {
619            snap.previous_remaining.max(1)
620        };
621        let more_text = SharedString::from(format!("+{shown_rem_num}"));
622        let more_natural_w = estimate_multi_select_slot_width(&more_text);
623        let more_w = if reduced {
624            if show_more { more_natural_w } else { 0.0 }
625        } else {
626            arc_spring(
627                (self.id.clone(), "slot-w-__more__"),
628                if show_more { more_natural_w } else { 0.0 },
629                motion.spring.smooth,
630                window,
631                cx,
632            )
633        };
634        let more_op = arc_transition(
635            (self.id.clone(), "slot-op-__more__"),
636            if show_more { 1.0 } else { 0.0 },
637            if reduced {
638                motion.duration.instant
639            } else if show_more {
640                motion.duration.fast
641            } else {
642                motion.duration.instant
643            },
644            if show_more {
645                motion.ease.enter
646            } else {
647                motion.ease.standard
648            },
649            window,
650            cx,
651        );
652
653        let count_roll_elapsed = (now - snap.count_roll_started_at_secs).max(0.0);
654        let count_roll_dur = if reduced { 0.12 } else { 0.24 };
655        let (cnt_in_op, cnt_in_y, cnt_out_op, cnt_out_y) = if count_roll_elapsed < count_roll_dur {
656            window.request_animation_frame();
657            multi_select_count_roll_sample(count_roll_elapsed, snap.count_direction, reduced)
658        } else {
659            (1.0, 0.0, 0.0, 0.0)
660        };
661
662        if show_more || more_w > 0.5 || more_op > 0.01 {
663            let mut count_cell = div()
664                .relative()
665                .h(px(16.0))
666                .overflow_hidden()
667                .flex()
668                .items_center()
669                .child(
670                    div()
671                        .mt(px(cnt_in_y))
672                        .opacity(cnt_in_op)
673                        .child(SharedString::from(format!("{shown_rem_num}"))),
674                );
675            if cnt_out_op > 0.01
676                && let Some(prev_num) = snap.previous_remaining_for_roll
677            {
678                count_cell = count_cell.child(
679                    div()
680                        .absolute()
681                        .top_0()
682                        .left_0()
683                        .mt(px(cnt_out_y))
684                        .opacity(cnt_out_op)
685                        .child(SharedString::from(format!("{prev_num}"))),
686                );
687            }
688
689            chip_slot_els.push(
690                div()
691                    .w(px(more_w.max(0.0)))
692                    .flex_none()
693                    .flex()
694                    .flex_row()
695                    .items_center()
696                    .overflow_hidden()
697                    .opacity(more_op.clamp(0.0, 1.0))
698                    .child(
699                        div()
700                            .flex_none()
701                            .mr(px(MULTI_SELECT_CHIP_GAP_PX))
702                            .px(px(8.0))
703                            .py(px(4.0))
704                            .flex()
705                            .flex_row()
706                            .items_center()
707                            .whitespace_nowrap()
708                            .rounded(Radii::PILL)
709                            .border_1()
710                            .border_color(colors.border_subtle)
711                            .bg(chip_bg)
712                            .text_size(Typography::TEXT_XS)
713                            .text_color(colors.text_secondary)
714                            .child("+")
715                            .child(count_cell),
716                    )
717                    .into_any_element(),
718            );
719        }
720
721        // Floating menu presence (`duration.fast` 160ms enter / `duration.instant` 120ms exit).
722        let menu_presence = ArcPresence::new((self.id.clone(), "menu-presence"), is_open)
723            .animate_initial(false)
724            .config(ArcPresenceConfig {
725                enter_duration: motion.duration.fast,
726                exit_duration: motion.duration.instant,
727                enter_ease: motion.ease.enter,
728                exit_ease: motion.ease.standard,
729                fade_on_reduced_motion: true,
730            })
731            .sample(window, cx);
732        let menu_y = if reduced {
733            0.0
734        } else {
735            arc_spring(
736                (self.id.clone(), "menu-y"),
737                if is_open { 0.0 } else { -6.0 },
738                motion.spring.snappy,
739                window,
740                cx,
741            )
742        };
743
744        let trigger_bounds_ref = snap.trigger_bounds.clone();
745        let trigger_bounds_outside = snap.trigger_bounds.clone();
746        let menu_bounds_outside = snap.menu_bounds.clone();
747        let internal_outside = internal.clone();
748        let trigger_probe = canvas(
749            move |rect, _, _| {
750                *trigger_bounds_ref.borrow_mut() = Some(rect);
751            },
752            move |_, _, window, _| {
753                if is_open {
754                    let t_ref = trigger_bounds_outside.clone();
755                    let m_ref = menu_bounds_outside.clone();
756                    let st = internal_outside.clone();
757                    window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
758                        if !phase.bubble() {
759                            return;
760                        }
761                        let in_trigger =
762                            t_ref.borrow().is_some_and(|b| b.contains(&event.position));
763                        let in_menu = m_ref.borrow().is_some_and(|b| b.contains(&event.position));
764                        if !in_trigger && !in_menu {
765                            st.update(cx, |s, _| {
766                                s.open = false;
767                                s.active_index = None;
768                            });
769                            window.refresh();
770                        }
771                    });
772                }
773            },
774        )
775        .absolute()
776        .inset_0();
777
778        let trigger_id = ElementId::NamedChild(self.id.clone().into(), "trigger".into());
779        let int_hover = internal.clone();
780        let int_down = internal.clone();
781        let int_up = internal.clone();
782        let int_out = internal.clone();
783        let int_click = internal.clone();
784        let focus_for_open = snap.focus_handle.clone();
785        let disabled = self.disabled;
786        let chevron_color = colors.text_muted;
787
788        let value_row = div()
789            .relative()
790            .flex_1()
791            .min_w_0()
792            .min_h(px(26.0))
793            .flex()
794            .flex_row()
795            .items_center()
796            .overflow_hidden()
797            .when(placeholder_op > 0.01, |this| {
798                this.child(
799                    div()
800                        .absolute()
801                        .inset_0()
802                        .flex()
803                        .items_center()
804                        .opacity(placeholder_op)
805                        .text_size(Typography::TEXT_SM)
806                        .text_color(colors.text_muted)
807                        .truncate()
808                        .child(self.placeholder.clone()),
809                )
810            })
811            .children(chip_slot_els);
812
813        let trigger = BaseButton::new(trigger_id)
814            .accessibility_label(self.label.clone())
815            .disabled(disabled)
816            .on_click(move |_, window, cx| {
817                if disabled {
818                    return;
819                }
820                let mut became_open = false;
821                int_click.update(cx, |s, _| {
822                    s.open = !s.open;
823                    became_open = s.open;
824                    if !s.open {
825                        // A closed menu forgets its highlight so the next open starts clean.
826                        s.active_index = None;
827                    }
828                });
829                if became_open {
830                    window.focus(&focus_for_open, cx);
831                }
832                window.refresh();
833            })
834            .relative()
835            .w_full()
836            .min_h(ControlHeights::MD)
837            .pl(px(12.0))
838            .pr(px(11.0))
839            .py(px(5.0))
840            .flex()
841            .flex_row()
842            .items_center()
843            .gap(px(8.0))
844            .rounded(Radii::CONTROL)
845            .border_1()
846            .border_color(trigger_border)
847            .bg(trigger_bg)
848            .opacity(if disabled { 0.5 } else { 1.0 })
849            .when(!disabled, |this| this.cursor_pointer())
850            .on_hover(move |hovered, window, cx| {
851                int_hover.update(cx, |s, _| {
852                    s.trigger_hovered = *hovered;
853                    if !*hovered {
854                        s.trigger_pressed = false;
855                    }
856                });
857                window.refresh();
858            })
859            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
860                if !disabled {
861                    int_down.update(cx, |s, _| s.trigger_pressed = true);
862                    window.refresh();
863                }
864            })
865            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
866                int_up.update(cx, |s, _| s.trigger_pressed = false);
867                window.refresh();
868            })
869            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
870                int_out.update(cx, |s, _| s.trigger_pressed = false);
871                window.refresh();
872            })
873            .child(trigger_probe)
874            .child(value_row)
875            .child(
876                div()
877                    .when(has_selections, |this| this.ml(px(26.0)))
878                    .size(px(16.0))
879                    .flex_none()
880                    .child(
881                        canvas(
882                            |_, _, _| {},
883                            move |rect, _, window, _| {
884                                let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
885                                let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
886                                paint_rotated_chevron(
887                                    cx_pt,
888                                    cy_pt,
889                                    chevron_deg,
890                                    chevron_color,
891                                    window,
892                                );
893                            },
894                        )
895                        .size_full(),
896                    ),
897            );
898
899        // Trailing clear button positioned at `right: 36px` inside `.control`.
900        let int_clear_click = internal.clone();
901        let int_clear_down = internal.clone();
902        let int_clear_up = internal.clone();
903        let int_clear_out = internal.clone();
904        let on_change_clear = self.on_value_change.clone();
905        let clear_hover_bg = colors.surface;
906        let clear_hover_fg = colors.foreground;
907
908        let clear_el = if render_clear {
909            let btn_sz = (22.0 * clear_scale).clamp(13.0, 24.0);
910            let icon_sz = (14.0 * clear_scale).clamp(9.0, 15.0);
911            let top_offset = (44.0 - btn_sz) * 0.5;
912            Some(
913                div()
914                    .absolute()
915                    .top(px(top_offset))
916                    .right(px(36.0 + (22.0 - btn_sz) * 0.5))
917                    .child(
918                        BaseButton::new(ElementId::NamedChild(
919                            self.id.clone().into(),
920                            "clear".into(),
921                        ))
922                        .accessibility_label("Clear selections")
923                        .on_click(move |_, window, cx| {
924                            int_clear_click.update(cx, |s, _| {
925                                s.uncontrolled_value.clear();
926                                s.open = false;
927                                s.active_index = None;
928                                s.clear_pressed = false;
929                            });
930                            if let Some(cb) = &on_change_clear {
931                                cb(&[], window, cx);
932                            }
933                            window.refresh();
934                        })
935                        .w(px(btn_sz))
936                        .h(px(btn_sz))
937                        .flex()
938                        .items_center()
939                        .justify_center()
940                        .rounded(Radii::PILL)
941                        .opacity((clear_op * clear_blur.opacity_multiplier).clamp(0.0, 1.0))
942                        .text_color(colors.text_muted)
943                        .cursor_pointer()
944                        .hover(move |s| s.bg(clear_hover_bg).text_color(clear_hover_fg))
945                        .on_mouse_down(MouseButton::Left, move |_, window, cx| {
946                            int_clear_down.update(cx, |s, _| s.clear_pressed = true);
947                            window.refresh();
948                        })
949                        .on_mouse_up(MouseButton::Left, move |_, window, cx| {
950                            int_clear_up.update(cx, |s, _| s.clear_pressed = false);
951                            window.refresh();
952                        })
953                        .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
954                            int_clear_out.update(cx, |s, _| s.clear_pressed = false);
955                            window.refresh();
956                        })
957                        .child(Icon::new(IconName::X).text_size(px(icon_sz))),
958                    ),
959            )
960        } else {
961            None
962        };
963
964        // Floating multiselect menu (`top: calc(100% + 8px)`, `Radii::PANEL` 26px, `5px` padding).
965        let menu_el = if menu_presence.should_render() && !self.options.is_empty() {
966            let p = menu_presence.progress.clamp(0.0, 1.0);
967            let menu_bounds_ref = snap.menu_bounds.clone();
968            let menu_probe = canvas(
969                move |rect, _, _| {
970                    *menu_bounds_ref.borrow_mut() = Some(rect);
971                },
972                |_, _, _, _| {},
973            )
974            .absolute()
975            .inset_0();
976
977            let int_key = internal.clone();
978            let options_for_key = self.options.clone();
979            let selected_for_key = selected.clone();
980            let on_change_key = self.on_value_change.clone();
981            let focus_handle = snap.focus_handle.clone();
982
983            let option_els = self
984                .options
985                .into_iter()
986                .enumerate()
987                .map(|(idx, option)| {
988                    let is_checked = selected.iter().any(|v| v == &option.value);
989                    let is_active = snap.active_index == Some(idx) && !option.disabled;
990                    let check_len = arc_transition(
991                        (self.id.clone(), format!("check-len-{}", option.value)),
992                        if is_checked { 1.0 } else { 0.0 },
993                        if reduced {
994                            motion.duration.instant
995                        } else if is_checked {
996                            motion.duration.standard
997                        } else {
998                            motion.duration.instant
999                        },
1000                        if is_checked {
1001                            motion.ease.enter
1002                        } else {
1003                            motion.ease.standard
1004                        },
1005                        window,
1006                        cx,
1007                    );
1008                    let check_op = arc_transition(
1009                        (self.id.clone(), format!("check-op-{}", option.value)),
1010                        if is_checked { 1.0 } else { 0.0 },
1011                        motion.duration.instant,
1012                        motion.ease.standard,
1013                        window,
1014                        cx,
1015                    );
1016
1017                    let row_bg = if is_active {
1018                        colors.surface_muted
1019                    } else {
1020                        Hsla::transparent_black()
1021                    };
1022                    let int_hi = internal.clone();
1023                    let int_toggle = internal.clone();
1024                    let on_change = self.on_value_change.clone();
1025                    let cur_selected = selected.clone();
1026                    let opt_val = option.value.clone();
1027                    let opt_label = option.label.clone();
1028                    let opt_disabled = option.disabled;
1029                    let check_color = colors.foreground;
1030
1031                    div()
1032                        .id(ElementId::NamedChild(
1033                            self.id.clone().into(),
1034                            SharedString::from(format!("option-{}", option.value)),
1035                        ))
1036                        .test_support()
1037                        .role(Role::ListBoxOption)
1038                        .aria_label(opt_label.clone())
1039                        .w_full()
1040                        .min_h(px(38.0))
1041                        .px(px(11.0))
1042                        .flex()
1043                        .flex_row()
1044                        .items_center()
1045                        .justify_between()
1046                        .gap(px(12.0))
1047                        .rounded((Radii::PANEL - px(4.0)).max(px(4.0)))
1048                        .bg(row_bg)
1049                        .text_size(Typography::TEXT_SM)
1050                        .text_color(colors.foreground)
1051                        .opacity(if opt_disabled { 0.42 } else { 1.0 })
1052                        .when(!opt_disabled, |this| this.cursor_pointer())
1053                        .on_hover(move |hovered, window, cx| {
1054                            if opt_disabled {
1055                                return;
1056                            }
1057                            int_hi.update(cx, |s, _| {
1058                                if *hovered {
1059                                    s.active_index = Some(idx);
1060                                }
1061                            });
1062                            window.refresh();
1063                        })
1064                        .on_click(move |_, window, cx| {
1065                            if opt_disabled {
1066                                return;
1067                            }
1068                            let next_vals = toggle_multi_select_value(&cur_selected, &opt_val);
1069                            int_toggle.update(cx, |s, _| {
1070                                s.uncontrolled_value = next_vals.clone();
1071                                s.active_index = Some(idx);
1072                            });
1073                            if let Some(cb) = &on_change {
1074                                cb(&next_vals, window, cx);
1075                            }
1076                            window.refresh();
1077                        })
1078                        .child(div().flex_1().min_w_0().truncate().child(opt_label))
1079                        .child(
1080                            div().size(px(16.0)).flex_none().child(
1081                                canvas(
1082                                    |_, _, _| {},
1083                                    move |rect, _, window, _| {
1084                                        paint_drawn_check(
1085                                            rect.origin.x,
1086                                            rect.origin.y,
1087                                            check_len,
1088                                            check_op,
1089                                            check_color,
1090                                            window,
1091                                        );
1092                                    },
1093                                )
1094                                .size_full(),
1095                            ),
1096                        )
1097                        .into_any_element()
1098                })
1099                .collect::<Vec<_>>();
1100
1101            Some(
1102                deferred(
1103                    div()
1104                        .id(ElementId::NamedChild(
1105                            self.id.clone().into(),
1106                            "listbox".into(),
1107                        ))
1108                        .test_support()
1109                        .role(Role::ListBox)
1110                        .track_focus(&focus_handle)
1111                        .on_key_down(move |event: &KeyDownEvent, window, cx| {
1112                            match event.keystroke.key.as_str() {
1113                                "escape" => {
1114                                    int_key.update(cx, |s, _| {
1115                                        s.open = false;
1116                                        s.active_index = None;
1117                                    });
1118                                    window.refresh();
1119                                }
1120                                "down" | "arrowdown" => {
1121                                    let cur = int_key.read(cx).active_index;
1122                                    if let Some(next_idx) =
1123                                        next_enabled_multi_select_option(&options_for_key, cur, 1)
1124                                    {
1125                                        int_key.update(cx, |s, _| {
1126                                            s.active_index = Some(next_idx);
1127                                        });
1128                                        window.refresh();
1129                                    }
1130                                }
1131                                "up" | "arrowup" => {
1132                                    let cur = int_key.read(cx).active_index;
1133                                    if let Some(prev_idx) =
1134                                        next_enabled_multi_select_option(&options_for_key, cur, -1)
1135                                    {
1136                                        int_key.update(cx, |s, _| {
1137                                            s.active_index = Some(prev_idx);
1138                                        });
1139                                        window.refresh();
1140                                    }
1141                                }
1142                                "enter" | " " | "space" => {
1143                                    let active = int_key.read(cx).active_index;
1144                                    if let Some(idx) = active
1145                                        && let Some(opt) = options_for_key.get(idx)
1146                                        && !opt.disabled
1147                                    {
1148                                        let next_vals = toggle_multi_select_value(
1149                                            &selected_for_key,
1150                                            &opt.value,
1151                                        );
1152                                        int_key.update(cx, |s, _| {
1153                                            s.uncontrolled_value = next_vals.clone();
1154                                        });
1155                                        if let Some(cb) = &on_change_key {
1156                                            cb(&next_vals, window, cx);
1157                                        }
1158                                        window.refresh();
1159                                    }
1160                                }
1161                                _ => {}
1162                            }
1163                        })
1164                        .absolute()
1165                        .top_full()
1166                        .left_0()
1167                        .right_0()
1168                        .mt(px(8.0 + menu_y))
1169                        .p(px(5.0))
1170                        .rounded(Radii::PANEL)
1171                        .border_1()
1172                        .border_color(colors.border)
1173                        .bg(colors.surface_raised)
1174                        .shadow(Shadows::floating(theme.mode))
1175                        .opacity(p)
1176                        .overflow_hidden()
1177                        .child(menu_probe)
1178                        .child(div().w_full().flex().flex_col().children(option_els)),
1179                )
1180                .with_priority(20),
1181            )
1182        } else {
1183            None
1184        };
1185
1186        div()
1187            .id(self.id)
1188            .test_support()
1189            .when_some(self.width, |this, w| this.w(w))
1190            .when(self.width.is_none(), |this| this.w_full())
1191            .flex()
1192            .flex_col()
1193            .gap(Spacing::S2)
1194            .child(
1195                div()
1196                    .text_size(Typography::TEXT_SM)
1197                    .font_medium()
1198                    .text_color(colors.foreground)
1199                    .child(self.label),
1200            )
1201            .child(
1202                div()
1203                    .relative()
1204                    .w_full()
1205                    .child(trigger)
1206                    .when_some(clear_el, |this, btn| this.child(btn))
1207                    .when_some(menu_el, |this, m| this.child(m)),
1208            )
1209            .when_some(self.description, |this, desc| {
1210                this.child(
1211                    div()
1212                        .text_size(Typography::TEXT_XS)
1213                        .text_color(colors.text_muted)
1214                        .child(desc),
1215                )
1216            })
1217    }
1218}
1219
1220#[cfg(test)]
1221mod tests {
1222    use super::*;
1223
1224    #[test]
1225    fn toggle_multi_select_value_adds_and_removes_preserving_order() {
1226        let initial: Vec<SharedString> = vec!["rust".into(), "gpui".into()];
1227        let added = toggle_multi_select_value(&initial, &"metal".into());
1228        assert_eq!(
1229            added,
1230            vec![
1231                SharedString::from("rust"),
1232                SharedString::from("gpui"),
1233                SharedString::from("metal")
1234            ]
1235        );
1236
1237        let removed = toggle_multi_select_value(&added, &"rust".into());
1238        assert_eq!(
1239            removed,
1240            vec![SharedString::from("gpui"), SharedString::from("metal")]
1241        );
1242    }
1243
1244    #[test]
1245    fn multi_select_count_roll_moves_directionally_and_settles() {
1246        let (in_op0, in_y0, out_op0, _) = multi_select_count_roll_sample(0.0, 1, false);
1247        assert!(in_op0 < 0.01);
1248        assert!((in_y0 - 6.0).abs() < 1e-4);
1249        assert!(out_op0 > 0.99);
1250
1251        let (_, in_y_neg, _, out_y_neg) = multi_select_count_roll_sample(0.06, -1, false);
1252        assert!(in_y_neg < 0.0);
1253        assert!(out_y_neg > 0.0);
1254
1255        let (in_op_done, in_y_done, out_op_done, _) =
1256            multi_select_count_roll_sample(0.28, 1, false);
1257        assert!((in_op_done - 1.0).abs() < 1e-4);
1258        assert!(in_y_done.abs() < 1e-4);
1259        assert!(out_op_done < 1e-4);
1260    }
1261
1262    #[test]
1263    fn next_enabled_multi_select_option_skips_disabled_and_wraps() {
1264        let options = vec![
1265            MultiSelectOption::new("a", "Alpha"),
1266            MultiSelectOption::new("b", "Beta").disabled(true),
1267            MultiSelectOption::new("c", "Gamma"),
1268        ];
1269        assert_eq!(next_enabled_multi_select_option(&options, None, 1), Some(0));
1270        assert_eq!(
1271            next_enabled_multi_select_option(&options, Some(0), 1),
1272            Some(2)
1273        );
1274        assert_eq!(
1275            next_enabled_multi_select_option(&options, Some(2), 1),
1276            Some(0)
1277        );
1278    }
1279}