polyhorn_ui/hooks/
safe_area_insets.rs

1use polyhorn_core::UseContext;
2use std::ops::Deref;
3
4use crate::geometry::ByEdge;
5use crate::layout::{LayoutAxisX, LayoutAxisY};
6
7/// Immutable structure that contains the layout direction independent insets
8/// of the safe area of a view with respect to each edge of its rectangle. All
9/// insets are positive numbers.
10#[derive(Copy, Clone, Debug, PartialEq)]
11pub struct SafeAreaInsets(ByEdge<f32>);
12
13impl SafeAreaInsets {
14    /// Returns a new safe area insets structure with the given values in
15    /// clockwise order starting with the top edge. The insets are layout
16    /// direction independent.
17    pub fn new(top: f32, right: f32, bottom: f32, left: f32) -> SafeAreaInsets {
18        SafeAreaInsets(ByEdge {
19            horizontal: LayoutAxisX::DirectionIndependent { left, right },
20            vertical: LayoutAxisY { top, bottom },
21        })
22    }
23}
24
25impl Deref for SafeAreaInsets {
26    type Target = ByEdge<f32>;
27
28    fn deref(&self) -> &Self::Target {
29        &self.0
30    }
31}
32
33/// Hook that is implemented by any type that can provide its safe area insets.
34pub trait UseSafeAreaInsets {
35    /// This function should returns the safe area insets of a view.
36    fn use_safe_area_insets(&mut self) -> SafeAreaInsets;
37}
38
39impl<T> UseSafeAreaInsets for T
40where
41    T: UseContext,
42{
43    fn use_safe_area_insets(&mut self) -> SafeAreaInsets {
44        self.use_context()
45            .and_then(|context| context.to_owned())
46            .unwrap_or(SafeAreaInsets(Default::default()))
47    }
48}
49
50/// Hook that returns the safe area insets of a view.
51#[macro_export]
52macro_rules! use_safe_area_insets {
53    ($manager:expr) => {
54        $crate::hooks::UseSafeAreaInsets::use_safe_area_insets($manager)
55    };
56}