1use std::rc::Rc;
2
3use gpui::{
4 Anchor, AnyElement, App, Context, DismissEvent, Element, ElementId, Entity, FocusHandle,
5 Focusable, GlobalElementId, InspectorElementId, InteractiveElement, IntoElement, LayoutId,
6 RenderOnce, SharedString, Styled, Window, prelude::FluentBuilder,
7};
8
9use crate::{Selectable, button::Button, menu::PopupMenu, popover::Popover};
10
11pub trait DropdownMenu: Styled + Selectable + InteractiveElement + IntoElement + 'static {
13 fn dropdown_menu(
15 self,
16 f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
17 ) -> DropdownMenuPopover<Self> {
18 self.dropdown_menu_with_anchor(Anchor::TopLeft, f)
19 }
20
21 fn dropdown_menu_with_anchor(
23 mut self,
24 anchor: impl Into<Anchor>,
25 f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
26 ) -> DropdownMenuPopover<Self> {
27 let id = self.interactivity().element_id.clone();
28
29 DropdownMenuPopover::new(id.unwrap_or(0.into()), anchor, self, f)
30 }
31}
32
33impl DropdownMenu for Button {}
34
35#[derive(IntoElement)]
36pub struct DropdownMenuPopover<T: Selectable + IntoElement + 'static> {
37 id: ElementId,
38 anchor: Anchor,
39 trigger: T,
40 builder: Rc<dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu>,
41 on_open_change: Option<Rc<dyn Fn(&bool, &mut Window, &mut App)>>,
42}
43
44impl<T> DropdownMenuPopover<T>
45where
46 T: Selectable + IntoElement + 'static,
47{
48 fn new(
49 id: ElementId,
50 anchor: impl Into<Anchor>,
51 trigger: T,
52 builder: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
53 ) -> Self {
54 Self {
55 id: SharedString::from(format!("dropdown-menu:{:?}", id)).into(),
56 anchor: anchor.into(),
57 trigger,
58 builder: Rc::new(builder),
59 on_open_change: None,
60 }
61 }
62
63 pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
65 self.anchor = anchor.into();
66 self
67 }
68
69 pub fn on_open_change(
73 mut self,
74 callback: impl Fn(&bool, &mut Window, &mut App) + 'static,
75 ) -> Self {
76 self.on_open_change = Some(Rc::new(callback));
77 self
78 }
79}
80
81#[derive(Default)]
82struct DropdownMenuState {
83 menu: Option<Entity<PopupMenu>>,
84}
85
86impl<T> RenderOnce for DropdownMenuPopover<T>
87where
88 T: Selectable + IntoElement + 'static,
89{
90 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
91 TriggerFocus::new(self.id.clone(), move |trigger_focus, window, cx| {
92 self.render_popover(trigger_focus, window, cx)
93 .into_any_element()
94 })
95 }
96}
97
98impl<T> DropdownMenuPopover<T>
99where
100 T: Selectable + IntoElement + 'static,
101{
102 fn render_popover(
103 self,
104 trigger_focus: FocusHandle,
105 window: &mut Window,
106 cx: &mut App,
107 ) -> Popover {
108 let builder = self.builder.clone();
109 let menu_state =
110 window.use_keyed_state(self.id.clone(), cx, |_, _| DropdownMenuState::default());
111
112 Popover::new(SharedString::from(format!("popover:{}", self.id)))
113 .appearance(false)
114 .overlay_closable(false)
115 .trigger(self.trigger)
116 .anchor(self.anchor)
117 .when_some(self.on_open_change, |this, callback| {
118 this.on_open_change(move |open, window, cx| callback(open, window, cx))
119 })
120 .content(move |_, window, cx| {
121 let menu = match menu_state.read(cx).menu.clone() {
128 Some(menu) => menu,
129 None => {
130 let builder = builder.clone();
131 let menu = PopupMenu::build(window, cx, move |menu, window, cx| {
132 builder(menu, window, cx)
133 });
134 menu.update(cx, |menu, cx| {
135 menu.set_trigger_focus(Some(trigger_focus.clone()), cx)
136 });
137 menu_state.update(cx, |state, _| {
138 state.menu = Some(menu.clone());
139 });
140 menu.focus_handle(cx).focus(window, cx);
141
142 let popover_state = cx.entity().downgrade();
151 window
152 .subscribe(&menu, cx, {
153 let menu_state = menu_state.downgrade();
154 move |_, _: &DismissEvent, window, cx| {
155 if let Some(popover_state) = popover_state.upgrade() {
156 popover_state.update(cx, |state, cx| {
157 state.dismiss(window, cx);
158 });
159 }
160 _ = menu_state.update(cx, |state, _| {
161 state.menu = None;
162 });
163 }
164 })
165 .detach();
166
167 menu
168 }
169 };
170
171 menu
172 })
173 }
174}
175
176type TriggerFocusBuild = Box<dyn FnOnce(FocusHandle, &mut Window, &mut App) -> AnyElement>;
177
178struct TriggerFocus {
184 id: ElementId,
185 build: Option<TriggerFocusBuild>,
186}
187
188#[derive(Default)]
189struct TriggerFocusState {
190 focus_handle: Option<FocusHandle>,
191}
192
193struct TriggerFocusFrame {
194 focus_handle: FocusHandle,
195 child: AnyElement,
196}
197
198impl TriggerFocus {
199 fn new(
200 id: ElementId,
201 build: impl FnOnce(FocusHandle, &mut Window, &mut App) -> AnyElement + 'static,
202 ) -> Self {
203 Self {
204 id,
205 build: Some(Box::new(build)),
206 }
207 }
208}
209
210impl Element for TriggerFocus {
211 type RequestLayoutState = TriggerFocusFrame;
212 type PrepaintState = ();
213
214 fn id(&self) -> Option<ElementId> {
215 Some(self.id.clone())
216 }
217
218 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
219 None
220 }
221
222 fn request_layout(
223 &mut self,
224 id: Option<&GlobalElementId>,
225 _: Option<&InspectorElementId>,
226 window: &mut Window,
227 cx: &mut App,
228 ) -> (LayoutId, Self::RequestLayoutState) {
229 let focus_handle =
230 window.with_optional_element_state::<TriggerFocusState, _>(id, |state, _| {
231 let mut state = state.flatten().unwrap_or_default();
232 let focus_handle = state
233 .focus_handle
234 .get_or_insert_with(|| cx.focus_handle())
235 .clone();
236 (focus_handle, Some(state))
237 });
238 let build = self.build.take().expect("TriggerFocus is laid out once");
239 let mut child = build(focus_handle.clone(), window, cx);
240 let layout_id = child.request_layout(window, cx);
241
242 (
243 layout_id,
244 TriggerFocusFrame {
245 focus_handle,
246 child,
247 },
248 )
249 }
250
251 fn prepaint(
252 &mut self,
253 _: Option<&GlobalElementId>,
254 _: Option<&InspectorElementId>,
255 _: gpui::Bounds<gpui::Pixels>,
256 frame: &mut Self::RequestLayoutState,
257 window: &mut Window,
258 cx: &mut App,
259 ) {
260 window.set_focus_handle(&frame.focus_handle, cx);
261 frame.child.prepaint(window, cx);
262 }
263
264 fn paint(
265 &mut self,
266 _: Option<&GlobalElementId>,
267 _: Option<&InspectorElementId>,
268 _: gpui::Bounds<gpui::Pixels>,
269 frame: &mut Self::RequestLayoutState,
270 _: &mut Self::PrepaintState,
271 window: &mut Window,
272 cx: &mut App,
273 ) {
274 frame.child.paint(window, cx);
275 }
276}
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281 use gpui::{
282 KeyBinding, MouseButton, ParentElement as _, Render, TestAppContext, WeakEntity, actions,
283 div, point, px,
284 };
285 use std::cell::{Cell, RefCell};
286
287 actions!(dropdown_menu_test, [CopyText]);
288
289 const CONTEXT: &str = "dropdown_menu_test";
290
291 struct TestRoot {
295 frames: Rc<Cell<usize>>,
296 }
297
298 impl Render for TestRoot {
299 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
300 self.frames.set(self.frames.get() + 1);
301 div()
302 .size_full()
303 .child(
304 div()
305 .key_context(CONTEXT)
306 .on_action(|_: &CopyText, _, _| {})
307 .child(
308 Button::new("trigger")
309 .label("Edit")
310 .w(px(100.))
311 .h(px(30.))
312 .dropdown_menu(|menu, _, _| menu.menu("Copy", Box::new(CopyText))),
313 ),
314 )
315 .child(div().child("Status"))
316 }
317 }
318
319 struct MenuProbeRoot {
322 menu: Rc<RefCell<Option<WeakEntity<PopupMenu>>>>,
323 }
324
325 impl Render for MenuProbeRoot {
326 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
327 let slot = self.menu.clone();
328 div().size_full().child(
329 Button::new("trigger")
330 .label("Edit")
331 .w(px(100.))
332 .h(px(30.))
333 .dropdown_menu(move |menu, _, cx| {
334 *slot.borrow_mut() = Some(cx.weak_entity());
335 menu.menu("Copy", Box::new(CopyText))
336 }),
337 )
338 }
339 }
340
341 #[gpui::test]
352 fn open_without_dismiss_releases_the_menu(cx: &mut TestAppContext) {
353 cx.update(|cx| crate::init(cx));
354 let menu = Rc::new(RefCell::new(None::<WeakEntity<PopupMenu>>));
355
356 {
357 let (_, cx) = cx.add_window_view(|_, _| MenuProbeRoot { menu: menu.clone() });
358 cx.update(|window, cx| window.draw(cx).clear(cx));
359
360 cx.simulate_mouse_down(
362 point(px(10.), px(10.)),
363 MouseButton::Left,
364 Default::default(),
365 );
366 cx.run_until_parked();
367 assert!(
368 menu.borrow()
369 .as_ref()
370 .and_then(|menu| menu.upgrade())
371 .is_some(),
372 "the menu must be open before the window closes"
373 );
374
375 cx.update(|window, _| window.remove_window());
377 cx.run_until_parked();
378 }
379
380 assert!(
381 menu.borrow()
382 .as_ref()
383 .and_then(|menu| menu.upgrade())
384 .is_none(),
385 "the PopupMenu must be released with the window"
386 );
387 cx.update(|cx| {
388 assert!(
389 !gpui_base::GlobalState::is_in_deferred_context(cx),
390 "the popover's deferred registration must be released with the window"
391 )
392 });
393 }
394
395 #[gpui::test]
396 fn shortcut_hint_is_painted_on_the_frame_the_menu_opens(cx: &mut TestAppContext) {
397 cx.update(|cx| {
398 crate::init(cx);
399 cx.bind_keys([KeyBinding::new("ctrl-c", CopyText, Some(CONTEXT))]);
400 });
401 let frames = Rc::new(Cell::new(0));
402 let (_, cx) = cx.add_window_view({
403 let frames = frames.clone();
404 move |_, _| TestRoot { frames }
405 });
406 cx.update(|window, cx| window.draw(cx).clear(cx));
408 let frames_before_open = frames.get();
409
410 cx.simulate_mouse_down(
411 point(px(10.), px(10.)),
412 MouseButton::Left,
413 Default::default(),
414 );
415
416 assert_eq!(
417 frames.get(),
418 frames_before_open + 1,
419 "the press must be followed by exactly one frame for this to test the first one"
420 );
421 assert!(
422 cx.debug_bounds("kbd:ctrl-c").is_some(),
423 "the shortcut hint must be painted on the same frame as its item"
424 );
425 }
426}