1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
//! ContextMenu: a menu opened with a secondary click → Carbon `Menu` +
//! `useContextMenu` (the menu's top-left corner at the pointer).
//!
//! - **Behavior**: a right press inside the area opens the [`super::menu`]
//! Carbon menu at the pointer; Shift+F10 or the Menu key opens it at the
//! area's top-left while focus is inside; a press outside, Escape, Tab or an
//! activated item closes it. Placement is Base's `Positioner` in a corner
//! mode (clamped to the window, like Carbon's menu) on the deferred popup
//! layer. Kit's `context_menu` wraps its own `PopupMenu`, whose rendering
//! cannot be made Carbon (see [`super::menu`]).
//! - `default_open_at` opens it on arrival at a point relative to the area's
//! top-left (the reference preview's `defaultOpenAt`).
//!
//! ```ignore
//! ContextMenu::new("file", area)
//! .item(MenuItem::item("Copy").shortcut("⌘C"))
//! .item(MenuItem::divider())
//! .item(MenuItem::item("Delete").danger(true))
//! ```
use super::menu::{self, MenuItem, MenuSize};
use super::overlay;
use gpui_kit::{
Anchor, AnyElement, App, Bounds, ElementId, InteractiveElement, IntoElement, KeyDownEvent,
MouseButton, ParentElement, Pixels, Point, RenderOnce, SharedString, Styled,
TestSupportExt as _, Window, canvas, deferred, div, point, prelude::FluentBuilder as _, px,
};
use std::rc::Rc;
/// The keys that open a context menu from the keyboard.
pub fn is_menu_key(key: &str, shift: bool) -> bool {
key == "menu" || (key == "f10" && shift)
}
/// A context menu around an area. See the module docs.
#[derive(IntoElement)]
pub struct ContextMenu {
id: ElementId,
area: AnyElement,
items: Vec<MenuItem>,
label: SharedString,
size: MenuSize,
default_open_at: Option<(f32, f32)>,
}
/// Where the menu is and whether it is open.
#[derive(Default)]
struct Placed {
open: bool,
/// Where the menu opened, from the area's top-left: the menu follows the
/// area when a resize moves it, as the reference's does in its card.
at: Point<Pixels>,
area: Bounds<Pixels>,
measured: bool,
defaulted: bool,
}
impl ContextMenu {
/// A context menu with a stable `id` for `area` (the right-click target).
pub fn new(id: impl Into<ElementId>, area: impl IntoElement) -> Self {
Self {
id: id.into(),
area: area.into_any_element(),
items: Vec::new(),
label: SharedString::default(),
size: MenuSize::Sm,
default_open_at: None,
}
}
/// Append a menu item.
pub fn item(mut self, item: MenuItem) -> Self {
self.items.push(item);
self
}
/// Append menu items.
pub fn items(mut self, items: impl IntoIterator<Item = MenuItem>) -> Self {
self.items.extend(items);
self
}
/// The menu's accessible name.
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = label.into();
self
}
/// Menu size (default `sm`, as the reference passes).
pub fn size(mut self, size: MenuSize) -> Self {
self.size = size;
self
}
/// Open on arrival at `(x, y)` px from the area's top-left (demos).
pub fn default_open_at(mut self, x: f32, y: f32) -> Self {
self.default_open_at = Some((x, y));
self
}
}
impl RenderOnce for ContextMenu {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let placed = window.use_keyed_state((id.clone(), "placed"), cx, |_, _| Placed::default());
if let Some((x, y)) = self.default_open_at {
let p = placed.read(cx);
if p.measured && !p.defaulted {
let at = point(px(x), px(y));
placed.update(cx, |p, _| {
p.defaulted = true;
p.open = true;
p.at = at;
});
}
}
let area_focus = window
.use_keyed_state((id.clone(), "area-focus"), cx, |_, cx| cx.focus_handle())
.read(cx)
.clone();
// The area is a tab stop of ours (the reference's `.cu-context-area`
// is not focusable), so keyboard focus shows the 2px `focus` ring
// every focusable element draws.
let ring = area_focus.is_focused(window) && crate::focus::focus_visible_mode(window);
let (open, at) = {
let p = placed.read(cx);
(p.open, p.area.origin + p.at)
};
let set_open: overlay::OpenChange = {
let placed = placed.clone();
Rc::new(move |open, window, cx| {
placed.update(cx, |p, cx| {
p.open = open;
cx.notify();
});
window.refresh();
})
};
let surface = menu::menu_surface(
&id,
menu::MenuSpec {
items: self.items,
size: self.size,
label: self.label,
open,
set_open,
min_width: None,
on_unhandled_key: None,
},
window,
cx,
);
let measure = {
let placed = placed.clone();
canvas(
move |bounds, window, cx| {
let p = placed.read(cx);
if !p.measured || p.area != bounds {
// The default-open menu waits for the first
// measurement, and an open menu's place reads the
// area: draw them where it is now. (A closed menu's
// area moving, e.g. on scroll, needs no frame.)
let redraw = !p.measured || p.open;
placed.update(cx, |p, cx| {
p.area = bounds;
p.measured = true;
cx.notify();
});
if redraw {
crate::measure::redraw_next_frame(window);
}
}
},
|_, _, _, _| {},
)
.absolute()
.top_0()
.left_0()
.size_full()
};
div()
.id((id.clone(), "area"))
.test_support()
// The area is a tab stop so Shift+F10 / the Menu key can reach it.
.track_focus(&area_focus.tab_stop(true))
.relative()
.on_mouse_down(MouseButton::Right, {
let placed = placed.clone();
move |event, window, cx| {
placed.update(cx, |p, cx| {
p.open = true;
p.at = event.position - p.area.origin;
cx.notify();
});
window.refresh();
cx.stop_propagation();
}
})
.on_key_down({
let placed = placed.clone();
move |event: &KeyDownEvent, window, cx| {
if is_menu_key(&event.keystroke.key, event.keystroke.modifiers.shift) {
placed.update(cx, |p, cx| {
p.open = true;
p.at = Point::default();
cx.notify();
});
window.refresh();
cx.stop_propagation();
}
}
})
.child(self.area)
.child(measure)
.when(ring, |d| {
d.child(super::form::inset_outline(
2.,
crate::theme::color(crate::tokens::ColorRole::Focus),
))
})
.children(surface.map(|surface| {
deferred(
gpui_kit::base::Positioner::corner(Anchor::TopLeft, at)
.margin(px(8.))
.occlude()
.child(surface),
)
.with_priority(gpui_kit::base::POPUP_PRIORITY)
}))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn menu_keys() {
assert!(is_menu_key("menu", false));
assert!(is_menu_key("f10", true));
assert!(!is_menu_key("f10", false));
assert_eq!(ContextMenu::new("c", div()).size, MenuSize::Sm);
}
}