overlay.rs

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