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