BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-component / src / menu / dropdown_menu.rs

dropdown_menu.rs

dropdown_menu.rs 16.3 KiB Download Raw
1use std::cell::Cell;
2use std::rc::Rc;
3
4use gpui::{
5 Anchor, AnyElement, App, Context, DismissEvent, Element, ElementId, Entity, FocusHandle,
6 Focusable, GlobalElementId, InspectorElementId, InteractiveElement, IntoElement, LayoutId,
7 Pixels, RenderOnce, SharedString, Styled, Window, prelude::FluentBuilder,
8};
9
10use crate::{
11 Selectable, button::Button, fluent::DROPDOWN_OFFSET, menu::PopupMenu, popover::Popover,
12};
13
14/// A dropdown menu trait for buttons and other interactive elements
15pub trait DropdownMenu: Styled + Selectable + InteractiveElement + IntoElement + 'static {
16 /// Create a dropdown menu with the given items, anchored to the TopLeft corner
17 fn dropdown_menu(
18 self,
19 f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
20 ) -> DropdownMenuPopover<Self> {
21 self.dropdown_menu_with_anchor(Anchor::TopLeft, f)
22 }
23
24 /// Create a dropdown menu with the given items, anchored to the given corner
25 fn dropdown_menu_with_anchor(
26 mut self,
27 anchor: impl Into<Anchor>,
28 f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
29 ) -> DropdownMenuPopover<Self> {
30 let id = self.interactivity().element_id.clone();
31
32 DropdownMenuPopover::new(id.unwrap_or(0.into()), anchor, self, f)
33 }
34}
35
36impl DropdownMenu for Button {}
37
38#[derive(IntoElement)]
39pub struct DropdownMenuPopover<T: Selectable + IntoElement + 'static> {
40 id: ElementId,
41 anchor: Anchor,
42 trigger: T,
43 builder: Rc<dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu>,
44 on_open_change: Option<Rc<dyn Fn(&bool, &mut Window, &mut App)>>,
45 open: Option<bool>,
46 listbox: bool,
47}
48
49impl<T> DropdownMenuPopover<T>
50where
51 T: Selectable + IntoElement + 'static,
52{
53 fn new(
54 id: ElementId,
55 anchor: impl Into<Anchor>,
56 trigger: T,
57 builder: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
58 ) -> Self {
59 Self {
60 id: SharedString::from(format!("dropdown-menu:{:?}", id)).into(),
61 anchor: anchor.into(),
62 trigger,
63 builder: Rc::new(builder),
64 on_open_change: None,
65 open: None,
66 listbox: false,
67 }
68 }
69
70 /// Control the open state from outside; pair it with `on_open_change`.
71 pub fn open(mut self, open: bool) -> Self {
72 self.open = Some(open);
73 self
74 }
75
76 /// Open the menu as a Fluent `Listbox`: left aligned under the trigger,
77 /// 2 px below it and at least as wide, with a check column.
78 pub fn listbox(mut self) -> Self {
79 self.listbox = true;
80 self
81 }
82
83 /// Set the anchor corner for the dropdown menu popover.
84 pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
85 self.anchor = anchor.into();
86 self
87 }
88
89 /// Add a callback to be called when the menu opens or closes.
90 ///
91 /// The `&bool` parameter is the **new open state**.
92 pub fn on_open_change(
93 mut self,
94 callback: impl Fn(&bool, &mut Window, &mut App) + 'static,
95 ) -> Self {
96 self.on_open_change = Some(Rc::new(callback));
97 self
98 }
99}
100
101#[derive(Default)]
102struct DropdownMenuState {
103 menu: Option<Entity<PopupMenu>>,
104}
105
106#[derive(Default)]
107struct TriggerWidth(Rc<Cell<Pixels>>);
108
109impl<T> RenderOnce for DropdownMenuPopover<T>
110where
111 T: Selectable + IntoElement + 'static,
112{
113 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
114 let width_key = SharedString::from(format!("{}:trigger-width", self.id));
115 let trigger_width = window
116 .use_keyed_state(width_key, cx, |_, _| TriggerWidth::default())
117 .read(cx)
118 .0
119 .clone();
120 TriggerFocus::new(
121 self.id.clone(),
122 trigger_width.clone(),
123 move |trigger_focus, window, cx| {
124 self.render_popover(trigger_focus, trigger_width, window, cx)
125 .into_any_element()
126 },
127 )
128 }
129}
130
131impl<T> DropdownMenuPopover<T>
132where
133 T: Selectable + IntoElement + 'static,
134{
135 fn render_popover(
136 self,
137 trigger_focus: FocusHandle,
138 trigger_width: Rc<Cell<Pixels>>,
139 window: &mut Window,
140 cx: &mut App,
141 ) -> Popover {
142 let builder = self.builder.clone();
143 let listbox = self.listbox;
144 let menu_state =
145 window.use_keyed_state(self.id.clone(), cx, |_, _| DropdownMenuState::default());
146
147 Popover::new(SharedString::from(format!("popover:{}", self.id)))
148 .appearance(false)
149 .overlay_closable(false)
150 .trigger(self.trigger)
151 .anchor(self.anchor)
152 .when(listbox, |this| this.offset(DROPDOWN_OFFSET))
153 .when_some(self.open, |this, open| this.open(open))
154 .when_some(self.on_open_change, |this, callback| {
155 this.on_open_change(move |open, window, cx| callback(open, window, cx))
156 })
157 .content(move |_, window, cx| {
158 // Here is special logic to only create the PopupMenu once and reuse it.
159 // Because this `content` will called in every time render, so we need to store the menu
160 // in state to avoid recreating at every render.
161 //
162 // And we also need to rebuild the menu when it is dismissed, to rebuild menu items
163 // dynamically for support `dropdown_menu` method, so we listen for DismissEvent below.
164 let menu = match menu_state.read(cx).menu.clone() {
165 Some(menu) => menu,
166 None => {
167 let builder = builder.clone();
168 let width = trigger_width.get();
169 let menu = PopupMenu::build(window, cx, move |menu, window, cx| {
170 let menu = if listbox { menu.listbox(width) } else { menu };
171 builder(menu, window, cx)
172 });
173 menu.update(cx, |menu, cx| {
174 menu.set_trigger_focus(Some(trigger_focus.clone()), cx)
175 });
176 menu_state.update(cx, |state, _| {
177 state.menu = Some(menu.clone());
178 });
179 menu.focus_handle(cx).focus(window, cx);
180
181 // Listen for dismiss events from the PopupMenu to close the popover.
182 //
183 // Hold Weak handles here, not strong clones: the listener
184 // lives as long as `menu`, which `menu_state` owns, so a
185 // strong capture would close the cycle
186 // `menu_state -> menu -> listener -> menu_state` and leak
187 // the `PopupMenu` and `DropdownMenuState` when the trigger
188 // stops being rendered while the menu is open.
189 let popover_state = cx.entity().downgrade();
190 window
191 .subscribe(&menu, cx, {
192 let menu_state = menu_state.downgrade();
193 move |_, _: &DismissEvent, window, cx| {
194 if let Some(popover_state) = popover_state.upgrade() {
195 popover_state.update(cx, |state, cx| {
196 state.dismiss(window, cx);
197 });
198 }
199 _ = menu_state.update(cx, |state, _| {
200 state.menu = None;
201 });
202 }
203 })
204 .detach();
205
206 menu.clone()
207 }
208 };
209
210 menu.clone()
211 })
212 }
213}
214
215type TriggerFocusBuild = Box<dyn FnOnce(FocusHandle, &mut Window, &mut App) -> AnyElement>;
216
217/// Registers a focus handle on the trigger's dispatch node without ever
218/// focusing it, so the menu opened from the trigger can resolve its shortcut
219/// hints against the trigger's key contexts on the frame it opens. GPUI looks
220/// a handle up in the previously rendered frame; the trigger was in it when
221/// the menu was not yet.
222struct TriggerFocus {
223 id: ElementId,
224 width: Rc<Cell<Pixels>>,
225 build: Option<TriggerFocusBuild>,
226}
227
228#[derive(Default)]
229struct TriggerFocusState {
230 focus_handle: Option<FocusHandle>,
231}
232
233struct TriggerFocusFrame {
234 focus_handle: FocusHandle,
235 child: AnyElement,
236}
237
238impl TriggerFocus {
239 fn new(
240 id: ElementId,
241 width: Rc<Cell<Pixels>>,
242 build: impl FnOnce(FocusHandle, &mut Window, &mut App) -> AnyElement + 'static,
243 ) -> Self {
244 Self {
245 id,
246 width,
247 build: Some(Box::new(build)),
248 }
249 }
250}
251
252impl IntoElement for TriggerFocus {
253 type Element = Self;
254
255 fn into_element(self) -> Self::Element {
256 self
257 }
258}
259
260impl Element for TriggerFocus {
261 type RequestLayoutState = TriggerFocusFrame;
262 type PrepaintState = ();
263
264 fn id(&self) -> Option<ElementId> {
265 Some(self.id.clone())
266 }
267
268 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
269 None
270 }
271
272 fn request_layout(
273 &mut self,
274 id: Option<&GlobalElementId>,
275 _: Option<&InspectorElementId>,
276 window: &mut Window,
277 cx: &mut App,
278 ) -> (LayoutId, Self::RequestLayoutState) {
279 let focus_handle =
280 window.with_optional_element_state::<TriggerFocusState, _>(id, |state, _| {
281 let mut state = state.flatten().unwrap_or_default();
282 let focus_handle = state
283 .focus_handle
284 .get_or_insert_with(|| cx.focus_handle())
285 .clone();
286 (focus_handle, Some(state))
287 });
288 let build = self.build.take().expect("TriggerFocus is laid out once");
289 let mut child = build(focus_handle.clone(), window, cx);
290 let layout_id = child.request_layout(window, cx);
291
292 (
293 layout_id,
294 TriggerFocusFrame {
295 focus_handle,
296 child,
297 },
298 )
299 }
300
301 fn prepaint(
302 &mut self,
303 _: Option<&GlobalElementId>,
304 _: Option<&InspectorElementId>,
305 bounds: gpui::Bounds<gpui::Pixels>,
306 frame: &mut Self::RequestLayoutState,
307 window: &mut Window,
308 cx: &mut App,
309 ) {
310 self.width.set(bounds.size.width);
311 window.set_focus_handle(&frame.focus_handle, cx);
312 frame.child.prepaint(window, cx);
313 }
314
315 fn paint(
316 &mut self,
317 _: Option<&GlobalElementId>,
318 _: Option<&InspectorElementId>,
319 _: gpui::Bounds<gpui::Pixels>,
320 frame: &mut Self::RequestLayoutState,
321 _: &mut Self::PrepaintState,
322 window: &mut Window,
323 cx: &mut App,
324 ) {
325 frame.child.paint(window, cx);
326 }
327}
328
329#[cfg(test)]
330mod tests {
331 use super::*;
332 use gpui::{
333 KeyBinding, MouseButton, ParentElement as _, Render, TestAppContext, WeakEntity, actions,
334 div, point, px,
335 };
336 use std::cell::{Cell, RefCell};
337
338 actions!(dropdown_menu_test, [CopyText]);
339
340 const CONTEXT: &str = "dropdown_menu_test";
341
342 /// The story shape: the key binding lives in the key context of the
343 /// trigger's ancestor, the menu names no `action_context`, and other
344 /// content outside that context paints after the trigger.
345 struct TestRoot {
346 frames: Rc<Cell<usize>>,
347 }
348
349 impl Render for TestRoot {
350 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
351 self.frames.set(self.frames.get() + 1);
352 div()
353 .size_full()
354 .child(
355 div()
356 .key_context(CONTEXT)
357 .on_action(|_: &CopyText, _, _| {})
358 .child(
359 Button::new("trigger")
360 .label("Edit")
361 .w(px(100.))
362 .h(px(30.))
363 .dropdown_menu(|menu, _, _| menu.menu("Copy", Box::new(CopyText))),
364 ),
365 )
366 .child(div().child("Status"))
367 }
368 }
369
370 /// Records the `PopupMenu` the dropdown builds, so a test can observe
371 /// its release through a weak handle.
372 struct MenuProbeRoot {
373 menu: Rc<RefCell<Option<WeakEntity<PopupMenu>>>>,
374 }
375
376 impl Render for MenuProbeRoot {
377 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
378 let slot = self.menu.clone();
379 div().size_full().child(
380 Button::new("trigger")
381 .label("Edit")
382 .w(px(100.))
383 .h(px(30.))
384 .dropdown_menu(move |menu, _, cx| {
385 *slot.borrow_mut() = Some(cx.weak_entity());
386 menu.menu("Copy", Box::new(CopyText))
387 }),
388 )
389 }
390 }
391
392 /// Opening the menu and closing the window without dismissing it must
393 /// release the `PopupMenu`: the dismiss subscription lives as long as the
394 /// menu, which `DropdownMenuState` owns, so strong captures in it formed
395 /// a cycle that no element-state collection could break. The state still
396 /// holds the menu while it is open, so the menu's release also proves the
397 /// `DropdownMenuState` was released.
398 ///
399 /// The popover must go too: it holds the deferred-popover registration
400 /// while open, and a leaked one keeps every later right-click menu
401 /// stepping aside as if a popup were still showing.
402 #[gpui::test]
403 fn open_without_dismiss_releases_the_menu(cx: &mut TestAppContext) {
404 cx.update(|cx| crate::init(cx));
405 let menu = Rc::new(RefCell::new(None::<WeakEntity<PopupMenu>>));
406
407 {
408 let (_, cx) = cx.add_window_view(|_, _| MenuProbeRoot { menu: menu.clone() });
409 cx.update(|window, cx| window.draw(cx).clear(cx));
410
411 // Click the trigger; the menu opens and is left open.
412 cx.simulate_mouse_down(
413 point(px(10.), px(10.)),
414 MouseButton::Left,
415 Default::default(),
416 );
417 cx.run_until_parked();
418 assert!(
419 menu.borrow()
420 .as_ref()
421 .and_then(|menu| menu.upgrade())
422 .is_some(),
423 "the menu must be open before the window closes"
424 );
425
426 // Close the window without dismissing the menu.
427 cx.update(|window, _| window.remove_window());
428 cx.run_until_parked();
429 }
430
431 assert!(
432 menu.borrow()
433 .as_ref()
434 .and_then(|menu| menu.upgrade())
435 .is_none(),
436 "the PopupMenu must be released with the window"
437 );
438 cx.update(|cx| {
439 assert!(
440 !gpui_base::GlobalState::is_in_deferred_context(cx),
441 "the popover's deferred registration must be released with the window"
442 )
443 });
444 }
445
446 #[gpui::test]
447 fn shortcut_hint_is_painted_on_the_frame_the_menu_opens(cx: &mut TestAppContext) {
448 cx.update(|cx| {
449 crate::init(cx);
450 cx.bind_keys([KeyBinding::new("ctrl-c", CopyText, Some(CONTEXT))]);
451 });
452 let frames = Rc::new(Cell::new(0));
453 let (_, cx) = cx.add_window_view({
454 let frames = frames.clone();
455 move |_, _| TestRoot { frames }
456 });
457 // The popup host captures its trigger bounds on the first frame.
458 cx.update(|window, cx| window.draw(cx).clear(cx));
459 let frames_before_open = frames.get();
460
461 cx.simulate_mouse_down(
462 point(px(10.), px(10.)),
463 MouseButton::Left,
464 Default::default(),
465 );
466
467 assert_eq!(
468 frames.get(),
469 frames_before_open + 1,
470 "the press must be followed by exactly one frame for this to test the first one"
471 );
472 assert!(
473 cx.debug_bounds("kbd:ctrl-c").is_some(),
474 "the shortcut hint must be painted on the same frame as its item"
475 );
476 }
477}