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