Skip to main content

gpui/elements/
anchored.rs

1use std::cmp::Ordering;
2
3use smallvec::SmallVec;
4
5use crate::{
6    Anchor, AnyElement, App, Axis, Bounds, Display, Edges, Element, GlobalElementId,
7    InspectorElementId, LayoutId, ParentElement, Pixels, Point, Position, Size, Style, Window,
8    point, px,
9};
10
11/// The state that the anchored element element uses to track its children.
12pub struct AnchoredState {
13    child_layout_ids: SmallVec<[LayoutId; 4]>,
14}
15
16/// An anchored element that can be used to display UI that
17/// will avoid overflowing the window bounds.
18pub struct Anchored {
19    children: SmallVec<[AnyElement; 2]>,
20    anchor: Anchor,
21    fit_mode: AnchoredFitMode,
22    placement: Placement,
23    position_mode: AnchoredPositionMode,
24    offset: Option<Point<Pixels>>,
25}
26
27#[derive(Clone, Copy)]
28enum Placement {
29    InPlace,
30    At(Point<Pixels>),
31    Attached {
32        target: Bounds<Pixels>,
33        corner: Anchor,
34    },
35}
36
37/// anchored gives you an element that will avoid overflowing the window bounds.
38/// Its children should have no margin to avoid measurement issues.
39pub fn anchored() -> Anchored {
40    Anchored {
41        children: SmallVec::new(),
42        anchor: Anchor::TopLeft,
43        fit_mode: AnchoredFitMode::SwitchAnchor,
44        placement: Placement::InPlace,
45        position_mode: AnchoredPositionMode::Window,
46        offset: None,
47    }
48}
49
50impl Anchored {
51    /// Sets which corner of the anchored element should be anchored to the current position.
52    pub fn anchor(mut self, anchor: Anchor) -> Self {
53        self.anchor = anchor;
54        self
55    }
56
57    /// Sets the position in window coordinates
58    /// (otherwise the location the anchored element is rendered is used)
59    pub fn position(mut self, anchor: Point<Pixels>) -> Self {
60        self.placement = Placement::At(anchor);
61        self
62    }
63
64    /// Places the element next to `target`, with the element's [`Anchored::anchor`] corner
65    /// on `corner` of `target`. For example, a submenu puts its top-left corner on its row's
66    /// top-right corner. Use this instead of [`Anchored::position`].
67    ///
68    /// If the element doesn't fit in the window, it moves to the other side of `target`, as
69    /// long as that side fits better. A submenu moves from the right of its row to the left,
70    /// and a dropdown moves from below its button to above. The offset flips with it.
71    /// [`AnchoredFitMode::SwitchAnchor`] has no effect here.
72    pub fn attach(mut self, target: Bounds<Pixels>, corner: Anchor) -> Self {
73        self.placement = Placement::Attached { target, corner };
74        self
75    }
76
77    /// Offset the final position by this amount.
78    /// Useful when you want to anchor to an element but offset from it, such as in PopoverMenu.
79    pub fn offset(mut self, offset: Point<Pixels>) -> Self {
80        self.offset = Some(offset);
81        self
82    }
83
84    /// Sets the position mode for this anchored element. Local will have this
85    /// interpret its [`Anchored::position`] or [`Anchored::attach`] target as
86    /// relative to the parent element. While Window will have it interpret the
87    /// position as relative to the window.
88    pub fn position_mode(mut self, mode: AnchoredPositionMode) -> Self {
89        self.position_mode = mode;
90        self
91    }
92
93    /// Snap to window edge instead of switching anchor corner when an overflow would occur.
94    pub fn snap_to_window(mut self) -> Self {
95        self.fit_mode = AnchoredFitMode::SnapToWindow;
96        self
97    }
98
99    /// Snap to window edge and leave some margins.
100    pub fn snap_to_window_with_margin(mut self, edges: impl Into<Edges<Pixels>>) -> Self {
101        self.fit_mode = AnchoredFitMode::SnapToWindowWithMargin(edges.into());
102        self
103    }
104}
105
106impl ParentElement for Anchored {
107    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
108        self.children.extend(elements)
109    }
110}
111
112impl Element for Anchored {
113    type RequestLayoutState = AnchoredState;
114    type PrepaintState = ();
115
116    fn id(&self) -> Option<crate::ElementId> {
117        None
118    }
119
120    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
121        None
122    }
123
124    fn request_layout(
125        &mut self,
126        _id: Option<&GlobalElementId>,
127        _inspector_id: Option<&InspectorElementId>,
128        window: &mut Window,
129        cx: &mut App,
130    ) -> (crate::LayoutId, Self::RequestLayoutState) {
131        let child_layout_ids = self
132            .children
133            .iter_mut()
134            .map(|child| child.request_layout(window, cx))
135            .collect::<SmallVec<_>>();
136
137        let anchored_style = Style {
138            position: Position::Absolute,
139            display: Display::Flex,
140            ..Style::default()
141        };
142
143        let layout_id = window.request_layout(anchored_style, child_layout_ids.iter().copied(), cx);
144
145        (layout_id, AnchoredState { child_layout_ids })
146    }
147
148    fn prepaint(
149        &mut self,
150        _id: Option<&GlobalElementId>,
151        _inspector_id: Option<&InspectorElementId>,
152        bounds: Bounds<Pixels>,
153        request_layout: &mut Self::RequestLayoutState,
154        window: &mut Window,
155        cx: &mut App,
156    ) {
157        if request_layout.child_layout_ids.is_empty() {
158            return;
159        }
160
161        let children_bounds = request_layout
162            .child_layout_ids
163            .iter()
164            .map(|id| window.layout_bounds(*id))
165            .reduce(|acc, bounds| acc.union(&bounds))
166            .unwrap();
167
168        let anchor_position = match self.placement {
169            Placement::InPlace => None,
170            Placement::At(position) => Some(position),
171            Placement::Attached { target, corner } => Some(target.corner(corner)),
172        };
173        let (origin, mut desired) = self.position_mode.get_position_and_bounds(
174            anchor_position,
175            self.anchor,
176            children_bounds.size,
177            bounds,
178            self.offset,
179        );
180
181        let limits = Bounds {
182            origin: Point::default(),
183            size: window.viewport_size(),
184        };
185
186        if let Placement::Attached { target, mut corner } = self.placement {
187            // Compare against the window edges, not the snap margin, so an element that
188            // already fits doesn't move. The client inset doesn't count as room either,
189            // since on Linux it's the window's transparent shadow.
190            let visible = limits.inset(window.client_inset.unwrap_or(px(0.)));
191            let overflow_along = |bounds: Bounds<Pixels>, axis: Axis| match axis {
192                Axis::Horizontal => {
193                    (visible.left() - bounds.left()).max(px(0.))
194                        + (bounds.right() - visible.right()).max(px(0.))
195                }
196                Axis::Vertical => {
197                    (visible.top() - bounds.top()).max(px(0.))
198                        + (bounds.bottom() - visible.bottom()).max(px(0.))
199                }
200            };
201            let mut anchor = self.anchor;
202            let mut offset = self.offset.unwrap_or_default();
203            for axis in [Axis::Horizontal, Axis::Vertical] {
204                let corner_side = side_along(corner, axis);
205                let is_outside_target = corner_side != Ordering::Equal
206                    && side_along(anchor, axis) == corner_side.reverse();
207                let overflow = overflow_along(desired, axis);
208                if !is_outside_target || overflow == px(0.) {
209                    continue;
210                }
211
212                let flipped_corner = corner.other_side_along(axis);
213                let flipped_anchor = anchor.other_side_along(axis);
214                let flipped_offset = match axis {
215                    Axis::Horizontal => point(-offset.x, offset.y),
216                    Axis::Vertical => point(offset.x, -offset.y),
217                };
218                let (_, flipped) = self.position_mode.get_position_and_bounds(
219                    Some(target.corner(flipped_corner)),
220                    flipped_anchor,
221                    children_bounds.size,
222                    bounds,
223                    Some(flipped_offset),
224                );
225                if overflow_along(flipped, axis) < overflow {
226                    corner = flipped_corner;
227                    anchor = flipped_anchor;
228                    offset = flipped_offset;
229                    desired = flipped;
230                }
231            }
232        } else if self.fit_mode == AnchoredFitMode::SwitchAnchor {
233            let mut anchor = self.anchor;
234
235            if desired.left() < limits.left() || desired.right() > limits.right() {
236                let switched = Bounds::from_anchor_and_size(
237                    anchor.other_side_along(Axis::Horizontal),
238                    origin,
239                    children_bounds.size,
240                );
241                if !(switched.left() < limits.left() || switched.right() > limits.right()) {
242                    anchor = anchor.other_side_along(Axis::Horizontal);
243                    desired = switched
244                }
245            }
246
247            if desired.top() < limits.top() || desired.bottom() > limits.bottom() {
248                let switched = Bounds::from_anchor_and_size(
249                    anchor.other_side_along(Axis::Vertical),
250                    origin,
251                    children_bounds.size,
252                );
253                if !(switched.top() < limits.top() || switched.bottom() > limits.bottom()) {
254                    desired = switched;
255                }
256            }
257        }
258
259        let client_inset = window.client_inset.unwrap_or(px(0.));
260        let edges = match self.fit_mode {
261            AnchoredFitMode::SnapToWindowWithMargin(edges) => edges,
262            _ => Edges::default(),
263        }
264        .map(|edge| *edge + client_inset);
265
266        // Snap the horizontal edges of the anchored element to the horizontal edges of the window if
267        // its horizontal bounds overflow, aligning to the left if it is wider than the limits.
268        if desired.right() > limits.right() {
269            desired.origin.x -= desired.right() - limits.right() + edges.right;
270        }
271        if desired.left() < limits.left() {
272            desired.origin.x = limits.origin.x + edges.left;
273        }
274
275        // Snap the vertical edges of the anchored element to the vertical edges of the window if
276        // its vertical bounds overflow, aligning to the top if it is taller than the limits.
277        if desired.bottom() > limits.bottom() {
278            desired.origin.y -= desired.bottom() - limits.bottom() + edges.bottom;
279        }
280        if desired.top() < limits.top() {
281            desired.origin.y = limits.origin.y + edges.top;
282        }
283
284        let offset = desired.origin - bounds.origin;
285        let offset = point(offset.x.round(), offset.y.round());
286
287        window.with_element_offset(offset, |window| {
288            for child in &mut self.children {
289                child.prepaint(window, cx);
290            }
291        })
292    }
293
294    fn paint(
295        &mut self,
296        _id: Option<&GlobalElementId>,
297        _inspector_id: Option<&InspectorElementId>,
298        _bounds: crate::Bounds<crate::Pixels>,
299        _request_layout: &mut Self::RequestLayoutState,
300        _prepaint: &mut Self::PrepaintState,
301        window: &mut Window,
302        cx: &mut App,
303    ) {
304        for child in &mut self.children {
305            child.paint(window, cx);
306        }
307    }
308}
309
310/// Which side of a box `anchor` is on along `axis`. `Less` is left or top, `Equal` is the
311/// center, and `Greater` is right or bottom.
312fn side_along(anchor: Anchor, axis: Axis) -> Ordering {
313    match axis {
314        Axis::Horizontal => match anchor {
315            Anchor::TopLeft | Anchor::BottomLeft | Anchor::LeftCenter => Ordering::Less,
316            Anchor::TopCenter | Anchor::BottomCenter => Ordering::Equal,
317            Anchor::TopRight | Anchor::BottomRight | Anchor::RightCenter => Ordering::Greater,
318        },
319        Axis::Vertical => match anchor {
320            Anchor::TopLeft | Anchor::TopRight | Anchor::TopCenter => Ordering::Less,
321            Anchor::LeftCenter | Anchor::RightCenter => Ordering::Equal,
322            Anchor::BottomLeft | Anchor::BottomRight | Anchor::BottomCenter => Ordering::Greater,
323        },
324    }
325}
326
327/// Which algorithm to use when fitting the anchored element to be inside the window.
328#[derive(Copy, Clone, PartialEq)]
329pub enum AnchoredFitMode {
330    /// Snap the anchored element to the window edge.
331    SnapToWindow,
332    /// Snap to window edge and leave some margins.
333    SnapToWindowWithMargin(Edges<Pixels>),
334    /// Switch which corner anchor this anchored element is attached to.
335    SwitchAnchor,
336}
337
338/// Which algorithm to use when positioning the anchored element.
339#[derive(Copy, Clone, PartialEq)]
340pub enum AnchoredPositionMode {
341    /// Position the anchored element relative to the window.
342    Window,
343    /// Position the anchored element relative to its parent.
344    Local,
345}
346
347impl AnchoredPositionMode {
348    fn get_position_and_bounds(
349        &self,
350        anchor_position: Option<Point<Pixels>>,
351        anchor: Anchor,
352        size: Size<Pixels>,
353        bounds: Bounds<Pixels>,
354        offset: Option<Point<Pixels>>,
355    ) -> (Point<Pixels>, Bounds<Pixels>) {
356        let offset = offset.unwrap_or_default();
357
358        match self {
359            AnchoredPositionMode::Window => {
360                let anchor_position = anchor_position.unwrap_or(bounds.origin);
361                let bounds = Bounds::from_anchor_and_size(anchor, anchor_position + offset, size);
362                (anchor_position, bounds)
363            }
364            AnchoredPositionMode::Local => {
365                let anchor_position = anchor_position.unwrap_or_default();
366                let bounds = Bounds::from_anchor_and_size(
367                    anchor,
368                    bounds.origin + anchor_position + offset,
369                    size,
370                );
371                (anchor_position, bounds)
372            }
373        }
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use crate::{
380        Anchor, Bounds, Context, Pixels, PlatformInput, Point, TestAppContext, Window, deferred,
381        div, point, prelude::*, px, size,
382    };
383
384    struct AnchoredTestView {
385        position: Point<Pixels>,
386    }
387
388    impl Render for AnchoredTestView {
389        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
390            div().size_full().child(
391                div()
392                    .id("scroll-container")
393                    .overflow_y_scroll()
394                    .size_full()
395                    .child(div().h(px(2000.)).w_full())
396                    .child(
397                        deferred(
398                            super::anchored()
399                                .snap_to_window()
400                                .position(self.position)
401                                .child(
402                                    div()
403                                        .id("menu")
404                                        .debug_selector(|| "MENU".into())
405                                        .w(px(200.))
406                                        .h(px(300.)),
407                                ),
408                        )
409                        .with_priority(1),
410                    ),
411            )
412        }
413    }
414
415    #[gpui::test]
416    fn test_anchored_position_without_scroll(cx: &mut TestAppContext) {
417        let window = cx.open_window(size(px(800.), px(600.)), |_, _| AnchoredTestView {
418            position: point(px(100.), px(100.)),
419        });
420
421        cx.run_until_parked();
422
423        let menu_bounds = window
424            .update(cx, |_, window, _| {
425                window.rendered_frame.debug_bounds.get("MENU").copied()
426            })
427            .unwrap()
428            .expect("MENU debug bounds not found");
429
430        assert_eq!(menu_bounds.origin, point(px(100.), px(100.)));
431        assert_eq!(menu_bounds.size, size(px(200.), px(300.)));
432    }
433
434    #[gpui::test]
435    fn test_anchored_position_when_scrolled(cx: &mut TestAppContext) {
436        let window = cx.open_window(size(px(800.), px(600.)), |_, _| AnchoredTestView {
437            position: point(px(100.), px(100.)),
438        });
439
440        cx.run_until_parked();
441
442        window
443            .update(cx, |_, window, cx| {
444                let event = gpui::ScrollEvent {
445                    position: point(px(400.), px(300.)),
446                    delta: gpui::ScrollDelta::Pixels(point(px(0.), px(-1000.))),
447                    ..Default::default()
448                };
449                window.dispatch_event(PlatformInput::Scroll(event), cx);
450            })
451            .unwrap();
452
453        cx.run_until_parked();
454
455        let menu_bounds = window
456            .update(cx, |_, window, _| {
457                window.rendered_frame.debug_bounds.get("MENU").copied()
458            })
459            .unwrap()
460            .expect("MENU debug bounds not found");
461
462        assert_eq!(menu_bounds.origin, point(px(100.), px(100.)));
463        assert_eq!(menu_bounds.size, size(px(200.), px(300.)));
464    }
465
466    #[gpui::test]
467    fn test_anchored_snaps_to_window(cx: &mut TestAppContext) {
468        let window = cx.open_window(size(px(800.), px(600.)), |_, _| AnchoredTestView {
469            position: point(px(100.), px(500.)),
470        });
471
472        cx.run_until_parked();
473
474        let menu_bounds = window
475            .update(cx, |_, window, _| {
476                window.rendered_frame.debug_bounds.get("MENU").copied()
477            })
478            .unwrap()
479            .expect("MENU debug bounds not found");
480
481        assert_eq!(menu_bounds.origin, point(px(100.), px(300.)));
482        assert_eq!(menu_bounds.size, size(px(200.), px(300.)));
483    }
484
485    struct AttachedTestView {
486        target: Bounds<Pixels>,
487        corner: Anchor,
488        anchor: Anchor,
489    }
490
491    impl Render for AttachedTestView {
492        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
493            div().size_full().child(
494                deferred(
495                    super::anchored()
496                        .attach(self.target, self.corner)
497                        .anchor(self.anchor)
498                        .offset(point(px(-2.), px(4.)))
499                        .snap_to_window_with_margin(px(8.))
500                        .child(
501                            div()
502                                .debug_selector(|| "MENU".into())
503                                .w(px(200.))
504                                .h(px(300.)),
505                        ),
506                )
507                .with_priority(1),
508            )
509        }
510    }
511
512    #[gpui::test]
513    fn test_anchored_attach_moves_to_the_side_with_room(cx: &mut TestAppContext) {
514        let trigger = |x: f32, y: f32| Bounds::new(point(px(x), px(y)), size(px(100.), px(20.)));
515        // A submenu sits to the right of its trigger, with their top edges lined up.
516        let submenu = (Anchor::TopRight, Anchor::TopLeft);
517        // A dropdown sits below its button, with their left edges lined up.
518        let dropdown = (Anchor::BottomLeft, Anchor::TopLeft);
519        for (target, (corner, anchor), expected_origin) in [
520            (trigger(100., 100.), submenu, point(px(198.), px(104.))),
521            (trigger(550., 100.), submenu, point(px(352.), px(104.))),
522            (trigger(100., 400.), dropdown, point(px(98.), px(96.))),
523            // Ends 4px from the window edge. That's inside the snap margin but still fits,
524            // so it stays.
525            (trigger(498., 100.), submenu, point(px(596.), px(104.))),
526            // Doesn't fit on either side. The left sticks out less, so it goes left and
527            // slides back into the window.
528            (
529                Bounds::new(point(px(180.), px(100.)), size(px(500.), px(20.))),
530                submenu,
531                point(px(8.), px(104.)),
532            ),
533            // Doesn't fit on either side, but the right sticks out less, so it stays right
534            // and slides back into the window.
535            (
536                Bounds::new(point(px(50.), px(100.)), size(px(650.), px(20.))),
537                submenu,
538                point(px(592.), px(104.)),
539            ),
540            // A dropdown that runs off the right edge slides left. It never moves beside its
541            // button.
542            (trigger(700., 100.), dropdown, point(px(592.), px(124.))),
543            // Centered under its button, so it can move above it but never sideways.
544            (
545                trigger(100., 400.),
546                (Anchor::BottomCenter, Anchor::TopCenter),
547                point(px(48.), px(96.)),
548            ),
549        ] {
550            let window = cx.open_window(size(px(800.), px(600.)), |_, _| AttachedTestView {
551                target,
552                corner,
553                anchor,
554            });
555
556            cx.run_until_parked();
557
558            let menu_bounds = window
559                .update(cx, |_, window, _| {
560                    window.rendered_frame.debug_bounds.get("MENU").copied()
561                })
562                .unwrap()
563                .expect("MENU debug bounds not found");
564
565            assert_eq!(
566                menu_bounds.origin, expected_origin,
567                "target: {target:?}, corner: {corner:?}, anchor: {anchor:?}"
568            );
569        }
570    }
571}