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