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)>;
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;
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),
)
}
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)
}
#[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
}
}
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);
}
}
}
#[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"
);
});
}
}