arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/select/select.tsx` & `.module.css`
//!
//! P4 Component #1: `select`
//!
//! - Field layout: vertical stack (`gap: space-2`) with top label (`text-sm`, `font-medium`),
//!   44px trigger (`ControlHeights::MD`, `Radii::CONTROL`, `1px border`, `surface` fill, press
//!   feedback in colour only so the anchored floating menu measures a stable rect), and optional
//!   bottom description (`text-xs`, `text_muted`).
//! - Directional value roll (`valueRoll` / `valueFade`): when the selected option changes, the
//!   displayed label rolls along the list direction (`+1` when moving to a later option, `-1`
//!   when moving to an earlier option):
//!   - Incoming value rises from `direction * 0.35em` (`4.9px`) to `0` over `duration.standard`
//!     (`240ms`, `ease.enter`) while sharpening from `blur.soft (4px)` to `0px`.
//!   - Outgoing value exits toward `direction * -0.3em` (`-4.2px`) over `duration.fast` (`160ms`,
//!     `ease.standard`) with `blur.subtle (2px)`.
//!   - Under `prefers-reduced-motion`, both use a short `duration.instant` (`120ms`) crossfade.
//! - Rotating chevron: `0° -> 180°` on `motion.spring.snappy` when open.
//! - Floating menu (`select-in` / `select-out`): anchored `4px` below the trigger (matching the
//!   trigger width), `Radii::CONTROL + 2px` (`24px`), `6px` padding, `surface_raised`, floating
//!   shadow; enters over `duration.standard` (`240ms`, `ease.enter`) from `y = -6px, scale = 0.97`
//!   and exits over `duration.instant` (`120ms`, `ease.standard`).
//! - Check indicator (`indicator-in`): selected option renders a checkmark at `right: 10px` that
//!   enters after a `40ms` delay over `duration.standard` (`240ms`, `ease.enter`) from `scale(0.6)`
//!   and `blur(2px)`.

use std::{cell::RefCell, rc::Rc, time::Duration};

use arc_motion::{
    ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, arc_spring, arc_transition,
    is_reduced_motion, motion_now,
};
use arc_tokens::{
    ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, Typography, oklab_mix,
};
use gpui_kit::{
    App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
    MouseDownEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
    TestSupportExt as _, Window,
    base::{Button as BaseButton, StyledExt as _},
    canvas, deferred, div, point,
    prelude::*,
    px,
};

type SelectChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;

/// Base font size (`14px`, `--text-sm`) used to convert `0.35em` / `-0.3em` value roll offsets.
pub const SELECT_TEXT_EM_PX: f32 = 14.0;
/// Delay (`40ms`) before the selected option checkmark plays `indicator-in`.
pub const SELECT_INDICATOR_DELAY_SECS: f64 = 0.04;

/// Sampled `(enter_opacity, enter_y_px, exit_opacity, exit_y_px)` for the directional value roll
/// at `elapsed` seconds after a selection change.
///
/// - `direction`: `+1` when moving to a later option (rises from below), `-1` when moving to an
///   earlier option (drops from above).
pub fn select_value_roll_sample(
    elapsed: f64,
    direction: i8,
    reduced: bool,
) -> (f32, f32, f32, f32) {
    let dir = if direction >= 0 { 1.0_f32 } else { -1.0_f32 };
    if reduced {
        let t = (elapsed / 0.12).clamp(0.0, 1.0) as f32;
        return (t, 0.0, 1.0 - t, 0.0);
    }

    // Incoming: 240ms (duration.standard), ease.enter (0.16, 1, 0.3, 1), y: dir * 0.35em -> 0, blur: 4px -> 0.
    let t_in = (elapsed / 0.24).clamp(0.0, 1.0) as f32;
    let e_in = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t_in);
    let blur_in = BlurFallback::evaluate(px(4.0 * (1.0 - e_in)), false);
    let enter_op = (e_in * blur_in.opacity_multiplier).clamp(0.0, 1.0);
    let enter_y = dir * (0.35 * SELECT_TEXT_EM_PX) * (1.0 - e_in);

    // Outgoing: 160ms (duration.fast), ease.standard (0.22, 1, 0.36, 1), y: 0 -> dir * -0.3em, blur: 0 -> 2px.
    let t_out = (elapsed / 0.16).clamp(0.0, 1.0) as f32;
    let e_out = CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t_out);
    let blur_out = BlurFallback::evaluate(px(2.0 * e_out), false);
    let exit_op = ((1.0 - e_out) * blur_out.opacity_multiplier).clamp(0.0, 1.0);
    let exit_y = -dir * (0.30 * SELECT_TEXT_EM_PX) * e_out;

    (enter_op, enter_y, exit_op, exit_y)
}

/// Sampled `(opacity, scale)` for the selected item checkmark (`indicator-in`: `240ms` with `40ms`
/// delay, `ease.enter`, `scale(0.6) -> 1.0`, `blur(2px) -> 0`).
pub fn select_indicator_sample(elapsed: f64, reduced: bool) -> (f32, f32) {
    if reduced {
        return (1.0, 1.0);
    }
    if elapsed <= SELECT_INDICATOR_DELAY_SECS {
        return (0.0, 0.6);
    }
    let t = ((elapsed - SELECT_INDICATOR_DELAY_SECS) / 0.24).clamp(0.0, 1.0) as f32;
    let e = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t);
    let blur = BlurFallback::evaluate(px(2.0 * (1.0 - e)), false);
    let op = (e * blur.opacity_multiplier).clamp(0.0, 1.0);
    let scale = 0.6 + 0.4 * e;
    (op, scale)
}

/// Loops forward (`step = 1`) or backward (`step = -1`) to the next enabled option index.
pub fn next_enabled_select_option(
    options: &[SelectOption],
    current: Option<usize>,
    step: isize,
) -> Option<usize> {
    if options.is_empty() {
        return None;
    }
    let len = options.len() as isize;
    let start = match current {
        Some(idx) => idx as isize,
        None => {
            if step > 0 {
                -1
            } else {
                len
            }
        }
    };
    for offset in 1..=len {
        let idx = (start + step * offset).rem_euclid(len) as usize;
        if !options[idx].disabled {
            return Some(idx);
        }
    }
    None
}

/// One option inside [`Select`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SelectOption {
    pub value: SharedString,
    pub label: SharedString,
    pub disabled: bool,
}

impl SelectOption {
    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        Self {
            value: value.into(),
            label: label.into(),
            disabled: false,
        }
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }
}

#[derive(Clone)]
struct SelectInternal {
    open: bool,
    opened_at_secs: f64,
    uncontrolled_value: SharedString,
    previous_index: Option<usize>,
    previous_shown: Option<SharedString>,
    direction: i8,
    roll_started_at_secs: f64,
    highlighted: Option<usize>,
    trigger_hovered: bool,
    trigger_pressed: bool,
    trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    menu_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    focus_handle: FocusHandle,
}

impl SelectInternal {
    fn new(
        default_value: SharedString,
        initial_index: Option<usize>,
        now: f64,
        focus_handle: FocusHandle,
    ) -> Self {
        Self {
            open: false,
            opened_at_secs: now - 10.0,
            uncontrolled_value: default_value,
            previous_index: initial_index,
            previous_shown: None,
            direction: 1,
            roll_started_at_secs: now - 10.0,
            highlighted: initial_index,
            trigger_hovered: false,
            trigger_pressed: false,
            trigger_bounds: Rc::new(RefCell::new(None)),
            menu_bounds: Rc::new(RefCell::new(None)),
            focus_handle,
        }
    }
}

fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
    let rad = angle_deg.to_radians();
    let cos_a = rad.cos();
    let sin_a = rad.sin();
    let pts = [(-4.0_f32, -2.0_f32), (0.0, 2.0), (4.0, -2.0)];
    let mut builder = PathBuilder::stroke(px(1.75));
    for (i, (lx, ly)) in pts.iter().enumerate() {
        let rx = cx + lx * cos_a - ly * sin_a;
        let ry = cy + lx * sin_a + ly * cos_a;
        let p = point(px(rx), px(ry));
        if i == 0 {
            builder.move_to(p);
        } else {
            builder.line_to(p);
        }
    }
    if let Ok(path) = builder.build() {
        window.paint_path(path, color);
    }
}

fn paint_scaled_check(cx: f32, cy: f32, scale: f32, color: Hsla, window: &mut Window) {
    let pts = [(-4.5_f32, 0.2_f32), (-1.4, 3.3), (4.8, -3.2)];
    let mut builder = PathBuilder::stroke(px(1.75));
    for (i, (lx, ly)) in pts.iter().enumerate() {
        let p = point(px(cx + lx * scale), px(cy + ly * scale));
        if i == 0 {
            builder.move_to(p);
        } else {
            builder.line_to(p);
        }
    }
    if let Ok(path) = builder.build() {
        window.paint_path(path, color);
    }
}

/// Arc `Select` — single-value dropdown selector with directional value-roll transition,
/// `spring.snappy` rotating chevron, and a trigger-width floating listbox.
#[derive(IntoElement)]
pub struct Select {
    id: ElementId,
    label: SharedString,
    description: Option<SharedString>,
    placeholder: SharedString,
    options: Vec<SelectOption>,
    value: Option<SharedString>,
    default_value: Option<SharedString>,
    disabled: bool,
    width: Option<Pixels>,
    on_value_change: Option<SelectChangeHandler>,
}

impl Select {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            description: None,
            placeholder: "Select an option".into(),
            options: Vec::new(),
            value: None,
            default_value: None,
            disabled: false,
            width: None,
            on_value_change: None,
        }
    }

    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
        self.description = Some(description.into());
        self
    }

    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
        self.placeholder = placeholder.into();
        self
    }

    pub fn option(mut self, option: SelectOption) -> Self {
        self.options.push(option);
        self
    }

    pub fn options(mut self, options: impl IntoIterator<Item = SelectOption>) -> Self {
        self.options.extend(options);
        self
    }

    pub fn value(mut self, value: impl Into<SharedString>) -> Self {
        self.value = Some(value.into());
        self
    }

    pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
        self.default_value = Some(value.into());
        self
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
        self.width = Some(width.into());
        self
    }

    pub fn on_value_change(
        mut self,
        handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_value_change = Some(Rc::new(handler));
        self
    }
}

impl RenderOnce for Select {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let motion = theme.motion;
        let reduced = is_reduced_motion(cx);
        let now = motion_now(cx);

        let initial_val = self
            .value
            .clone()
            .or_else(|| self.default_value.clone())
            .unwrap_or_default();
        let initial_idx = self.options.iter().position(|opt| opt.value == initial_val);

        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-select-state".into());
        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
            SelectInternal::new(initial_val.clone(), initial_idx, now, cx.focus_handle())
        });

        let current_value = self
            .value
            .clone()
            .unwrap_or_else(|| internal.read(cx).uncontrolled_value.clone());
        let current_index = self
            .options
            .iter()
            .position(|opt| opt.value == current_value);
        let shown: SharedString = current_index
            .and_then(|idx| self.options.get(idx))
            .map(|opt| opt.label.clone())
            .unwrap_or_else(|| self.placeholder.clone());
        let is_placeholder = current_index.is_none();

        // Detect external or internal index change to trigger the directional value roll.
        {
            let prev_idx = internal.read(cx).previous_index;
            if prev_idx != current_index {
                let prev_label = prev_idx
                    .and_then(|idx| self.options.get(idx))
                    .map(|opt| opt.label.clone())
                    .unwrap_or_else(|| self.placeholder.clone());
                let dir = match (current_index, prev_idx) {
                    (Some(cur), Some(prev)) => {
                        if cur >= prev {
                            1
                        } else {
                            -1
                        }
                    }
                    (Some(_), None) => 1,
                    (None, Some(_)) => -1,
                    (None, None) => 1,
                };
                internal.update(cx, |s, _| {
                    s.previous_index = current_index;
                    s.previous_shown = Some(prev_label);
                    s.direction = dir;
                    s.roll_started_at_secs = now;
                });
            }
        }

        let snap = internal.read(cx).clone();
        let is_open = snap.open && !self.disabled;

        // Chevron rotation `0 -> 180` on `motion.spring.snappy`.
        let chevron_deg = if reduced {
            if is_open { 180.0 } else { 0.0 }
        } else {
            arc_spring(
                (self.id.clone(), "chevron-deg"),
                if is_open { 180.0 } else { 0.0 },
                motion.spring.snappy,
                window,
                cx,
            )
        };

        // Value roll interpolation (`240ms` enter / `160ms` exit).
        let roll_elapsed = (now - snap.roll_started_at_secs).max(0.0);
        let roll_total_dur = if reduced { 0.12 } else { 0.24 };
        let (enter_op, enter_y, exit_op, exit_y) = if roll_elapsed < roll_total_dur {
            window.request_animation_frame();
            select_value_roll_sample(roll_elapsed, snap.direction, reduced)
        } else {
            (1.0, 0.0, 0.0, 0.0)
        };

        // Trigger hover/open background & border transition (`duration.fast` = 160ms).
        let hover_p = arc_transition(
            (self.id.clone(), "trigger-hover"),
            if !self.disabled && (is_open || snap.trigger_hovered || snap.trigger_pressed) {
                1.0
            } else {
                0.0
            },
            if reduced {
                Duration::ZERO
            } else {
                motion.duration.fast
            },
            motion.ease.standard,
            window,
            cx,
        );
        let trigger_bg = oklab_mix(colors.surface_muted, colors.surface, hover_p);
        let trigger_border = oklab_mix(colors.border_strong, colors.border, hover_p);

        // Floating menu presence (`duration.standard` 240ms enter / `duration.instant` 120ms exit).
        let content_presence = ArcPresence::new((self.id.clone(), "content-presence"), is_open)
            .animate_initial(false)
            .config(ArcPresenceConfig {
                enter_duration: motion.duration.standard,
                exit_duration: motion.duration.instant,
                enter_ease: motion.ease.enter,
                exit_ease: motion.ease.standard,
                fade_on_reduced_motion: true,
            })
            .sample(window, cx);

        let trigger_bounds_ref = snap.trigger_bounds.clone();
        let trigger_bounds_outside = snap.trigger_bounds.clone();
        let menu_bounds_outside = snap.menu_bounds.clone();
        let internal_outside = internal.clone();
        let trigger_probe = canvas(
            move |rect, _, _| {
                *trigger_bounds_ref.borrow_mut() = Some(rect);
            },
            move |_, _, window, _| {
                if is_open {
                    let t_ref = trigger_bounds_outside.clone();
                    let m_ref = menu_bounds_outside.clone();
                    let st = internal_outside.clone();
                    window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
                        if !phase.bubble() {
                            return;
                        }
                        let in_trigger =
                            t_ref.borrow().is_some_and(|b| b.contains(&event.position));
                        let in_menu = m_ref.borrow().is_some_and(|b| b.contains(&event.position));
                        if !in_trigger && !in_menu {
                            st.update(cx, |s, _| {
                                s.open = false;
                            });
                            window.refresh();
                        }
                    });
                }
            },
        )
        .absolute()
        .inset_0();

        let trigger_id = ElementId::NamedChild(self.id.clone().into(), "trigger".into());
        let int_hover = internal.clone();
        let int_down = internal.clone();
        let int_up = internal.clone();
        let int_out = internal.clone();
        let int_click = internal.clone();
        let focus_for_open = snap.focus_handle.clone();
        let options_for_open = self.options.clone();
        let disabled = self.disabled;
        let chevron_color = colors.text_muted;
        let value_fg = if is_placeholder {
            colors.text_muted
        } else {
            colors.foreground
        };

        let mut value_slot = div()
            .relative()
            .flex_1()
            .min_w_0()
            .h(px(20.0))
            .overflow_hidden()
            .child(
                div()
                    .w_full()
                    .mt(px(enter_y))
                    .opacity(enter_op)
                    .text_color(value_fg)
                    .truncate()
                    .child(shown.clone()),
            );

        if exit_op > 0.01
            && let Some(prev_text) = snap.previous_shown.clone()
        {
            value_slot = value_slot.child(
                div()
                    .absolute()
                    .top_0()
                    .left_0()
                    .right_0()
                    .mt(px(exit_y))
                    .opacity(exit_op)
                    .text_color(colors.text_secondary)
                    .truncate()
                    .child(prev_text),
            );
        }

        let trigger = BaseButton::new(trigger_id)
            .accessibility_label(self.label.clone())
            .disabled(disabled)
            .on_click(move |_, window, cx| {
                if disabled {
                    return;
                }
                let t_now = motion_now(cx);
                let mut became_open = false;
                int_click.update(cx, |s, _| {
                    s.open = !s.open;
                    became_open = s.open;
                    if s.open {
                        s.opened_at_secs = t_now;
                        s.highlighted = current_index
                            .or_else(|| next_enabled_select_option(&options_for_open, None, 1));
                    }
                });
                if became_open {
                    window.focus(&focus_for_open, cx);
                }
                window.refresh();
            })
            .relative()
            .w_full()
            .min_h(ControlHeights::MD)
            .px(Spacing::S3)
            .flex()
            .flex_row()
            .items_center()
            .justify_between()
            .gap(Spacing::S3)
            .rounded(Radii::CONTROL)
            .border_1()
            .border_color(trigger_border)
            .bg(trigger_bg)
            .text_size(Typography::TEXT_SM)
            .opacity(if disabled { 0.5 } else { 1.0 })
            .when(!disabled, |this| this.cursor_pointer())
            .on_hover(move |hovered, window, cx| {
                int_hover.update(cx, |s, _| {
                    s.trigger_hovered = *hovered;
                    if !*hovered {
                        s.trigger_pressed = false;
                    }
                });
                window.refresh();
            })
            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                if !disabled {
                    int_down.update(cx, |s, _| s.trigger_pressed = true);
                    window.refresh();
                }
            })
            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
                int_up.update(cx, |s, _| s.trigger_pressed = false);
                window.refresh();
            })
            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
                int_out.update(cx, |s, _| s.trigger_pressed = false);
                window.refresh();
            })
            .child(trigger_probe)
            .child(value_slot)
            .child(
                canvas(
                    |_, _, _| {},
                    move |rect, _, window, _| {
                        let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
                        let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
                        paint_rotated_chevron(cx_pt, cy_pt, chevron_deg, chevron_color, window);
                    },
                )
                .size(px(16.0))
                .flex_none(),
            );

        // Floating listbox content (`position="popper"`, `sideOffset={4}`).
        let menu_el = if content_presence.should_render() && !self.options.is_empty() {
            let p = content_presence.progress.clamp(0.0, 1.0);
            let menu_y = if reduced { 0.0 } else { -6.0 * (1.0 - p) };
            let menu_elapsed = (now - snap.opened_at_secs).max(0.0);
            let (ind_op, ind_scale) = select_indicator_sample(menu_elapsed, reduced);
            if is_open && !reduced && menu_elapsed < SELECT_INDICATOR_DELAY_SECS + 0.24 {
                window.request_animation_frame();
            }

            let menu_bounds_ref = snap.menu_bounds.clone();
            let menu_probe = canvas(
                move |rect, _, _| {
                    *menu_bounds_ref.borrow_mut() = Some(rect);
                },
                |_, _, _, _| {},
            )
            .absolute()
            .inset_0();

            let int_key = internal.clone();
            let options_for_key = self.options.clone();
            let on_change_key = self.on_value_change.clone();
            let focus_handle = snap.focus_handle.clone();
            let menu_id = ElementId::NamedChild(self.id.clone().into(), "content".into());

            let shown_for_key = shown.clone();
            let item_els = self
                .options
                .into_iter()
                .enumerate()
                .map(|(idx, option)| {
                    let shown_for_item = shown.clone();
                    let item_id = ElementId::NamedChild(
                        self.id.clone().into(),
                        SharedString::from(format!("option-{idx}")),
                    );
                    let is_selected = current_index == Some(idx);
                    let is_highlighted = snap.highlighted == Some(idx) && !option.disabled;
                    let item_bg = if is_highlighted {
                        colors.surface_muted
                    } else {
                        Hsla::transparent_black()
                    };
                    let int_hi = internal.clone();
                    let int_sel = internal.clone();
                    let on_change = self.on_value_change.clone();
                    let opt_val = option.value.clone();
                    let opt_label = option.label.clone();
                    let opt_disabled = option.disabled;
                    let check_color = colors.foreground;

                    div()
                        .id(item_id)
                        .test_support()
                        .role(Role::ListBoxOption)
                        .aria_label(opt_label.clone())
                        .relative()
                        .w_full()
                        .min_h(px(30.0))
                        .pl(px(10.0))
                        .pr(px(30.0))
                        .flex()
                        .flex_row()
                        .items_center()
                        .rounded((Radii::CONTROL - px(2.0)).max(px(4.0)))
                        .bg(item_bg)
                        .text_size(Typography::TEXT_SM)
                        .text_color(colors.foreground)
                        .opacity(if opt_disabled { 0.45 } else { 1.0 })
                        .when(!opt_disabled, |this| this.cursor_pointer())
                        .on_hover(move |hovered, window, cx| {
                            if opt_disabled {
                                return;
                            }
                            int_hi.update(cx, |s, _| {
                                if *hovered {
                                    s.highlighted = Some(idx);
                                }
                            });
                            window.refresh();
                        })
                        .on_click(move |_, window, cx| {
                            if opt_disabled {
                                return;
                            }
                            let t_now = motion_now(cx);
                            int_sel.update(cx, |s, _| {
                                let prev_idx = s.previous_index;
                                if prev_idx != Some(idx) {
                                    s.direction = match prev_idx {
                                        Some(prev) if idx < prev => -1,
                                        _ => 1,
                                    };
                                    s.previous_shown = Some(shown_for_item.clone());
                                    s.previous_index = Some(idx);
                                    s.roll_started_at_secs = t_now;
                                }
                                s.uncontrolled_value = opt_val.clone();
                                s.highlighted = Some(idx);
                                s.open = false;
                            });
                            if let Some(cb) = &on_change {
                                cb(&opt_val, window, cx);
                            }
                            window.refresh();
                        })
                        .child(div().flex_1().min_w_0().truncate().child(opt_label))
                        .when(is_selected, |this| {
                            this.child(
                                div()
                                    .absolute()
                                    .right(px(10.0))
                                    .size(px(16.0))
                                    .opacity(ind_op)
                                    .child(
                                        canvas(
                                            |_, _, _| {},
                                            move |rect, _, window, _| {
                                                let cx_pt = f32::from(
                                                    rect.origin.x + rect.size.width * 0.5,
                                                );
                                                let cy_pt = f32::from(
                                                    rect.origin.y + rect.size.height * 0.5,
                                                );
                                                paint_scaled_check(
                                                    cx_pt,
                                                    cy_pt,
                                                    ind_scale,
                                                    check_color,
                                                    window,
                                                );
                                            },
                                        )
                                        .size_full(),
                                    ),
                            )
                        })
                        .into_any_element()
                })
                .collect::<Vec<_>>();
            Some(
                deferred(
                    div()
                        .id(menu_id)
                        .test_support()
                        .role(Role::ListBox)
                        .track_focus(&focus_handle)
                        .on_key_down(move |event: &KeyDownEvent, window, cx| {
                            match event.keystroke.key.as_str() {
                                "escape" => {
                                    int_key.update(cx, |s, _| {
                                        s.open = false;
                                    });
                                    window.refresh();
                                }
                                "down" | "arrowdown" => {
                                    let cur = int_key.read(cx).highlighted;
                                    if let Some(next) =
                                        next_enabled_select_option(&options_for_key, cur, 1)
                                    {
                                        int_key.update(cx, |s, _| {
                                            s.highlighted = Some(next);
                                        });
                                        window.refresh();
                                    }
                                }
                                "up" | "arrowup" => {
                                    let cur = int_key.read(cx).highlighted;
                                    if let Some(prev) =
                                        next_enabled_select_option(&options_for_key, cur, -1)
                                    {
                                        int_key.update(cx, |s, _| {
                                            s.highlighted = Some(prev);
                                        });
                                        window.refresh();
                                    }
                                }
                                "home" => {
                                    if let Some(first) =
                                        next_enabled_select_option(&options_for_key, None, 1)
                                    {
                                        int_key.update(cx, |s, _| {
                                            s.highlighted = Some(first);
                                        });
                                        window.refresh();
                                    }
                                }
                                "end" => {
                                    if let Some(last) =
                                        next_enabled_select_option(&options_for_key, None, -1)
                                    {
                                        int_key.update(cx, |s, _| {
                                            s.highlighted = Some(last);
                                        });
                                        window.refresh();
                                    }
                                }
                                "enter" | " " | "space" => {
                                    let hi = int_key.read(cx).highlighted;
                                    if let Some(idx) = hi
                                        && let Some(opt) = options_for_key.get(idx)
                                        && !opt.disabled
                                    {
                                        let next_val = opt.value.clone();
                                        let t_now = motion_now(cx);
                                        int_key.update(cx, |s, _| {
                                            let prev_idx = s.previous_index;
                                            if prev_idx != Some(idx) {
                                                s.direction = match prev_idx {
                                                    Some(prev) if idx < prev => -1,
                                                    _ => 1,
                                                };
                                                s.previous_shown = Some(shown_for_key.clone());
                                                s.previous_index = Some(idx);
                                                s.roll_started_at_secs = t_now;
                                            }
                                            s.uncontrolled_value = next_val.clone();
                                            s.open = false;
                                        });
                                        if let Some(cb) = &on_change_key {
                                            cb(&next_val, window, cx);
                                        }
                                        window.refresh();
                                    }
                                }
                                _ => {}
                            }
                        })
                        .absolute()
                        .top_full()
                        .left_0()
                        .right_0()
                        .mt(px(4.0 + menu_y))
                        .p(px(6.0))
                        .rounded(Radii::CONTROL + px(2.0))
                        .border_1()
                        .border_color(colors.border)
                        .bg(colors.surface_raised)
                        .shadow(Shadows::floating(theme.mode))
                        .opacity(p)
                        .overflow_hidden()
                        .child(menu_probe)
                        .child(
                            div()
                                .w_full()
                                .py(px(2.0))
                                .flex()
                                .flex_col()
                                .children(item_els),
                        ),
                )
                .with_priority(20),
            )
        } else {
            None
        };

        div()
            .id(self.id)
            .test_support()
            .when_some(self.width, |this, w| this.w(w))
            .when(self.width.is_none(), |this| this.w_full())
            .flex()
            .flex_col()
            .gap(Spacing::S2)
            .child(
                div()
                    .text_size(Typography::TEXT_SM)
                    .font_medium()
                    .text_color(colors.foreground)
                    .child(self.label),
            )
            .child(
                div()
                    .relative()
                    .w_full()
                    .child(trigger)
                    .when_some(menu_el, |this, m| this.child(m)),
            )
            .when_some(self.description, |this, desc| {
                this.child(
                    div()
                        .text_size(Typography::TEXT_XS)
                        .text_color(colors.text_muted)
                        .child(desc),
                )
            })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn select_value_roll_moves_directionally_and_settles() {
        let (op_start, y_start, exit_op_start, exit_y_start) =
            select_value_roll_sample(0.0, 1, false);
        assert!(op_start < 0.01);
        assert!(y_start > 4.0);
        assert!(exit_op_start > 0.99);
        assert!(exit_y_start.abs() < 1e-4);

        let (op_neg, y_neg, _, exit_y_neg) = select_value_roll_sample(0.08, -1, false);
        assert!(op_neg > 0.2 && op_neg < 1.0);
        assert!(y_neg < 0.0);
        assert!(exit_y_neg > 0.0);

        let (op_done, y_done, exit_op_done, _) = select_value_roll_sample(0.30, 1, false);
        assert!((op_done - 1.0).abs() < 1e-4);
        assert!(y_done.abs() < 1e-4);
        assert!(exit_op_done < 1e-4);
    }

    #[test]
    fn select_indicator_respects_40ms_delay_and_reduced_motion() {
        let (op_before, scale_before) = select_indicator_sample(0.02, false);
        assert!(op_before < 1e-4);
        assert!((scale_before - 0.6).abs() < 1e-4);

        let (op_mid, scale_mid) = select_indicator_sample(0.14, false);
        assert!(op_mid > 0.3 && op_mid < 1.0);
        assert!(scale_mid > 0.7 && scale_mid < 1.0);

        let (op_red, scale_red) = select_indicator_sample(0.01, true);
        assert!((op_red - 1.0).abs() < 1e-4);
        assert!((scale_red - 1.0).abs() < 1e-4);
    }

    #[test]
    fn next_enabled_select_option_skips_disabled_and_wraps() {
        let options = vec![
            SelectOption::new("a", "Alpha"),
            SelectOption::new("b", "Beta").disabled(true),
            SelectOption::new("c", "Gamma"),
        ];
        assert_eq!(next_enabled_select_option(&options, Some(0), 1), Some(2));
        assert_eq!(next_enabled_select_option(&options, Some(2), 1), Some(0));
        assert_eq!(next_enabled_select_option(&options, Some(0), -1), Some(2));
    }
}