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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/context-menu/context-menu.tsx` & `.module.css`
//!
//! P3 Component #5: `context-menu`
//!
//! - Opens at the pointer position on right-click (`MouseButton::Right`), at `(left + 12, bottom + 8)`
//!   on left-click when closed, and on `Shift+F10` / `ContextMenu` key. A primary press while open
//!   closes the menu without reopening on the release.
//! - Clamped `8px` inside the window viewport (`clamp_to_viewport`).
//! - Floating menu: `min_w = 208px` (`13rem`), `5px` padding, `Radii::PANEL` (26px), `surface_raised`,
//!   `floating` shadow; `ArcPresence` (`160ms` enter / `120ms` exit).
//! - Rows: `min_h = 34px`, `9px` gap, `11px` horizontal padding, `20px` radius, leading `16px` icon
//!   slot (`icon`, or checkmark when `checked`, or 3-dot fallback), staggered by `min(i, 4) * 35ms`
//!   (`240ms` / `ease.enter`, `-2px -> 0` rise).
//! - Gliding highlight pill (`spring.snappy` on pointer with `70ms` grace, instant jump on keyboard
//!   `ArrowDown` / `ArrowUp` / `Home` / `End`).

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

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

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

/// Minimum width (`13rem = 208px`) and viewport margin (`8px`).
pub const MENU_WIDTH: f32 = 192.0;
pub const VIEWPORT_MARGIN: f32 = 8.0;
pub const ROW_HEIGHT: f32 = 30.0;
pub const HIGHLIGHT_GRACE_SECS: f64 = 0.07;
pub const ITEM_STAGGER_SECS: f64 = 0.035;
pub const ITEM_STAGGER_CAP: usize = 4;

/// Clamps a menu of `(width, height)` requested at `(x, y)` inside `(viewport_w, viewport_h)` with
/// an `8px` margin, returning `(left, top)`.
pub fn clamp_to_viewport(
    x: f32,
    y: f32,
    width: f32,
    height: f32,
    viewport_w: f32,
    viewport_h: f32,
) -> (f32, f32) {
    let max_x = (viewport_w - width - VIEWPORT_MARGIN).max(VIEWPORT_MARGIN);
    let max_y = (viewport_h - height - VIEWPORT_MARGIN).max(VIEWPORT_MARGIN);
    (
        x.clamp(VIEWPORT_MARGIN, max_x),
        y.clamp(VIEWPORT_MARGIN, max_y),
    )
}

/// `0..=1` entrance progress for row `index` at `elapsed` seconds after open.
pub fn row_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)
}

/// One row inside [`ContextMenu`].
#[derive(Clone)]
pub struct ContextMenuItem {
    pub id: SharedString,
    pub label: SharedString,
    pub icon: Option<IconName>,
    pub checked: bool,
    pub disabled: bool,
    pub destructive: bool,
    pub on_select: Option<SelectCallback>,
}

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

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

    pub fn checked(mut self, checked: bool) -> Self {
        self.checked = checked;
        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 on_select(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
        self.on_select = Some(Rc::new(handler));
        self
    }
}

/// Keyboard navigation helper supporting `ArrowDown`, `ArrowUp`, `Home`, and `End`.
pub fn navigate_enabled(
    items: &[ContextMenuItem],
    current: Option<usize>,
    key: &str,
) -> Option<usize> {
    let enabled: Vec<usize> = items
        .iter()
        .enumerate()
        .filter_map(|(i, it)| (!it.disabled).then_some(i))
        .collect();
    if enabled.is_empty() {
        return None;
    }
    let pos = current.and_then(|c| enabled.iter().position(|&i| i == c));
    let next_pos = match key {
        "down" => match pos {
            Some(p) => (p + 1) % enabled.len(),
            None => 0,
        },
        "up" => match pos {
            Some(p) => (p + enabled.len() - 1) % enabled.len(),
            None => enabled.len() - 1,
        },
        "home" => 0,
        "end" => enabled.len() - 1,
        _ => return current,
    };
    Some(enabled[next_pos])
}

#[derive(Clone)]
struct ContextMenuInternal {
    open: bool,
    opened_at_secs: f64,
    anchor_window_pt: Point<Pixels>,
    /// 打开时目标自身的窗口原点;之后目标因文档滚动而移动时,用它计算位移补偿。
    anchor_target_origin: Option<Point<Pixels>>,
    highlighted: Option<usize>,
    pressed_item: Option<usize>,
    pointer_mode: bool,
    grace_until_secs: Option<f64>,
    last_highlight_rect: Option<(f32, f32, bool)>,
    target_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    menu_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    item_offsets: Rc<RefCell<HashMap<usize, (f32, f32)>>>,
    menu_focus: FocusHandle,
}

impl ContextMenuInternal {
    fn new(now: f64, menu_focus: FocusHandle) -> Self {
        Self {
            open: false,
            opened_at_secs: now - 10.0,
            anchor_window_pt: point(px(0.0), px(0.0)),
            anchor_target_origin: None,
            highlighted: None,
            pressed_item: None,
            pointer_mode: false,
            grace_until_secs: None,
            last_highlight_rect: None,
            target_bounds: Rc::new(RefCell::new(None)),
            menu_bounds: Rc::new(RefCell::new(None)),
            item_offsets: Rc::new(RefCell::new(HashMap::new())),
            menu_focus,
        }
    }
}

fn paint_checkmark(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
    let mut builder = PathBuilder::stroke(px(1.75));
    builder.move_to(point(px(cx - 4.5), px(cy + 0.2)));
    builder.line_to(point(px(cx - 1.2), px(cy + 3.4)));
    builder.line_to(point(px(cx + 4.8), px(cy - 3.2)));
    if let Ok(path) = builder.build() {
        window.paint_path(path, color);
    }
}

fn paint_dots(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
    for dx in [-4.0_f32, 0.0, 4.0] {
        let mut builder = PathBuilder::stroke(px(2.0));
        builder.move_to(point(px(cx + dx - 0.5), px(cy)));
        builder.line_to(point(px(cx + dx + 0.5), px(cy)));
        if let Ok(path) = builder.build() {
            window.paint_path(path, color);
        }
    }
}

/// Arc `ContextMenu` — wraps a target surface and opens a pointer-anchored floating menu on right
/// click, left click, or `Shift+F10`.
#[derive(IntoElement)]
pub struct ContextMenu {
    id: ElementId,
    label: SharedString,
    items: Vec<ContextMenuItem>,
    child: AnyElement,
}

impl ContextMenu {
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            label: "Context menu".into(),
            items: Vec::new(),
            child: div().into_any_element(),
        }
    }

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

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

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

    pub fn child(mut self, child: impl IntoElement) -> Self {
        self.child = child.into_any_element();
        self
    }
}

impl RenderOnce for ContextMenu {
    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-context-menu-state".into());
        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
            ContextMenuInternal::new(now, cx.focus_handle())
        });

        {
            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;

        // 目标位于可滚动文档中时,滚动会改变目标的窗口坐标。这里把锚点按目标的
        // 实际位移一起平移,避免菜单停留在旧屏幕位置、与内容脱节。
        let mut anchor_pt = snap.anchor_window_pt;
        if is_open
            && let (Some(opened_origin), Some(target)) =
                (snap.anchor_target_origin, *snap.target_bounds.borrow())
        {
            let dx = target.origin.x - opened_origin.x;
            let dy = target.origin.y - opened_origin.y;
            if dx != px(0.0) || dy != px(0.0) {
                anchor_pt = point(anchor_pt.x + dx, anchor_pt.y + dy);
                internal.update(cx, |s, _| {
                    s.anchor_window_pt = anchor_pt;
                    s.anchor_target_origin = Some(target.origin);
                });
            }
        }

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

        let target_bounds_ref = snap.target_bounds.clone();
        let menu_bounds_outside = snap.menu_bounds.clone();
        let internal_outside = internal.clone();
        let target_probe = canvas(
            move |rect, _, _| {
                *target_bounds_ref.borrow_mut() = Some(rect);
            },
            move |_, _, window, _| {
                if is_open {
                    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_menu = m_ref.borrow().is_some_and(|b| b.contains(&event.position));
                        if !in_menu && event.button == MouseButton::Left {
                            st.update(cx, |s, _| {
                                s.open = false;
                                s.highlighted = None;
                                s.last_highlight_rect = None;
                            });
                            window.refresh();
                        }
                    });
                }
            },
        )
        .absolute()
        .inset_0();

        let int_right = internal.clone();
        let int_left = internal.clone();
        let target_b_for_left = snap.target_bounds.clone();
        let target_b_for_right = snap.target_bounds.clone();
        let focus_for_right = snap.menu_focus.clone();
        let focus_for_left = snap.menu_focus.clone();

        let target_id = ElementId::NamedChild(self.id.clone().into(), "target".into());
        let target = div()
            .id(target_id)
            .test_support()
            .aria_label(self.label.clone())
            .relative()
            .on_mouse_down(MouseButton::Right, move |event, window, cx| {
                let t_now = motion_now(cx);
                int_right.update(cx, |s, _| {
                    s.open = true;
                    s.opened_at_secs = t_now;
                    s.anchor_window_pt = event.position;
                    s.anchor_target_origin = target_b_for_right.borrow().map(|b| b.origin);
                    s.highlighted = None;
                    s.last_highlight_rect = None;
                    s.grace_until_secs = None;
                });
                window.focus(&focus_for_right, cx);
                window.refresh();
            })
            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                let was_open = int_left.read(cx).open;
                if was_open {
                    int_left.update(cx, |s, _| {
                        s.open = false;
                        s.highlighted = None;
                        s.last_highlight_rect = None;
                    });
                    window.refresh();
                    return;
                }
                let Some(rect) = *target_b_for_left.borrow() else {
                    return;
                };
                let t_now = motion_now(cx);
                int_left.update(cx, |s, _| {
                    s.open = true;
                    s.opened_at_secs = t_now;
                    s.anchor_window_pt = point(rect.origin.x + px(12.0), rect.bottom() + px(8.0));
                    s.anchor_target_origin = Some(rect.origin);
                    s.highlighted = None;
                    s.last_highlight_rect = None;
                    s.grace_until_secs = None;
                });
                window.focus(&focus_for_left, cx);
                window.refresh();
            })
            .child(target_probe)
            .child(self.child);

        let menu_el = if menu_presence.should_render() && !self.items.is_empty() {
            let p = menu_presence.progress.clamp(0.0, 1.0);
            let menu_elapsed = (now - snap.opened_at_secs).max(0.0);

            let vp = window.viewport_size();
            let est_h = (self.items.len() as f32 * ROW_HEIGHT + 12.0).min(300.0);
            let (clamped_x, clamped_y) = clamp_to_viewport(
                f32::from(anchor_pt.x),
                f32::from(anchor_pt.y),
                MENU_WIDTH,
                est_h,
                f32::from(vp.width),
                f32::from(vp.height),
            );
            let (rel_left, rel_top) = if let Some(tb) = *snap.target_bounds.borrow() {
                (
                    clamped_x - f32::from(tb.origin.x),
                    clamped_y - f32::from(tb.origin.y),
                )
            } else {
                (clamped_x, clamped_y)
            };

            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 {
                    motion.duration.instant
                },
                motion.ease.standard,
                window,
                cx,
            );

            let (target_top, target_h, is_danger) = active_geom.unwrap_or((5.0, ROW_HEIGHT, false));
            let (pill_top, pill_h) = if reduced || !snap.pointer_mode {
                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.menu_focus.clone();

            let rows = self.items.into_iter().enumerate().map(|(idx, item)| {
                let item_id = ElementId::NamedChild(
                    self.id.clone().into(),
                    SharedString::from(format!("item-{}", item.id)),
                );
                let item_p = if is_open {
                    let ip = row_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 rtop = f32::from(rect.origin.y - mb.origin.y);
                            let h = f32::from(rect.size.height);
                            offsets_ref.borrow_mut().insert(idx, (rtop, h));
                            if is_curr_hi {
                                int_rect.update(cx, |s, _| {
                                    s.last_highlight_rect = Some((rtop, h, is_item_danger));
                                });
                            }
                        }
                    },
                    |_, _, _, _| {},
                )
                .absolute()
                .inset_0();

                let int_hi = internal.clone();
                let int_down = internal.clone();
                let int_up = 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 is_pressed = snap.pressed_item == Some(idx) && !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
                };
                let checked = item.checked;

                let icon_slot = if let Some(icon) = item.icon {
                    div()
                        .w(px(16.0))
                        .flex_none()
                        .flex()
                        .items_center()
                        .justify_center()
                        .text_color(icon_fg)
                        .child(icon)
                        .into_any_element()
                } else {
                    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);
                            if checked {
                                paint_checkmark(cx, cy, icon_fg, window);
                            } else {
                                paint_dots(cx, cy, icon_fg, window);
                            }
                        },
                    )
                    .size(px(16.0))
                    .flex_none()
                    .into_any_element()
                };

                div()
                    .id(item_id)
                    .test_support()
                    .role(Role::MenuItem)
                    .aria_label(item.label.clone())
                    .relative()
                    .flex()
                    .flex_row()
                    .items_center()
                    .gap(px(9.0))
                    .min_h(px(ROW_HEIGHT))
                    .px(px(11.0))
                    .rounded(px(6.0))
                    .text_size(Typography::TEXT_SM)
                    .text_color(item_fg)
                    .when(is_pressed, |this| {
                        this.bg(oklab_mix(
                            colors.foreground,
                            Hsla::transparent_black(),
                            0.05,
                        ))
                    })
                    .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.pressed_item = None;
                                s.grace_until_secs = Some(t_now + HIGHLIGHT_GRACE_SECS);
                            }
                        });
                        window.refresh();
                    })
                    .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                        cx.stop_propagation();
                        if item_disabled {
                            return;
                        }
                        int_down.update(cx, |s, _| s.pressed_item = Some(idx));
                        window.refresh();
                    })
                    .on_mouse_up(MouseButton::Left, move |_, window, cx| {
                        int_up.update(cx, |s, _| s.pressed_item = None);
                        window.refresh();
                    })
                    .on_click(move |_, window, cx| {
                        if item_disabled {
                            return;
                        }
                        int_sel.update(cx, |s, _| {
                            s.open = false;
                            s.highlighted = None;
                            s.pressed_item = None;
                        });
                        if let Some(cb) = &on_select {
                            cb(&(), window, cx);
                        }
                        window.refresh();
                    })
                    .child(item_probe)
                    .child(icon_slot)
                    .child(div().min_w_0().truncate().child(item.label))
            });

            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)
                        .aria_label(self.label.clone())
                        .absolute()
                        .left(px(rel_left))
                        .top(px(rel_top))
                        .min_w(px(MENU_WIDTH))
                        .max_h(px(300.0))
                        .p(px(5.0))
                        .rounded(Radii::PANEL)
                        .border_1()
                        .border_color(colors.border)
                        .bg(colors.surface_raised)
                        .text_color(colors.foreground)
                        .shadow(Shadows::floating(theme.mode))
                        .opacity(p)
                        .flex()
                        .flex_col()
                        .on_key_down(move |event: &KeyDownEvent, window, cx| {
                            let key = event.keystroke.key.as_str();
                            match key {
                                "escape" => {
                                    int_key.update(cx, |s, _| {
                                        s.open = false;
                                        s.highlighted = None;
                                    });
                                    window.refresh();
                                }
                                "down" | "up" | "home" | "end" => {
                                    int_key.update(cx, |s, _| {
                                        s.pointer_mode = false;
                                        s.grace_until_secs = None;
                                        let next =
                                            navigate_enabled(&items_for_key, s.highlighted, key);
                                        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(rows),
                )
                .with_priority(1),
            )
        } else {
            None
        };

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

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

    use arc_tokens::{Accent, Spacing, ThemeMode, install_arc_theme};
    use gpui_kit::{
        Context, MouseButton, Render, Role, ScrollHandle, TestAppContext, TestSupportExt as _, div,
        point, px, size,
        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
    };

    use super::*;

    #[test]
    fn viewport_clamp_and_home_end_navigation_work() {
        assert_eq!(
            clamp_to_viewport(790.0, 580.0, 208.0, 120.0, 800.0, 600.0),
            (584.0, 472.0)
        );
        assert_eq!(
            clamp_to_viewport(2.0, 3.0, 208.0, 120.0, 800.0, 600.0),
            (8.0, 8.0)
        );

        let items = vec![
            ContextMenuItem::new("a", "A"),
            ContextMenuItem::new("b", "B").disabled(true),
            ContextMenuItem::new("c", "C"),
            ContextMenuItem::new("d", "D"),
        ];
        assert_eq!(navigate_enabled(&items, None, "down"), Some(0));
        assert_eq!(navigate_enabled(&items, Some(0), "down"), Some(2));
        assert_eq!(navigate_enabled(&items, Some(0), "end"), Some(3));
        assert_eq!(navigate_enabled(&items, Some(3), "home"), Some(0));
    }

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

    impl Render for Host {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let copied = self.copied.clone();
            div().size_full().p(Spacing::S6).child(
                ContextMenu::new("canvas-ctx")
                    .label("画布上下文菜单")
                    .items([
                        ContextMenuItem::new("copy", "复制链接").on_select(cx.listener(
                            move |_, _, _, _| {
                                copied.set(copied.get() + 1);
                            },
                        )),
                        ContextMenuItem::new("del", "删除项目").destructive(true),
                    ])
                    .child(div().w(px(220.0)).h(px(100.0)).child("右键此处")),
            )
        }
    }

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

        cx.update(|window, cx| {
            window.render_frame(cx);
            let target = window.find_by_label("画布上下文菜单");
            let pos = target.bounds().center();
            window.pointer_down(pos, MouseButton::Right, cx);
            window.pointer_up(pos, MouseButton::Right, 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!(copied.get(), 1);
        });
    }

    /// 可滚动文档中打开菜单后再滚动:菜单锚点应与目标同步位移,而不是停在旧屏幕位置。
    struct ScrollHost {
        scroll: ScrollHandle,
    }

    impl Render for ScrollHost {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div().size_full().child(
                div()
                    .id("ctx-scroll-host")
                    .size_full()
                    .overflow_y_scroll()
                    .track_scroll(&self.scroll)
                    .child(
                        div()
                            .flex()
                            .flex_col()
                            .child(div().h(px(320.0)))
                            .child(
                                ContextMenu::new("scroll-ctx")
                                    .label("滚动菜单目标")
                                    .items([
                                        ContextMenuItem::new("copy", "复制链接"),
                                        ContextMenuItem::new("del", "删除项目"),
                                    ])
                                    .child(
                                        div()
                                            .id("scroll-ctx-anchor")
                                            .test_support()
                                            .w(px(240.0))
                                            .h(px(80.0))
                                            .child("右键此处"),
                                    ),
                            )
                            .child(div().h(px(700.0))),
                    ),
            )
        }
    }

    #[gpui_kit::test]
    fn context_menu_follows_target_when_document_scrolls(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });
        let (view, cx) = cx.add_window_view(|_, _| ScrollHost {
            scroll: ScrollHandle::new(),
        });
        cx.simulate_resize(size(px(800.0), px(600.0)));

        cx.update(|window, cx| {
            window.render_frame(cx);
            let before = window.find("scroll-ctx-anchor").bounds();
            window.pointer_down(before.center(), MouseButton::Right, cx);
            window.pointer_up(before.center(), MouseButton::Right, cx);
            window.render_frame(cx);
            let item_before = window.find_by_label("复制链接").bounds();

            let scroll = view.read(cx).scroll.clone();
            scroll.set_offset(point(px(0.0), px(-120.0)));
            window.render_frame(cx);
            window.render_frame(cx);

            let after = window.find("scroll-ctx-anchor").bounds();
            let item_after = window.find_by_label("复制链接").bounds();
            let target_dy = f32::from(after.origin.y) - f32::from(before.origin.y);
            let menu_dy = f32::from(item_after.origin.y) - f32::from(item_before.origin.y);
            assert!(target_dy < -100.0, "目标应随文档上移,实际 {target_dy}px");
            assert!(
                (target_dy - menu_dy).abs() <= 1.5,
                "菜单应与目标同步位移:目标 {target_dy}px,菜单 {menu_dy}px"
            );
        });
    }
}