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    /// 打开时目标自身的窗口原点;之后目标因文档滚动而移动时,用它计算位移补偿。
158    anchor_target_origin: Option<Point<Pixels>>,
159    highlighted: Option<usize>,
160    pressed_item: Option<usize>,
161    pointer_mode: bool,
162    grace_until_secs: Option<f64>,
163    last_highlight_rect: Option<(f32, f32, bool)>,
164    target_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
165    menu_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
166    item_offsets: Rc<RefCell<HashMap<usize, (f32, f32)>>>,
167    menu_focus: FocusHandle,
168}
169
170impl ContextMenuInternal {
171    fn new(now: f64, menu_focus: FocusHandle) -> Self {
172        Self {
173            open: false,
174            opened_at_secs: now - 10.0,
175            anchor_window_pt: point(px(0.0), px(0.0)),
176            anchor_target_origin: None,
177            highlighted: None,
178            pressed_item: None,
179            pointer_mode: false,
180            grace_until_secs: None,
181            last_highlight_rect: None,
182            target_bounds: Rc::new(RefCell::new(None)),
183            menu_bounds: Rc::new(RefCell::new(None)),
184            item_offsets: Rc::new(RefCell::new(HashMap::new())),
185            menu_focus,
186        }
187    }
188}
189
190fn paint_checkmark(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
191    let mut builder = PathBuilder::stroke(px(1.75));
192    builder.move_to(point(px(cx - 4.5), px(cy + 0.2)));
193    builder.line_to(point(px(cx - 1.2), px(cy + 3.4)));
194    builder.line_to(point(px(cx + 4.8), px(cy - 3.2)));
195    if let Ok(path) = builder.build() {
196        window.paint_path(path, color);
197    }
198}
199
200fn paint_dots(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
201    for dx in [-4.0_f32, 0.0, 4.0] {
202        let mut builder = PathBuilder::stroke(px(2.0));
203        builder.move_to(point(px(cx + dx - 0.5), px(cy)));
204        builder.line_to(point(px(cx + dx + 0.5), px(cy)));
205        if let Ok(path) = builder.build() {
206            window.paint_path(path, color);
207        }
208    }
209}
210
211/// Arc `ContextMenu` — wraps a target surface and opens a pointer-anchored floating menu on right
212/// click, left click, or `Shift+F10`.
213#[derive(IntoElement)]
214pub struct ContextMenu {
215    id: ElementId,
216    label: SharedString,
217    items: Vec<ContextMenuItem>,
218    child: AnyElement,
219}
220
221impl ContextMenu {
222    pub fn new(id: impl Into<ElementId>) -> Self {
223        Self {
224            id: id.into(),
225            label: "Context menu".into(),
226            items: Vec::new(),
227            child: div().into_any_element(),
228        }
229    }
230
231    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
232        self.label = label.into();
233        self
234    }
235
236    pub fn item(mut self, item: ContextMenuItem) -> Self {
237        self.items.push(item);
238        self
239    }
240
241    pub fn items(mut self, items: impl IntoIterator<Item = ContextMenuItem>) -> Self {
242        self.items.extend(items);
243        self
244    }
245
246    pub fn child(mut self, child: impl IntoElement) -> Self {
247        self.child = child.into_any_element();
248        self
249    }
250}
251
252impl RenderOnce for ContextMenu {
253    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
254        let theme = cx.arc_theme().clone();
255        let colors = theme.colors;
256        let motion = theme.motion;
257        let reduced = is_reduced_motion(cx);
258        let now = motion_now(cx);
259
260        let state_id =
261            ElementId::NamedChild(self.id.clone().into(), "__arc-context-menu-state".into());
262        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
263            ContextMenuInternal::new(now, cx.focus_handle())
264        });
265
266        {
267            let grace = internal.read(cx).grace_until_secs;
268            if let Some(until) = grace {
269                if now >= until {
270                    internal.update(cx, |s, _| {
271                        if s.highlighted.is_none() {
272                            s.last_highlight_rect = None;
273                        }
274                        s.grace_until_secs = None;
275                    });
276                } else {
277                    window.request_animation_frame();
278                }
279            }
280        }
281
282        let snap = internal.read(cx).clone();
283        let is_open = snap.open;
284
285        // 目标位于可滚动文档中时,滚动会改变目标的窗口坐标。这里把锚点按目标的
286        // 实际位移一起平移,避免菜单停留在旧屏幕位置、与内容脱节。
287        let mut anchor_pt = snap.anchor_window_pt;
288        if is_open
289            && let (Some(opened_origin), Some(target)) =
290                (snap.anchor_target_origin, *snap.target_bounds.borrow())
291        {
292            let dx = target.origin.x - opened_origin.x;
293            let dy = target.origin.y - opened_origin.y;
294            if dx != px(0.0) || dy != px(0.0) {
295                anchor_pt = point(anchor_pt.x + dx, anchor_pt.y + dy);
296                internal.update(cx, |s, _| {
297                    s.anchor_window_pt = anchor_pt;
298                    s.anchor_target_origin = Some(target.origin);
299                });
300            }
301        }
302
303        let menu_presence = ArcPresence::new((self.id.clone(), "menu-presence"), is_open)
304            .animate_initial(false)
305            .config(ArcPresenceConfig {
306                enter_duration: motion.duration.fast,
307                exit_duration: motion.duration.instant,
308                enter_ease: motion.ease.enter,
309                exit_ease: motion.ease.standard,
310                fade_on_reduced_motion: true,
311            })
312            .sample(window, cx);
313
314        let target_bounds_ref = snap.target_bounds.clone();
315        let menu_bounds_outside = snap.menu_bounds.clone();
316        let internal_outside = internal.clone();
317        let target_probe = canvas(
318            move |rect, _, _| {
319                *target_bounds_ref.borrow_mut() = Some(rect);
320            },
321            move |_, _, window, _| {
322                if is_open {
323                    let m_ref = menu_bounds_outside.clone();
324                    let st = internal_outside.clone();
325                    window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
326                        if !phase.bubble() {
327                            return;
328                        }
329                        let in_menu = m_ref.borrow().is_some_and(|b| b.contains(&event.position));
330                        if !in_menu && event.button == MouseButton::Left {
331                            st.update(cx, |s, _| {
332                                s.open = false;
333                                s.highlighted = None;
334                                s.last_highlight_rect = None;
335                            });
336                            window.refresh();
337                        }
338                    });
339                }
340            },
341        )
342        .absolute()
343        .inset_0();
344
345        let int_right = internal.clone();
346        let int_left = internal.clone();
347        let target_b_for_left = snap.target_bounds.clone();
348        let target_b_for_right = snap.target_bounds.clone();
349        let focus_for_right = snap.menu_focus.clone();
350        let focus_for_left = snap.menu_focus.clone();
351
352        let target_id = ElementId::NamedChild(self.id.clone().into(), "target".into());
353        let target = div()
354            .id(target_id)
355            .test_support()
356            .aria_label(self.label.clone())
357            .relative()
358            .on_mouse_down(MouseButton::Right, move |event, window, cx| {
359                let t_now = motion_now(cx);
360                int_right.update(cx, |s, _| {
361                    s.open = true;
362                    s.opened_at_secs = t_now;
363                    s.anchor_window_pt = event.position;
364                    s.anchor_target_origin = target_b_for_right.borrow().map(|b| b.origin);
365                    s.highlighted = None;
366                    s.last_highlight_rect = None;
367                    s.grace_until_secs = None;
368                });
369                window.focus(&focus_for_right, cx);
370                window.refresh();
371            })
372            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
373                let was_open = int_left.read(cx).open;
374                if was_open {
375                    int_left.update(cx, |s, _| {
376                        s.open = false;
377                        s.highlighted = None;
378                        s.last_highlight_rect = None;
379                    });
380                    window.refresh();
381                    return;
382                }
383                let Some(rect) = *target_b_for_left.borrow() else {
384                    return;
385                };
386                let t_now = motion_now(cx);
387                int_left.update(cx, |s, _| {
388                    s.open = true;
389                    s.opened_at_secs = t_now;
390                    s.anchor_window_pt = point(rect.origin.x + px(12.0), rect.bottom() + px(8.0));
391                    s.anchor_target_origin = Some(rect.origin);
392                    s.highlighted = None;
393                    s.last_highlight_rect = None;
394                    s.grace_until_secs = None;
395                });
396                window.focus(&focus_for_left, cx);
397                window.refresh();
398            })
399            .child(target_probe)
400            .child(self.child);
401
402        let menu_el = if menu_presence.should_render() && !self.items.is_empty() {
403            let p = menu_presence.progress.clamp(0.0, 1.0);
404            let menu_elapsed = (now - snap.opened_at_secs).max(0.0);
405
406            let vp = window.viewport_size();
407            let est_h = (self.items.len() as f32 * ROW_HEIGHT + 12.0).min(300.0);
408            let (clamped_x, clamped_y) = clamp_to_viewport(
409                f32::from(anchor_pt.x),
410                f32::from(anchor_pt.y),
411                MENU_WIDTH,
412                est_h,
413                f32::from(vp.width),
414                f32::from(vp.height),
415            );
416            let (rel_left, rel_top) = if let Some(tb) = *snap.target_bounds.borrow() {
417                (
418                    clamped_x - f32::from(tb.origin.x),
419                    clamped_y - f32::from(tb.origin.y),
420                )
421            } else {
422                (clamped_x, clamped_y)
423            };
424
425            let active_geom = snap
426                .highlighted
427                .and_then(|idx| {
428                    let (top, h) = snap.item_offsets.borrow().get(&idx).copied()?;
429                    let danger = self.items.get(idx).is_some_and(|it| it.destructive);
430                    Some((top, h, danger))
431                })
432                .or(snap.last_highlight_rect);
433
434            let has_hi = snap.highlighted.is_some()
435                || snap.grace_until_secs.is_some_and(|until| now < until);
436            let hi_op = arc_transition(
437                (self.id.clone(), "hi-op"),
438                if has_hi && active_geom.is_some() {
439                    1.0
440                } else {
441                    0.0
442                },
443                if reduced {
444                    Duration::ZERO
445                } else {
446                    motion.duration.instant
447                },
448                motion.ease.standard,
449                window,
450                cx,
451            );
452
453            let (target_top, target_h, is_danger) = active_geom.unwrap_or((5.0, ROW_HEIGHT, false));
454            let (pill_top, pill_h) = if reduced || !snap.pointer_mode {
455                let _ = arc_spring_with_options(
456                    (self.id.clone(), "hi-top"),
457                    target_top,
458                    SpringOptions::new(motion.spring.snappy),
459                    window,
460                    cx,
461                );
462                let _ = arc_spring_with_options(
463                    (self.id.clone(), "hi-h"),
464                    target_h,
465                    SpringOptions::new(motion.spring.snappy),
466                    window,
467                    cx,
468                );
469                (target_top, target_h)
470            } else {
471                (
472                    arc_spring(
473                        (self.id.clone(), "hi-top"),
474                        target_top,
475                        motion.spring.snappy,
476                        window,
477                        cx,
478                    ),
479                    arc_spring(
480                        (self.id.clone(), "hi-h"),
481                        target_h,
482                        motion.spring.snappy,
483                        window,
484                        cx,
485                    ),
486                )
487            };
488
489            let pill_bg = if is_danger {
490                oklab_mix(colors.danger, colors.surface, 0.08)
491            } else {
492                colors.surface_muted
493            };
494
495            let menu_bounds_ref = snap.menu_bounds.clone();
496            let menu_probe = canvas(
497                move |rect, _, _| {
498                    *menu_bounds_ref.borrow_mut() = Some(rect);
499                },
500                |_, _, _, _| {},
501            )
502            .absolute()
503            .inset_0();
504
505            let int_key = internal.clone();
506            let items_for_key = self.items.clone();
507            let offsets_for_key = snap.item_offsets.clone();
508            let menu_id = ElementId::NamedChild(self.id.clone().into(), "menu".into());
509            let focus_handle = snap.menu_focus.clone();
510
511            let rows = self.items.into_iter().enumerate().map(|(idx, item)| {
512                let item_id = ElementId::NamedChild(
513                    self.id.clone().into(),
514                    SharedString::from(format!("item-{}", item.id)),
515                );
516                let item_p = if is_open {
517                    let ip = row_enter_progress(menu_elapsed, idx, reduced);
518                    if ip < 0.999 {
519                        window.request_animation_frame();
520                    }
521                    ip
522                } else {
523                    1.0
524                };
525                let item_dy = if reduced || !is_open {
526                    0.0
527                } else {
528                    -2.0 * (1.0 - item_p)
529                };
530
531                let offsets_ref = snap.item_offsets.clone();
532                let menu_b_ref = snap.menu_bounds.clone();
533                let int_rect = internal.clone();
534                let is_curr_hi = snap.highlighted == Some(idx);
535                let is_item_danger = item.destructive;
536                let item_probe = canvas(
537                    move |rect, _, cx| {
538                        if let Some(mb) = *menu_b_ref.borrow() {
539                            let rtop = f32::from(rect.origin.y - mb.origin.y);
540                            let h = f32::from(rect.size.height);
541                            offsets_ref.borrow_mut().insert(idx, (rtop, h));
542                            if is_curr_hi {
543                                int_rect.update(cx, |s, _| {
544                                    s.last_highlight_rect = Some((rtop, h, is_item_danger));
545                                });
546                            }
547                        }
548                    },
549                    |_, _, _, _| {},
550                )
551                .absolute()
552                .inset_0();
553
554                let int_hi = internal.clone();
555                let int_down = internal.clone();
556                let int_up = internal.clone();
557                let int_sel = internal.clone();
558                let offsets_for_hover = snap.item_offsets.clone();
559                let on_select = item.on_select.clone();
560                let item_disabled = item.disabled;
561                let is_pressed = snap.pressed_item == Some(idx) && !item_disabled;
562                let item_fg = if item.destructive {
563                    colors.danger
564                } else {
565                    colors.foreground
566                };
567                let icon_fg = if item.destructive {
568                    colors.danger
569                } else {
570                    colors.text_secondary
571                };
572                let checked = item.checked;
573
574                let icon_slot = if let Some(icon) = item.icon {
575                    div()
576                        .w(px(16.0))
577                        .flex_none()
578                        .flex()
579                        .items_center()
580                        .justify_center()
581                        .text_color(icon_fg)
582                        .child(icon)
583                        .into_any_element()
584                } else {
585                    canvas(
586                        |_, _, _| {},
587                        move |rect, _, window, _| {
588                            let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
589                            let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
590                            if checked {
591                                paint_checkmark(cx, cy, icon_fg, window);
592                            } else {
593                                paint_dots(cx, cy, icon_fg, window);
594                            }
595                        },
596                    )
597                    .size(px(16.0))
598                    .flex_none()
599                    .into_any_element()
600                };
601
602                div()
603                    .id(item_id)
604                    .test_support()
605                    .role(Role::MenuItem)
606                    .aria_label(item.label.clone())
607                    .relative()
608                    .flex()
609                    .flex_row()
610                    .items_center()
611                    .gap(px(9.0))
612                    .min_h(px(ROW_HEIGHT))
613                    .px(px(11.0))
614                    .rounded(px(6.0))
615                    .text_size(Typography::TEXT_SM)
616                    .text_color(item_fg)
617                    .when(is_pressed, |this| {
618                        this.bg(oklab_mix(
619                            colors.foreground,
620                            Hsla::transparent_black(),
621                            0.05,
622                        ))
623                    })
624                    .mt(px(item_dy))
625                    .opacity(if item_disabled { 0.45 } else { item_p })
626                    .when(!item_disabled, |this| this.cursor_pointer())
627                    .on_hover(move |hovered, window, cx| {
628                        if item_disabled {
629                            return;
630                        }
631                        let t_now = motion_now(cx);
632                        let geom = offsets_for_hover.borrow().get(&idx).copied();
633                        int_hi.update(cx, |s, _| {
634                            s.pointer_mode = true;
635                            if *hovered {
636                                s.highlighted = Some(idx);
637                                s.grace_until_secs = None;
638                                if let Some((top, h)) = geom {
639                                    s.last_highlight_rect = Some((top, h, is_item_danger));
640                                }
641                            } else if s.highlighted == Some(idx) {
642                                s.highlighted = None;
643                                s.pressed_item = None;
644                                s.grace_until_secs = Some(t_now + HIGHLIGHT_GRACE_SECS);
645                            }
646                        });
647                        window.refresh();
648                    })
649                    .on_mouse_down(MouseButton::Left, move |_, window, cx| {
650                        cx.stop_propagation();
651                        if item_disabled {
652                            return;
653                        }
654                        int_down.update(cx, |s, _| s.pressed_item = Some(idx));
655                        window.refresh();
656                    })
657                    .on_mouse_up(MouseButton::Left, move |_, window, cx| {
658                        int_up.update(cx, |s, _| s.pressed_item = None);
659                        window.refresh();
660                    })
661                    .on_click(move |_, window, cx| {
662                        if item_disabled {
663                            return;
664                        }
665                        int_sel.update(cx, |s, _| {
666                            s.open = false;
667                            s.highlighted = None;
668                            s.pressed_item = None;
669                        });
670                        if let Some(cb) = &on_select {
671                            cb(&(), window, cx);
672                        }
673                        window.refresh();
674                    })
675                    .child(item_probe)
676                    .child(icon_slot)
677                    .child(div().min_w_0().truncate().child(item.label))
678            });
679
680            let highlight_pill = div()
681                .absolute()
682                .left(px(5.0))
683                .right(px(5.0))
684                .top(px(pill_top))
685                .h(px(pill_h))
686                .rounded(px(6.0))
687                .bg(pill_bg)
688                .opacity(hi_op.clamp(0.0, 1.0));
689
690            Some(
691                deferred(
692                    div()
693                        .id(menu_id)
694                        .test_support()
695                        .track_focus(&focus_handle)
696                        .role(Role::Menu)
697                        .aria_label(self.label.clone())
698                        .absolute()
699                        .left(px(rel_left))
700                        .top(px(rel_top))
701                        .min_w(px(MENU_WIDTH))
702                        .max_h(px(300.0))
703                        .p(px(5.0))
704                        .rounded(Radii::PANEL)
705                        .border_1()
706                        .border_color(colors.border)
707                        .bg(colors.surface_raised)
708                        .text_color(colors.foreground)
709                        .shadow(Shadows::floating(theme.mode))
710                        .opacity(p)
711                        .flex()
712                        .flex_col()
713                        .on_key_down(move |event: &KeyDownEvent, window, cx| {
714                            let key = event.keystroke.key.as_str();
715                            match key {
716                                "escape" => {
717                                    int_key.update(cx, |s, _| {
718                                        s.open = false;
719                                        s.highlighted = None;
720                                    });
721                                    window.refresh();
722                                }
723                                "down" | "up" | "home" | "end" => {
724                                    int_key.update(cx, |s, _| {
725                                        s.pointer_mode = false;
726                                        s.grace_until_secs = None;
727                                        let next =
728                                            navigate_enabled(&items_for_key, s.highlighted, key);
729                                        s.highlighted = next;
730                                        if let Some(idx) = next
731                                            && let Some(&(top, h)) =
732                                                offsets_for_key.borrow().get(&idx)
733                                        {
734                                            let danger = items_for_key
735                                                .get(idx)
736                                                .is_some_and(|it| it.destructive);
737                                            s.last_highlight_rect = Some((top, h, danger));
738                                        }
739                                    });
740                                    window.refresh();
741                                }
742                                "enter" | "space" => {
743                                    let sel = int_key.read(cx).highlighted;
744                                    if let Some(idx) = sel
745                                        && let Some(act) = items_for_key.get(idx)
746                                        && !act.disabled
747                                    {
748                                        int_key.update(cx, |s, _| {
749                                            s.open = false;
750                                            s.highlighted = None;
751                                        });
752                                        if let Some(cb) = &act.on_select {
753                                            cb(&(), window, cx);
754                                        }
755                                        window.refresh();
756                                    }
757                                }
758                                _ => {}
759                            }
760                        })
761                        .child(menu_probe)
762                        .child(highlight_pill)
763                        .children(rows),
764                )
765                .with_priority(1),
766            )
767        } else {
768            None
769        };
770
771        div()
772            .id(self.id)
773            .relative()
774            .child(target)
775            .when_some(menu_el, |this, menu| this.child(menu))
776    }
777}
778
779#[cfg(test)]
780mod tests {
781    use std::{cell::Cell, rc::Rc};
782
783    use arc_tokens::{Accent, Spacing, ThemeMode, install_arc_theme};
784    use gpui_kit::{
785        Context, MouseButton, Render, Role, ScrollHandle, TestAppContext, TestSupportExt as _, div,
786        point, px, size,
787        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
788    };
789
790    use super::*;
791
792    #[test]
793    fn viewport_clamp_and_home_end_navigation_work() {
794        assert_eq!(
795            clamp_to_viewport(790.0, 580.0, 208.0, 120.0, 800.0, 600.0),
796            (584.0, 472.0)
797        );
798        assert_eq!(
799            clamp_to_viewport(2.0, 3.0, 208.0, 120.0, 800.0, 600.0),
800            (8.0, 8.0)
801        );
802
803        let items = vec![
804            ContextMenuItem::new("a", "A"),
805            ContextMenuItem::new("b", "B").disabled(true),
806            ContextMenuItem::new("c", "C"),
807            ContextMenuItem::new("d", "D"),
808        ];
809        assert_eq!(navigate_enabled(&items, None, "down"), Some(0));
810        assert_eq!(navigate_enabled(&items, Some(0), "down"), Some(2));
811        assert_eq!(navigate_enabled(&items, Some(0), "end"), Some(3));
812        assert_eq!(navigate_enabled(&items, Some(3), "home"), Some(0));
813    }
814
815    struct Host {
816        copied: Rc<Cell<usize>>,
817    }
818
819    impl Render for Host {
820        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
821            let copied = self.copied.clone();
822            div().size_full().p(Spacing::S6).child(
823                ContextMenu::new("canvas-ctx")
824                    .label("画布上下文菜单")
825                    .items([
826                        ContextMenuItem::new("copy", "复制链接").on_select(cx.listener(
827                            move |_, _, _, _| {
828                                copied.set(copied.get() + 1);
829                            },
830                        )),
831                        ContextMenuItem::new("del", "删除项目").destructive(true),
832                    ])
833                    .child(div().w(px(220.0)).h(px(100.0)).child("右键此处")),
834            )
835        }
836    }
837
838    #[gpui_kit::test]
839    fn context_menu_opens_on_right_click_and_selects_item(cx: &mut TestAppContext) {
840        cx.update(|cx| {
841            gpui_kit::init(cx);
842            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
843        });
844        let copied = Rc::new(Cell::new(0));
845        let (_view, cx) = cx.add_window_view(|_, _| Host {
846            copied: copied.clone(),
847        });
848
849        cx.update(|window, cx| {
850            window.render_frame(cx);
851            let target = window.find_by_label("画布上下文菜单");
852            let pos = target.bounds().center();
853            window.pointer_down(pos, MouseButton::Right, cx);
854            window.pointer_up(pos, MouseButton::Right, cx);
855            window.render_frame(cx);
856
857            let item = window.find_by_label("复制链接");
858            assert_eq!(item.role(), Some(Role::MenuItem));
859            let ipos = item.bounds().center();
860            window.pointer_down(ipos, MouseButton::Left, cx);
861            window.pointer_up(ipos, MouseButton::Left, cx);
862            assert_eq!(copied.get(), 1);
863        });
864    }
865
866    /// 可滚动文档中打开菜单后再滚动:菜单锚点应与目标同步位移,而不是停在旧屏幕位置。
867    struct ScrollHost {
868        scroll: ScrollHandle,
869    }
870
871    impl Render for ScrollHost {
872        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
873            div().size_full().child(
874                div()
875                    .id("ctx-scroll-host")
876                    .size_full()
877                    .overflow_y_scroll()
878                    .track_scroll(&self.scroll)
879                    .child(
880                        div()
881                            .flex()
882                            .flex_col()
883                            .child(div().h(px(320.0)))
884                            .child(
885                                ContextMenu::new("scroll-ctx")
886                                    .label("滚动菜单目标")
887                                    .items([
888                                        ContextMenuItem::new("copy", "复制链接"),
889                                        ContextMenuItem::new("del", "删除项目"),
890                                    ])
891                                    .child(
892                                        div()
893                                            .id("scroll-ctx-anchor")
894                                            .test_support()
895                                            .w(px(240.0))
896                                            .h(px(80.0))
897                                            .child("右键此处"),
898                                    ),
899                            )
900                            .child(div().h(px(700.0))),
901                    ),
902            )
903        }
904    }
905
906    #[gpui_kit::test]
907    fn context_menu_follows_target_when_document_scrolls(cx: &mut TestAppContext) {
908        cx.update(|cx| {
909            gpui_kit::init(cx);
910            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
911        });
912        let (view, cx) = cx.add_window_view(|_, _| ScrollHost {
913            scroll: ScrollHandle::new(),
914        });
915        cx.simulate_resize(size(px(800.0), px(600.0)));
916
917        cx.update(|window, cx| {
918            window.render_frame(cx);
919            let before = window.find("scroll-ctx-anchor").bounds();
920            window.pointer_down(before.center(), MouseButton::Right, cx);
921            window.pointer_up(before.center(), MouseButton::Right, cx);
922            window.render_frame(cx);
923            let item_before = window.find_by_label("复制链接").bounds();
924
925            let scroll = view.read(cx).scroll.clone();
926            scroll.set_offset(point(px(0.0), px(-120.0)));
927            window.render_frame(cx);
928            window.render_frame(cx);
929
930            let after = window.find("scroll-ctx-anchor").bounds();
931            let item_after = window.find_by_label("复制链接").bounds();
932            let target_dy = f32::from(after.origin.y) - f32::from(before.origin.y);
933            let menu_dy = f32::from(item_after.origin.y) - f32::from(item_before.origin.y);
934            assert!(target_dy < -100.0, "目标应随文档上移,实际 {target_dy}px");
935            assert!(
936                (target_dy - menu_dy).abs() <= 1.5,
937                "菜单应与目标同步位移:目标 {target_dy}px,菜单 {menu_dy}px"
938            );
939        });
940    }
941}