1use std::{cell::RefCell, rc::Rc};
2
3use gpui::{
4 overlay, point, prelude::FluentBuilder, px, rems, AnchorCorner, AnyElement, Bounds,
5 DismissEvent, DispatchPhase, Element, ElementContext, ElementId, InteractiveBounds,
6 IntoElement, LayoutId, ManagedView, MouseDownEvent, ParentElement, Pixels, Point, View,
7 VisualContext, WindowContext,
8};
9
10use crate::{Clickable, Selectable};
11
12pub trait PopoverTrigger: IntoElement + Clickable + Selectable + 'static {}
13
14impl<T: IntoElement + Clickable + Selectable + 'static> PopoverTrigger for T {}
15
16pub struct PopoverMenu<M: ManagedView> {
17 id: ElementId,
18 child_builder: Option<
19 Box<
20 dyn FnOnce(
21 Rc<RefCell<Option<View<M>>>>,
22 Option<Rc<dyn Fn(&mut WindowContext) -> Option<View<M>> + 'static>>,
23 ) -> AnyElement
24 + 'static,
25 >,
26 >,
27 menu_builder: Option<Rc<dyn Fn(&mut WindowContext) -> Option<View<M>> + 'static>>,
28 anchor: AnchorCorner,
29 attach: Option<AnchorCorner>,
30 offset: Option<Point<Pixels>>,
31}
32
33impl<M: ManagedView> PopoverMenu<M> {
34 pub fn menu(mut self, f: impl Fn(&mut WindowContext) -> Option<View<M>> + 'static) -> Self {
35 self.menu_builder = Some(Rc::new(f));
36 self
37 }
38
39 pub fn trigger<T: PopoverTrigger>(mut self, t: T) -> Self {
40 self.child_builder = Some(Box::new(|menu, builder| {
41 let open = menu.borrow().is_some();
42 t.selected(open)
43 .when_some(builder, |el, builder| {
44 el.on_click({
45 move |_, cx| {
46 let Some(new_menu) = (builder)(cx) else {
47 return;
48 };
49 let menu2 = menu.clone();
50 let previous_focus_handle = cx.focused();
51
52 cx.subscribe(&new_menu, move |modal, _: &DismissEvent, cx| {
53 if modal.focus_handle(cx).contains_focused(cx) {
54 if let Some(previous_focus_handle) =
55 previous_focus_handle.as_ref()
56 {
57 cx.focus(previous_focus_handle);
58 }
59 }
60 *menu2.borrow_mut() = None;
61 cx.refresh();
62 })
63 .detach();
64 cx.focus_view(&new_menu);
65 *menu.borrow_mut() = Some(new_menu);
66 }
67 })
68 })
69 .into_any_element()
70 }));
71 self
72 }
73
74 /// anchor defines which corner of the menu to anchor to the attachment point
75 /// (by default the cursor position, but see attach)
76 pub fn anchor(mut self, anchor: AnchorCorner) -> Self {
77 self.anchor = anchor;
78 self
79 }
80
81 /// attach defines which corner of the handle to attach the menu's anchor to
82 pub fn attach(mut self, attach: AnchorCorner) -> Self {
83 self.attach = Some(attach);
84 self
85 }
86
87 /// offset offsets the position of the content by that many pixels.
88 pub fn offset(mut self, offset: Point<Pixels>) -> Self {
89 self.offset = Some(offset);
90 self
91 }
92
93 fn resolved_attach(&self) -> AnchorCorner {
94 self.attach.unwrap_or_else(|| match self.anchor {
95 AnchorCorner::TopLeft => AnchorCorner::BottomLeft,
96 AnchorCorner::TopRight => AnchorCorner::BottomRight,
97 AnchorCorner::BottomLeft => AnchorCorner::TopLeft,
98 AnchorCorner::BottomRight => AnchorCorner::TopRight,
99 })
100 }
101
102 fn resolved_offset(&self, cx: &WindowContext) -> Point<Pixels> {
103 self.offset.unwrap_or_else(|| {
104 // Default offset = 4px padding + 1px border
105 let offset = rems(5. / 16.) * cx.rem_size();
106 match self.anchor {
107 AnchorCorner::TopRight | AnchorCorner::BottomRight => point(offset, px(0.)),
108 AnchorCorner::TopLeft | AnchorCorner::BottomLeft => point(-offset, px(0.)),
109 }
110 })
111 }
112}
113
114/// Creates a [`PopoverMenu`]
115pub fn popover_menu<M: ManagedView>(id: impl Into<ElementId>) -> PopoverMenu<M> {
116 PopoverMenu {
117 id: id.into(),
118 child_builder: None,
119 menu_builder: None,
120 anchor: AnchorCorner::TopLeft,
121 attach: None,
122 offset: None,
123 }
124}
125
126pub struct PopoverMenuState<M> {
127 child_layout_id: Option<LayoutId>,
128 child_element: Option<AnyElement>,
129 child_bounds: Option<Bounds<Pixels>>,
130 menu_element: Option<AnyElement>,
131 menu: Rc<RefCell<Option<View<M>>>>,
132}
133
134impl<M: ManagedView> Element for PopoverMenu<M> {
135 type State = PopoverMenuState<M>;
136
137 fn request_layout(
138 &mut self,
139 element_state: Option<Self::State>,
140 cx: &mut ElementContext,
141 ) -> (gpui::LayoutId, Self::State) {
142 let mut menu_layout_id = None;
143
144 let (menu, child_bounds) = if let Some(element_state) = element_state {
145 (element_state.menu, element_state.child_bounds)
146 } else {
147 (Rc::default(), None)
148 };
149
150 let menu_element = menu.borrow_mut().as_mut().map(|menu| {
151 let mut overlay = overlay().snap_to_window().anchor(self.anchor);
152
153 if let Some(child_bounds) = child_bounds {
154 overlay = overlay.position(
155 self.resolved_attach().corner(child_bounds) + self.resolved_offset(cx),
156 );
157 }
158
159 let mut element = overlay.child(menu.clone()).into_any();
160 menu_layout_id = Some(element.request_layout(cx));
161 element
162 });
163
164 let mut child_element = self
165 .child_builder
166 .take()
167 .map(|child_builder| (child_builder)(menu.clone(), self.menu_builder.clone()));
168
169 let child_layout_id = child_element
170 .as_mut()
171 .map(|child_element| child_element.request_layout(cx));
172
173 let layout_id = cx.request_layout(
174 &gpui::Style::default(),
175 menu_layout_id.into_iter().chain(child_layout_id),
176 );
177
178 (
179 layout_id,
180 PopoverMenuState {
181 menu,
182 child_element,
183 child_layout_id,
184 menu_element,
185 child_bounds,
186 },
187 )
188 }
189
190 fn paint(
191 &mut self,
192 _: Bounds<gpui::Pixels>,
193 element_state: &mut Self::State,
194 cx: &mut ElementContext,
195 ) {
196 if let Some(mut child) = element_state.child_element.take() {
197 child.paint(cx);
198 }
199
200 if let Some(child_layout_id) = element_state.child_layout_id.take() {
201 element_state.child_bounds = Some(cx.layout_bounds(child_layout_id));
202 }
203
204 if let Some(mut menu) = element_state.menu_element.take() {
205 menu.paint(cx);
206
207 if let Some(child_bounds) = element_state.child_bounds {
208 let interactive_bounds = InteractiveBounds {
209 bounds: child_bounds,
210 stacking_order: cx.stacking_order().clone(),
211 };
212
213 // Mouse-downing outside the menu dismisses it, so we don't
214 // want a click on the toggle to re-open it.
215 cx.on_mouse_event(move |e: &MouseDownEvent, phase, cx| {
216 if phase == DispatchPhase::Bubble
217 && interactive_bounds.visibly_contains(&e.position, cx)
218 {
219 cx.stop_propagation()
220 }
221 })
222 }
223 }
224 }
225}
226
227impl<M: ManagedView> IntoElement for PopoverMenu<M> {
228 type Element = Self;
229
230 fn element_id(&self) -> Option<gpui::ElementId> {
231 Some(self.id.clone())
232 }
233
234 fn into_element(self) -> Self::Element {
235 self
236 }
237}