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
937
938
939
940
941
942
943
944
945
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/dropdown-menu/dropdown-menu.tsx` & `.module.css`
//!
//! P3 Component #4: `dropdown-menu`
//!
//! - Trigger button: `ControlHeights::SM` (36px), `Radii::CONTROL`, `1px border`, `surface` fill,
//!   press feedback in colour only (no scale, so the anchored menu always measures a still rect).
//! - Trigger label morph: changing `label` springs the label slot width on `motion.spring.morph`
//!   while rising in (`duration.standard` / `ease.enter`, `BlurFallback` soft).
//! - Chevron: rotates `0° -> 180°` on `motion.spring.snappy` when the menu opens.
//! - Floating menu: `ArcPresence` (`160ms` enter / `130ms` exit, `-5px` vertical travel), `5px`
//!   padding, `Radii::PANEL` (26px), `surface_raised`, `floating` shadow, items staggered by
//!   `min(i, 4) * 35ms` (`240ms` / `ease.enter`).
//! - Travelling highlight pill: glides across items on `motion.spring.snappy` under pointer hover
//!   (with a `70ms` grace across separators/gaps) and jumps instantly under keyboard `Up` / `Down`.
//!   Destructive items tint the pill `8% danger` over `surface`.

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

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

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

/// Grace window (`70ms`) that keeps the pointer highlight alive across separators and item gaps.
pub const HIGHLIGHT_GRACE_SECS: f64 = 0.07;
/// Per-item stagger step (`35ms`) capped at index `4`.
pub const ITEM_STAGGER_SECS: f64 = 0.035;
pub const ITEM_STAGGER_CAP: usize = 4;

/// One item inside [`DropdownMenu`].
#[derive(Clone)]
pub struct DropdownItem {
    pub label: SharedString,
    pub icon: Option<IconName>,
    pub disabled: bool,
    pub destructive: bool,
    pub separator_before: bool,
    pub on_select: Option<SelectCallback>,
}

impl DropdownItem {
    pub fn new(label: impl Into<SharedString>) -> Self {
        Self {
            label: label.into(),
            icon: None,
            disabled: false,
            destructive: false,
            separator_before: false,
            on_select: None,
        }
    }

    pub fn icon(mut self, icon: IconName) -> Self {
        self.icon = Some(icon);
        self
    }

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

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

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

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

#[derive(Clone)]
struct DropdownMenuInternal {
    open: bool,
    opened_at_secs: f64,
    highlighted: Option<usize>,
    pointer_mode: bool,
    grace_until_secs: Option<f64>,
    last_highlight_rect: Option<(f32, f32, bool)>,
    trigger_hovered: bool,
    trigger_pressed: bool,
    last_label: SharedString,
    morph_armed_until_secs: f64,
    label_changed_at_secs: f64,
    measured_label_width: Rc<RefCell<f32>>,
    has_measured_label: Rc<RefCell<bool>>,
    trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    menu_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    item_offsets: Rc<RefCell<HashMap<usize, (f32, f32)>>>,
    focus_handle: FocusHandle,
}

impl DropdownMenuInternal {
    fn new(initial_label: SharedString, now: f64, focus_handle: FocusHandle) -> Self {
        Self {
            open: false,
            opened_at_secs: now - 10.0,
            highlighted: None,
            pointer_mode: false,
            grace_until_secs: None,
            last_highlight_rect: None,
            trigger_hovered: false,
            trigger_pressed: false,
            last_label: initial_label,
            morph_armed_until_secs: f64::NEG_INFINITY,
            label_changed_at_secs: now - 10.0,
            measured_label_width: Rc::new(RefCell::new(0.0)),
            has_measured_label: Rc::new(RefCell::new(false)),
            trigger_bounds: Rc::new(RefCell::new(None)),
            menu_bounds: Rc::new(RefCell::new(None)),
            item_offsets: Rc::new(RefCell::new(HashMap::new())),
            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 = [(-3.75_f32, -1.85_f32), (0.0, 1.85), (3.75, -1.85)];
    let mut builder = PathBuilder::stroke(px(1.8));
    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);
    }
}

/// Loops forward (`step = 1`) or backward (`step = -1`) to the next enabled item.
pub fn next_enabled_item(
    items: &[DropdownItem],
    current: Option<usize>,
    step: isize,
) -> Option<usize> {
    if items.is_empty() {
        return None;
    }
    let len = items.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 !items[idx].disabled {
            return Some(idx);
        }
    }
    None
}

/// `0..=1` entrance progress for menu item `index` at `elapsed` seconds after open.
pub fn item_enter_progress(elapsed: f64, index: usize, reduced: bool) -> f32 {
    if reduced {
        return 1.0;
    }
    let delay = (index.min(ITEM_STAGGER_CAP) as f64) * ITEM_STAGGER_SECS;
    let t = ((elapsed - delay) / 0.24).clamp(0.0, 1.0) as f32;
    CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
}

/// Arc `DropdownMenu` — button trigger with spring label morph, rotating chevron, and a floating
/// action menu with a gliding pointer / instant keyboard highlight pill.
#[derive(IntoElement)]
pub struct DropdownMenu {
    id: ElementId,
    label: SharedString,
    icon: Option<IconName>,
    items: Vec<DropdownItem>,
}

impl DropdownMenu {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            icon: None,
            items: Vec::new(),
        }
    }

    pub fn icon(mut self, icon: IconName) -> Self {
        self.icon = Some(icon);
        self
    }

    pub fn item(mut self, item: DropdownItem) -> Self {
        self.items.push(item);
        self
    }

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

impl RenderOnce for DropdownMenu {
    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 state_id =
            ElementId::NamedChild(self.id.clone().into(), "__arc-dropdown-menu-state".into());
        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
            DropdownMenuInternal::new(self.label.clone(), now, cx.focus_handle())
        });

        {
            let prev = internal.read(cx).last_label.clone();
            if prev != self.label {
                internal.update(cx, |s, _| {
                    s.last_label = self.label.clone();
                    s.morph_armed_until_secs = now + 0.7;
                    s.label_changed_at_secs = now;
                });
            }
        }

        // Expire the 70ms pointer highlight grace window if elapsed.
        {
            let grace = internal.read(cx).grace_until_secs;
            if let Some(until) = grace {
                if now >= until {
                    internal.update(cx, |s, _| {
                        if s.highlighted.is_none() {
                            s.last_highlight_rect = None;
                        }
                        s.grace_until_secs = None;
                    });
                } else {
                    window.request_animation_frame();
                }
            }
        }

        let snap = internal.read(cx).clone();
        let is_open = snap.open;

        // 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,
            )
        };

        // Trigger label width morph (`motion.spring.morph`).
        let measured_w = *snap.measured_label_width.borrow();
        let morph_active = !reduced
            && *snap.has_measured_label.borrow()
            && measured_w > 0.0
            && now <= snap.morph_armed_until_secs;
        let morphed_w = if measured_w > 0.0 {
            let sample = arc_spring_with_options(
                (self.id.clone(), "label-width"),
                measured_w,
                SpringOptions::new(motion.spring.morph),
                window,
                cx,
            );
            if morph_active {
                Some(sample.value)
            } else {
                None
            }
        } else {
            None
        };

        // Trigger label text rise + blur fallback.
        let label_elapsed = (now - snap.label_changed_at_secs).max(0.0);
        let label_dur = if reduced {
            motion.duration.instant.as_secs_f64()
        } else {
            motion.duration.standard.as_secs_f64()
        };
        let (label_op, label_y) = if label_elapsed < label_dur {
            window.request_animation_frame();
            let t = (label_elapsed / label_dur).clamp(0.0, 1.0) as f32;
            let e = if reduced {
                t
            } else {
                CubicBezier::from_spec(motion.ease.enter).sample(t)
            };
            let blur = BlurFallback::evaluate(px((1.0 - e) * f32::from(motion.blur.soft)), reduced);
            (
                (e * blur.opacity_multiplier).clamp(0.0, 1.0),
                if reduced { 0.0 } else { 4.0 * (1.0 - e) },
            )
        } else {
            (1.0, 0.0)
        };

        // Menu presence (`160ms` enter / `130ms` exit).
        let menu_presence = ArcPresence::new((self.id.clone(), "menu-presence"), is_open)
            .animate_initial(false)
            .config(ArcPresenceConfig {
                enter_duration: motion.duration.fast,
                exit_duration: Duration::from_millis(130),
                enter_ease: motion.ease.enter,
                exit_ease: motion.ease.standard,
                fade_on_reduced_motion: true,
            })
            .sample(window, cx);

        let trigger_bg = if snap.trigger_pressed {
            oklab_mix(colors.surface_muted, colors.border, 0.55)
        } else if is_open || snap.trigger_hovered {
            colors.surface_muted
        } else {
            colors.surface
        };
        let trigger_border = if snap.trigger_pressed || is_open || snap.trigger_hovered {
            colors.border_strong
        } else {
            colors.border
        };

        let label_w_ref = snap.measured_label_width.clone();
        let has_m_ref = snap.has_measured_label.clone();
        let label_probe = canvas(
            move |rect, window, _| {
                let w = f32::from(rect.size.width);
                let prev = *label_w_ref.borrow();
                *label_w_ref.borrow_mut() = w;
                if w > 0.0 {
                    *has_m_ref.borrow_mut() = true;
                }
                if (w - prev).abs() > 0.5 && prev > 0.0 {
                    window.request_animation_frame();
                }
            },
            |_, _, _, _| {},
        )
        .absolute()
        .inset_0();

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

        let trigger_id = ElementId::NamedChild(self.id.clone().into(), "trigger".into());
        let int_hover = internal.clone();
        let int_down = internal.clone();
        let int_up = internal.clone();
        let int_out = internal.clone();
        let int_click = internal.clone();
        let focus_for_open = snap.focus_handle.clone();
        let chevron_color = colors.text_muted;

        let trigger_btn = BaseButton::new(trigger_id)
            .accessibility_label(self.label.clone())
            .on_click(move |_, window, cx| {
                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 = None;
                        s.last_highlight_rect = None;
                        s.grace_until_secs = None;
                    }
                });
                if became_open {
                    window.focus(&focus_for_open, cx);
                }
                window.refresh();
            })
            .relative()
            .flex()
            .flex_row()
            .items_center()
            .gap(Spacing::S2)
            .min_h(ControlHeights::SM)
            .px(Spacing::S3)
            .rounded(Radii::CONTROL)
            .border_1()
            .border_color(trigger_border)
            .bg(trigger_bg)
            .text_color(colors.foreground)
            .text_size(Typography::TEXT_SM)
            .font_medium()
            .when(
                snap.trigger_hovered && !is_open && !snap.trigger_pressed,
                |this| this.shadow(Shadows::resting(theme.mode)),
            )
            .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| {
                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)
            .when_some(self.icon, |this, icon| {
                this.child(div().text_color(colors.text_secondary).child(icon))
            })
            .child(
                div()
                    .relative()
                    .flex()
                    .items_center()
                    .when_some(morphed_w, |this, w| this.w(px(w)).overflow_hidden())
                    .child(
                        div()
                            .relative()
                            .flex_none()
                            .mt(px(label_y))
                            .opacity(label_op)
                            .child(label_probe)
                            .child(self.label.clone()),
                    ),
            )
            .child(
                canvas(
                    |_, _, _| {},
                    move |rect, _, window, _| {
                        let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
                        let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
                        paint_rotated_chevron(cx, cy, chevron_deg, chevron_color, window);
                    },
                )
                .size(px(15.0)),
            );

        // Floating menu.
        let menu_el = if menu_presence.should_render() && !self.items.is_empty() {
            let p = menu_presence.progress.clamp(0.0, 1.0);
            let menu_y = if reduced { 0.0 } else { -5.0 * (1.0 - p) };
            let menu_elapsed = (now - snap.opened_at_secs).max(0.0);

            // Resolve current highlight geometry (item offset relative to menu top).
            let active_geom = snap
                .highlighted
                .and_then(|idx| {
                    let (top, h) = snap.item_offsets.borrow().get(&idx).copied()?;
                    let danger = self.items.get(idx).is_some_and(|it| it.destructive);
                    Some((top, h, danger))
                })
                .or(snap.last_highlight_rect);

            let has_hi = snap.highlighted.is_some()
                || snap.grace_until_secs.is_some_and(|until| now < until);
            let hi_op = arc_transition(
                (self.id.clone(), "hi-op"),
                if has_hi && active_geom.is_some() {
                    1.0
                } else {
                    0.0
                },
                if reduced {
                    Duration::ZERO
                } else {
                    Duration::from_millis(80)
                },
                motion.ease.standard,
                window,
                cx,
            );

            let (target_top, target_h, is_danger) = active_geom.unwrap_or((5.0, 36.0, false));
            let (pill_top, pill_h) = if reduced || !snap.pointer_mode {
                // Keyboard jumps instantly; still seed the spring so switching back to pointer
                // glides from the keyboard's position.
                let _ = arc_spring_with_options(
                    (self.id.clone(), "hi-top"),
                    target_top,
                    SpringOptions::new(motion.spring.snappy),
                    window,
                    cx,
                );
                let _ = arc_spring_with_options(
                    (self.id.clone(), "hi-h"),
                    target_h,
                    SpringOptions::new(motion.spring.snappy),
                    window,
                    cx,
                );
                (target_top, target_h)
            } else {
                (
                    arc_spring(
                        (self.id.clone(), "hi-top"),
                        target_top,
                        motion.spring.snappy,
                        window,
                        cx,
                    ),
                    arc_spring(
                        (self.id.clone(), "hi-h"),
                        target_h,
                        motion.spring.snappy,
                        window,
                        cx,
                    ),
                )
            };

            let pill_bg = if is_danger {
                oklab_mix(colors.danger, colors.surface, 0.08)
            } else {
                colors.surface_muted
            };

            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 items_for_key = self.items.clone();
            let offsets_for_key = snap.item_offsets.clone();
            let menu_id = ElementId::NamedChild(self.id.clone().into(), "menu".into());
            let focus_handle = snap.focus_handle.clone();

            let mut children_els = Vec::with_capacity(self.items.len() * 2);
            for (idx, item) in self.items.into_iter().enumerate() {
                if item.separator_before {
                    children_els.push(
                        div()
                            .h(px(1.0))
                            .my(Spacing::S1)
                            .mx(px(-5.0))
                            .bg(colors.border_subtle)
                            .into_any_element(),
                    );
                }

                let item_id = ElementId::NamedChild(
                    self.id.clone().into(),
                    SharedString::from(format!("item-{idx}")),
                );
                let item_p = if is_open {
                    let ip = item_enter_progress(menu_elapsed, idx, reduced);
                    if ip < 0.999 {
                        window.request_animation_frame();
                    }
                    ip
                } else {
                    1.0
                };
                let item_dy = if reduced || !is_open {
                    0.0
                } else {
                    -2.0 * (1.0 - item_p)
                };

                let offsets_ref = snap.item_offsets.clone();
                let menu_b_ref = snap.menu_bounds.clone();
                let int_rect = internal.clone();
                let is_curr_hi = snap.highlighted == Some(idx);
                let is_item_danger = item.destructive;
                let item_probe = canvas(
                    move |rect, _, cx| {
                        if let Some(mb) = *menu_b_ref.borrow() {
                            let rel_top = f32::from(rect.origin.y - mb.origin.y);
                            let h = f32::from(rect.size.height);
                            offsets_ref.borrow_mut().insert(idx, (rel_top, h));
                            if is_curr_hi {
                                int_rect.update(cx, |s, _| {
                                    s.last_highlight_rect = Some((rel_top, h, is_item_danger));
                                });
                            }
                        }
                    },
                    |_, _, _, _| {},
                )
                .absolute()
                .inset_0();

                let int_hi = internal.clone();
                let int_sel = internal.clone();
                let offsets_for_hover = snap.item_offsets.clone();
                let on_select = item.on_select.clone();
                let item_disabled = item.disabled;
                let item_fg = if item.destructive {
                    colors.danger
                } else {
                    colors.foreground
                };
                let icon_fg = if item.destructive {
                    colors.danger
                } else {
                    colors.text_secondary
                };

                children_els.push(
                    div()
                        .id(item_id)
                        .test_support()
                        .role(Role::MenuItem)
                        .aria_label(item.label.clone())
                        .relative()
                        .flex()
                        .flex_row()
                        .items_center()
                        .gap(px(10.0))
                        .min_h(ControlHeights::SM)
                        .px(px(11.0))
                        .rounded(px(6.0))
                        .text_size(Typography::TEXT_SM)
                        .text_color(item_fg)
                        .mt(px(item_dy))
                        .opacity(if item_disabled { 0.45 } else { item_p })
                        .when(!item_disabled, |this| this.cursor_pointer())
                        .on_hover(move |hovered, window, cx| {
                            if item_disabled {
                                return;
                            }
                            let t_now = motion_now(cx);
                            let geom = offsets_for_hover.borrow().get(&idx).copied();
                            int_hi.update(cx, |s, _| {
                                s.pointer_mode = true;
                                if *hovered {
                                    s.highlighted = Some(idx);
                                    s.grace_until_secs = None;
                                    if let Some((top, h)) = geom {
                                        s.last_highlight_rect = Some((top, h, is_item_danger));
                                    }
                                } else if s.highlighted == Some(idx) {
                                    s.highlighted = None;
                                    s.grace_until_secs = Some(t_now + HIGHLIGHT_GRACE_SECS);
                                }
                            });
                            window.refresh();
                        })
                        .on_click(move |_, window, cx| {
                            if item_disabled {
                                return;
                            }
                            int_sel.update(cx, |s, _| {
                                s.open = false;
                                s.highlighted = None;
                            });
                            if let Some(cb) = &on_select {
                                cb(&(), window, cx);
                            }
                            window.refresh();
                        })
                        .child(item_probe)
                        .when_some(item.icon, |this, icon| {
                            this.child(div().w(px(17.0)).text_color(icon_fg).child(icon))
                        })
                        .child(item.label)
                        .into_any_element(),
                );
            }

            let highlight_pill = div()
                .absolute()
                .left(px(5.0))
                .right(px(5.0))
                .top(px(pill_top))
                .h(px(pill_h))
                .rounded(px(6.0))
                .bg(pill_bg)
                .opacity(hi_op.clamp(0.0, 1.0));

            Some(
                deferred(
                    div()
                        .id(menu_id)
                        .test_support()
                        .track_focus(&focus_handle)
                        .role(Role::Menu)
                        .absolute()
                        .top(ControlHeights::SM + px(6.0 + menu_y))
                        .right_0()
                        .min_w(px(192.0))
                        .p(px(5.0))
                        .rounded(Radii::PANEL)
                        .border_1()
                        .border_color(colors.border)
                        .bg(colors.surface_raised)
                        .shadow(Shadows::floating(theme.mode))
                        .opacity(p)
                        .flex()
                        .flex_col()
                        .on_key_down(move |event: &KeyDownEvent, window, cx| {
                            match event.keystroke.key.as_str() {
                                "escape" => {
                                    int_key.update(cx, |s, _| {
                                        s.open = false;
                                        s.highlighted = None;
                                    });
                                    window.refresh();
                                }
                                "down" => {
                                    int_key.update(cx, |s, _| {
                                        s.pointer_mode = false;
                                        s.grace_until_secs = None;
                                        let next =
                                            next_enabled_item(&items_for_key, s.highlighted, 1);
                                        s.highlighted = next;
                                        if let Some(idx) = next
                                            && let Some(&(top, h)) =
                                                offsets_for_key.borrow().get(&idx)
                                        {
                                            let danger = items_for_key
                                                .get(idx)
                                                .is_some_and(|it| it.destructive);
                                            s.last_highlight_rect = Some((top, h, danger));
                                        }
                                    });
                                    window.refresh();
                                }
                                "up" => {
                                    int_key.update(cx, |s, _| {
                                        s.pointer_mode = false;
                                        s.grace_until_secs = None;
                                        let next =
                                            next_enabled_item(&items_for_key, s.highlighted, -1);
                                        s.highlighted = next;
                                        if let Some(idx) = next
                                            && let Some(&(top, h)) =
                                                offsets_for_key.borrow().get(&idx)
                                        {
                                            let danger = items_for_key
                                                .get(idx)
                                                .is_some_and(|it| it.destructive);
                                            s.last_highlight_rect = Some((top, h, danger));
                                        }
                                    });
                                    window.refresh();
                                }
                                "enter" | "space" => {
                                    let sel = int_key.read(cx).highlighted;
                                    if let Some(idx) = sel
                                        && let Some(act) = items_for_key.get(idx)
                                        && !act.disabled
                                    {
                                        int_key.update(cx, |s, _| {
                                            s.open = false;
                                            s.highlighted = None;
                                        });
                                        if let Some(cb) = &act.on_select {
                                            cb(&(), window, cx);
                                        }
                                        window.refresh();
                                    }
                                }
                                _ => {}
                            }
                        })
                        .child(menu_probe)
                        .child(highlight_pill)
                        .children(children_els),
                )
                .with_priority(1),
            )
        } else {
            None
        };

        div()
            .id(self.id)
            .relative()
            .self_start()
            .child(trigger_btn)
            .when_some(menu_el, |this, menu| this.child(menu))
    }
}

#[cfg(test)]
mod tests {
    use std::{cell::Cell, rc::Rc};

    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{
        Context, MouseButton, Render, Role, TestAppContext, div,
        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
    };

    use super::*;

    #[test]
    fn loop_navigation_skips_disabled_and_stagger_caps_at_four() {
        let items = vec![
            DropdownItem::new("Rename"),
            DropdownItem::new("Duplicate").disabled(true),
            DropdownItem::new("Delete").destructive(true),
        ];
        assert_eq!(next_enabled_item(&items, None, 1), Some(0));
        assert_eq!(next_enabled_item(&items, Some(0), 1), Some(2));
        assert_eq!(next_enabled_item(&items, Some(2), 1), Some(0));
        assert_eq!(next_enabled_item(&items, Some(0), -1), Some(2));

        let p0 = item_enter_progress(0.05, 0, false);
        let p4 = item_enter_progress(0.05, 4, false);
        let p9 = item_enter_progress(0.05, 9, false);
        assert!(p0 > p4);
        assert_eq!(p4, p9, "indices >= 4 share the capped 140ms delay");
        assert_eq!(item_enter_progress(0.0, 3, true), 1.0);
    }

    struct Host {
        selected: Rc<Cell<usize>>,
    }

    impl Render for Host {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let sel = self.selected.clone();
            div().p(Spacing::S6).child(
                DropdownMenu::new("actions-menu", "选项").items([
                    DropdownItem::new("重命名").on_select(cx.listener(move |_, _, _, _| {
                        sel.set(1);
                    })),
                    DropdownItem::new("归档").disabled(true),
                    DropdownItem::new("删除")
                        .separator_before(true)
                        .destructive(true),
                ]),
            )
        }
    }

    #[gpui_kit::test]
    fn dropdown_menu_opens_and_invokes_item_callback(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });
        let selected = Rc::new(Cell::new(0));
        let (_view, cx) = cx.add_window_view(|_, _| Host {
            selected: selected.clone(),
        });

        cx.update(|window, cx| {
            window.render_frame(cx);
            let trigger = window.find_by_label("选项");
            assert_eq!(trigger.role(), Some(Role::Button));
            let pos = trigger.bounds().center();
            window.pointer_down(pos, MouseButton::Left, cx);
            window.pointer_up(pos, MouseButton::Left, cx);
            window.render_frame(cx);

            let item = window.find_by_label("重命名");
            assert_eq!(item.role(), Some(Role::MenuItem));
            let ipos = item.bounds().center();
            window.pointer_down(ipos, MouseButton::Left, cx);
            window.pointer_up(ipos, MouseButton::Left, cx);
            assert_eq!(selected.get(), 1);
        });
    }
}