1use std::{cell::RefCell, rc::Rc};
2
3use gpui::{
4 anchored, deferred, div, point, prelude::FluentBuilder, px, AnchorCorner, AnyElement, Bounds,
5 DismissEvent, DispatchPhase, Element, ElementId, GlobalElementId, HitboxId, InteractiveElement,
6 IntoElement, LayoutId, ManagedView, MouseDownEvent, ParentElement, Pixels, Point, View,
7 VisualContext, WindowContext,
8};
9
10use crate::prelude::*;
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_from_px(5.) * 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 PopoverMenuElementState<M> {
127 menu: Rc<RefCell<Option<View<M>>>>,
128 child_bounds: Option<Bounds<Pixels>>,
129}
130
131impl<M> Clone for PopoverMenuElementState<M> {
132 fn clone(&self) -> Self {
133 Self {
134 menu: Rc::clone(&self.menu),
135 child_bounds: self.child_bounds,
136 }
137 }
138}
139
140impl<M> Default for PopoverMenuElementState<M> {
141 fn default() -> Self {
142 Self {
143 menu: Rc::default(),
144 child_bounds: None,
145 }
146 }
147}
148
149pub struct PopoverMenuFrameState {
150 child_layout_id: Option<LayoutId>,
151 child_element: Option<AnyElement>,
152 menu_element: Option<AnyElement>,
153}
154
155impl<M: ManagedView> Element for PopoverMenu<M> {
156 type RequestLayoutState = PopoverMenuFrameState;
157 type PrepaintState = Option<HitboxId>;
158
159 fn id(&self) -> Option<ElementId> {
160 Some(self.id.clone())
161 }
162
163 fn request_layout(
164 &mut self,
165 global_id: Option<&GlobalElementId>,
166 cx: &mut WindowContext,
167 ) -> (gpui::LayoutId, Self::RequestLayoutState) {
168 cx.with_element_state(
169 global_id.unwrap(),
170 |element_state: Option<PopoverMenuElementState<M>>, cx| {
171 let element_state = element_state.unwrap_or_default();
172 let mut menu_layout_id = None;
173
174 let menu_element = element_state.menu.borrow_mut().as_mut().map(|menu| {
175 let mut anchored = anchored().snap_to_window().anchor(self.anchor);
176 if let Some(child_bounds) = element_state.child_bounds {
177 anchored = anchored.position(
178 self.resolved_attach().corner(child_bounds) + self.resolved_offset(cx),
179 );
180 }
181 let mut element = deferred(anchored.child(div().occlude().child(menu.clone())))
182 .with_priority(1)
183 .into_any();
184
185 menu_layout_id = Some(element.request_layout(cx));
186 element
187 });
188
189 let mut child_element = self.child_builder.take().map(|child_builder| {
190 (child_builder)(element_state.menu.clone(), self.menu_builder.clone())
191 });
192
193 let child_layout_id = child_element
194 .as_mut()
195 .map(|child_element| child_element.request_layout(cx));
196
197 let layout_id = cx.request_layout(
198 gpui::Style::default(),
199 menu_layout_id.into_iter().chain(child_layout_id),
200 );
201
202 (
203 (
204 layout_id,
205 PopoverMenuFrameState {
206 child_element,
207 child_layout_id,
208 menu_element,
209 },
210 ),
211 element_state,
212 )
213 },
214 )
215 }
216
217 fn prepaint(
218 &mut self,
219 global_id: Option<&GlobalElementId>,
220 _bounds: Bounds<Pixels>,
221 request_layout: &mut Self::RequestLayoutState,
222 cx: &mut WindowContext,
223 ) -> Option<HitboxId> {
224 if let Some(child) = request_layout.child_element.as_mut() {
225 child.prepaint(cx);
226 }
227
228 if let Some(menu) = request_layout.menu_element.as_mut() {
229 menu.prepaint(cx);
230 }
231
232 let hitbox_id = request_layout.child_layout_id.map(|layout_id| {
233 let bounds = cx.layout_bounds(layout_id);
234 cx.with_element_state(global_id.unwrap(), |element_state, _cx| {
235 let mut element_state: PopoverMenuElementState<M> = element_state.unwrap();
236 element_state.child_bounds = Some(bounds);
237 ((), element_state)
238 });
239
240 cx.insert_hitbox(bounds, false).id
241 });
242
243 hitbox_id
244 }
245
246 fn paint(
247 &mut self,
248 _id: Option<&GlobalElementId>,
249 _: Bounds<gpui::Pixels>,
250 request_layout: &mut Self::RequestLayoutState,
251 child_hitbox: &mut Option<HitboxId>,
252 cx: &mut WindowContext,
253 ) {
254 if let Some(mut child) = request_layout.child_element.take() {
255 child.paint(cx);
256 }
257
258 if let Some(mut menu) = request_layout.menu_element.take() {
259 menu.paint(cx);
260
261 if let Some(child_hitbox) = *child_hitbox {
262 // Mouse-downing outside the menu dismisses it, so we don't
263 // want a click on the toggle to re-open it.
264 cx.on_mouse_event(move |_: &MouseDownEvent, phase, cx| {
265 if phase == DispatchPhase::Bubble && child_hitbox.is_hovered(cx) {
266 cx.stop_propagation()
267 }
268 })
269 }
270 }
271 }
272}
273
274impl<M: ManagedView> IntoElement for PopoverMenu<M> {
275 type Element = Self;
276
277 fn into_element(self) -> Self::Element {
278 self
279 }
280}