gpui/elements/
anchored.rs

1use smallvec::SmallVec;
2
3use crate::{
4    AnyElement, App, Axis, Bounds, Corner, Display, Edges, Element, GlobalElementId,
5    InspectorElementId, IntoElement, LayoutId, ParentElement, Pixels, Point, Position, Size, Style,
6    Window, point, px,
7};
8
9/// The state that the anchored element element uses to track its children.
10pub struct AnchoredState {
11    child_layout_ids: SmallVec<[LayoutId; 4]>,
12}
13
14/// An anchored element that can be used to display UI that
15/// will avoid overflowing the window bounds.
16pub struct Anchored {
17    children: SmallVec<[AnyElement; 2]>,
18    anchor_corner: Corner,
19    fit_mode: AnchoredFitMode,
20    anchor_position: Option<Point<Pixels>>,
21    position_mode: AnchoredPositionMode,
22    offset: Option<Point<Pixels>>,
23}
24
25/// anchored gives you an element that will avoid overflowing the window bounds.
26/// Its children should have no margin to avoid measurement issues.
27pub fn anchored() -> Anchored {
28    Anchored {
29        children: SmallVec::new(),
30        anchor_corner: Corner::TopLeft,
31        fit_mode: AnchoredFitMode::SwitchAnchor,
32        anchor_position: None,
33        position_mode: AnchoredPositionMode::Window,
34        offset: None,
35    }
36}
37
38impl Anchored {
39    /// Sets which corner of the anchored element should be anchored to the current position.
40    pub fn anchor(mut self, anchor: Corner) -> Self {
41        self.anchor_corner = anchor;
42        self
43    }
44
45    /// Sets the position in window coordinates
46    /// (otherwise the location the anchored element is rendered is used)
47    pub fn position(mut self, anchor: Point<Pixels>) -> Self {
48        self.anchor_position = Some(anchor);
49        self
50    }
51
52    /// Offset the final position by this amount.
53    /// Useful when you want to anchor to an element but offset from it, such as in PopoverMenu.
54    pub fn offset(mut self, offset: Point<Pixels>) -> Self {
55        self.offset = Some(offset);
56        self
57    }
58
59    /// Sets the position mode for this anchored element. Local will have this
60    /// interpret its [`Anchored::position`] as relative to the parent element.
61    /// While Window will have it interpret the position as relative to the window.
62    pub fn position_mode(mut self, mode: AnchoredPositionMode) -> Self {
63        self.position_mode = mode;
64        self
65    }
66
67    /// Snap to window edge instead of switching anchor corner when an overflow would occur.
68    pub fn snap_to_window(mut self) -> Self {
69        self.fit_mode = AnchoredFitMode::SnapToWindow;
70        self
71    }
72
73    /// Snap to window edge and leave some margins.
74    pub fn snap_to_window_with_margin(mut self, edges: impl Into<Edges<Pixels>>) -> Self {
75        self.fit_mode = AnchoredFitMode::SnapToWindowWithMargin(edges.into());
76        self
77    }
78}
79
80impl ParentElement for Anchored {
81    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
82        self.children.extend(elements)
83    }
84}
85
86impl Element for Anchored {
87    type RequestLayoutState = AnchoredState;
88    type PrepaintState = ();
89
90    fn id(&self) -> Option<crate::ElementId> {
91        None
92    }
93
94    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
95        None
96    }
97
98    fn request_layout(
99        &mut self,
100        _id: Option<&GlobalElementId>,
101        _inspector_id: Option<&InspectorElementId>,
102        window: &mut Window,
103        cx: &mut App,
104    ) -> (crate::LayoutId, Self::RequestLayoutState) {
105        let child_layout_ids = self
106            .children
107            .iter_mut()
108            .map(|child| child.request_layout(window, cx))
109            .collect::<SmallVec<_>>();
110
111        let anchored_style = Style {
112            position: Position::Absolute,
113            display: Display::Flex,
114            ..Style::default()
115        };
116
117        let layout_id = window.request_layout(anchored_style, child_layout_ids.iter().copied(), cx);
118
119        (layout_id, AnchoredState { child_layout_ids })
120    }
121
122    fn prepaint(
123        &mut self,
124        _id: Option<&GlobalElementId>,
125        _inspector_id: Option<&InspectorElementId>,
126        bounds: Bounds<Pixels>,
127        request_layout: &mut Self::RequestLayoutState,
128        window: &mut Window,
129        cx: &mut App,
130    ) {
131        if request_layout.child_layout_ids.is_empty() {
132            return;
133        }
134
135        let mut child_min = point(Pixels::MAX, Pixels::MAX);
136        let mut child_max = Point::default();
137        for child_layout_id in &request_layout.child_layout_ids {
138            let child_bounds = window.layout_bounds(*child_layout_id);
139            child_min = child_min.min(&child_bounds.origin);
140            child_max = child_max.max(&child_bounds.bottom_right());
141        }
142        let size: Size<Pixels> = (child_max - child_min).into();
143
144        let (origin, mut desired) = self.position_mode.get_position_and_bounds(
145            self.anchor_position,
146            self.anchor_corner,
147            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_corner = self.anchor_corner;
159
160            if desired.left() < limits.left() || desired.right() > limits.right() {
161                let switched = Bounds::from_corner_and_size(
162                    anchor_corner.other_side_corner_along(Axis::Horizontal),
163                    origin,
164                    size,
165                );
166                if !(switched.left() < limits.left() || switched.right() > limits.right()) {
167                    anchor_corner = anchor_corner.other_side_corner_along(Axis::Horizontal);
168                    desired = switched
169                }
170            }
171
172            if desired.top() < limits.top() || desired.bottom() > limits.bottom() {
173                let switched = Bounds::from_corner_and_size(
174                    anchor_corner.other_side_corner_along(Axis::Vertical),
175                    origin,
176                    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_corner: Corner,
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 =
278                    Bounds::from_corner_and_size(anchor_corner, anchor_position + offset, size);
279                (anchor_position, bounds)
280            }
281            AnchoredPositionMode::Local => {
282                let anchor_position = anchor_position.unwrap_or_default();
283                let bounds = Bounds::from_corner_and_size(
284                    anchor_corner,
285                    bounds.origin + anchor_position + offset,
286                    size,
287                );
288                (anchor_position, bounds)
289            }
290        }
291    }
292}