overlay.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 overlay element uses to track its children.
 10pub struct OverlayState {
 11    child_layout_ids: SmallVec<[LayoutId; 4]>,
 12}
 13
 14/// An overlay element that can be used to display UI that
 15/// floats on top of other UI elements.
 16pub struct Overlay {
 17    children: SmallVec<[AnyElement; 2]>,
 18    anchor_corner: AnchorCorner,
 19    fit_mode: OverlayFitMode,
 20    anchor_position: Option<Point<Pixels>>,
 21    position_mode: OverlayPositionMode,
 22}
 23
 24/// overlay gives you a floating element that will avoid overflowing the window bounds.
 25/// Its children should have no margin to avoid measurement issues.
 26pub fn overlay() -> Overlay {
 27    Overlay {
 28        children: SmallVec::new(),
 29        anchor_corner: AnchorCorner::TopLeft,
 30        fit_mode: OverlayFitMode::SwitchAnchor,
 31        anchor_position: None,
 32        position_mode: OverlayPositionMode::Window,
 33    }
 34}
 35
 36impl Overlay {
 37    /// Sets which corner of the overlay 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 co-ordinates
 44    /// (otherwise the location the overlay 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 overlay. Local will have this
 51    /// interpret its [`Overlay::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: OverlayPositionMode) -> 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 = OverlayFitMode::SnapToWindow;
 61        self
 62    }
 63}
 64
 65impl ParentElement for Overlay {
 66    fn extend(&mut self, elements: impl Iterator<Item = AnyElement>) {
 67        self.children.extend(elements)
 68    }
 69}
 70
 71impl Element for Overlay {
 72    type State = OverlayState;
 73
 74    fn request_layout(
 75        &mut self,
 76        _: Option<Self::State>,
 77        cx: &mut ElementContext,
 78    ) -> (crate::LayoutId, Self::State) {
 79        let child_layout_ids = self
 80            .children
 81            .iter_mut()
 82            .map(|child| child.request_layout(cx))
 83            .collect::<SmallVec<_>>();
 84
 85        let overlay_style = Style {
 86            position: Position::Absolute,
 87            display: Display::Flex,
 88            ..Style::default()
 89        };
 90
 91        let layout_id = cx.request_layout(&overlay_style, child_layout_ids.iter().copied());
 92
 93        (layout_id, OverlayState { child_layout_ids })
 94    }
 95
 96    fn paint(
 97        &mut self,
 98        bounds: crate::Bounds<crate::Pixels>,
 99        element_state: &mut Self::State,
100        cx: &mut ElementContext,
101    ) {
102        if element_state.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 &element_state.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 == OverlayFitMode::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 overlay 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 overlay 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 mut offset = cx.element_offset() + desired.origin - bounds.origin;
169        offset = point(offset.x.round(), offset.y.round());
170        cx.with_absolute_element_offset(offset, |cx| {
171            cx.break_content_mask(|cx| {
172                for child in &mut self.children {
173                    child.paint(cx);
174                }
175            })
176        })
177    }
178}
179
180impl IntoElement for Overlay {
181    type Element = Self;
182
183    fn element_id(&self) -> Option<crate::ElementId> {
184        None
185    }
186
187    fn into_element(self) -> Self::Element {
188        self
189    }
190}
191
192enum Axis {
193    Horizontal,
194    Vertical,
195}
196
197/// Which algorithm to use when fitting the overlay to be inside the window.
198#[derive(Copy, Clone, PartialEq)]
199pub enum OverlayFitMode {
200    /// Snap the overlay to the window edge
201    SnapToWindow,
202    /// Switch which corner anchor this overlay is attached to
203    SwitchAnchor,
204}
205
206/// Which algorithm to use when positioning the overlay.
207#[derive(Copy, Clone, PartialEq)]
208pub enum OverlayPositionMode {
209    /// Position the overlay relative to the window
210    Window,
211    /// Position the overlay relative to its parent
212    Local,
213}
214
215impl OverlayPositionMode {
216    fn get_position_and_bounds(
217        &self,
218        anchor_position: Option<Point<Pixels>>,
219        anchor_corner: AnchorCorner,
220        size: Size<Pixels>,
221        bounds: Bounds<Pixels>,
222    ) -> (Point<Pixels>, Bounds<Pixels>) {
223        match self {
224            OverlayPositionMode::Window => {
225                let anchor_position = anchor_position.unwrap_or(bounds.origin);
226                let bounds = anchor_corner.get_bounds(anchor_position, size);
227                (anchor_position, bounds)
228            }
229            OverlayPositionMode::Local => {
230                let anchor_position = anchor_position.unwrap_or_default();
231                let bounds = anchor_corner.get_bounds(bounds.origin + anchor_position, size);
232                (anchor_position, bounds)
233            }
234        }
235    }
236}
237
238/// Which corner of the overlay should be considered the anchor.
239#[derive(Clone, Copy, PartialEq, Eq)]
240pub enum AnchorCorner {
241    /// The top left corner
242    TopLeft,
243    /// The top right corner
244    TopRight,
245    /// The bottom left corner
246    BottomLeft,
247    /// The bottom right corner
248    BottomRight,
249}
250
251impl AnchorCorner {
252    fn get_bounds(&self, origin: Point<Pixels>, size: Size<Pixels>) -> Bounds<Pixels> {
253        let origin = match self {
254            Self::TopLeft => origin,
255            Self::TopRight => Point {
256                x: origin.x - size.width,
257                y: origin.y,
258            },
259            Self::BottomLeft => Point {
260                x: origin.x,
261                y: origin.y - size.height,
262            },
263            Self::BottomRight => Point {
264                x: origin.x - size.width,
265                y: origin.y - size.height,
266            },
267        };
268
269        Bounds { origin, size }
270    }
271
272    /// Get the point corresponding to this anchor corner in `bounds`.
273    pub fn corner(&self, bounds: Bounds<Pixels>) -> Point<Pixels> {
274        match self {
275            Self::TopLeft => bounds.origin,
276            Self::TopRight => bounds.upper_right(),
277            Self::BottomLeft => bounds.lower_left(),
278            Self::BottomRight => bounds.lower_right(),
279        }
280    }
281
282    fn switch_axis(self, axis: Axis) -> Self {
283        match axis {
284            Axis::Vertical => match self {
285                AnchorCorner::TopLeft => AnchorCorner::BottomLeft,
286                AnchorCorner::TopRight => AnchorCorner::BottomRight,
287                AnchorCorner::BottomLeft => AnchorCorner::TopLeft,
288                AnchorCorner::BottomRight => AnchorCorner::TopRight,
289            },
290            Axis::Horizontal => match self {
291                AnchorCorner::TopLeft => AnchorCorner::TopRight,
292                AnchorCorner::TopRight => AnchorCorner::TopLeft,
293                AnchorCorner::BottomLeft => AnchorCorner::BottomRight,
294                AnchorCorner::BottomRight => AnchorCorner::BottomLeft,
295            },
296        }
297    }
298}