overlay.rs

  1use std::ops::Range;
  2
  3use crate::{
  4    geometry::{rect::RectF, vector::Vector2F},
  5    json::ToJson,
  6    AnyElement, Axis, Element, LayoutContext, MouseRegion, PaintContext, SizeConstraint,
  7    ViewContext,
  8};
  9use serde_json::json;
 10
 11pub struct Overlay<V> {
 12    child: AnyElement<V>,
 13    anchor_position: Option<Vector2F>,
 14    anchor_corner: AnchorCorner,
 15    fit_mode: OverlayFitMode,
 16    position_mode: OverlayPositionMode,
 17    hoverable: bool,
 18    z_index: Option<usize>,
 19}
 20
 21#[derive(Copy, Clone)]
 22pub enum OverlayFitMode {
 23    SnapToWindow,
 24    SwitchAnchor,
 25    None,
 26}
 27
 28#[derive(Copy, Clone, PartialEq, Eq)]
 29pub enum OverlayPositionMode {
 30    Window,
 31    Local,
 32}
 33
 34#[derive(Clone, Copy, PartialEq, Eq)]
 35pub enum AnchorCorner {
 36    TopLeft,
 37    TopRight,
 38    BottomLeft,
 39    BottomRight,
 40}
 41
 42impl AnchorCorner {
 43    fn get_bounds(&self, anchor_position: Vector2F, size: Vector2F) -> RectF {
 44        match self {
 45            Self::TopLeft => RectF::from_points(anchor_position, anchor_position + size),
 46            Self::TopRight => RectF::from_points(
 47                anchor_position - Vector2F::new(size.x(), 0.),
 48                anchor_position + Vector2F::new(0., size.y()),
 49            ),
 50            Self::BottomLeft => RectF::from_points(
 51                anchor_position - Vector2F::new(0., size.y()),
 52                anchor_position + Vector2F::new(size.x(), 0.),
 53            ),
 54            Self::BottomRight => RectF::from_points(anchor_position - size, anchor_position),
 55        }
 56    }
 57
 58    fn switch_axis(self, axis: Axis) -> Self {
 59        match axis {
 60            Axis::Vertical => match self {
 61                AnchorCorner::TopLeft => AnchorCorner::BottomLeft,
 62                AnchorCorner::TopRight => AnchorCorner::BottomRight,
 63                AnchorCorner::BottomLeft => AnchorCorner::TopLeft,
 64                AnchorCorner::BottomRight => AnchorCorner::TopRight,
 65            },
 66            Axis::Horizontal => match self {
 67                AnchorCorner::TopLeft => AnchorCorner::TopRight,
 68                AnchorCorner::TopRight => AnchorCorner::TopLeft,
 69                AnchorCorner::BottomLeft => AnchorCorner::BottomRight,
 70                AnchorCorner::BottomRight => AnchorCorner::BottomLeft,
 71            },
 72        }
 73    }
 74}
 75
 76impl<V: 'static> Overlay<V> {
 77    pub fn new(child: impl Element<V>) -> Self {
 78        Self {
 79            child: child.into_any(),
 80            anchor_position: None,
 81            anchor_corner: AnchorCorner::TopLeft,
 82            fit_mode: OverlayFitMode::None,
 83            position_mode: OverlayPositionMode::Window,
 84            hoverable: false,
 85            z_index: None,
 86        }
 87    }
 88
 89    pub fn with_anchor_position(mut self, position: Vector2F) -> Self {
 90        self.anchor_position = Some(position);
 91        self
 92    }
 93
 94    pub fn with_anchor_corner(mut self, anchor_corner: AnchorCorner) -> Self {
 95        self.anchor_corner = anchor_corner;
 96        self
 97    }
 98
 99    pub fn with_fit_mode(mut self, fit_mode: OverlayFitMode) -> Self {
100        self.fit_mode = fit_mode;
101        self
102    }
103
104    pub fn with_position_mode(mut self, position_mode: OverlayPositionMode) -> Self {
105        self.position_mode = position_mode;
106        self
107    }
108
109    pub fn with_hoverable(mut self, hoverable: bool) -> Self {
110        self.hoverable = hoverable;
111        self
112    }
113
114    pub fn with_z_index(mut self, z_index: usize) -> Self {
115        self.z_index = Some(z_index);
116        self
117    }
118}
119
120impl<V: 'static> Element<V> for Overlay<V> {
121    type LayoutState = Vector2F;
122    type PaintState = ();
123
124    fn layout(
125        &mut self,
126        constraint: SizeConstraint,
127        view: &mut V,
128        cx: &mut LayoutContext<V>,
129    ) -> (Vector2F, Self::LayoutState) {
130        let constraint = if self.anchor_position.is_some() {
131            SizeConstraint::new(Vector2F::zero(), cx.window_size())
132        } else {
133            constraint
134        };
135        let size = self.child.layout(constraint, view, cx);
136        (Vector2F::zero(), size)
137    }
138
139    fn paint(
140        &mut self,
141        bounds: RectF,
142        _: RectF,
143        size: &mut Self::LayoutState,
144        view: &mut V,
145        cx: &mut PaintContext<V>,
146    ) {
147        let (anchor_position, mut bounds) = match self.position_mode {
148            OverlayPositionMode::Window => {
149                let anchor_position = self.anchor_position.unwrap_or_else(|| bounds.origin());
150                let bounds = self.anchor_corner.get_bounds(anchor_position, *size);
151                (anchor_position, bounds)
152            }
153            OverlayPositionMode::Local => {
154                let anchor_position = self.anchor_position.unwrap_or_default();
155                let bounds = self
156                    .anchor_corner
157                    .get_bounds(bounds.origin() + anchor_position, *size);
158                (anchor_position, bounds)
159            }
160        };
161
162        match self.fit_mode {
163            OverlayFitMode::SnapToWindow => {
164                // Snap the horizontal edges of the overlay to the horizontal edges of the window if
165                // its horizontal bounds overflow
166                if bounds.max_x() > cx.window_size().x() {
167                    let mut lower_right = bounds.lower_right();
168                    lower_right.set_x(cx.window_size().x());
169                    bounds = RectF::from_points(lower_right - *size, lower_right);
170                } else if bounds.min_x() < 0. {
171                    let mut upper_left = bounds.origin();
172                    upper_left.set_x(0.);
173                    bounds = RectF::from_points(upper_left, upper_left + *size);
174                }
175
176                // Snap the vertical edges of the overlay to the vertical edges of the window if
177                // its vertical bounds overflow.
178                if bounds.max_y() > cx.window_size().y() {
179                    let mut lower_right = bounds.lower_right();
180                    lower_right.set_y(cx.window_size().y());
181                    bounds = RectF::from_points(lower_right - *size, lower_right);
182                } else if bounds.min_y() < 0. {
183                    let mut upper_left = bounds.origin();
184                    upper_left.set_y(0.);
185                    bounds = RectF::from_points(upper_left, upper_left + *size);
186                }
187            }
188            OverlayFitMode::SwitchAnchor => {
189                let mut anchor_corner = self.anchor_corner;
190
191                if bounds.max_x() > cx.window_size().x() {
192                    anchor_corner = anchor_corner.switch_axis(Axis::Horizontal);
193                }
194
195                if bounds.max_y() > cx.window_size().y() {
196                    anchor_corner = anchor_corner.switch_axis(Axis::Vertical);
197                }
198
199                if bounds.min_x() < 0. {
200                    anchor_corner = anchor_corner.switch_axis(Axis::Horizontal)
201                }
202
203                if bounds.min_y() < 0. {
204                    anchor_corner = anchor_corner.switch_axis(Axis::Vertical)
205                }
206
207                // Update bounds if needed
208                if anchor_corner != self.anchor_corner {
209                    bounds = anchor_corner.get_bounds(anchor_position, *size)
210                }
211            }
212            OverlayFitMode::None => {}
213        }
214
215        cx.scene().push_stacking_context(None, self.z_index);
216        if self.hoverable {
217            enum OverlayHoverCapture {}
218            // Block hovers in lower stacking contexts
219            let view_id = cx.view_id();
220            cx.scene()
221                .push_mouse_region(MouseRegion::new::<OverlayHoverCapture>(
222                    view_id, view_id, bounds,
223                ));
224        }
225        self.child.paint(
226            bounds.origin(),
227            RectF::new(Vector2F::zero(), cx.window_size()),
228            view,
229            cx,
230        );
231        cx.scene().pop_stacking_context();
232    }
233
234    fn rect_for_text_range(
235        &self,
236        range_utf16: Range<usize>,
237        _: RectF,
238        _: RectF,
239        _: &Self::LayoutState,
240        _: &Self::PaintState,
241        view: &V,
242        cx: &ViewContext<V>,
243    ) -> Option<RectF> {
244        self.child.rect_for_text_range(range_utf16, view, cx)
245    }
246
247    fn debug(
248        &self,
249        _: RectF,
250        _: &Self::LayoutState,
251        _: &Self::PaintState,
252        view: &V,
253        cx: &ViewContext<V>,
254    ) -> serde_json::Value {
255        json!({
256            "type": "Overlay",
257            "abs_position": self.anchor_position.to_json(),
258            "child": self.child.debug(view, cx),
259        })
260    }
261}