anchored.rs

  1use smallvec::SmallVec;
  2use taffy::style::{Display, Position};
  3
  4use crate::{
  5    point, AnyElement, Bounds, Element, ElementContext, IntoElement, LayoutId, ParentElement,
  6    Pixels, Point, Size, Style,
  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: AnchorCorner,
 19    fit_mode: AnchoredFitMode,
 20    anchor_position: Option<Point<Pixels>>,
 21    position_mode: AnchoredPositionMode,
 22}
 23
 24/// anchored gives you an element that will avoid overflowing the window bounds.
 25/// Its children should have no margin to avoid measurement issues.
 26pub fn anchored() -> Anchored {
 27    Anchored {
 28        children: SmallVec::new(),
 29        anchor_corner: AnchorCorner::TopLeft,
 30        fit_mode: AnchoredFitMode::SwitchAnchor,
 31        anchor_position: None,
 32        position_mode: AnchoredPositionMode::Window,
 33    }
 34}
 35
 36impl Anchored {
 37    /// Sets which corner of the anchored element should be anchored to the current position.
 38    pub fn anchor(mut self, anchor: AnchorCorner) -> Self {
 39        self.anchor_corner = anchor;
 40        self
 41    }
 42
 43    /// Sets the position in window coordinates
 44    /// (otherwise the location the anchored element is rendered is used)
 45    pub fn position(mut self, anchor: Point<Pixels>) -> Self {
 46        self.anchor_position = Some(anchor);
 47        self
 48    }
 49
 50    /// Sets the position mode for this anchored element. Local will have this
 51    /// interpret its [`Anchored::position`] as relative to the parent element.
 52    /// While Window will have it interpret the position as relative to the window.
 53    pub fn position_mode(mut self, mode: AnchoredPositionMode) -> Self {
 54        self.position_mode = mode;
 55        self
 56    }
 57
 58    /// Snap to window edge instead of switching anchor corner when an overflow would occur.
 59    pub fn snap_to_window(mut self) -> Self {
 60        self.fit_mode = AnchoredFitMode::SnapToWindow;
 61        self
 62    }
 63}
 64
 65impl ParentElement for Anchored {
 66    fn extend(&mut self, elements: impl Iterator<Item = AnyElement>) {
 67        self.children.extend(elements)
 68    }
 69}
 70
 71impl Element for Anchored {
 72    type RequestLayoutState = AnchoredState;
 73    type PrepaintState = ();
 74
 75    fn request_layout(
 76        &mut self,
 77        cx: &mut ElementContext,
 78    ) -> (crate::LayoutId, Self::RequestLayoutState) {
 79        let child_layout_ids = self
 80            .children
 81            .iter_mut()
 82            .map(|child| child.request_layout(cx))
 83            .collect::<SmallVec<_>>();
 84
 85        let anchored_style = Style {
 86            position: Position::Absolute,
 87            display: Display::Flex,
 88            ..Style::default()
 89        };
 90
 91        let layout_id = cx.request_layout(&anchored_style, child_layout_ids.iter().copied());
 92
 93        (layout_id, AnchoredState { child_layout_ids })
 94    }
 95
 96    fn prepaint(
 97        &mut self,
 98        bounds: Bounds<Pixels>,
 99        request_layout: &mut Self::RequestLayoutState,
100        cx: &mut ElementContext,
101    ) {
102        if request_layout.child_layout_ids.is_empty() {
103            return;
104        }
105
106        let mut child_min = point(Pixels::MAX, Pixels::MAX);
107        let mut child_max = Point::default();
108        for child_layout_id in &request_layout.child_layout_ids {
109            let child_bounds = cx.layout_bounds(*child_layout_id);
110            child_min = child_min.min(&child_bounds.origin);
111            child_max = child_max.max(&child_bounds.lower_right());
112        }
113        let size: Size<Pixels> = (child_max - child_min).into();
114
115        let (origin, mut desired) = self.position_mode.get_position_and_bounds(
116            self.anchor_position,
117            self.anchor_corner,
118            size,
119            bounds,
120        );
121
122        let limits = Bounds {
123            origin: Point::default(),
124            size: cx.viewport_size(),
125        };
126
127        if self.fit_mode == AnchoredFitMode::SwitchAnchor {
128            let mut anchor_corner = self.anchor_corner;
129
130            if desired.left() < limits.left() || desired.right() > limits.right() {
131                let switched = anchor_corner
132                    .switch_axis(Axis::Horizontal)
133                    .get_bounds(origin, size);
134                if !(switched.left() < limits.left() || switched.right() > limits.right()) {
135                    anchor_corner = anchor_corner.switch_axis(Axis::Horizontal);
136                    desired = switched
137                }
138            }
139
140            if desired.top() < limits.top() || desired.bottom() > limits.bottom() {
141                let switched = anchor_corner
142                    .switch_axis(Axis::Vertical)
143                    .get_bounds(origin, size);
144                if !(switched.top() < limits.top() || switched.bottom() > limits.bottom()) {
145                    desired = switched;
146                }
147            }
148        }
149
150        // Snap the horizontal edges of the anchored element to the horizontal edges of the window if
151        // its horizontal bounds overflow, aligning to the left if it is wider than the limits.
152        if desired.right() > limits.right() {
153            desired.origin.x -= desired.right() - limits.right();
154        }
155        if desired.left() < limits.left() {
156            desired.origin.x = limits.origin.x;
157        }
158
159        // Snap the vertical edges of the anchored element to the vertical edges of the window if
160        // its vertical bounds overflow, aligning to the top if it is taller than the limits.
161        if desired.bottom() > limits.bottom() {
162            desired.origin.y -= desired.bottom() - limits.bottom();
163        }
164        if desired.top() < limits.top() {
165            desired.origin.y = limits.origin.y;
166        }
167
168        let offset = desired.origin - bounds.origin;
169        let offset = point(offset.x.round(), offset.y.round());
170
171        cx.with_element_offset(offset, |cx| {
172            for child in &mut self.children {
173                child.prepaint(cx);
174            }
175        })
176    }
177
178    fn paint(
179        &mut self,
180        _bounds: crate::Bounds<crate::Pixels>,
181        _request_layout: &mut Self::RequestLayoutState,
182        _prepaint: &mut Self::PrepaintState,
183        cx: &mut ElementContext,
184    ) {
185        for child in &mut self.children {
186            child.paint(cx);
187        }
188    }
189}
190
191impl IntoElement for Anchored {
192    type Element = Self;
193
194    fn into_element(self) -> Self::Element {
195        self
196    }
197}
198
199enum Axis {
200    Horizontal,
201    Vertical,
202}
203
204/// Which algorithm to use when fitting the anchored element to be inside the window.
205#[derive(Copy, Clone, PartialEq)]
206pub enum AnchoredFitMode {
207    /// Snap the anchored element to the window edge
208    SnapToWindow,
209    /// Switch which corner anchor this anchored element is attached to
210    SwitchAnchor,
211}
212
213/// Which algorithm to use when positioning the anchored element.
214#[derive(Copy, Clone, PartialEq)]
215pub enum AnchoredPositionMode {
216    /// Position the anchored element relative to the window
217    Window,
218    /// Position the anchored element relative to its parent
219    Local,
220}
221
222impl AnchoredPositionMode {
223    fn get_position_and_bounds(
224        &self,
225        anchor_position: Option<Point<Pixels>>,
226        anchor_corner: AnchorCorner,
227        size: Size<Pixels>,
228        bounds: Bounds<Pixels>,
229    ) -> (Point<Pixels>, Bounds<Pixels>) {
230        match self {
231            AnchoredPositionMode::Window => {
232                let anchor_position = anchor_position.unwrap_or(bounds.origin);
233                let bounds = anchor_corner.get_bounds(anchor_position, size);
234                (anchor_position, bounds)
235            }
236            AnchoredPositionMode::Local => {
237                let anchor_position = anchor_position.unwrap_or_default();
238                let bounds = anchor_corner.get_bounds(bounds.origin + anchor_position, size);
239                (anchor_position, bounds)
240            }
241        }
242    }
243}
244
245/// Which corner of the anchored element should be considered the anchor.
246#[derive(Clone, Copy, PartialEq, Eq)]
247pub enum AnchorCorner {
248    /// The top left corner
249    TopLeft,
250    /// The top right corner
251    TopRight,
252    /// The bottom left corner
253    BottomLeft,
254    /// The bottom right corner
255    BottomRight,
256}
257
258impl AnchorCorner {
259    fn get_bounds(&self, origin: Point<Pixels>, size: Size<Pixels>) -> Bounds<Pixels> {
260        let origin = match self {
261            Self::TopLeft => origin,
262            Self::TopRight => Point {
263                x: origin.x - size.width,
264                y: origin.y,
265            },
266            Self::BottomLeft => Point {
267                x: origin.x,
268                y: origin.y - size.height,
269            },
270            Self::BottomRight => Point {
271                x: origin.x - size.width,
272                y: origin.y - size.height,
273            },
274        };
275
276        Bounds { origin, size }
277    }
278
279    /// Get the point corresponding to this anchor corner in `bounds`.
280    pub fn corner(&self, bounds: Bounds<Pixels>) -> Point<Pixels> {
281        match self {
282            Self::TopLeft => bounds.origin,
283            Self::TopRight => bounds.upper_right(),
284            Self::BottomLeft => bounds.lower_left(),
285            Self::BottomRight => bounds.lower_right(),
286        }
287    }
288
289    fn switch_axis(self, axis: Axis) -> Self {
290        match axis {
291            Axis::Vertical => match self {
292                AnchorCorner::TopLeft => AnchorCorner::BottomLeft,
293                AnchorCorner::TopRight => AnchorCorner::BottomRight,
294                AnchorCorner::BottomLeft => AnchorCorner::TopLeft,
295                AnchorCorner::BottomRight => AnchorCorner::TopRight,
296            },
297            Axis::Horizontal => match self {
298                AnchorCorner::TopLeft => AnchorCorner::TopRight,
299                AnchorCorner::TopRight => AnchorCorner::TopLeft,
300                AnchorCorner::BottomLeft => AnchorCorner::BottomRight,
301                AnchorCorner::BottomRight => AnchorCorner::BottomLeft,
302            },
303        }
304    }
305}