overlay.rs

  1use smallvec::SmallVec;
  2use taffy::style::{Display, Position};
  3
  4use crate::{
  5    point, AnyElement, BorrowWindow, Bounds, Element, LayoutId, ParentElement, Pixels, Point,
  6    RenderOnce, Size, Style,
  7};
  8
  9pub struct OverlayState {
 10    child_layout_ids: SmallVec<[LayoutId; 4]>,
 11}
 12
 13pub struct Overlay<V> {
 14    children: SmallVec<[AnyElement<V>; 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<V: 'static>() -> Overlay<V> {
 25    Overlay {
 26        children: SmallVec::new(),
 27        anchor_corner: AnchorCorner::TopLeft,
 28        fit_mode: OverlayFitMode::SwitchAnchor,
 29        anchor_position: None,
 30    }
 31}
 32
 33impl<V> Overlay<V> {
 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<V: 'static> ParentElement<V> for Overlay<V> {
 55    fn children_mut(&mut self) -> &mut SmallVec<[AnyElement<V>; 2]> {
 56        &mut self.children
 57    }
 58}
 59
 60impl<V: 'static> Element<V> for Overlay<V> {
 61    type State = OverlayState;
 62
 63    fn layout(
 64        &mut self,
 65        view_state: &mut V,
 66        _: Option<Self::State>,
 67        cx: &mut crate::ViewContext<V>,
 68    ) -> (crate::LayoutId, Self::State) {
 69        let child_layout_ids = self
 70            .children
 71            .iter_mut()
 72            .map(|child| child.layout(view_state, cx))
 73            .collect::<SmallVec<_>>();
 74
 75        let mut overlay_style = Style::default();
 76        overlay_style.position = Position::Absolute;
 77        overlay_style.display = Display::Flex;
 78
 79        let layout_id = cx.request_layout(&overlay_style, child_layout_ids.iter().copied());
 80
 81        (layout_id, OverlayState { child_layout_ids })
 82    }
 83
 84    fn paint(
 85        self,
 86        bounds: crate::Bounds<crate::Pixels>,
 87        view_state: &mut V,
 88        element_state: &mut Self::State,
 89        cx: &mut crate::ViewContext<V>,
 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::zero(),
108            size: cx.viewport_size(),
109        };
110
111        match self.fit_mode {
112            OverlayFitMode::SnapToWindow => {
113                // Snap the horizontal edges of the overlay to the horizontal edges of the window if
114                // its horizontal bounds overflow
115                if desired.right() > limits.right() {
116                    desired.origin.x -= desired.right() - limits.right();
117                } else if desired.left() < limits.left() {
118                    desired.origin.x = limits.origin.x;
119                }
120
121                // Snap the vertical edges of the overlay to the vertical edges of the window if
122                // its vertical bounds overflow.
123                if desired.bottom() > limits.bottom() {
124                    desired.origin.y -= desired.bottom() - limits.bottom();
125                } else if desired.top() < limits.top() {
126                    desired.origin.y = limits.origin.y;
127                }
128            }
129            OverlayFitMode::SwitchAnchor => {
130                let mut anchor_corner = self.anchor_corner;
131
132                if desired.left() < limits.left() || desired.right() > limits.right() {
133                    anchor_corner = anchor_corner.switch_axis(Axis::Horizontal);
134                }
135
136                if bounds.top() < limits.top() || bounds.bottom() > limits.bottom() {
137                    anchor_corner = anchor_corner.switch_axis(Axis::Vertical);
138                }
139
140                // Update bounds if needed
141                if anchor_corner != self.anchor_corner {
142                    desired = anchor_corner.get_bounds(origin, size)
143                }
144            }
145            OverlayFitMode::None => {}
146        }
147
148        cx.with_element_offset(desired.origin - bounds.origin, |cx| {
149            for child in self.children {
150                child.paint(view_state, cx);
151            }
152        })
153    }
154}
155
156impl<V: 'static> RenderOnce<V> for Overlay<V> {
157    type Element = Self;
158
159    fn element_id(&self) -> Option<crate::ElementId> {
160        None
161    }
162
163    fn render_once(self) -> Self::Element {
164        self
165    }
166}
167
168enum Axis {
169    Horizontal,
170    Vertical,
171}
172
173#[derive(Copy, Clone)]
174pub enum OverlayFitMode {
175    SnapToWindow,
176    SwitchAnchor,
177    None,
178}
179
180#[derive(Clone, Copy, PartialEq, Eq)]
181pub enum AnchorCorner {
182    TopLeft,
183    TopRight,
184    BottomLeft,
185    BottomRight,
186}
187
188impl AnchorCorner {
189    fn get_bounds(&self, origin: Point<Pixels>, size: Size<Pixels>) -> Bounds<Pixels> {
190        let origin = match self {
191            Self::TopLeft => origin,
192            Self::TopRight => Point {
193                x: origin.x - size.width,
194                y: origin.y,
195            },
196            Self::BottomLeft => Point {
197                x: origin.x,
198                y: origin.y - size.height,
199            },
200            Self::BottomRight => Point {
201                x: origin.x - size.width,
202                y: origin.y - size.height,
203            },
204        };
205
206        Bounds { origin, size }
207    }
208
209    pub fn corner(&self, bounds: Bounds<Pixels>) -> Point<Pixels> {
210        match self {
211            Self::TopLeft => bounds.origin,
212            Self::TopRight => bounds.upper_right(),
213            Self::BottomLeft => bounds.lower_left(),
214            Self::BottomRight => bounds.lower_right(),
215        }
216    }
217
218    fn switch_axis(self, axis: Axis) -> Self {
219        match axis {
220            Axis::Vertical => match self {
221                AnchorCorner::TopLeft => AnchorCorner::BottomLeft,
222                AnchorCorner::TopRight => AnchorCorner::BottomRight,
223                AnchorCorner::BottomLeft => AnchorCorner::TopLeft,
224                AnchorCorner::BottomRight => AnchorCorner::TopRight,
225            },
226            Axis::Horizontal => match self {
227                AnchorCorner::TopLeft => AnchorCorner::TopRight,
228                AnchorCorner::TopRight => AnchorCorner::TopLeft,
229                AnchorCorner::BottomLeft => AnchorCorner::BottomRight,
230                AnchorCorner::BottomRight => AnchorCorner::BottomLeft,
231            },
232        }
233    }
234}