overlay.rs

  1use smallvec::SmallVec;
  2use taffy::style::{Display, Position};
  3
  4use crate::{
  5    point, AnyElement, BorrowWindow, Bounds, Element, IntoElement, LayoutId, ParentElement, Pixels,
  6    Point, Size, Style, WindowContext,
  7};
  8
  9pub struct OverlayState {
 10    child_layout_ids: SmallVec<[LayoutId; 4]>,
 11}
 12
 13pub struct Overlay {
 14    children: SmallVec<[AnyElement; 2]>,
 15    anchor_corner: AnchorCorner,
 16    fit_mode: OverlayFitMode,
 17    // todo!();
 18    anchor_position: Option<Point<Pixels>>,
 19    // position_mode: OverlayPositionMode,
 20}
 21
 22/// overlay gives you a floating element that will avoid overflowing the window bounds.
 23/// Its children should have no margin to avoid measurement issues.
 24pub fn overlay() -> Overlay {
 25    Overlay {
 26        children: SmallVec::new(),
 27        anchor_corner: AnchorCorner::TopLeft,
 28        fit_mode: OverlayFitMode::SwitchAnchor,
 29        anchor_position: None,
 30    }
 31}
 32
 33impl Overlay {
 34    /// Sets which corner of the overlay should be anchored to the current position.
 35    pub fn anchor(mut self, anchor: AnchorCorner) -> Self {
 36        self.anchor_corner = anchor;
 37        self
 38    }
 39
 40    /// Sets the position in window co-ordinates
 41    /// (otherwise the location the overlay is rendered is used)
 42    pub fn position(mut self, anchor: Point<Pixels>) -> Self {
 43        self.anchor_position = Some(anchor);
 44        self
 45    }
 46
 47    /// Snap to window edge instead of switching anchor corner when an overflow would occur.
 48    pub fn snap_to_window(mut self) -> Self {
 49        self.fit_mode = OverlayFitMode::SnapToWindow;
 50        self
 51    }
 52}
 53
 54impl ParentElement for Overlay {
 55    fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> {
 56        &mut self.children
 57    }
 58}
 59
 60impl Element for Overlay {
 61    type State = OverlayState;
 62
 63    fn request_layout(
 64        &mut self,
 65        _: Option<Self::State>,
 66        cx: &mut WindowContext,
 67    ) -> (crate::LayoutId, Self::State) {
 68        let child_layout_ids = self
 69            .children
 70            .iter_mut()
 71            .map(|child| child.request_layout(cx))
 72            .collect::<SmallVec<_>>();
 73
 74        let overlay_style = Style {
 75            position: Position::Absolute,
 76            display: Display::Flex,
 77            ..Style::default()
 78        };
 79
 80        let layout_id = cx.request_layout(&overlay_style, child_layout_ids.iter().copied());
 81
 82        (layout_id, OverlayState { child_layout_ids })
 83    }
 84
 85    fn paint(
 86        &mut self,
 87        bounds: crate::Bounds<crate::Pixels>,
 88        element_state: &mut Self::State,
 89        cx: &mut WindowContext,
 90    ) {
 91        if element_state.child_layout_ids.is_empty() {
 92            return;
 93        }
 94
 95        let mut child_min = point(Pixels::MAX, Pixels::MAX);
 96        let mut child_max = Point::default();
 97        for child_layout_id in &element_state.child_layout_ids {
 98            let child_bounds = cx.layout_bounds(*child_layout_id);
 99            child_min = child_min.min(&child_bounds.origin);
100            child_max = child_max.max(&child_bounds.lower_right());
101        }
102        let size: Size<Pixels> = (child_max - child_min).into();
103        let origin = self.anchor_position.unwrap_or(bounds.origin);
104
105        let mut desired = self.anchor_corner.get_bounds(origin, size);
106        let limits = Bounds {
107            origin: Point::default(),
108            size: cx.viewport_size(),
109        };
110
111        if self.fit_mode == OverlayFitMode::SwitchAnchor {
112            let mut anchor_corner = self.anchor_corner;
113
114            if desired.left() < limits.left() || desired.right() > limits.right() {
115                let switched = anchor_corner
116                    .switch_axis(Axis::Horizontal)
117                    .get_bounds(origin, size);
118                if !(switched.left() < limits.left() || switched.right() > limits.right()) {
119                    anchor_corner = anchor_corner.switch_axis(Axis::Horizontal);
120                    desired = switched
121                }
122            }
123
124            if desired.top() < limits.top() || desired.bottom() > limits.bottom() {
125                let switched = anchor_corner
126                    .switch_axis(Axis::Vertical)
127                    .get_bounds(origin, size);
128                if !(switched.top() < limits.top() || switched.bottom() > limits.bottom()) {
129                    desired = switched;
130                }
131            }
132        }
133
134        // Snap the horizontal edges of the overlay to the horizontal edges of the window if
135        // its horizontal bounds overflow, aligning to the left if it is wider than the limits.
136        if desired.right() > limits.right() {
137            desired.origin.x -= desired.right() - limits.right();
138        }
139        if desired.left() < limits.left() {
140            desired.origin.x = limits.origin.x;
141        }
142
143        // Snap the vertical edges of the overlay to the vertical edges of the window if
144        // its vertical bounds overflow, aligning to the top if it is taller than the limits.
145        if desired.bottom() > limits.bottom() {
146            desired.origin.y -= desired.bottom() - limits.bottom();
147        }
148        if desired.top() < limits.top() {
149            desired.origin.y = limits.origin.y;
150        }
151
152        let mut offset = cx.element_offset() + desired.origin - bounds.origin;
153        offset = point(offset.x.round(), offset.y.round());
154        cx.with_absolute_element_offset(offset, |cx| {
155            cx.break_content_mask(|cx| {
156                for child in &mut self.children {
157                    child.paint(cx);
158                }
159            })
160        })
161    }
162}
163
164impl IntoElement for Overlay {
165    type Element = Self;
166
167    fn element_id(&self) -> Option<crate::ElementId> {
168        None
169    }
170
171    fn into_element(self) -> Self::Element {
172        self
173    }
174}
175
176enum Axis {
177    Horizontal,
178    Vertical,
179}
180
181#[derive(Copy, Clone, PartialEq)]
182pub enum OverlayFitMode {
183    SnapToWindow,
184    SwitchAnchor,
185}
186
187#[derive(Clone, Copy, PartialEq, Eq)]
188pub enum AnchorCorner {
189    TopLeft,
190    TopRight,
191    BottomLeft,
192    BottomRight,
193}
194
195impl AnchorCorner {
196    fn get_bounds(&self, origin: Point<Pixels>, size: Size<Pixels>) -> Bounds<Pixels> {
197        let origin = match self {
198            Self::TopLeft => origin,
199            Self::TopRight => Point {
200                x: origin.x - size.width,
201                y: origin.y,
202            },
203            Self::BottomLeft => Point {
204                x: origin.x,
205                y: origin.y - size.height,
206            },
207            Self::BottomRight => Point {
208                x: origin.x - size.width,
209                y: origin.y - size.height,
210            },
211        };
212
213        Bounds { origin, size }
214    }
215
216    pub fn corner(&self, bounds: Bounds<Pixels>) -> Point<Pixels> {
217        match self {
218            Self::TopLeft => bounds.origin,
219            Self::TopRight => bounds.upper_right(),
220            Self::BottomLeft => bounds.lower_left(),
221            Self::BottomRight => bounds.lower_right(),
222        }
223    }
224
225    fn switch_axis(self, axis: Axis) -> Self {
226        match axis {
227            Axis::Vertical => match self {
228                AnchorCorner::TopLeft => AnchorCorner::BottomLeft,
229                AnchorCorner::TopRight => AnchorCorner::BottomRight,
230                AnchorCorner::BottomLeft => AnchorCorner::TopLeft,
231                AnchorCorner::BottomRight => AnchorCorner::TopRight,
232            },
233            Axis::Horizontal => match self {
234                AnchorCorner::TopLeft => AnchorCorner::TopRight,
235                AnchorCorner::TopRight => AnchorCorner::TopLeft,
236                AnchorCorner::BottomLeft => AnchorCorner::BottomRight,
237                AnchorCorner::BottomRight => AnchorCorner::BottomLeft,
238            },
239        }
240    }
241}