Skip to main content

arc_ui/inputs/
select.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/select/select.tsx` & `.module.css`
3//!
4//! P4 Component #1: `select`
5//!
6//! - Field layout: vertical stack (`gap: space-2`) with top label (`text-sm`, `font-medium`),
7//!   44px trigger (`ControlHeights::MD`, `Radii::CONTROL`, `1px border`, `surface` fill, press
8//!   feedback in colour only so the anchored floating menu measures a stable rect), and optional
9//!   bottom description (`text-xs`, `text_muted`).
10//! - Directional value roll (`valueRoll` / `valueFade`): when the selected option changes, the
11//!   displayed label rolls along the list direction (`+1` when moving to a later option, `-1`
12//!   when moving to an earlier option):
13//!   - Incoming value rises from `direction * 0.35em` (`4.9px`) to `0` over `duration.standard`
14//!     (`240ms`, `ease.enter`) while sharpening from `blur.soft (4px)` to `0px`.
15//!   - Outgoing value exits toward `direction * -0.3em` (`-4.2px`) over `duration.fast` (`160ms`,
16//!     `ease.standard`) with `blur.subtle (2px)`.
17//!   - Under `prefers-reduced-motion`, both use a short `duration.instant` (`120ms`) crossfade.
18//! - Rotating chevron: `0° -> 180°` on `motion.spring.snappy` when open.
19//! - Floating menu (`select-in` / `select-out`): anchored `4px` below the trigger (matching the
20//!   trigger width), `Radii::CONTROL + 2px` (`24px`), `6px` padding, `surface_raised`, floating
21//!   shadow; enters over `duration.standard` (`240ms`, `ease.enter`) from `y = -6px, scale = 0.97`
22//!   and exits over `duration.instant` (`120ms`, `ease.standard`).
23//! - Check indicator (`indicator-in`): selected option renders a checkmark at `right: 10px` that
24//!   enters after a `40ms` delay over `duration.standard` (`240ms`, `ease.enter`) from `scale(0.6)`
25//!   and `blur(2px)`.
26
27use std::{cell::RefCell, rc::Rc, time::Duration};
28
29use arc_motion::{
30    ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, arc_spring, arc_transition,
31    is_reduced_motion, motion_now,
32};
33use arc_tokens::{
34    ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, Typography, oklab_mix,
35};
36use gpui_kit::{
37    App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
38    MouseDownEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
39    TestSupportExt as _, Window,
40    base::{Button as BaseButton, StyledExt as _},
41    canvas, deferred, div, point,
42    prelude::*,
43    px,
44};
45
46type SelectChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
47
48/// Base font size (`14px`, `--text-sm`) used to convert `0.35em` / `-0.3em` value roll offsets.
49pub const SELECT_TEXT_EM_PX: f32 = 14.0;
50/// Delay (`40ms`) before the selected option checkmark plays `indicator-in`.
51pub const SELECT_INDICATOR_DELAY_SECS: f64 = 0.04;
52
53/// Sampled `(enter_opacity, enter_y_px, exit_opacity, exit_y_px)` for the directional value roll
54/// at `elapsed` seconds after a selection change.
55///
56/// - `direction`: `+1` when moving to a later option (rises from below), `-1` when moving to an
57///   earlier option (drops from above).
58pub fn select_value_roll_sample(
59    elapsed: f64,
60    direction: i8,
61    reduced: bool,
62) -> (f32, f32, f32, f32) {
63    let dir = if direction >= 0 { 1.0_f32 } else { -1.0_f32 };
64    if reduced {
65        let t = (elapsed / 0.12).clamp(0.0, 1.0) as f32;
66        return (t, 0.0, 1.0 - t, 0.0);
67    }
68
69    // Incoming: 240ms (duration.standard), ease.enter (0.16, 1, 0.3, 1), y: dir * 0.35em -> 0, blur: 4px -> 0.
70    let t_in = (elapsed / 0.24).clamp(0.0, 1.0) as f32;
71    let e_in = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t_in);
72    let blur_in = BlurFallback::evaluate(px(4.0 * (1.0 - e_in)), false);
73    let enter_op = (e_in * blur_in.opacity_multiplier).clamp(0.0, 1.0);
74    let enter_y = dir * (0.35 * SELECT_TEXT_EM_PX) * (1.0 - e_in);
75
76    // Outgoing: 160ms (duration.fast), ease.standard (0.22, 1, 0.36, 1), y: 0 -> dir * -0.3em, blur: 0 -> 2px.
77    let t_out = (elapsed / 0.16).clamp(0.0, 1.0) as f32;
78    let e_out = CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t_out);
79    let blur_out = BlurFallback::evaluate(px(2.0 * e_out), false);
80    let exit_op = ((1.0 - e_out) * blur_out.opacity_multiplier).clamp(0.0, 1.0);
81    let exit_y = -dir * (0.30 * SELECT_TEXT_EM_PX) * e_out;
82
83    (enter_op, enter_y, exit_op, exit_y)
84}
85
86/// Sampled `(opacity, scale)` for the selected item checkmark (`indicator-in`: `240ms` with `40ms`
87/// delay, `ease.enter`, `scale(0.6) -> 1.0`, `blur(2px) -> 0`).
88pub fn select_indicator_sample(elapsed: f64, reduced: bool) -> (f32, f32) {
89    if reduced {
90        return (1.0, 1.0);
91    }
92    if elapsed <= SELECT_INDICATOR_DELAY_SECS {
93        return (0.0, 0.6);
94    }
95    let t = ((elapsed - SELECT_INDICATOR_DELAY_SECS) / 0.24).clamp(0.0, 1.0) as f32;
96    let e = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t);
97    let blur = BlurFallback::evaluate(px(2.0 * (1.0 - e)), false);
98    let op = (e * blur.opacity_multiplier).clamp(0.0, 1.0);
99    let scale = 0.6 + 0.4 * e;
100    (op, scale)
101}
102
103/// Loops forward (`step = 1`) or backward (`step = -1`) to the next enabled option index.
104pub fn next_enabled_select_option(
105    options: &[SelectOption],
106    current: Option<usize>,
107    step: isize,
108) -> Option<usize> {
109    if options.is_empty() {
110        return None;
111    }
112    let len = options.len() as isize;
113    let start = match current {
114        Some(idx) => idx as isize,
115        None => {
116            if step > 0 {
117                -1
118            } else {
119                len
120            }
121        }
122    };
123    for offset in 1..=len {
124        let idx = (start + step * offset).rem_euclid(len) as usize;
125        if !options[idx].disabled {
126            return Some(idx);
127        }
128    }
129    None
130}
131
132/// One option inside [`Select`].
133#[derive(Clone, Debug, PartialEq, Eq)]
134pub struct SelectOption {
135    pub value: SharedString,
136    pub label: SharedString,
137    pub disabled: bool,
138}
139
140impl SelectOption {
141    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
142        Self {
143            value: value.into(),
144            label: label.into(),
145            disabled: false,
146        }
147    }
148
149    pub fn disabled(mut self, disabled: bool) -> Self {
150        self.disabled = disabled;
151        self
152    }
153}
154
155#[derive(Clone)]
156struct SelectInternal {
157    open: bool,
158    opened_at_secs: f64,
159    uncontrolled_value: SharedString,
160    previous_index: Option<usize>,
161    previous_shown: Option<SharedString>,
162    direction: i8,
163    roll_started_at_secs: f64,
164    highlighted: Option<usize>,
165    trigger_hovered: bool,
166    trigger_pressed: bool,
167    trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
168    menu_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
169    focus_handle: FocusHandle,
170}
171
172impl SelectInternal {
173    fn new(
174        default_value: SharedString,
175        initial_index: Option<usize>,
176        now: f64,
177        focus_handle: FocusHandle,
178    ) -> Self {
179        Self {
180            open: false,
181            opened_at_secs: now - 10.0,
182            uncontrolled_value: default_value,
183            previous_index: initial_index,
184            previous_shown: None,
185            direction: 1,
186            roll_started_at_secs: now - 10.0,
187            highlighted: initial_index,
188            trigger_hovered: false,
189            trigger_pressed: false,
190            trigger_bounds: Rc::new(RefCell::new(None)),
191            menu_bounds: Rc::new(RefCell::new(None)),
192            focus_handle,
193        }
194    }
195}
196
197fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
198    let rad = angle_deg.to_radians();
199    let cos_a = rad.cos();
200    let sin_a = rad.sin();
201    let pts = [(-4.0_f32, -2.0_f32), (0.0, 2.0), (4.0, -2.0)];
202    let mut builder = PathBuilder::stroke(px(1.75));
203    for (i, (lx, ly)) in pts.iter().enumerate() {
204        let rx = cx + lx * cos_a - ly * sin_a;
205        let ry = cy + lx * sin_a + ly * cos_a;
206        let p = point(px(rx), px(ry));
207        if i == 0 {
208            builder.move_to(p);
209        } else {
210            builder.line_to(p);
211        }
212    }
213    if let Ok(path) = builder.build() {
214        window.paint_path(path, color);
215    }
216}
217
218fn paint_scaled_check(cx: f32, cy: f32, scale: f32, color: Hsla, window: &mut Window) {
219    let pts = [(-4.5_f32, 0.2_f32), (-1.4, 3.3), (4.8, -3.2)];
220    let mut builder = PathBuilder::stroke(px(1.75));
221    for (i, (lx, ly)) in pts.iter().enumerate() {
222        let p = point(px(cx + lx * scale), px(cy + ly * scale));
223        if i == 0 {
224            builder.move_to(p);
225        } else {
226            builder.line_to(p);
227        }
228    }
229    if let Ok(path) = builder.build() {
230        window.paint_path(path, color);
231    }
232}
233
234/// Arc `Select` — single-value dropdown selector with directional value-roll transition,
235/// `spring.snappy` rotating chevron, and a trigger-width floating listbox.
236#[derive(IntoElement)]
237pub struct Select {
238    id: ElementId,
239    label: SharedString,
240    description: Option<SharedString>,
241    placeholder: SharedString,
242    options: Vec<SelectOption>,
243    value: Option<SharedString>,
244    default_value: Option<SharedString>,
245    disabled: bool,
246    width: Option<Pixels>,
247    on_value_change: Option<SelectChangeHandler>,
248}
249
250impl Select {
251    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
252        Self {
253            id: id.into(),
254            label: label.into(),
255            description: None,
256            placeholder: "Select an option".into(),
257            options: Vec::new(),
258            value: None,
259            default_value: None,
260            disabled: false,
261            width: None,
262            on_value_change: None,
263        }
264    }
265
266    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
267        self.description = Some(description.into());
268        self
269    }
270
271    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
272        self.placeholder = placeholder.into();
273        self
274    }
275
276    pub fn option(mut self, option: SelectOption) -> Self {
277        self.options.push(option);
278        self
279    }
280
281    pub fn options(mut self, options: impl IntoIterator<Item = SelectOption>) -> Self {
282        self.options.extend(options);
283        self
284    }
285
286    pub fn value(mut self, value: impl Into<SharedString>) -> Self {
287        self.value = Some(value.into());
288        self
289    }
290
291    pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
292        self.default_value = Some(value.into());
293        self
294    }
295
296    pub fn disabled(mut self, disabled: bool) -> Self {
297        self.disabled = disabled;
298        self
299    }
300
301    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
302        self.width = Some(width.into());
303        self
304    }
305
306    pub fn on_value_change(
307        mut self,
308        handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
309    ) -> Self {
310        self.on_value_change = Some(Rc::new(handler));
311        self
312    }
313}
314
315impl RenderOnce for Select {
316    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
317        let theme = cx.arc_theme().clone();
318        let colors = theme.colors;
319        let motion = theme.motion;
320        let reduced = is_reduced_motion(cx);
321        let now = motion_now(cx);
322
323        let initial_val = self
324            .value
325            .clone()
326            .or_else(|| self.default_value.clone())
327            .unwrap_or_default();
328        let initial_idx = self.options.iter().position(|opt| opt.value == initial_val);
329
330        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-select-state".into());
331        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
332            SelectInternal::new(initial_val.clone(), initial_idx, now, cx.focus_handle())
333        });
334
335        let current_value = self
336            .value
337            .clone()
338            .unwrap_or_else(|| internal.read(cx).uncontrolled_value.clone());
339        let current_index = self
340            .options
341            .iter()
342            .position(|opt| opt.value == current_value);
343        let shown: SharedString = current_index
344            .and_then(|idx| self.options.get(idx))
345            .map(|opt| opt.label.clone())
346            .unwrap_or_else(|| self.placeholder.clone());
347        let is_placeholder = current_index.is_none();
348
349        // Detect external or internal index change to trigger the directional value roll.
350        {
351            let prev_idx = internal.read(cx).previous_index;
352            if prev_idx != current_index {
353                let prev_label = prev_idx
354                    .and_then(|idx| self.options.get(idx))
355                    .map(|opt| opt.label.clone())
356                    .unwrap_or_else(|| self.placeholder.clone());
357                let dir = match (current_index, prev_idx) {
358                    (Some(cur), Some(prev)) => {
359                        if cur >= prev {
360                            1
361                        } else {
362                            -1
363                        }
364                    }
365                    (Some(_), None) => 1,
366                    (None, Some(_)) => -1,
367                    (None, None) => 1,
368                };
369                internal.update(cx, |s, _| {
370                    s.previous_index = current_index;
371                    s.previous_shown = Some(prev_label);
372                    s.direction = dir;
373                    s.roll_started_at_secs = now;
374                });
375            }
376        }
377
378        let snap = internal.read(cx).clone();
379        let is_open = snap.open && !self.disabled;
380
381        // Chevron rotation `0 -> 180` on `motion.spring.snappy`.
382        let chevron_deg = if reduced {
383            if is_open { 180.0 } else { 0.0 }
384        } else {
385            arc_spring(
386                (self.id.clone(), "chevron-deg"),
387                if is_open { 180.0 } else { 0.0 },
388                motion.spring.snappy,
389                window,
390                cx,
391            )
392        };
393
394        // Value roll interpolation (`240ms` enter / `160ms` exit).
395        let roll_elapsed = (now - snap.roll_started_at_secs).max(0.0);
396        let roll_total_dur = if reduced { 0.12 } else { 0.24 };
397        let (enter_op, enter_y, exit_op, exit_y) = if roll_elapsed < roll_total_dur {
398            window.request_animation_frame();
399            select_value_roll_sample(roll_elapsed, snap.direction, reduced)
400        } else {
401            (1.0, 0.0, 0.0, 0.0)
402        };
403
404        // Trigger hover/open background & border transition (`duration.fast` = 160ms).
405        let hover_p = arc_transition(
406            (self.id.clone(), "trigger-hover"),
407            if !self.disabled && (is_open || snap.trigger_hovered || snap.trigger_pressed) {
408                1.0
409            } else {
410                0.0
411            },
412            if reduced {
413                Duration::ZERO
414            } else {
415                motion.duration.fast
416            },
417            motion.ease.standard,
418            window,
419            cx,
420        );
421        let trigger_bg = oklab_mix(colors.surface_muted, colors.surface, hover_p);
422        let trigger_border = oklab_mix(colors.border_strong, colors.border, hover_p);
423
424        // Floating menu presence (`duration.standard` 240ms enter / `duration.instant` 120ms exit).
425        let content_presence = ArcPresence::new((self.id.clone(), "content-presence"), is_open)
426            .animate_initial(false)
427            .config(ArcPresenceConfig {
428                enter_duration: motion.duration.standard,
429                exit_duration: motion.duration.instant,
430                enter_ease: motion.ease.enter,
431                exit_ease: motion.ease.standard,
432                fade_on_reduced_motion: true,
433            })
434            .sample(window, cx);
435
436        let trigger_bounds_ref = snap.trigger_bounds.clone();
437        let trigger_bounds_outside = snap.trigger_bounds.clone();
438        let menu_bounds_outside = snap.menu_bounds.clone();
439        let internal_outside = internal.clone();
440        let trigger_probe = canvas(
441            move |rect, _, _| {
442                *trigger_bounds_ref.borrow_mut() = Some(rect);
443            },
444            move |_, _, window, _| {
445                if is_open {
446                    let t_ref = trigger_bounds_outside.clone();
447                    let m_ref = menu_bounds_outside.clone();
448                    let st = internal_outside.clone();
449                    window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
450                        if !phase.bubble() {
451                            return;
452                        }
453                        let in_trigger =
454                            t_ref.borrow().is_some_and(|b| b.contains(&event.position));
455                        let in_menu = m_ref.borrow().is_some_and(|b| b.contains(&event.position));
456                        if !in_trigger && !in_menu {
457                            st.update(cx, |s, _| {
458                                s.open = false;
459                            });
460                            window.refresh();
461                        }
462                    });
463                }
464            },
465        )
466        .absolute()
467        .inset_0();
468
469        let trigger_id = ElementId::NamedChild(self.id.clone().into(), "trigger".into());
470        let int_hover = internal.clone();
471        let int_down = internal.clone();
472        let int_up = internal.clone();
473        let int_out = internal.clone();
474        let int_click = internal.clone();
475        let focus_for_open = snap.focus_handle.clone();
476        let options_for_open = self.options.clone();
477        let disabled = self.disabled;
478        let chevron_color = colors.text_muted;
479        let value_fg = if is_placeholder {
480            colors.text_muted
481        } else {
482            colors.foreground
483        };
484
485        let mut value_slot = div()
486            .relative()
487            .flex_1()
488            .min_w_0()
489            .h(px(20.0))
490            .overflow_hidden()
491            .child(
492                div()
493                    .w_full()
494                    .mt(px(enter_y))
495                    .opacity(enter_op)
496                    .text_color(value_fg)
497                    .truncate()
498                    .child(shown.clone()),
499            );
500
501        if exit_op > 0.01
502            && let Some(prev_text) = snap.previous_shown.clone()
503        {
504            value_slot = value_slot.child(
505                div()
506                    .absolute()
507                    .top_0()
508                    .left_0()
509                    .right_0()
510                    .mt(px(exit_y))
511                    .opacity(exit_op)
512                    .text_color(colors.text_secondary)
513                    .truncate()
514                    .child(prev_text),
515            );
516        }
517
518        let trigger = BaseButton::new(trigger_id)
519            .accessibility_label(self.label.clone())
520            .disabled(disabled)
521            .on_click(move |_, window, cx| {
522                if disabled {
523                    return;
524                }
525                let t_now = motion_now(cx);
526                let mut became_open = false;
527                int_click.update(cx, |s, _| {
528                    s.open = !s.open;
529                    became_open = s.open;
530                    if s.open {
531                        s.opened_at_secs = t_now;
532                        s.highlighted = current_index
533                            .or_else(|| next_enabled_select_option(&options_for_open, None, 1));
534                    }
535                });
536                if became_open {
537                    window.focus(&focus_for_open, cx);
538                }
539                window.refresh();
540            })
541            .relative()
542            .w_full()
543            .min_h(ControlHeights::MD)
544            .px(Spacing::S3)
545            .flex()
546            .flex_row()
547            .items_center()
548            .justify_between()
549            .gap(Spacing::S3)
550            .rounded(Radii::CONTROL)
551            .border_1()
552            .border_color(trigger_border)
553            .bg(trigger_bg)
554            .text_size(Typography::TEXT_SM)
555            .opacity(if disabled { 0.5 } else { 1.0 })
556            .when(!disabled, |this| this.cursor_pointer())
557            .on_hover(move |hovered, window, cx| {
558                int_hover.update(cx, |s, _| {
559                    s.trigger_hovered = *hovered;
560                    if !*hovered {
561                        s.trigger_pressed = false;
562                    }
563                });
564                window.refresh();
565            })
566            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
567                if !disabled {
568                    int_down.update(cx, |s, _| s.trigger_pressed = true);
569                    window.refresh();
570                }
571            })
572            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
573                int_up.update(cx, |s, _| s.trigger_pressed = false);
574                window.refresh();
575            })
576            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
577                int_out.update(cx, |s, _| s.trigger_pressed = false);
578                window.refresh();
579            })
580            .child(trigger_probe)
581            .child(value_slot)
582            .child(
583                canvas(
584                    |_, _, _| {},
585                    move |rect, _, window, _| {
586                        let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
587                        let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
588                        paint_rotated_chevron(cx_pt, cy_pt, chevron_deg, chevron_color, window);
589                    },
590                )
591                .size(px(16.0))
592                .flex_none(),
593            );
594
595        // Floating listbox content (`position="popper"`, `sideOffset={4}`).
596        let menu_el = if content_presence.should_render() && !self.options.is_empty() {
597            let p = content_presence.progress.clamp(0.0, 1.0);
598            let menu_y = if reduced { 0.0 } else { -6.0 * (1.0 - p) };
599            let menu_elapsed = (now - snap.opened_at_secs).max(0.0);
600            let (ind_op, ind_scale) = select_indicator_sample(menu_elapsed, reduced);
601            if is_open && !reduced && menu_elapsed < SELECT_INDICATOR_DELAY_SECS + 0.24 {
602                window.request_animation_frame();
603            }
604
605            let menu_bounds_ref = snap.menu_bounds.clone();
606            let menu_probe = canvas(
607                move |rect, _, _| {
608                    *menu_bounds_ref.borrow_mut() = Some(rect);
609                },
610                |_, _, _, _| {},
611            )
612            .absolute()
613            .inset_0();
614
615            let int_key = internal.clone();
616            let options_for_key = self.options.clone();
617            let on_change_key = self.on_value_change.clone();
618            let focus_handle = snap.focus_handle.clone();
619            let menu_id = ElementId::NamedChild(self.id.clone().into(), "content".into());
620
621            let shown_for_key = shown.clone();
622            let item_els = self
623                .options
624                .into_iter()
625                .enumerate()
626                .map(|(idx, option)| {
627                    let shown_for_item = shown.clone();
628                    let item_id = ElementId::NamedChild(
629                        self.id.clone().into(),
630                        SharedString::from(format!("option-{idx}")),
631                    );
632                    let is_selected = current_index == Some(idx);
633                    let is_highlighted = snap.highlighted == Some(idx) && !option.disabled;
634                    let item_bg = if is_highlighted {
635                        colors.surface_muted
636                    } else {
637                        Hsla::transparent_black()
638                    };
639                    let int_hi = internal.clone();
640                    let int_sel = internal.clone();
641                    let on_change = self.on_value_change.clone();
642                    let opt_val = option.value.clone();
643                    let opt_label = option.label.clone();
644                    let opt_disabled = option.disabled;
645                    let check_color = colors.foreground;
646
647                    div()
648                        .id(item_id)
649                        .test_support()
650                        .role(Role::ListBoxOption)
651                        .aria_label(opt_label.clone())
652                        .relative()
653                        .w_full()
654                        .min_h(px(30.0))
655                        .pl(px(10.0))
656                        .pr(px(30.0))
657                        .flex()
658                        .flex_row()
659                        .items_center()
660                        .rounded((Radii::CONTROL - px(2.0)).max(px(4.0)))
661                        .bg(item_bg)
662                        .text_size(Typography::TEXT_SM)
663                        .text_color(colors.foreground)
664                        .opacity(if opt_disabled { 0.45 } else { 1.0 })
665                        .when(!opt_disabled, |this| this.cursor_pointer())
666                        .on_hover(move |hovered, window, cx| {
667                            if opt_disabled {
668                                return;
669                            }
670                            int_hi.update(cx, |s, _| {
671                                if *hovered {
672                                    s.highlighted = Some(idx);
673                                }
674                            });
675                            window.refresh();
676                        })
677                        .on_click(move |_, window, cx| {
678                            if opt_disabled {
679                                return;
680                            }
681                            let t_now = motion_now(cx);
682                            int_sel.update(cx, |s, _| {
683                                let prev_idx = s.previous_index;
684                                if prev_idx != Some(idx) {
685                                    s.direction = match prev_idx {
686                                        Some(prev) if idx < prev => -1,
687                                        _ => 1,
688                                    };
689                                    s.previous_shown = Some(shown_for_item.clone());
690                                    s.previous_index = Some(idx);
691                                    s.roll_started_at_secs = t_now;
692                                }
693                                s.uncontrolled_value = opt_val.clone();
694                                s.highlighted = Some(idx);
695                                s.open = false;
696                            });
697                            if let Some(cb) = &on_change {
698                                cb(&opt_val, window, cx);
699                            }
700                            window.refresh();
701                        })
702                        .child(div().flex_1().min_w_0().truncate().child(opt_label))
703                        .when(is_selected, |this| {
704                            this.child(
705                                div()
706                                    .absolute()
707                                    .right(px(10.0))
708                                    .size(px(16.0))
709                                    .opacity(ind_op)
710                                    .child(
711                                        canvas(
712                                            |_, _, _| {},
713                                            move |rect, _, window, _| {
714                                                let cx_pt = f32::from(
715                                                    rect.origin.x + rect.size.width * 0.5,
716                                                );
717                                                let cy_pt = f32::from(
718                                                    rect.origin.y + rect.size.height * 0.5,
719                                                );
720                                                paint_scaled_check(
721                                                    cx_pt,
722                                                    cy_pt,
723                                                    ind_scale,
724                                                    check_color,
725                                                    window,
726                                                );
727                                            },
728                                        )
729                                        .size_full(),
730                                    ),
731                            )
732                        })
733                        .into_any_element()
734                })
735                .collect::<Vec<_>>();
736            Some(
737                deferred(
738                    div()
739                        .id(menu_id)
740                        .test_support()
741                        .role(Role::ListBox)
742                        .track_focus(&focus_handle)
743                        .on_key_down(move |event: &KeyDownEvent, window, cx| {
744                            match event.keystroke.key.as_str() {
745                                "escape" => {
746                                    int_key.update(cx, |s, _| {
747                                        s.open = false;
748                                    });
749                                    window.refresh();
750                                }
751                                "down" | "arrowdown" => {
752                                    let cur = int_key.read(cx).highlighted;
753                                    if let Some(next) =
754                                        next_enabled_select_option(&options_for_key, cur, 1)
755                                    {
756                                        int_key.update(cx, |s, _| {
757                                            s.highlighted = Some(next);
758                                        });
759                                        window.refresh();
760                                    }
761                                }
762                                "up" | "arrowup" => {
763                                    let cur = int_key.read(cx).highlighted;
764                                    if let Some(prev) =
765                                        next_enabled_select_option(&options_for_key, cur, -1)
766                                    {
767                                        int_key.update(cx, |s, _| {
768                                            s.highlighted = Some(prev);
769                                        });
770                                        window.refresh();
771                                    }
772                                }
773                                "home" => {
774                                    if let Some(first) =
775                                        next_enabled_select_option(&options_for_key, None, 1)
776                                    {
777                                        int_key.update(cx, |s, _| {
778                                            s.highlighted = Some(first);
779                                        });
780                                        window.refresh();
781                                    }
782                                }
783                                "end" => {
784                                    if let Some(last) =
785                                        next_enabled_select_option(&options_for_key, None, -1)
786                                    {
787                                        int_key.update(cx, |s, _| {
788                                            s.highlighted = Some(last);
789                                        });
790                                        window.refresh();
791                                    }
792                                }
793                                "enter" | " " | "space" => {
794                                    let hi = int_key.read(cx).highlighted;
795                                    if let Some(idx) = hi
796                                        && let Some(opt) = options_for_key.get(idx)
797                                        && !opt.disabled
798                                    {
799                                        let next_val = opt.value.clone();
800                                        let t_now = motion_now(cx);
801                                        int_key.update(cx, |s, _| {
802                                            let prev_idx = s.previous_index;
803                                            if prev_idx != Some(idx) {
804                                                s.direction = match prev_idx {
805                                                    Some(prev) if idx < prev => -1,
806                                                    _ => 1,
807                                                };
808                                                s.previous_shown = Some(shown_for_key.clone());
809                                                s.previous_index = Some(idx);
810                                                s.roll_started_at_secs = t_now;
811                                            }
812                                            s.uncontrolled_value = next_val.clone();
813                                            s.open = false;
814                                        });
815                                        if let Some(cb) = &on_change_key {
816                                            cb(&next_val, window, cx);
817                                        }
818                                        window.refresh();
819                                    }
820                                }
821                                _ => {}
822                            }
823                        })
824                        .absolute()
825                        .top_full()
826                        .left_0()
827                        .right_0()
828                        .mt(px(4.0 + menu_y))
829                        .p(px(6.0))
830                        .rounded(Radii::CONTROL + px(2.0))
831                        .border_1()
832                        .border_color(colors.border)
833                        .bg(colors.surface_raised)
834                        .shadow(Shadows::floating(theme.mode))
835                        .opacity(p)
836                        .overflow_hidden()
837                        .child(menu_probe)
838                        .child(
839                            div()
840                                .w_full()
841                                .py(px(2.0))
842                                .flex()
843                                .flex_col()
844                                .children(item_els),
845                        ),
846                )
847                .with_priority(20),
848            )
849        } else {
850            None
851        };
852
853        div()
854            .id(self.id)
855            .test_support()
856            .when_some(self.width, |this, w| this.w(w))
857            .when(self.width.is_none(), |this| this.w_full())
858            .flex()
859            .flex_col()
860            .gap(Spacing::S2)
861            .child(
862                div()
863                    .text_size(Typography::TEXT_SM)
864                    .font_medium()
865                    .text_color(colors.foreground)
866                    .child(self.label),
867            )
868            .child(
869                div()
870                    .relative()
871                    .w_full()
872                    .child(trigger)
873                    .when_some(menu_el, |this, m| this.child(m)),
874            )
875            .when_some(self.description, |this, desc| {
876                this.child(
877                    div()
878                        .text_size(Typography::TEXT_XS)
879                        .text_color(colors.text_muted)
880                        .child(desc),
881                )
882            })
883    }
884}
885
886#[cfg(test)]
887mod tests {
888    use super::*;
889
890    #[test]
891    fn select_value_roll_moves_directionally_and_settles() {
892        let (op_start, y_start, exit_op_start, exit_y_start) =
893            select_value_roll_sample(0.0, 1, false);
894        assert!(op_start < 0.01);
895        assert!(y_start > 4.0);
896        assert!(exit_op_start > 0.99);
897        assert!(exit_y_start.abs() < 1e-4);
898
899        let (op_neg, y_neg, _, exit_y_neg) = select_value_roll_sample(0.08, -1, false);
900        assert!(op_neg > 0.2 && op_neg < 1.0);
901        assert!(y_neg < 0.0);
902        assert!(exit_y_neg > 0.0);
903
904        let (op_done, y_done, exit_op_done, _) = select_value_roll_sample(0.30, 1, false);
905        assert!((op_done - 1.0).abs() < 1e-4);
906        assert!(y_done.abs() < 1e-4);
907        assert!(exit_op_done < 1e-4);
908    }
909
910    #[test]
911    fn select_indicator_respects_40ms_delay_and_reduced_motion() {
912        let (op_before, scale_before) = select_indicator_sample(0.02, false);
913        assert!(op_before < 1e-4);
914        assert!((scale_before - 0.6).abs() < 1e-4);
915
916        let (op_mid, scale_mid) = select_indicator_sample(0.14, false);
917        assert!(op_mid > 0.3 && op_mid < 1.0);
918        assert!(scale_mid > 0.7 && scale_mid < 1.0);
919
920        let (op_red, scale_red) = select_indicator_sample(0.01, true);
921        assert!((op_red - 1.0).abs() < 1e-4);
922        assert!((scale_red - 1.0).abs() < 1e-4);
923    }
924
925    #[test]
926    fn next_enabled_select_option_skips_disabled_and_wraps() {
927        let options = vec![
928            SelectOption::new("a", "Alpha"),
929            SelectOption::new("b", "Beta").disabled(true),
930            SelectOption::new("c", "Gamma"),
931        ];
932        assert_eq!(next_enabled_select_option(&options, Some(0), 1), Some(2));
933        assert_eq!(next_enabled_select_option(&options, Some(2), 1), Some(0));
934        assert_eq!(next_enabled_select_option(&options, Some(0), -1), Some(2));
935    }
936}