Skip to main content

gpui/elements/
anchored.rs

1// Modified by Longbridge for gpui-fast.
2use smallvec::SmallVec;
3
4use crate::{
5    Anchor, AnyElement, App, Axis, Bounds, Display, Edges, Element, GlobalElementId,
6    InspectorElementId, IntoElement, LayoutId, ParentElement, Pixels, Point, Position, Size, Style,
7    Window, point, px,
8};
9
10/// The state that the anchored element element uses to track its children.
11pub struct AnchoredState {
12    child_layout_ids: SmallVec<[LayoutId; 4]>,
13}
14
15/// An anchored element that can be used to display UI that
16/// will avoid overflowing the window bounds.
17pub struct Anchored {
18    children: SmallVec<[AnyElement; 2]>,
19    anchor: Anchor,
20    fit_mode: AnchoredFitMode,
21    anchor_position: Option<Point<Pixels>>,
22    position_mode: AnchoredPositionMode,
23    offset: Option<Point<Pixels>>,
24}
25
26/// anchored gives you an element that will avoid overflowing the window bounds.
27/// Its children should have no margin to avoid measurement issues.
28pub fn anchored() -> Anchored {
29    Anchored {
30        children: SmallVec::new(),
31        anchor: Anchor::TopLeft,
32        fit_mode: AnchoredFitMode::SwitchAnchor,
33        anchor_position: None,
34        position_mode: AnchoredPositionMode::Window,
35        offset: None,
36    }
37}
38
39impl Anchored {
40    /// Sets which corner of the anchored element should be anchored to the current position.
41    pub fn anchor(mut self, anchor: Anchor) -> Self {
42        self.anchor = anchor;
43        self
44    }
45
46    /// Sets the position in window coordinates
47    /// (otherwise the location the anchored element is rendered is used)
48    pub fn position(mut self, anchor: Point<Pixels>) -> Self {
49        self.anchor_position = Some(anchor);
50        self
51    }
52
53    /// Offset the final position by this amount.
54    /// Useful when you want to anchor to an element but offset from it, such as in PopoverMenu.
55    pub fn offset(mut self, offset: Point<Pixels>) -> Self {
56        self.offset = Some(offset);
57        self
58    }
59
60    /// Sets the position mode for this anchored element. Local will have this
61    /// interpret its [`Anchored::position`] as relative to the parent element.
62    /// While Window will have it interpret the position as relative to the window.
63    pub fn position_mode(mut self, mode: AnchoredPositionMode) -> Self {
64        self.position_mode = mode;
65        self
66    }
67
68    /// Snap to window edge instead of switching anchor corner when an overflow would occur.
69    pub fn snap_to_window(mut self) -> Self {
70        self.fit_mode = AnchoredFitMode::SnapToWindow;
71        self
72    }
73
74    /// Snap to window edge and leave some margins.
75    pub fn snap_to_window_with_margin(mut self, edges: impl Into<Edges<Pixels>>) -> Self {
76        self.fit_mode = AnchoredFitMode::SnapToWindowWithMargin(edges.into());
77        self
78    }
79}
80
81impl ParentElement for Anchored {
82    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
83        self.children.extend(elements)
84    }
85}
86
87impl Element for Anchored {
88    type RequestLayoutState = AnchoredState;
89    type PrepaintState = ();
90
91    fn id(&self) -> Option<crate::ElementId> {
92        None
93    }
94
95    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
96        None
97    }
98
99    fn request_layout(
100        &mut self,
101        _id: Option<&GlobalElementId>,
102        _inspector_id: Option<&InspectorElementId>,
103        window: &mut Window,
104        cx: &mut App,
105    ) -> (crate::LayoutId, Self::RequestLayoutState) {
106        let child_layout_ids = self
107            .children
108            .iter_mut()
109            .map(|child| child.request_layout(window, cx))
110            .collect::<SmallVec<_>>();
111
112        let anchored_style = Style {
113            position: Position::Absolute,
114            display: Display::Flex,
115            ..Style::default()
116        };
117
118        let layout_id = window.request_layout(anchored_style, child_layout_ids.iter().copied(), cx);
119
120        (layout_id, AnchoredState { child_layout_ids })
121    }
122
123    fn prepaint(
124        &mut self,
125        _id: Option<&GlobalElementId>,
126        _inspector_id: Option<&InspectorElementId>,
127        bounds: Bounds<Pixels>,
128        request_layout: &mut Self::RequestLayoutState,
129        window: &mut Window,
130        cx: &mut App,
131    ) {
132        if request_layout.child_layout_ids.is_empty() {
133            return;
134        }
135        crate::fast::layers::invalidate::note_anchored(window);
136
137        let children_bounds = request_layout
138            .child_layout_ids
139            .iter()
140            .map(|id| window.layout_bounds(*id))
141            .reduce(|acc, bounds| acc.union(&bounds))
142            .unwrap();
143
144        let (origin, mut desired) = self.position_mode.get_position_and_bounds(
145            self.anchor_position,
146            self.anchor,
147            children_bounds.size,
148            bounds,
149            self.offset,
150        );
151
152        let limits = Bounds {
153            origin: Point::default(),
154            size: window.viewport_size(),
155        };
156
157        if self.fit_mode == AnchoredFitMode::SwitchAnchor {
158            let mut anchor = self.anchor;
159
160            if desired.left() < limits.left() || desired.right() > limits.right() {
161                let switched = Bounds::from_anchor_and_size(
162                    anchor.other_side_along(Axis::Horizontal),
163                    origin,
164                    children_bounds.size,
165                );
166                if !(switched.left() < limits.left() || switched.right() > limits.right()) {
167                    anchor = anchor.other_side_along(Axis::Horizontal);
168                    desired = switched
169                }
170            }
171
172            if desired.top() < limits.top() || desired.bottom() > limits.bottom() {
173                let switched = Bounds::from_anchor_and_size(
174                    anchor.other_side_along(Axis::Vertical),
175                    origin,
176                    children_bounds.size,
177                );
178                if !(switched.top() < limits.top() || switched.bottom() > limits.bottom()) {
179                    desired = switched;
180                }
181            }
182        }
183
184        let client_inset = window.client_inset.unwrap_or(px(0.));
185        let edges = match self.fit_mode {
186            AnchoredFitMode::SnapToWindowWithMargin(edges) => edges,
187            _ => Edges::default(),
188        }
189        .map(|edge| *edge + client_inset);
190
191        // Snap the horizontal edges of the anchored element to the horizontal edges of the window if
192        // its horizontal bounds overflow, aligning to the left if it is wider than the limits.
193        if desired.right() > limits.right() {
194            desired.origin.x -= desired.right() - limits.right() + edges.right;
195        }
196        if desired.left() < limits.left() {
197            desired.origin.x = limits.origin.x + edges.left;
198        }
199
200        // Snap the vertical edges of the anchored element to the vertical edges of the window if
201        // its vertical bounds overflow, aligning to the top if it is taller than the limits.
202        if desired.bottom() > limits.bottom() {
203            desired.origin.y -= desired.bottom() - limits.bottom() + edges.bottom;
204        }
205        if desired.top() < limits.top() {
206            desired.origin.y = limits.origin.y + edges.top;
207        }
208
209        let offset = desired.origin - bounds.origin;
210        let offset = point(offset.x.round(), offset.y.round());
211
212        window.with_element_offset(offset, |window| {
213            for child in &mut self.children {
214                child.prepaint(window, cx);
215            }
216        })
217    }
218
219    fn paint(
220        &mut self,
221        _id: Option<&GlobalElementId>,
222        _inspector_id: Option<&InspectorElementId>,
223        _bounds: crate::Bounds<crate::Pixels>,
224        _request_layout: &mut Self::RequestLayoutState,
225        _prepaint: &mut Self::PrepaintState,
226        window: &mut Window,
227        cx: &mut App,
228    ) {
229        for child in &mut self.children {
230            child.paint(window, cx);
231        }
232    }
233}
234
235impl IntoElement for Anchored {
236    type Element = Self;
237
238    fn into_element(self) -> Self::Element {
239        self
240    }
241}
242
243/// Which algorithm to use when fitting the anchored element to be inside the window.
244#[derive(Copy, Clone, PartialEq)]
245pub enum AnchoredFitMode {
246    /// Snap the anchored element to the window edge.
247    SnapToWindow,
248    /// Snap to window edge and leave some margins.
249    SnapToWindowWithMargin(Edges<Pixels>),
250    /// Switch which corner anchor this anchored element is attached to.
251    SwitchAnchor,
252}
253
254/// Which algorithm to use when positioning the anchored element.
255#[derive(Copy, Clone, PartialEq)]
256pub enum AnchoredPositionMode {
257    /// Position the anchored element relative to the window.
258    Window,
259    /// Position the anchored element relative to its parent.
260    Local,
261}
262
263impl AnchoredPositionMode {
264    fn get_position_and_bounds(
265        &self,
266        anchor_position: Option<Point<Pixels>>,
267        anchor: Anchor,
268        size: Size<Pixels>,
269        bounds: Bounds<Pixels>,
270        offset: Option<Point<Pixels>>,
271    ) -> (Point<Pixels>, Bounds<Pixels>) {
272        let offset = offset.unwrap_or_default();
273
274        match self {
275            AnchoredPositionMode::Window => {
276                let anchor_position = anchor_position.unwrap_or(bounds.origin);
277                let bounds = Bounds::from_anchor_and_size(anchor, anchor_position + offset, size);
278                (anchor_position, bounds)
279            }
280            AnchoredPositionMode::Local => {
281                let anchor_position = anchor_position.unwrap_or_default();
282                let bounds = Bounds::from_anchor_and_size(
283                    anchor,
284                    bounds.origin + anchor_position + offset,
285                    size,
286                );
287                (anchor_position, bounds)
288            }
289        }
290    }
291}
292
293#[cfg(test)]
294mod tests {
295    use crate::{
296        Context, Pixels, PlatformInput, Point, TestAppContext, Window, deferred, div, point,
297        prelude::*, px, size,
298    };
299
300    struct AnchoredTestView {
301        position: Point<Pixels>,
302    }
303
304    impl Render for AnchoredTestView {
305        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
306            div().size_full().child(
307                div()
308                    .id("scroll-container")
309                    .overflow_y_scroll()
310                    .size_full()
311                    .child(div().h(px(2000.)).w_full())
312                    .child(
313                        deferred(
314                            super::anchored()
315                                .snap_to_window()
316                                .position(self.position)
317                                .child(
318                                    div()
319                                        .id("menu")
320                                        .debug_selector(|| "MENU".into())
321                                        .w(px(200.))
322                                        .h(px(300.)),
323                                ),
324                        )
325                        .with_priority(1),
326                    ),
327            )
328        }
329    }
330
331    #[gpui::test]
332    fn test_anchored_position_without_scroll(cx: &mut TestAppContext) {
333        let window = cx.open_window(size(px(800.), px(600.)), |_, _| AnchoredTestView {
334            position: point(px(100.), px(100.)),
335        });
336
337        cx.run_until_parked();
338
339        let menu_bounds = window
340            .update(cx, |_, window, _| {
341                window.rendered_frame.debug_bounds.get("MENU").copied()
342            })
343            .unwrap()
344            .expect("MENU debug bounds not found");
345
346        assert_eq!(menu_bounds.origin, point(px(100.), px(100.)));
347        assert_eq!(menu_bounds.size, size(px(200.), px(300.)));
348    }
349
350    #[gpui::test]
351    fn test_anchored_position_when_scrolled(cx: &mut TestAppContext) {
352        let window = cx.open_window(size(px(800.), px(600.)), |_, _| AnchoredTestView {
353            position: point(px(100.), px(100.)),
354        });
355
356        cx.run_until_parked();
357
358        window
359            .update(cx, |_, window, cx| {
360                let event = gpui::ScrollWheelEvent {
361                    position: point(px(400.), px(300.)),
362                    delta: gpui::ScrollDelta::Pixels(point(px(0.), px(-1000.))),
363                    ..Default::default()
364                };
365                window.dispatch_event(PlatformInput::ScrollWheel(event), cx);
366            })
367            .unwrap();
368
369        cx.run_until_parked();
370
371        let menu_bounds = window
372            .update(cx, |_, window, _| {
373                window.rendered_frame.debug_bounds.get("MENU").copied()
374            })
375            .unwrap()
376            .expect("MENU debug bounds not found");
377
378        assert_eq!(menu_bounds.origin, point(px(100.), px(100.)));
379        assert_eq!(menu_bounds.size, size(px(200.), px(300.)));
380    }
381
382    #[gpui::test]
383    fn test_anchored_snaps_to_window(cx: &mut TestAppContext) {
384        let window = cx.open_window(size(px(800.), px(600.)), |_, _| AnchoredTestView {
385            position: point(px(100.), px(500.)),
386        });
387
388        cx.run_until_parked();
389
390        let menu_bounds = window
391            .update(cx, |_, window, _| {
392                window.rendered_frame.debug_bounds.get("MENU").copied()
393            })
394            .unwrap()
395            .expect("MENU debug bounds not found");
396
397        assert_eq!(menu_bounds.origin, point(px(100.), px(300.)));
398        assert_eq!(menu_bounds.size, size(px(200.), px(300.)));
399    }
400}