Skip to main content

arc_ui/overlay/
context_menu.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/context-menu/context-menu.tsx` & `.module.css`
3//!
4//! P3 Component #5: `context-menu`
5//!
6//! - Opens at the pointer position on right-click (`MouseButton::Right`), at `(left + 12, bottom + 8)`
7//!   on left-click when closed, and on `Shift+F10` / `ContextMenu` key. A primary press while open
8//!   closes the menu without reopening on the release.
9//! - Clamped `8px` inside the window viewport (`clamp_to_viewport`).
10//! - Floating menu: `min_w = 208px` (`13rem`), `5px` padding, `Radii::PANEL` (26px), `surface_raised`,
11//!   `floating` shadow; `ArcPresence` (`160ms` enter / `120ms` exit).
12//! - Rows: `min_h = 34px`, `9px` gap, `11px` horizontal padding, `20px` radius, leading `16px` icon
13//!   slot (`icon`, or checkmark when `checked`, or 3-dot fallback), staggered by `min(i, 4) * 35ms`
14//!   (`240ms` / `ease.enter`, `-2px -> 0` rise).
15//! - Gliding highlight pill (`spring.snappy` on pointer with `70ms` grace, instant jump on keyboard
16//!   `ArrowDown` / `ArrowUp` / `Home` / `End`).
17
18use std::{cell::RefCell, collections::HashMap, rc::Rc, time::Duration};
19
20use arc_motion::{
21    ArcPresence, ArcPresenceConfig, CubicBezier, arc_spring, arc_spring_with_options,
22    arc_transition, is_reduced_motion, motion_now, spring::SpringOptions,
23};
24use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Typography, oklab_mix};
25use gpui_kit::{
26    AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
27    MouseDownEvent, ParentElement, PathBuilder, Pixels, Point, RenderOnce, Role, SharedString,
28    Styled, TestSupportExt as _, Window, assets::IconName, canvas, deferred, div, point,
29    prelude::*, px,
30};
31
32type SelectCallback = Rc<dyn Fn(&(), &mut Window, &mut App)>;
33
34/// Minimum width (`13rem = 208px`) and viewport margin (`8px`).
35pub const MENU_WIDTH: f32 = 192.0;
36pub const VIEWPORT_MARGIN: f32 = 8.0;
37pub const ROW_HEIGHT: f32 = 30.0;
38pub const HIGHLIGHT_GRACE_SECS: f64 = 0.07;
39pub const ITEM_STAGGER_SECS: f64 = 0.035;
40pub const ITEM_STAGGER_CAP: usize = 4;
41
42/// Clamps a menu of `(width, height)` requested at `(x, y)` inside `(viewport_w, viewport_h)` with
43/// an `8px` margin, returning `(left, top)`.
44pub fn clamp_to_viewport(
45    x: f32,
46    y: f32,
47    width: f32,
48    height: f32,
49    viewport_w: f32,
50    viewport_h: f32,
51) -> (f32, f32) {
52    let max_x = (viewport_w - width - VIEWPORT_MARGIN).max(VIEWPORT_MARGIN);
53    let max_y = (viewport_h - height - VIEWPORT_MARGIN).max(VIEWPORT_MARGIN);
54    (
55        x.clamp(VIEWPORT_MARGIN, max_x),
56        y.clamp(VIEWPORT_MARGIN, max_y),
57    )
58}
59
60/// `0..=1` entrance progress for row `index` at `elapsed` seconds after open.
61pub fn row_enter_progress(elapsed: f64, index: usize, reduced: bool) -> f32 {
62    if reduced {
63        return 1.0;
64    }
65    let delay = (index.min(ITEM_STAGGER_CAP) as f64) * ITEM_STAGGER_SECS;
66    let t = ((elapsed - delay) / 0.24).clamp(0.0, 1.0) as f32;
67    CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
68}
69
70/// One row inside [`ContextMenu`].
71#[derive(Clone)]
72pub struct ContextMenuItem {
73    pub id: SharedString,
74    pub label: SharedString,
75    pub icon: Option<IconName>,
76    pub checked: bool,
77    pub disabled: bool,
78    pub destructive: bool,
79    pub on_select: Option<SelectCallback>,
80}
81
82impl ContextMenuItem {
83    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
84        Self {
85            id: id.into(),
86            label: label.into(),
87            icon: None,
88            checked: false,
89            disabled: false,
90            destructive: false,
91            on_select: None,
92        }
93    }
94
95    pub fn icon(mut self, icon: IconName) -> Self {
96        self.icon = Some(icon);
97        self
98    }
99
100    pub fn checked(mut self, checked: bool) -> Self {
101        self.checked = checked;
102        self
103    }
104
105    pub fn disabled(mut self, disabled: bool) -> Self {
106        self.disabled = disabled;
107        self
108    }
109
110    pub fn destructive(mut self, destructive: bool) -> Self {
111        self.destructive = destructive;
112        self
113    }
114
115    pub fn on_select(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
116        self.on_select = Some(Rc::new(handler));
117        self
118    }
119}
120
121/// Keyboard navigation helper supporting `ArrowDown`, `ArrowUp`, `Home`, and `End`.
122pub fn navigate_enabled(
123    items: &[ContextMenuItem],
124    current: Option<usize>,
125    key: &str,
126) -> Option<usize> {
127    let enabled: Vec<usize> = items
128        .iter()
129        .enumerate()
130        .filter_map(|(i, it)| (!it.disabled).then_some(i))
131        .collect();
132    if enabled.is_empty() {
133        return None;
134    }
135    let pos = current.and_then(|c| enabled.iter().position(|&i| i == c));
136    let next_pos = match key {
137        "down" => match pos {
138            Some(p) => (p + 1) % enabled.len(),
139            None => 0,
140        },
141        "up" => match pos {
142            Some(p) => (p + enabled.len() - 1) % enabled.len(),
143            None => enabled.len() - 1,
144        },
145        "home" => 0,
146        "end" => enabled.len() - 1,
147        _ => return current,
148    };
149    Some(enabled[next_pos])
150}
151
152#[derive(Clone)]
153struct ContextMenuInternal {
154    open: bool,
155    opened_at_secs: f64,
156    anchor_window_pt: Point<Pixels>,
157    highlighted: Option<usize>,
158    pressed_item: Option<usize>,
159    pointer_mode: bool,
160    grace_until_secs: Option<f64>,
161    last_highlight_rect: Option<(f32, f32, bool)>,
162    target_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
163    menu_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
164    item_offsets: Rc<RefCell<HashMap<usize, (f32, f32)>>>,
165    menu_focus: FocusHandle,
166}
167
168impl ContextMenuInternal {
169    fn new(now: f64, menu_focus: FocusHandle) -> Self {
170        Self {
171            open: false,
172            opened_at_secs: now - 10.0,
173            anchor_window_pt: point(px(0.0), px(0.0)),
174            highlighted: None,
175            pressed_item: None,
176            pointer_mode: false,
177            grace_until_secs: None,
178            last_highlight_rect: None,
179            target_bounds: Rc::new(RefCell::new(None)),
180            menu_bounds: Rc::new(RefCell::new(None)),
181            item_offsets: Rc::new(RefCell::new(HashMap::new())),
182            menu_focus,
183        }
184    }
185}
186
187fn paint_checkmark(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
188    let mut builder = PathBuilder::stroke(px(1.75));
189    builder.move_to(point(px(cx - 4.5), px(cy + 0.2)));
190    builder.line_to(point(px(cx - 1.2), px(cy + 3.4)));
191    builder.line_to(point(px(cx + 4.8), px(cy - 3.2)));
192    if let Ok(path) = builder.build() {
193        window.paint_path(path, color);
194    }
195}
196
197fn paint_dots(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
198    for dx in [-4.0_f32, 0.0, 4.0] {
199        let mut builder = PathBuilder::stroke(px(2.0));
200        builder.move_to(point(px(cx + dx - 0.5), px(cy)));
201        builder.line_to(point(px(cx + dx + 0.5), px(cy)));
202        if let Ok(path) = builder.build() {
203            window.paint_path(path, color);
204        }
205    }
206}
207
208/// Arc `ContextMenu` — wraps a target surface and opens a pointer-anchored floating menu on right
209/// click, left click, or `Shift+F10`.
210#[derive(IntoElement)]
211pub struct ContextMenu {
212    id: ElementId,
213    label: SharedString,
214    items: Vec<ContextMenuItem>,
215    child: AnyElement,
216}
217
218impl ContextMenu {
219    pub fn new(id: impl Into<ElementId>) -> Self {
220        Self {
221            id: id.into(),
222            label: "Context menu".into(),
223            items: Vec::new(),
224            child: div().into_any_element(),
225        }
226    }
227
228    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
229        self.label = label.into();
230        self
231    }
232
233    pub fn item(mut self, item: ContextMenuItem) -> Self {
234        self.items.push(item);
235        self
236    }
237
238    pub fn items(mut self, items: impl IntoIterator<Item = ContextMenuItem>) -> Self {
239        self.items.extend(items);
240        self
241    }
242
243    pub fn child(mut self, child: impl IntoElement) -> Self {
244        self.child = child.into_any_element();
245        self
246    }
247}
248
249impl RenderOnce for ContextMenu {
250    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
251        let theme = cx.arc_theme().clone();
252        let colors = theme.colors;
253        let motion = theme.motion;
254        let reduced = is_reduced_motion(cx);
255        let now = motion_now(cx);
256
257        let state_id =
258            ElementId::NamedChild(self.id.clone().into(), "__arc-context-menu-state".into());
259        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
260            ContextMenuInternal::new(now, cx.focus_handle())
261        });
262
263        {
264            let grace = internal.read(cx).grace_until_secs;
265            if let Some(until) = grace {
266                if now >= until {
267                    internal.update(cx, |s, _| {
268                        if s.highlighted.is_none() {
269                            s.last_highlight_rect = None;
270                        }
271                        s.grace_until_secs = None;
272                    });
273                } else {
274                    window.request_animation_frame();
275                }
276            }
277        }
278
279        let snap = internal.read(cx).clone();
280        let is_open = snap.open;
281
282        let menu_presence = ArcPresence::new((self.id.clone(), "menu-presence"), is_open)
283            .animate_initial(false)
284            .config(ArcPresenceConfig {
285                enter_duration: motion.duration.fast,
286                exit_duration: motion.duration.instant,
287                enter_ease: motion.ease.enter,
288                exit_ease: motion.ease.standard,
289                fade_on_reduced_motion: true,
290            })
291            .sample(window, cx);
292
293        let target_bounds_ref = snap.target_bounds.clone();
294        let menu_bounds_outside = snap.menu_bounds.clone();
295        let internal_outside = internal.clone();
296        let target_probe = canvas(
297            move |rect, _, _| {
298                *target_bounds_ref.borrow_mut() = Some(rect);
299            },
300            move |_, _, window, _| {
301                if is_open {
302                    let m_ref = menu_bounds_outside.clone();
303                    let st = internal_outside.clone();
304                    window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
305                        if !phase.bubble() {
306                            return;
307                        }
308                        let in_menu = m_ref.borrow().is_some_and(|b| b.contains(&event.position));
309                        if !in_menu && event.button == MouseButton::Left {
310                            st.update(cx, |s, _| {
311                                s.open = false;
312                                s.highlighted = None;
313                                s.last_highlight_rect = None;
314                            });
315                            window.refresh();
316                        }
317                    });
318                }
319            },
320        )
321        .absolute()
322        .inset_0();
323
324        let int_right = internal.clone();
325        let int_left = internal.clone();
326        let target_b_for_left = snap.target_bounds.clone();
327        let focus_for_right = snap.menu_focus.clone();
328        let focus_for_left = snap.menu_focus.clone();
329
330        let target_id = ElementId::NamedChild(self.id.clone().into(), "target".into());
331        let target = div()
332            .id(target_id)
333            .test_support()
334            .aria_label(self.label.clone())
335            .relative()
336            .on_mouse_down(MouseButton::Right, move |event, window, cx| {
337                let t_now = motion_now(cx);
338                int_right.update(cx, |s, _| {
339                    s.open = true;
340                    s.opened_at_secs = t_now;
341                    s.anchor_window_pt = event.position;
342                    s.highlighted = None;
343                    s.last_highlight_rect = None;
344                    s.grace_until_secs = None;
345                });
346                window.focus(&focus_for_right, cx);
347                window.refresh();
348            })
349            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
350                let was_open = int_left.read(cx).open;
351                if was_open {
352                    int_left.update(cx, |s, _| {
353                        s.open = false;
354                        s.highlighted = None;
355                        s.last_highlight_rect = None;
356                    });
357                    window.refresh();
358                    return;
359                }
360                let Some(rect) = *target_b_for_left.borrow() else {
361                    return;
362                };
363                let t_now = motion_now(cx);
364                int_left.update(cx, |s, _| {
365                    s.open = true;
366                    s.opened_at_secs = t_now;
367                    s.anchor_window_pt = point(rect.origin.x + px(12.0), rect.bottom() + px(8.0));
368                    s.highlighted = None;
369                    s.last_highlight_rect = None;
370                    s.grace_until_secs = None;
371                });
372                window.focus(&focus_for_left, cx);
373                window.refresh();
374            })
375            .child(target_probe)
376            .child(self.child);
377
378        let menu_el = if menu_presence.should_render() && !self.items.is_empty() {
379            let p = menu_presence.progress.clamp(0.0, 1.0);
380            let menu_elapsed = (now - snap.opened_at_secs).max(0.0);
381
382            let vp = window.viewport_size();
383            let est_h = (self.items.len() as f32 * ROW_HEIGHT + 12.0).min(300.0);
384            let (clamped_x, clamped_y) = clamp_to_viewport(
385                f32::from(snap.anchor_window_pt.x),
386                f32::from(snap.anchor_window_pt.y),
387                MENU_WIDTH,
388                est_h,
389                f32::from(vp.width),
390                f32::from(vp.height),
391            );
392            let (rel_left, rel_top) = if let Some(tb) = *snap.target_bounds.borrow() {
393                (
394                    clamped_x - f32::from(tb.origin.x),
395                    clamped_y - f32::from(tb.origin.y),
396                )
397            } else {
398                (clamped_x, clamped_y)
399            };
400
401            let active_geom = snap
402                .highlighted
403                .and_then(|idx| {
404                    let (top, h) = snap.item_offsets.borrow().get(&idx).copied()?;
405                    let danger = self.items.get(idx).is_some_and(|it| it.destructive);
406                    Some((top, h, danger))
407                })
408                .or(snap.last_highlight_rect);
409
410            let has_hi = snap.highlighted.is_some()
411                || snap.grace_until_secs.is_some_and(|until| now < until);
412            let hi_op = arc_transition(
413                (self.id.clone(), "hi-op"),
414                if has_hi && active_geom.is_some() {
415                    1.0
416                } else {
417                    0.0
418                },
419                if reduced {
420                    Duration::ZERO
421                } else {
422                    motion.duration.instant
423                },
424                motion.ease.standard,
425                window,
426                cx,
427            );
428
429            let (target_top, target_h, is_danger) = active_geom.unwrap_or((5.0, ROW_HEIGHT, false));
430            let (pill_top, pill_h) = if reduced || !snap.pointer_mode {
431                let _ = arc_spring_with_options(
432                    (self.id.clone(), "hi-top"),
433                    target_top,
434                    SpringOptions::new(motion.spring.snappy),
435                    window,
436                    cx,
437                );
438                let _ = arc_spring_with_options(
439                    (self.id.clone(), "hi-h"),
440                    target_h,
441                    SpringOptions::new(motion.spring.snappy),
442                    window,
443                    cx,
444                );
445                (target_top, target_h)
446            } else {
447                (
448                    arc_spring(
449                        (self.id.clone(), "hi-top"),
450                        target_top,
451                        motion.spring.snappy,
452                        window,
453                        cx,
454                    ),
455                    arc_spring(
456                        (self.id.clone(), "hi-h"),
457                        target_h,
458                        motion.spring.snappy,
459                        window,
460                        cx,
461                    ),
462                )
463            };
464
465            let pill_bg = if is_danger {
466                oklab_mix(colors.danger, colors.surface, 0.08)
467            } else {
468                colors.surface_muted
469            };
470
471            let menu_bounds_ref = snap.menu_bounds.clone();
472            let menu_probe = canvas(
473                move |rect, _, _| {
474                    *menu_bounds_ref.borrow_mut() = Some(rect);
475                },
476                |_, _, _, _| {},
477            )
478            .absolute()
479            .inset_0();
480
481            let int_key = internal.clone();
482            let items_for_key = self.items.clone();
483            let offsets_for_key = snap.item_offsets.clone();
484            let menu_id = ElementId::NamedChild(self.id.clone().into(), "menu".into());
485            let focus_handle = snap.menu_focus.clone();
486
487            let rows = self.items.into_iter().enumerate().map(|(idx, item)| {
488                let item_id = ElementId::NamedChild(
489                    self.id.clone().into(),
490                    SharedString::from(format!("item-{}", item.id)),
491                );
492                let item_p = if is_open {
493                    let ip = row_enter_progress(menu_elapsed, idx, reduced);
494                    if ip < 0.999 {
495                        window.request_animation_frame();
496                    }
497                    ip
498                } else {
499                    1.0
500                };
501                let item_dy = if reduced || !is_open {
502                    0.0
503                } else {
504                    -2.0 * (1.0 - item_p)
505                };
506
507                let offsets_ref = snap.item_offsets.clone();
508                let menu_b_ref = snap.menu_bounds.clone();
509                let int_rect = internal.clone();
510                let is_curr_hi = snap.highlighted == Some(idx);
511                let is_item_danger = item.destructive;
512                let item_probe = canvas(
513                    move |rect, _, cx| {
514                        if let Some(mb) = *menu_b_ref.borrow() {
515                            let rtop = f32::from(rect.origin.y - mb.origin.y);
516                            let h = f32::from(rect.size.height);
517                            offsets_ref.borrow_mut().insert(idx, (rtop, h));
518                            if is_curr_hi {
519                                int_rect.update(cx, |s, _| {
520                                    s.last_highlight_rect = Some((rtop, h, is_item_danger));
521                                });
522                            }
523                        }
524                    },
525                    |_, _, _, _| {},
526                )
527                .absolute()
528                .inset_0();
529
530                let int_hi = internal.clone();
531                let int_down = internal.clone();
532                let int_up = internal.clone();
533                let int_sel = internal.clone();
534                let offsets_for_hover = snap.item_offsets.clone();
535                let on_select = item.on_select.clone();
536                let item_disabled = item.disabled;
537                let is_pressed = snap.pressed_item == Some(idx) && !item_disabled;
538                let item_fg = if item.destructive {
539                    colors.danger
540                } else {
541                    colors.foreground
542                };
543                let icon_fg = if item.destructive {
544                    colors.danger
545                } else {
546                    colors.text_secondary
547                };
548                let checked = item.checked;
549
550                let icon_slot = if let Some(icon) = item.icon {
551                    div()
552                        .w(px(16.0))
553                        .flex_none()
554                        .flex()
555                        .items_center()
556                        .justify_center()
557                        .text_color(icon_fg)
558                        .child(icon)
559                        .into_any_element()
560                } else {
561                    canvas(
562                        |_, _, _| {},
563                        move |rect, _, window, _| {
564                            let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
565                            let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
566                            if checked {
567                                paint_checkmark(cx, cy, icon_fg, window);
568                            } else {
569                                paint_dots(cx, cy, icon_fg, window);
570                            }
571                        },
572                    )
573                    .size(px(16.0))
574                    .flex_none()
575                    .into_any_element()
576                };
577
578                div()
579                    .id(item_id)
580                    .test_support()
581                    .role(Role::MenuItem)
582                    .aria_label(item.label.clone())
583                    .relative()
584                    .flex()
585                    .flex_row()
586                    .items_center()
587                    .gap(px(9.0))
588                    .min_h(px(ROW_HEIGHT))
589                    .px(px(11.0))
590                    .rounded(px(6.0))
591                    .text_size(Typography::TEXT_SM)
592                    .text_color(item_fg)
593                    .when(is_pressed, |this| {
594                        this.bg(oklab_mix(
595                            colors.foreground,
596                            Hsla::transparent_black(),
597                            0.05,
598                        ))
599                    })
600                    .mt(px(item_dy))
601                    .opacity(if item_disabled { 0.45 } else { item_p })
602                    .when(!item_disabled, |this| this.cursor_pointer())
603                    .on_hover(move |hovered, window, cx| {
604                        if item_disabled {
605                            return;
606                        }
607                        let t_now = motion_now(cx);
608                        let geom = offsets_for_hover.borrow().get(&idx).copied();
609                        int_hi.update(cx, |s, _| {
610                            s.pointer_mode = true;
611                            if *hovered {
612                                s.highlighted = Some(idx);
613                                s.grace_until_secs = None;
614                                if let Some((top, h)) = geom {
615                                    s.last_highlight_rect = Some((top, h, is_item_danger));
616                                }
617                            } else if s.highlighted == Some(idx) {
618                                s.highlighted = None;
619                                s.pressed_item = None;
620                                s.grace_until_secs = Some(t_now + HIGHLIGHT_GRACE_SECS);
621                            }
622                        });
623                        window.refresh();
624                    })
625                    .on_mouse_down(MouseButton::Left, move |_, window, cx| {
626                        cx.stop_propagation();
627                        if item_disabled {
628                            return;
629                        }
630                        int_down.update(cx, |s, _| s.pressed_item = Some(idx));
631                        window.refresh();
632                    })
633                    .on_mouse_up(MouseButton::Left, move |_, window, cx| {
634                        int_up.update(cx, |s, _| s.pressed_item = None);
635                        window.refresh();
636                    })
637                    .on_click(move |_, window, cx| {
638                        if item_disabled {
639                            return;
640                        }
641                        int_sel.update(cx, |s, _| {
642                            s.open = false;
643                            s.highlighted = None;
644                            s.pressed_item = None;
645                        });
646                        if let Some(cb) = &on_select {
647                            cb(&(), window, cx);
648                        }
649                        window.refresh();
650                    })
651                    .child(item_probe)
652                    .child(icon_slot)
653                    .child(div().min_w_0().truncate().child(item.label))
654            });
655
656            let highlight_pill = div()
657                .absolute()
658                .left(px(5.0))
659                .right(px(5.0))
660                .top(px(pill_top))
661                .h(px(pill_h))
662                .rounded(px(6.0))
663                .bg(pill_bg)
664                .opacity(hi_op.clamp(0.0, 1.0));
665
666            Some(
667                deferred(
668                    div()
669                        .id(menu_id)
670                        .test_support()
671                        .track_focus(&focus_handle)
672                        .role(Role::Menu)
673                        .aria_label(self.label.clone())
674                        .absolute()
675                        .left(px(rel_left))
676                        .top(px(rel_top))
677                        .min_w(px(MENU_WIDTH))
678                        .max_h(px(300.0))
679                        .p(px(5.0))
680                        .rounded(Radii::PANEL)
681                        .border_1()
682                        .border_color(colors.border)
683                        .bg(colors.surface_raised)
684                        .text_color(colors.foreground)
685                        .shadow(Shadows::floating(theme.mode))
686                        .opacity(p)
687                        .flex()
688                        .flex_col()
689                        .on_key_down(move |event: &KeyDownEvent, window, cx| {
690                            let key = event.keystroke.key.as_str();
691                            match key {
692                                "escape" => {
693                                    int_key.update(cx, |s, _| {
694                                        s.open = false;
695                                        s.highlighted = None;
696                                    });
697                                    window.refresh();
698                                }
699                                "down" | "up" | "home" | "end" => {
700                                    int_key.update(cx, |s, _| {
701                                        s.pointer_mode = false;
702                                        s.grace_until_secs = None;
703                                        let next =
704                                            navigate_enabled(&items_for_key, s.highlighted, key);
705                                        s.highlighted = next;
706                                        if let Some(idx) = next
707                                            && let Some(&(top, h)) =
708                                                offsets_for_key.borrow().get(&idx)
709                                        {
710                                            let danger = items_for_key
711                                                .get(idx)
712                                                .is_some_and(|it| it.destructive);
713                                            s.last_highlight_rect = Some((top, h, danger));
714                                        }
715                                    });
716                                    window.refresh();
717                                }
718                                "enter" | "space" => {
719                                    let sel = int_key.read(cx).highlighted;
720                                    if let Some(idx) = sel
721                                        && let Some(act) = items_for_key.get(idx)
722                                        && !act.disabled
723                                    {
724                                        int_key.update(cx, |s, _| {
725                                            s.open = false;
726                                            s.highlighted = None;
727                                        });
728                                        if let Some(cb) = &act.on_select {
729                                            cb(&(), window, cx);
730                                        }
731                                        window.refresh();
732                                    }
733                                }
734                                _ => {}
735                            }
736                        })
737                        .child(menu_probe)
738                        .child(highlight_pill)
739                        .children(rows),
740                )
741                .with_priority(1),
742            )
743        } else {
744            None
745        };
746
747        div()
748            .id(self.id)
749            .relative()
750            .child(target)
751            .when_some(menu_el, |this, menu| this.child(menu))
752    }
753}
754
755#[cfg(test)]
756mod tests {
757    use std::{cell::Cell, rc::Rc};
758
759    use arc_tokens::{Accent, Spacing, ThemeMode, install_arc_theme};
760    use gpui_kit::{
761        Context, MouseButton, Render, Role, TestAppContext, div,
762        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
763    };
764
765    use super::*;
766
767    #[test]
768    fn viewport_clamp_and_home_end_navigation_work() {
769        assert_eq!(
770            clamp_to_viewport(790.0, 580.0, 208.0, 120.0, 800.0, 600.0),
771            (584.0, 472.0)
772        );
773        assert_eq!(
774            clamp_to_viewport(2.0, 3.0, 208.0, 120.0, 800.0, 600.0),
775            (8.0, 8.0)
776        );
777
778        let items = vec![
779            ContextMenuItem::new("a", "A"),
780            ContextMenuItem::new("b", "B").disabled(true),
781            ContextMenuItem::new("c", "C"),
782            ContextMenuItem::new("d", "D"),
783        ];
784        assert_eq!(navigate_enabled(&items, None, "down"), Some(0));
785        assert_eq!(navigate_enabled(&items, Some(0), "down"), Some(2));
786        assert_eq!(navigate_enabled(&items, Some(0), "end"), Some(3));
787        assert_eq!(navigate_enabled(&items, Some(3), "home"), Some(0));
788    }
789
790    struct Host {
791        copied: Rc<Cell<usize>>,
792    }
793
794    impl Render for Host {
795        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
796            let copied = self.copied.clone();
797            div().size_full().p(Spacing::S6).child(
798                ContextMenu::new("canvas-ctx")
799                    .label("画布上下文菜单")
800                    .items([
801                        ContextMenuItem::new("copy", "复制链接").on_select(cx.listener(
802                            move |_, _, _, _| {
803                                copied.set(copied.get() + 1);
804                            },
805                        )),
806                        ContextMenuItem::new("del", "删除项目").destructive(true),
807                    ])
808                    .child(div().w(px(220.0)).h(px(100.0)).child("右键此处")),
809            )
810        }
811    }
812
813    #[gpui_kit::test]
814    fn context_menu_opens_on_right_click_and_selects_item(cx: &mut TestAppContext) {
815        cx.update(|cx| {
816            gpui_kit::init(cx);
817            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
818        });
819        let copied = Rc::new(Cell::new(0));
820        let (_view, cx) = cx.add_window_view(|_, _| Host {
821            copied: copied.clone(),
822        });
823
824        cx.update(|window, cx| {
825            window.render_frame(cx);
826            let target = window.find_by_label("画布上下文菜单");
827            let pos = target.bounds().center();
828            window.pointer_down(pos, MouseButton::Right, cx);
829            window.pointer_up(pos, MouseButton::Right, cx);
830            window.render_frame(cx);
831
832            let item = window.find_by_label("复制链接");
833            assert_eq!(item.role(), Some(Role::MenuItem));
834            let ipos = item.bounds().center();
835            window.pointer_down(ipos, MouseButton::Left, cx);
836            window.pointer_up(ipos, MouseButton::Left, cx);
837            assert_eq!(copied.get(), 1);
838        });
839    }
840}