1use std::{cell::RefCell, rc::Rc};
2
3use gpui::{
4 AnyElement, AnyView, App, Bounds, Corner, DismissEvent, DispatchPhase, Element, ElementId,
5 Entity, Focusable as _, GlobalElementId, HitboxBehavior, HitboxId, InteractiveElement,
6 IntoElement, LayoutId, Length, ManagedView, MouseDownEvent, ParentElement, Pixels, Point,
7 Style, Window, anchored, deferred, div, point, prelude::FluentBuilder, px, size,
8};
9
10use crate::prelude::*;
11
12pub trait PopoverTrigger: IntoElement + Clickable + Toggleable + 'static {}
13
14impl<T: IntoElement + Clickable + Toggleable + 'static> PopoverTrigger for T {}
15
16impl<T: Clickable> Clickable for gpui::AnimationElement<T>
17where
18 T: Clickable + 'static,
19{
20 fn on_click(
21 self,
22 handler: impl Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static,
23 ) -> Self {
24 self.map_element(|e| e.on_click(handler))
25 }
26
27 fn cursor_style(self, cursor_style: gpui::CursorStyle) -> Self {
28 self.map_element(|e| e.cursor_style(cursor_style))
29 }
30}
31
32impl<T: Toggleable> Toggleable for gpui::AnimationElement<T>
33where
34 T: Toggleable + 'static,
35{
36 fn toggle_state(self, selected: bool) -> Self {
37 self.map_element(|e| e.toggle_state(selected))
38 }
39}
40
41pub struct PopoverMenuHandle<M>(Rc<RefCell<Option<PopoverMenuHandleState<M>>>>);
42
43impl<M> Clone for PopoverMenuHandle<M> {
44 fn clone(&self) -> Self {
45 Self(self.0.clone())
46 }
47}
48
49impl<M> Default for PopoverMenuHandle<M> {
50 fn default() -> Self {
51 Self(Rc::default())
52 }
53}
54
55struct PopoverMenuHandleState<M> {
56 menu_builder: Rc<dyn Fn(&mut Window, &mut App) -> Option<Entity<M>>>,
57 menu: Rc<RefCell<Option<Entity<M>>>>,
58 on_open: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
59}
60
61impl<M: ManagedView> PopoverMenuHandle<M> {
62 pub fn show(&self, window: &mut Window, cx: &mut App) {
63 if let Some(state) = self.0.borrow().as_ref() {
64 show_menu(
65 &state.menu_builder,
66 &state.menu,
67 state.on_open.clone(),
68 window,
69 cx,
70 );
71 }
72 }
73
74 pub fn hide(&self, cx: &mut App) {
75 if let Some(state) = self.0.borrow().as_ref() {
76 if let Some(menu) = state.menu.borrow().as_ref() {
77 menu.update(cx, |_, cx| cx.emit(DismissEvent));
78 }
79 }
80 }
81
82 pub fn toggle(&self, window: &mut Window, cx: &mut App) {
83 if let Some(state) = self.0.borrow().as_ref() {
84 if state.menu.borrow().is_some() {
85 self.hide(cx);
86 } else {
87 self.show(window, cx);
88 }
89 }
90 }
91
92 pub fn is_deployed(&self) -> bool {
93 self.0
94 .borrow()
95 .as_ref()
96 .map_or(false, |state| state.menu.borrow().as_ref().is_some())
97 }
98
99 pub fn is_focused(&self, window: &Window, cx: &App) -> bool {
100 self.0.borrow().as_ref().map_or(false, |state| {
101 state
102 .menu
103 .borrow()
104 .as_ref()
105 .map_or(false, |model| model.focus_handle(cx).is_focused(window))
106 })
107 }
108}
109
110pub struct PopoverMenu<M: ManagedView> {
111 id: ElementId,
112 child_builder: Option<
113 Box<
114 dyn FnOnce(
115 Rc<RefCell<Option<Entity<M>>>>,
116 Option<Rc<dyn Fn(&mut Window, &mut App) -> Option<Entity<M>> + 'static>>,
117 ) -> AnyElement
118 + 'static,
119 >,
120 >,
121 menu_builder: Option<Rc<dyn Fn(&mut Window, &mut App) -> Option<Entity<M>> + 'static>>,
122 anchor: Corner,
123 attach: Option<Corner>,
124 offset: Option<Point<Pixels>>,
125 trigger_handle: Option<PopoverMenuHandle<M>>,
126 on_open: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
127 full_width: bool,
128}
129
130impl<M: ManagedView> PopoverMenu<M> {
131 /// Returns a new [`PopoverMenu`].
132 pub fn new(id: impl Into<ElementId>) -> Self {
133 Self {
134 id: id.into(),
135 child_builder: None,
136 menu_builder: None,
137 anchor: Corner::TopLeft,
138 attach: None,
139 offset: None,
140 trigger_handle: None,
141 on_open: None,
142 full_width: false,
143 }
144 }
145
146 pub fn full_width(mut self, full_width: bool) -> Self {
147 self.full_width = full_width;
148 self
149 }
150
151 pub fn menu(
152 mut self,
153 f: impl Fn(&mut Window, &mut App) -> Option<Entity<M>> + 'static,
154 ) -> Self {
155 self.menu_builder = Some(Rc::new(f));
156 self
157 }
158
159 pub fn with_handle(mut self, handle: PopoverMenuHandle<M>) -> Self {
160 self.trigger_handle = Some(handle);
161 self
162 }
163
164 pub fn trigger<T: PopoverTrigger>(mut self, t: T) -> Self {
165 let on_open = self.on_open.clone();
166 self.child_builder = Some(Box::new(move |menu, builder| {
167 let open = menu.borrow().is_some();
168 t.toggle_state(open)
169 .when_some(builder, |el, builder| {
170 el.on_click(move |_event, window, cx| {
171 show_menu(&builder, &menu, on_open.clone(), window, cx)
172 })
173 })
174 .into_any_element()
175 }));
176 self
177 }
178
179 /// This method prevents the trigger button tooltip from being seen when the menu is open.
180 pub fn trigger_with_tooltip<T: PopoverTrigger + ButtonCommon>(
181 mut self,
182 t: T,
183 tooltip_builder: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
184 ) -> Self {
185 let on_open = self.on_open.clone();
186 self.child_builder = Some(Box::new(move |menu, builder| {
187 let open = menu.borrow().is_some();
188 t.toggle_state(open)
189 .when_some(builder, |el, builder| {
190 el.on_click(move |_, window, cx| {
191 show_menu(&builder, &menu, on_open.clone(), window, cx)
192 })
193 .when(!open, |t| {
194 t.tooltip(move |window, cx| tooltip_builder(window, cx))
195 })
196 })
197 .into_any_element()
198 }));
199 self
200 }
201
202 /// Defines which corner of the menu to anchor to the attachment point.
203 /// By default, it uses the cursor position. Also see the `attach` method.
204 pub fn anchor(mut self, anchor: Corner) -> Self {
205 self.anchor = anchor;
206 self
207 }
208
209 /// Defines which corner of the handle to attach the menu's anchor to.
210 pub fn attach(mut self, attach: Corner) -> Self {
211 self.attach = Some(attach);
212 self
213 }
214
215 /// Offsets the position of the content by that many pixels.
216 pub fn offset(mut self, offset: Point<Pixels>) -> Self {
217 self.offset = Some(offset);
218 self
219 }
220
221 /// Attaches something upon opening the menu.
222 pub fn on_open(mut self, on_open: Rc<dyn Fn(&mut Window, &mut App)>) -> Self {
223 self.on_open = Some(on_open);
224 self
225 }
226
227 fn resolved_attach(&self) -> Corner {
228 self.attach.unwrap_or(match self.anchor {
229 Corner::TopLeft => Corner::BottomLeft,
230 Corner::TopRight => Corner::BottomRight,
231 Corner::BottomLeft => Corner::TopLeft,
232 Corner::BottomRight => Corner::TopRight,
233 })
234 }
235
236 fn resolved_offset(&self, window: &mut Window) -> Point<Pixels> {
237 self.offset.unwrap_or_else(|| {
238 // Default offset = 4px padding + 1px border
239 let offset = rems_from_px(5.) * window.rem_size();
240 match self.anchor {
241 Corner::TopRight | Corner::BottomRight => point(offset, px(0.)),
242 Corner::TopLeft | Corner::BottomLeft => point(-offset, px(0.)),
243 }
244 })
245 }
246}
247
248fn show_menu<M: ManagedView>(
249 builder: &Rc<dyn Fn(&mut Window, &mut App) -> Option<Entity<M>>>,
250 menu: &Rc<RefCell<Option<Entity<M>>>>,
251 on_open: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
252 window: &mut Window,
253 cx: &mut App,
254) {
255 let Some(new_menu) = (builder)(window, cx) else {
256 return;
257 };
258 let menu2 = menu.clone();
259 let previous_focus_handle = window.focused(cx);
260
261 window
262 .subscribe(&new_menu, cx, move |modal, _: &DismissEvent, window, cx| {
263 if modal.focus_handle(cx).contains_focused(window, cx) {
264 if let Some(previous_focus_handle) = previous_focus_handle.as_ref() {
265 window.focus(previous_focus_handle);
266 }
267 }
268 *menu2.borrow_mut() = None;
269 window.refresh();
270 })
271 .detach();
272 window.focus(&new_menu.focus_handle(cx));
273 *menu.borrow_mut() = Some(new_menu);
274 window.refresh();
275
276 if let Some(on_open) = on_open {
277 on_open(window, cx);
278 }
279}
280
281pub struct PopoverMenuElementState<M> {
282 menu: Rc<RefCell<Option<Entity<M>>>>,
283 child_bounds: Option<Bounds<Pixels>>,
284}
285
286impl<M> Clone for PopoverMenuElementState<M> {
287 fn clone(&self) -> Self {
288 Self {
289 menu: Rc::clone(&self.menu),
290 child_bounds: self.child_bounds,
291 }
292 }
293}
294
295impl<M> Default for PopoverMenuElementState<M> {
296 fn default() -> Self {
297 Self {
298 menu: Rc::default(),
299 child_bounds: None,
300 }
301 }
302}
303
304pub struct PopoverMenuFrameState<M: ManagedView> {
305 child_layout_id: Option<LayoutId>,
306 child_element: Option<AnyElement>,
307 menu_element: Option<AnyElement>,
308 menu_handle: Rc<RefCell<Option<Entity<M>>>>,
309}
310
311impl<M: ManagedView> Element for PopoverMenu<M> {
312 type RequestLayoutState = PopoverMenuFrameState<M>;
313 type PrepaintState = Option<HitboxId>;
314
315 fn id(&self) -> Option<ElementId> {
316 Some(self.id.clone())
317 }
318
319 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
320 None
321 }
322
323 fn request_layout(
324 &mut self,
325 global_id: Option<&GlobalElementId>,
326 _inspector_id: Option<&gpui::InspectorElementId>,
327 window: &mut Window,
328 cx: &mut App,
329 ) -> (gpui::LayoutId, Self::RequestLayoutState) {
330 window.with_element_state(
331 global_id.unwrap(),
332 |element_state: Option<PopoverMenuElementState<M>>, window| {
333 let element_state = element_state.unwrap_or_default();
334 let mut menu_layout_id = None;
335
336 let menu_element = element_state.menu.borrow_mut().as_mut().map(|menu| {
337 let offset = self.resolved_offset(window);
338 let mut anchored = anchored()
339 .snap_to_window_with_margin(px(8.))
340 .anchor(self.anchor)
341 .offset(offset);
342 if let Some(child_bounds) = element_state.child_bounds {
343 anchored =
344 anchored.position(child_bounds.corner(self.resolved_attach()) + offset);
345 }
346 let mut element = deferred(anchored.child(div().occlude().child(menu.clone())))
347 .with_priority(1)
348 .into_any();
349
350 menu_layout_id = Some(element.request_layout(window, cx));
351 element
352 });
353
354 let mut child_element = self.child_builder.take().map(|child_builder| {
355 (child_builder)(element_state.menu.clone(), self.menu_builder.clone())
356 });
357
358 if let Some(trigger_handle) = self.trigger_handle.take() {
359 if let Some(menu_builder) = self.menu_builder.clone() {
360 *trigger_handle.0.borrow_mut() = Some(PopoverMenuHandleState {
361 menu_builder,
362 menu: element_state.menu.clone(),
363 on_open: self.on_open.clone(),
364 });
365 }
366 }
367
368 let child_layout_id = child_element
369 .as_mut()
370 .map(|child_element| child_element.request_layout(window, cx));
371
372 let mut style = Style::default();
373 if self.full_width {
374 style.size = size(relative(1.).into(), Length::Auto);
375 }
376
377 let layout_id = window.request_layout(
378 style,
379 menu_layout_id.into_iter().chain(child_layout_id),
380 cx,
381 );
382
383 (
384 (
385 layout_id,
386 PopoverMenuFrameState {
387 child_element,
388 child_layout_id,
389 menu_element,
390 menu_handle: element_state.menu.clone(),
391 },
392 ),
393 element_state,
394 )
395 },
396 )
397 }
398
399 fn prepaint(
400 &mut self,
401 global_id: Option<&GlobalElementId>,
402 _inspector_id: Option<&gpui::InspectorElementId>,
403 _bounds: Bounds<Pixels>,
404 request_layout: &mut Self::RequestLayoutState,
405 window: &mut Window,
406 cx: &mut App,
407 ) -> Option<HitboxId> {
408 if let Some(child) = request_layout.child_element.as_mut() {
409 child.prepaint(window, cx);
410 }
411
412 if let Some(menu) = request_layout.menu_element.as_mut() {
413 menu.prepaint(window, cx);
414 }
415
416 request_layout.child_layout_id.map(|layout_id| {
417 let bounds = window.layout_bounds(layout_id);
418 window.with_element_state(global_id.unwrap(), |element_state, _cx| {
419 let mut element_state: PopoverMenuElementState<M> = element_state.unwrap();
420 element_state.child_bounds = Some(bounds);
421 ((), element_state)
422 });
423
424 window.insert_hitbox(bounds, HitboxBehavior::Normal).id
425 })
426 }
427
428 fn paint(
429 &mut self,
430 _id: Option<&GlobalElementId>,
431 _inspector_id: Option<&gpui::InspectorElementId>,
432 _: Bounds<gpui::Pixels>,
433 request_layout: &mut Self::RequestLayoutState,
434 child_hitbox: &mut Option<HitboxId>,
435 window: &mut Window,
436 cx: &mut App,
437 ) {
438 if let Some(mut child) = request_layout.child_element.take() {
439 child.paint(window, cx);
440 }
441
442 if let Some(mut menu) = request_layout.menu_element.take() {
443 menu.paint(window, cx);
444
445 if let Some(child_hitbox) = *child_hitbox {
446 let menu_handle = request_layout.menu_handle.clone();
447 // Mouse-downing outside the menu dismisses it, so we don't
448 // want a click on the toggle to re-open it.
449 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
450 if phase == DispatchPhase::Bubble && child_hitbox.is_hovered(window) {
451 if let Some(menu) = menu_handle.borrow().as_ref() {
452 menu.update(cx, |_, cx| {
453 cx.emit(DismissEvent);
454 });
455 }
456 cx.stop_propagation();
457 }
458 })
459 }
460 }
461 }
462}
463
464impl<M: ManagedView> IntoElement for PopoverMenu<M> {
465 type Element = Self;
466
467 fn into_element(self) -> Self::Element {
468 self
469 }
470}