1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4 Anchor, AnyElement, App, Bounds, Div, ElementId, InteractiveElement, Interactivity,
5 IntoElement, ParentElement, Pixels, Point, RenderOnce, StatefulInteractiveElement,
6 StyleRefinement, Styled, Window, canvas, deferred, div, point, px,
7};
8
9use crate::{LayoutDirection, Positioner, ResolvedPosition, StyledExt as _};
10
11const WINDOW_MARGIN: Pixels = px(8.);
13
14pub const POPUP_PRIORITY: usize = 100;
16
17#[derive(Default)]
18struct PopupAnchorState {
19 bounds: Bounds<Pixels>,
20 captured: bool,
21}
22
23#[derive(IntoElement)]
29pub struct Popup {
30 id: ElementId,
31 base: gpui::Stateful<Div>,
32 style: StyleRefinement,
33 anchor: Anchor,
34 offset: Pixels,
35 boundary: Option<Bounds<Pixels>>,
36 on_position: Option<Box<dyn Fn(ResolvedPosition, Bounds<Pixels>)>>,
37 trigger: AnyElement,
38 content: Option<AnyElement>,
39}
40
41impl Popup {
42 pub fn new(id: impl Into<ElementId>, trigger: impl IntoElement) -> Self {
43 let id = id.into();
44 Self {
45 base: div().id(id.clone()),
46 id,
47 style: StyleRefinement::default(),
48 anchor: Anchor::TopLeft,
49 offset: px(0.),
50 boundary: None,
51 on_position: None,
52 trigger: trigger.into_any_element(),
53 content: None,
54 }
55 }
56
57 pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
58 self.anchor = anchor.into();
59 self
60 }
61
62 pub fn offset(mut self, offset: Pixels) -> Self {
64 self.offset = offset;
65 self
66 }
67
68 pub fn boundary(mut self, boundary: Bounds<Pixels>) -> Self {
71 self.boundary = Some(boundary);
72 self
73 }
74
75 pub fn on_position(
77 mut self,
78 callback: impl Fn(ResolvedPosition, Bounds<Pixels>) + 'static,
79 ) -> Self {
80 self.on_position = Some(Box::new(callback));
81 self
82 }
83
84 pub fn content(mut self, content: impl IntoElement) -> Self {
85 self.content = Some(content.into_any_element());
86 self
87 }
88
89 pub fn resolved_corner(anchor: Anchor, trigger_bounds: Bounds<Pixels>) -> Point<Pixels> {
90 match anchor {
91 Anchor::TopLeft => trigger_bounds.origin,
92 Anchor::TopCenter => trigger_bounds.top_center(),
93 Anchor::TopRight => trigger_bounds.top_right(),
94 Anchor::BottomLeft => Point {
95 x: trigger_bounds.origin.x,
96 y: trigger_bounds.origin.y - trigger_bounds.size.height,
97 },
98 Anchor::BottomCenter => Point {
99 x: trigger_bounds.top_center().x,
100 y: trigger_bounds.origin.y - trigger_bounds.size.height,
101 },
102 Anchor::BottomRight => Point {
103 x: trigger_bounds.top_right().x,
104 y: trigger_bounds.origin.y - trigger_bounds.size.height,
105 },
106 Anchor::LeftCenter | Anchor::RightCenter => trigger_bounds.origin,
107 }
108 }
109}
110
111pub fn logical_anchor(anchor: Anchor, direction: LayoutDirection) -> Anchor {
117 if !direction.is_rtl() {
118 return anchor;
119 }
120 match anchor {
121 Anchor::TopLeft => Anchor::TopRight,
122 Anchor::TopRight => Anchor::TopLeft,
123 Anchor::BottomLeft => Anchor::BottomRight,
124 Anchor::BottomRight => Anchor::BottomLeft,
125 Anchor::LeftCenter => Anchor::RightCenter,
126 Anchor::RightCenter => Anchor::LeftCenter,
127 Anchor::TopCenter | Anchor::BottomCenter => anchor,
128 }
129}
130
131fn anchor_position(anchor: Anchor, trigger: Bounds<Pixels>, offset: Pixels) -> Point<Pixels> {
133 match anchor {
134 Anchor::TopLeft => trigger.bottom_left() + point(px(0.), offset),
135 Anchor::TopCenter => trigger.bottom_center() + point(px(0.), offset),
136 Anchor::TopRight => trigger.bottom_right() + point(px(0.), offset),
137 Anchor::BottomLeft => trigger.origin - point(px(0.), offset),
138 Anchor::BottomCenter => trigger.top_center() - point(px(0.), offset),
139 Anchor::BottomRight => trigger.top_right() - point(px(0.), offset),
140 Anchor::LeftCenter => trigger.right_center() + point(offset, px(0.)),
141 Anchor::RightCenter => trigger.left_center() - point(offset, px(0.)),
142 }
143}
144
145impl Styled for Popup {
146 fn style(&mut self) -> &mut StyleRefinement {
147 &mut self.style
148 }
149}
150
151impl InteractiveElement for Popup {
152 fn interactivity(&mut self) -> &mut Interactivity {
153 self.base.interactivity()
154 }
155}
156
157impl StatefulInteractiveElement for Popup {}
158
159impl RenderOnce for Popup {
160 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
161 let state =
162 window.use_keyed_state((self.id, "anchor"), cx, |_, _| PopupAnchorState::default());
163 let anchor = logical_anchor(self.anchor, LayoutDirection::global(cx));
164 let trigger_bounds = Rc::new(Cell::new(state.read(cx).bounds));
165 let offset = self.offset;
166 let position = Rc::new(Cell::new(anchor_position(
167 anchor,
168 state.read(cx).bounds,
169 offset,
170 )));
171
172 let has_content = self.content.is_some();
175 let root = self
176 .base
177 .child(self.trigger)
178 .child(
179 canvas(
180 {
181 let state = state.clone();
182 let position = position.clone();
183 let trigger_bounds = trigger_bounds.clone();
184 move |bounds, window, cx| {
185 trigger_bounds.set(bounds);
186 position.set(anchor_position(anchor, bounds, offset));
187 let first = state.update(cx, |state, _| {
188 let first = !state.captured;
189 state.bounds = bounds;
190 state.captured = true;
191 first
192 });
193 if first && has_content {
194 window.request_animation_frame();
195 }
196 }
197 },
198 |_, _, _, _| {},
199 )
200 .absolute()
201 .size_full()
202 .top_0()
203 .left_0(),
204 )
205 .refine_style(&self.style);
206
207 let Some(content) = self.content else {
208 return root;
209 };
210 if !state.read(cx).captured {
211 return root;
212 }
213
214 let positioner =
215 Positioner::corner(anchor, position.get()).tracked_corner_position(position);
216 let positioner = match self.boundary {
217 Some(boundary) => positioner.boundary(boundary),
218 None => positioner,
219 };
220 let positioner = if let Some(callback) = self.on_position {
221 positioner.on_position(move |position| callback(position, trigger_bounds.get()))
222 } else {
223 positioner
224 };
225 root.child(
226 deferred(
227 positioner
228 .margin(WINDOW_MARGIN)
229 .occlude()
232 .child(content),
233 )
234 .with_priority(POPUP_PRIORITY),
235 )
236 }
237}
238
239#[cfg(test)]
240mod tests {
241 use super::*;
242 use gpui::{Context, Render, px};
243
244 #[test]
245 fn resolved_corner_preserves_existing_anchor_math() {
246 let bounds = Bounds {
247 origin: Point::new(px(100.), px(100.)),
248 size: gpui::Size::new(px(200.), px(50.)),
249 };
250 assert_eq!(
251 Popup::resolved_corner(Anchor::TopCenter, bounds),
252 Point::new(px(200.), px(100.))
253 );
254 assert_eq!(
255 Popup::resolved_corner(Anchor::BottomRight, bounds),
256 Point::new(px(300.), px(50.))
257 );
258 }
259
260 #[test]
261 fn rtl_mirrors_the_horizontal_side_of_the_anchor() {
262 let rtl = LayoutDirection::Rtl;
263 assert_eq!(logical_anchor(Anchor::TopLeft, rtl), Anchor::TopRight);
264 assert_eq!(logical_anchor(Anchor::BottomRight, rtl), Anchor::BottomLeft);
265 assert_eq!(logical_anchor(Anchor::LeftCenter, rtl), Anchor::RightCenter);
266 assert_eq!(logical_anchor(Anchor::TopCenter, rtl), Anchor::TopCenter);
267 assert_eq!(
268 logical_anchor(Anchor::TopLeft, LayoutDirection::Ltr),
269 Anchor::TopLeft
270 );
271 }
272
273 struct Harness;
274
275 impl Render for Harness {
276 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
277 Popup::new(
278 "popup",
279 div()
280 .debug_selector(|| "popup-trigger".into())
281 .size(px(100.)),
282 )
283 .content(
284 div()
285 .debug_selector(|| "popup-content".into())
286 .size(px(20.)),
287 )
288 }
289 }
290
291 struct OcclusionHarness {
295 background_hovered: Rc<Cell<bool>>,
296 content_hovered: Rc<Cell<bool>>,
297 }
298
299 impl Render for OcclusionHarness {
300 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
301 let background = self.background_hovered.clone();
302 let content = self.content_hovered.clone();
303 div()
304 .relative()
305 .size(px(200.))
306 .child(
307 div()
308 .id("background")
309 .absolute()
310 .size_full()
311 .on_mouse_move(move |_, _, _| background.set(true)),
312 )
313 .child(
314 Popup::new("popup", div().size(px(100.))).content(
315 div()
316 .id("content")
317 .size(px(40.))
318 .on_mouse_move(move |_, _, _| content.set(true)),
319 ),
320 )
321 }
322 }
323
324 #[gpui::test]
325 fn the_popup_surface_blocks_the_panel_it_covers(cx: &mut gpui::TestAppContext) {
326 let background_hovered = Rc::new(Cell::new(false));
327 let content_hovered = Rc::new(Cell::new(false));
328 let (_, window) = cx.add_window_view({
329 let background_hovered = background_hovered.clone();
330 let content_hovered = content_hovered.clone();
331 move |_, _| OcclusionHarness {
332 background_hovered,
333 content_hovered,
334 }
335 });
336 window.update(|window, cx| window.draw(cx).clear(cx));
337 window.update(|window, cx| window.draw(cx).clear(cx));
338
339 window.simulate_mouse_move(
340 gpui::point(px(20.), px(110.)),
341 None,
342 gpui::Modifiers::default(),
343 );
344 assert!(!background_hovered.get());
345 assert!(content_hovered.get());
348
349 window.simulate_mouse_move(
352 gpui::point(px(150.), px(180.)),
353 None,
354 gpui::Modifiers::default(),
355 );
356 assert!(background_hovered.get());
357 }
358
359 struct ClosedHarness {
361 open: bool,
362 }
363
364 impl Render for ClosedHarness {
365 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
366 let popup = Popup::new(
367 "popup",
368 div()
369 .debug_selector(|| "popup-trigger".into())
370 .size(px(100.)),
371 );
372 if self.open {
373 popup.content(
374 div()
375 .debug_selector(|| "popup-content".into())
376 .size(px(20.)),
377 )
378 } else {
379 popup
380 }
381 }
382 }
383
384 #[gpui::test]
388 fn a_closed_popup_asks_for_no_frame_and_opens_at_once(cx: &mut gpui::TestAppContext) {
389 let (view, window) = cx.add_window_view(|_, _| ClosedHarness { open: false });
390 window.update(|window, cx| {
391 window.draw(cx).clear(cx);
392 assert_eq!(window.simulate_next_frame(cx), 0, "no frame was asked for");
393 });
394
395 view.update(window, |harness, cx| {
396 harness.open = true;
397 cx.notify();
398 });
399 window.update(|window, cx| window.draw(cx).clear(cx));
400 assert_eq!(
401 window.debug_bounds("popup-content").unwrap().size,
402 gpui::Size::new(px(20.), px(20.))
403 );
404 }
405
406 #[gpui::test]
407 fn trigger_capture_enables_deferred_content_on_the_next_frame(cx: &mut gpui::TestAppContext) {
408 let (_, window) = cx.add_window_view(|_, _| Harness);
409 window.update(|window, cx| window.draw(cx).clear(cx));
410 window.update(|window, cx| window.draw(cx).clear(cx));
411
412 assert_eq!(
413 window.debug_bounds("popup-trigger").unwrap().size,
414 gpui::Size::new(px(100.), px(100.))
415 );
416 assert_eq!(
417 window.debug_bounds("popup-content").unwrap().size,
418 gpui::Size::new(px(20.), px(20.))
419 );
420 }
421}