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_motion::arc_measured_spring(
527                    (self.id.clone(), format!("slot-w-{val}")),
528                    if is_vis {
529                        snap.measured_slot_widths.borrow().get(val).copied()
530                    } else {
531                        Some(0.0)
532                    },
533                    natural_w,
534                    motion.spring.smooth,
535                    window,
536                    cx,
537                )
538            };
539            let slot_op = arc_transition(
540                (self.id.clone(), format!("slot-op-{val}")),
541                if is_vis { 1.0 } else { 0.0 },
542                if reduced {
543                    motion.duration.instant
544                } else if is_vis {
545                    motion.duration.fast
546                } else {
547                    motion.duration.instant
548                },
549                if is_vis {
550                    motion.ease.enter
551                } else {
552                    motion.ease.standard
553                },
554                window,
555                cx,
556            );
557            let blur_mult = BlurFallback::evaluate(
558                if is_vis {
559                    motion.blur.soft * (1.0 - slot_op)
560                } else {
561                    motion.blur.subtle * (1.0 - slot_op)
562                },
563                reduced,
564            )
565            .opacity_multiplier;
566
567            if is_vis || slot_w > 0.5 || slot_op > 0.01 {
568                let measured_map = snap.measured_slot_widths.clone();
569                let key_for_probe = val.clone();
570                let chip_probe = canvas(
571                    move |rect, window, _| {
572                        let w = f32::from(rect.size.width) + MULTI_SELECT_CHIP_GAP_PX;
573                        if w > MULTI_SELECT_CHIP_GAP_PX {
574                            let prev = measured_map.borrow().get(&key_for_probe).copied();
575                            measured_map.borrow_mut().insert(key_for_probe.clone(), w);
576                            if prev.is_none_or(|p| (p - w).abs() > 0.5) {
577                                window.request_animation_frame();
578                            }
579                        }
580                    },
581                    |_, _, _, _| {},
582                )
583                .absolute()
584                .inset_0();
585
586                chip_slot_els.push(
587                    div()
588                        .w(px(slot_w.max(0.0)))
589                        .flex_none()
590                        .flex()
591                        .flex_row()
592                        .items_center()
593                        .overflow_hidden()
594                        .opacity((slot_op * blur_mult).clamp(0.0, 1.0))
595                        .child(
596                            div()
597                                .relative()
598                                .flex_none()
599                                .max_w(px(MULTI_SELECT_CHIP_MAX_W_PX))
600                                .mr(px(MULTI_SELECT_CHIP_GAP_PX))
601                                .px(px(8.0))
602                                .py(px(4.0))
603                                .rounded(Radii::PILL)
604                                .border_1()
605                                .border_color(colors.border_subtle)
606                                .bg(chip_bg)
607                                .text_size(Typography::TEXT_XS)
608                                .text_color(colors.foreground)
609                                .whitespace_nowrap()
610                                .truncate()
611                                .child(chip_probe)
612                                .child(label),
613                        )
614                        .into_any_element(),
615                );
616            }
617        }
618
619        // `+N` overflow chip slot (`more`) with directional count roll.
620        let show_more = remaining > 0;
621        let shown_rem_num = if show_more {
622            remaining
623        } else {
624            snap.previous_remaining.max(1)
625        };
626        let more_text = SharedString::from(format!("+{shown_rem_num}"));
627        let more_natural_w = estimate_multi_select_slot_width(&more_text);
628        let more_w = if reduced {
629            if show_more { more_natural_w } else { 0.0 }
630        } else {
631            arc_spring(
632                (self.id.clone(), "slot-w-__more__"),
633                if show_more { more_natural_w } else { 0.0 },
634                motion.spring.smooth,
635                window,
636                cx,
637            )
638        };
639        let more_op = arc_transition(
640            (self.id.clone(), "slot-op-__more__"),
641            if show_more { 1.0 } else { 0.0 },
642            if reduced {
643                motion.duration.instant
644            } else if show_more {
645                motion.duration.fast
646            } else {
647                motion.duration.instant
648            },
649            if show_more {
650                motion.ease.enter
651            } else {
652                motion.ease.standard
653            },
654            window,
655            cx,
656        );
657
658        let count_roll_elapsed = (now - snap.count_roll_started_at_secs).max(0.0);
659        let count_roll_dur = if reduced { 0.12 } else { 0.24 };
660        let (cnt_in_op, cnt_in_y, cnt_out_op, cnt_out_y) = if count_roll_elapsed < count_roll_dur {
661            window.request_animation_frame();
662            multi_select_count_roll_sample(count_roll_elapsed, snap.count_direction, reduced)
663        } else {
664            (1.0, 0.0, 0.0, 0.0)
665        };
666
667        if show_more || more_w > 0.5 || more_op > 0.01 {
668            let mut count_cell = div()
669                .relative()
670                .h(px(16.0))
671                .overflow_hidden()
672                .flex()
673                .items_center()
674                .child(
675                    div()
676                        .mt(px(cnt_in_y))
677                        .opacity(cnt_in_op)
678                        .child(SharedString::from(format!("{shown_rem_num}"))),
679                );
680            if cnt_out_op > 0.01
681                && let Some(prev_num) = snap.previous_remaining_for_roll
682            {
683                count_cell = count_cell.child(
684                    div()
685                        .absolute()
686                        .top_0()
687                        .left_0()
688                        .mt(px(cnt_out_y))
689                        .opacity(cnt_out_op)
690                        .child(SharedString::from(format!("{prev_num}"))),
691                );
692            }
693
694            chip_slot_els.push(
695                div()
696                    .w(px(more_w.max(0.0)))
697                    .flex_none()
698                    .flex()
699                    .flex_row()
700                    .items_center()
701                    .overflow_hidden()
702                    .opacity(more_op.clamp(0.0, 1.0))
703                    .child(
704                        div()
705                            .flex_none()
706                            .mr(px(MULTI_SELECT_CHIP_GAP_PX))
707                            .px(px(8.0))
708                            .py(px(4.0))
709                            .flex()
710                            .flex_row()
711                            .items_center()
712                            .whitespace_nowrap()
713                            .rounded(Radii::PILL)
714                            .border_1()
715                            .border_color(colors.border_subtle)
716                            .bg(chip_bg)
717                            .text_size(Typography::TEXT_XS)
718                            .text_color(colors.text_secondary)
719                            .child("+")
720                            .child(count_cell),
721                    )
722                    .into_any_element(),
723            );
724        }
725
726        // Floating menu presence (`duration.fast` 160ms enter / `duration.instant` 120ms exit).
727        let menu_presence = ArcPresence::new((self.id.clone(), "menu-presence"), is_open)
728            .animate_initial(false)
729            .config(ArcPresenceConfig {
730                enter_duration: motion.duration.fast,
731                exit_duration: motion.duration.instant,
732                enter_ease: motion.ease.enter,
733                exit_ease: motion.ease.standard,
734                fade_on_reduced_motion: true,
735            })
736            .sample(window, cx);
737        let menu_y = if reduced {
738            0.0
739        } else {
740            arc_spring(
741                (self.id.clone(), "menu-y"),
742                if is_open { 0.0 } else { -6.0 },
743                motion.spring.snappy,
744                window,
745                cx,
746            )
747        };
748
749        let trigger_bounds_ref = snap.trigger_bounds.clone();
750        let trigger_bounds_outside = snap.trigger_bounds.clone();
751        let menu_bounds_outside = snap.menu_bounds.clone();
752        let internal_outside = internal.clone();
753        let trigger_probe = canvas(
754            move |rect, _, _| {
755                *trigger_bounds_ref.borrow_mut() = Some(rect);
756            },
757            move |_, _, window, _| {
758                if is_open {
759                    let t_ref = trigger_bounds_outside.clone();
760                    let m_ref = menu_bounds_outside.clone();
761                    let st = internal_outside.clone();
762                    window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
763                        if !phase.bubble() {
764                            return;
765                        }
766                        let in_trigger =
767                            t_ref.borrow().is_some_and(|b| b.contains(&event.position));
768                        let in_menu = m_ref.borrow().is_some_and(|b| b.contains(&event.position));
769                        if !in_trigger && !in_menu {
770                            st.update(cx, |s, _| {
771                                s.open = false;
772                                s.active_index = None;
773                            });
774                            window.refresh();
775                        }
776                    });
777                }
778            },
779        )
780        .absolute()
781        .inset_0();
782
783        let trigger_id = ElementId::NamedChild(self.id.clone().into(), "trigger".into());
784        let int_hover = internal.clone();
785        let int_down = internal.clone();
786        let int_up = internal.clone();
787        let int_out = internal.clone();
788        let int_click = internal.clone();
789        let focus_for_open = snap.focus_handle.clone();
790        let disabled = self.disabled;
791        let chevron_color = colors.text_muted;
792
793        let value_row = div()
794            .relative()
795            .flex_1()
796            .min_w_0()
797            .min_h(px(26.0))
798            .flex()
799            .flex_row()
800            .items_center()
801            .overflow_hidden()
802            .when(placeholder_op > 0.01, |this| {
803                this.child(
804                    div()
805                        .absolute()
806                        .inset_0()
807                        .flex()
808                        .items_center()
809                        .opacity(placeholder_op)
810                        .text_size(Typography::TEXT_SM)
811                        .text_color(colors.text_muted)
812                        .truncate()
813                        .child(self.placeholder.clone()),
814                )
815            })
816            .children(chip_slot_els);
817
818        let trigger = BaseButton::new(trigger_id)
819            .accessibility_label(self.label.clone())
820            .disabled(disabled)
821            .on_click(move |_, window, cx| {
822                if disabled {
823                    return;
824                }
825                let mut became_open = false;
826                int_click.update(cx, |s, _| {
827                    s.open = !s.open;
828                    became_open = s.open;
829                    if !s.open {
830                        // A closed menu forgets its highlight so the next open starts clean.
831                        s.active_index = None;
832                    }
833                });
834                if became_open {
835                    window.focus(&focus_for_open, cx);
836                }
837                window.refresh();
838            })
839            .relative()
840            .w_full()
841            .min_h(ControlHeights::MD)
842            .pl(px(12.0))
843            .pr(px(11.0))
844            .py(px(5.0))
845            .flex()
846            .flex_row()
847            .items_center()
848            .gap(px(8.0))
849            .rounded(Radii::CONTROL)
850            .border_1()
851            .border_color(trigger_border)
852            .bg(trigger_bg)
853            .opacity(if disabled { 0.5 } else { 1.0 })
854            .when(!disabled, |this| this.cursor_pointer())
855            .on_hover(move |hovered, window, cx| {
856                int_hover.update(cx, |s, _| {
857                    s.trigger_hovered = *hovered;
858                    if !*hovered {
859                        s.trigger_pressed = false;
860                    }
861                });
862                window.refresh();
863            })
864            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
865                if !disabled {
866                    int_down.update(cx, |s, _| s.trigger_pressed = true);
867                    window.refresh();
868                }
869            })
870            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
871                int_up.update(cx, |s, _| s.trigger_pressed = false);
872                window.refresh();
873            })
874            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
875                int_out.update(cx, |s, _| s.trigger_pressed = false);
876                window.refresh();
877            })
878            .child(trigger_probe)
879            .child(value_row)
880            .child(
881                div()
882                    .when(has_selections, |this| this.ml(px(26.0)))
883                    .size(px(16.0))
884                    .flex_none()
885                    .child(
886                        canvas(
887                            |_, _, _| {},
888                            move |rect, _, window, _| {
889                                let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
890                                let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
891                                paint_rotated_chevron(
892                                    cx_pt,
893                                    cy_pt,
894                                    chevron_deg,
895                                    chevron_color,
896                                    window,
897                                );
898                            },
899                        )
900                        .size_full(),
901                    ),
902            );
903
904        // Trailing clear button positioned at `right: 36px` inside `.control`.
905        let int_clear_click = internal.clone();
906        let int_clear_down = internal.clone();
907        let int_clear_up = internal.clone();
908        let int_clear_out = internal.clone();
909        let on_change_clear = self.on_value_change.clone();
910        let clear_hover_bg = colors.surface;
911        let clear_hover_fg = colors.foreground;
912
913        let clear_el = if render_clear {
914            let btn_sz = (22.0 * clear_scale).clamp(13.0, 24.0);
915            let icon_sz = (14.0 * clear_scale).clamp(9.0, 15.0);
916            let top_offset = (44.0 - btn_sz) * 0.5;
917            Some(
918                div()
919                    .absolute()
920                    .top(px(top_offset))
921                    .right(px(36.0 + (22.0 - btn_sz) * 0.5))
922                    .child(
923                        BaseButton::new(ElementId::NamedChild(
924                            self.id.clone().into(),
925                            "clear".into(),
926                        ))
927                        .accessibility_label("Clear selections")
928                        .on_click(move |_, window, cx| {
929                            int_clear_click.update(cx, |s, _| {
930                                s.uncontrolled_value.clear();
931                                s.open = false;
932                                s.active_index = None;
933                                s.clear_pressed = false;
934                            });
935                            if let Some(cb) = &on_change_clear {
936                                cb(&[], window, cx);
937                            }
938                            window.refresh();
939                        })
940                        .w(px(btn_sz))
941                        .h(px(btn_sz))
942                        .flex()
943                        .items_center()
944                        .justify_center()
945                        .rounded(Radii::PILL)
946                        .opacity((clear_op * clear_blur.opacity_multiplier).clamp(0.0, 1.0))
947                        .text_color(colors.text_muted)
948                        .cursor_pointer()
949                        .hover(move |s| s.bg(clear_hover_bg).text_color(clear_hover_fg))
950                        .on_mouse_down(MouseButton::Left, move |_, window, cx| {
951                            int_clear_down.update(cx, |s, _| s.clear_pressed = true);
952                            window.refresh();
953                        })
954                        .on_mouse_up(MouseButton::Left, move |_, window, cx| {
955                            int_clear_up.update(cx, |s, _| s.clear_pressed = false);
956                            window.refresh();
957                        })
958                        .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
959                            int_clear_out.update(cx, |s, _| s.clear_pressed = false);
960                            window.refresh();
961                        })
962                        .child(Icon::new(IconName::X).text_size(px(icon_sz))),
963                    ),
964            )
965        } else {
966            None
967        };
968
969        // Floating multiselect menu (`top: calc(100% + 8px)`, `Radii::PANEL` 26px, `5px` padding).
970        let menu_el = if menu_presence.should_render() && !self.options.is_empty() {
971            let p = menu_presence.progress.clamp(0.0, 1.0);
972            let menu_bounds_ref = snap.menu_bounds.clone();
973            let menu_probe = canvas(
974                move |rect, _, _| {
975                    *menu_bounds_ref.borrow_mut() = Some(rect);
976                },
977                |_, _, _, _| {},
978            )
979            .absolute()
980            .inset_0();
981
982            let int_key = internal.clone();
983            let options_for_key = self.options.clone();
984            let selected_for_key = selected.clone();
985            let on_change_key = self.on_value_change.clone();
986            let focus_handle = snap.focus_handle.clone();
987
988            let option_els = self
989                .options
990                .into_iter()
991                .enumerate()
992                .map(|(idx, option)| {
993                    let is_checked = selected.iter().any(|v| v == &option.value);
994                    let is_active = snap.active_index == Some(idx) && !option.disabled;
995                    let check_len = arc_transition(
996                        (self.id.clone(), format!("check-len-{}", option.value)),
997                        if is_checked { 1.0 } else { 0.0 },
998                        if reduced {
999                            motion.duration.instant
1000                        } else if is_checked {
1001                            motion.duration.standard
1002                        } else {
1003                            motion.duration.instant
1004                        },
1005                        if is_checked {
1006                            motion.ease.enter
1007                        } else {
1008                            motion.ease.standard
1009                        },
1010                        window,
1011                        cx,
1012                    );
1013                    let check_op = arc_transition(
1014                        (self.id.clone(), format!("check-op-{}", option.value)),
1015                        if is_checked { 1.0 } else { 0.0 },
1016                        motion.duration.instant,
1017                        motion.ease.standard,
1018                        window,
1019                        cx,
1020                    );
1021
1022                    let row_bg = if is_active {
1023                        colors.surface_muted
1024                    } else {
1025                        Hsla::transparent_black()
1026                    };
1027                    let int_hi = internal.clone();
1028                    let int_toggle = internal.clone();
1029                    let on_change = self.on_value_change.clone();
1030                    let cur_selected = selected.clone();
1031                    let opt_val = option.value.clone();
1032                    let opt_label = option.label.clone();
1033                    let opt_disabled = option.disabled;
1034                    let check_color = colors.foreground;
1035
1036                    div()
1037                        .id(ElementId::NamedChild(
1038                            self.id.clone().into(),
1039                            SharedString::from(format!("option-{}", option.value)),
1040                        ))
1041                        .test_support()
1042                        .role(Role::ListBoxOption)
1043                        .aria_label(opt_label.clone())
1044                        .w_full()
1045                        .min_h(px(38.0))
1046                        .px(px(11.0))
1047                        .flex()
1048                        .flex_row()
1049                        .items_center()
1050                        .justify_between()
1051                        .gap(px(12.0))
1052                        .rounded((Radii::PANEL - px(4.0)).max(px(4.0)))
1053                        .bg(row_bg)
1054                        .text_size(Typography::TEXT_SM)
1055                        .text_color(colors.foreground)
1056                        .opacity(if opt_disabled { 0.42 } else { 1.0 })
1057                        .when(!opt_disabled, |this| this.cursor_pointer())
1058                        .on_hover(move |hovered, window, cx| {
1059                            if opt_disabled {
1060                                return;
1061                            }
1062                            int_hi.update(cx, |s, _| {
1063                                if *hovered {
1064                                    s.active_index = Some(idx);
1065                                }
1066                            });
1067                            window.refresh();
1068                        })
1069                        .on_click(move |_, window, cx| {
1070                            if opt_disabled {
1071                                return;
1072                            }
1073                            let next_vals = toggle_multi_select_value(&cur_selected, &opt_val);
1074                            int_toggle.update(cx, |s, _| {
1075                                s.uncontrolled_value = next_vals.clone();
1076                                s.active_index = Some(idx);
1077                            });
1078                            if let Some(cb) = &on_change {
1079                                cb(&next_vals, window, cx);
1080                            }
1081                            window.refresh();
1082                        })
1083                        .child(div().flex_1().min_w_0().truncate().child(opt_label))
1084                        .child(
1085                            div().size(px(16.0)).flex_none().child(
1086                                canvas(
1087                                    |_, _, _| {},
1088                                    move |rect, _, window, _| {
1089                                        paint_drawn_check(
1090                                            rect.origin.x,
1091                                            rect.origin.y,
1092                                            check_len,
1093                                            check_op,
1094                                            check_color,
1095                                            window,
1096                                        );
1097                                    },
1098                                )
1099                                .size_full(),
1100                            ),
1101                        )
1102                        .into_any_element()
1103                })
1104                .collect::<Vec<_>>();
1105
1106            Some(
1107                deferred(
1108                    div()
1109                        .id(ElementId::NamedChild(
1110                            self.id.clone().into(),
1111                            "listbox".into(),
1112                        ))
1113                        .test_support()
1114                        .role(Role::ListBox)
1115                        .track_focus(&focus_handle)
1116                        .on_key_down(move |event: &KeyDownEvent, window, cx| {
1117                            match event.keystroke.key.as_str() {
1118                                "escape" => {
1119                                    int_key.update(cx, |s, _| {
1120                                        s.open = false;
1121                                        s.active_index = None;
1122                                    });
1123                                    window.refresh();
1124                                }
1125                                "down" | "arrowdown" => {
1126                                    let cur = int_key.read(cx).active_index;
1127                                    if let Some(next_idx) =
1128                                        next_enabled_multi_select_option(&options_for_key, cur, 1)
1129                                    {
1130                                        int_key.update(cx, |s, _| {
1131                                            s.active_index = Some(next_idx);
1132                                        });
1133                                        window.refresh();
1134                                    }
1135                                }
1136                                "up" | "arrowup" => {
1137                                    let cur = int_key.read(cx).active_index;
1138                                    if let Some(prev_idx) =
1139                                        next_enabled_multi_select_option(&options_for_key, cur, -1)
1140                                    {
1141                                        int_key.update(cx, |s, _| {
1142                                            s.active_index = Some(prev_idx);
1143                                        });
1144                                        window.refresh();
1145                                    }
1146                                }
1147                                "enter" | " " | "space" => {
1148                                    let active = int_key.read(cx).active_index;
1149                                    if let Some(idx) = active
1150                                        && let Some(opt) = options_for_key.get(idx)
1151                                        && !opt.disabled
1152                                    {
1153                                        let next_vals = toggle_multi_select_value(
1154                                            &selected_for_key,
1155                                            &opt.value,
1156                                        );
1157                                        int_key.update(cx, |s, _| {
1158                                            s.uncontrolled_value = next_vals.clone();
1159                                        });
1160                                        if let Some(cb) = &on_change_key {
1161                                            cb(&next_vals, window, cx);
1162                                        }
1163                                        window.refresh();
1164                                    }
1165                                }
1166                                _ => {}
1167                            }
1168                        })
1169                        .absolute()
1170                        .top_full()
1171                        .left_0()
1172                        .right_0()
1173                        .mt(px(8.0 + menu_y))
1174                        .p(px(5.0))
1175                        .rounded(Radii::PANEL)
1176                        .border_1()
1177                        .border_color(colors.border)
1178                        .bg(colors.surface_raised)
1179                        .shadow(Shadows::floating(theme.mode))
1180                        .opacity(p)
1181                        .overflow_hidden()
1182                        .child(menu_probe)
1183                        .child(div().w_full().flex().flex_col().children(option_els)),
1184                )
1185                .with_priority(20),
1186            )
1187        } else {
1188            None
1189        };
1190
1191        div()
1192            .id(self.id)
1193            .test_support()
1194            .when_some(self.width, |this, w| this.w(w))
1195            .when(self.width.is_none(), |this| this.w_full())
1196            .flex()
1197            .flex_col()
1198            .gap(Spacing::S2)
1199            .child(
1200                div()
1201                    .text_size(Typography::TEXT_SM)
1202                    .font_medium()
1203                    .text_color(colors.foreground)
1204                    .child(self.label),
1205            )
1206            .child(
1207                div()
1208                    .relative()
1209                    .w_full()
1210                    .child(trigger)
1211                    .when_some(clear_el, |this, btn| this.child(btn))
1212                    .when_some(menu_el, |this, m| this.child(m)),
1213            )
1214            .when_some(self.description, |this, desc| {
1215                this.child(
1216                    div()
1217                        .text_size(Typography::TEXT_XS)
1218                        .text_color(colors.text_muted)
1219                        .child(desc),
1220                )
1221            })
1222    }
1223}
1224
1225#[cfg(test)]
1226mod tests {
1227    use super::*;
1228
1229    #[test]
1230    fn toggle_multi_select_value_adds_and_removes_preserving_order() {
1231        let initial: Vec<SharedString> = vec!["rust".into(), "gpui".into()];
1232        let added = toggle_multi_select_value(&initial, &"metal".into());
1233        assert_eq!(
1234            added,
1235            vec![
1236                SharedString::from("rust"),
1237                SharedString::from("gpui"),
1238                SharedString::from("metal")
1239            ]
1240        );
1241
1242        let removed = toggle_multi_select_value(&added, &"rust".into());
1243        assert_eq!(
1244            removed,
1245            vec![SharedString::from("gpui"), SharedString::from("metal")]
1246        );
1247    }
1248
1249    #[test]
1250    fn multi_select_count_roll_moves_directionally_and_settles() {
1251        let (in_op0, in_y0, out_op0, _) = multi_select_count_roll_sample(0.0, 1, false);
1252        assert!(in_op0 < 0.01);
1253        assert!((in_y0 - 6.0).abs() < 1e-4);
1254        assert!(out_op0 > 0.99);
1255
1256        let (_, in_y_neg, _, out_y_neg) = multi_select_count_roll_sample(0.06, -1, false);
1257        assert!(in_y_neg < 0.0);
1258        assert!(out_y_neg > 0.0);
1259
1260        let (in_op_done, in_y_done, out_op_done, _) =
1261            multi_select_count_roll_sample(0.28, 1, false);
1262        assert!((in_op_done - 1.0).abs() < 1e-4);
1263        assert!(in_y_done.abs() < 1e-4);
1264        assert!(out_op_done < 1e-4);
1265    }
1266
1267    #[test]
1268    fn next_enabled_multi_select_option_skips_disabled_and_wraps() {
1269        let options = vec![
1270            MultiSelectOption::new("a", "Alpha"),
1271            MultiSelectOption::new("b", "Beta").disabled(true),
1272            MultiSelectOption::new("c", "Gamma"),
1273        ];
1274        assert_eq!(next_enabled_multi_select_option(&options, None, 1), Some(0));
1275        assert_eq!(
1276            next_enabled_multi_select_option(&options, Some(0), 1),
1277            Some(2)
1278        );
1279        assert_eq!(
1280            next_enabled_multi_select_option(&options, Some(2), 1),
1281            Some(0)
1282        );
1283    }
1284}