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