use std::cell::RefCell;
use cranpose_core::{CompositionLocal, compositionLocalOf};
use cranpose_ui_graphics::EdgeInsets;
use crate::Modifier;
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct WindowInsets {
pub safe_area: EdgeInsets,
pub ime: EdgeInsets,
}
impl WindowInsets {
pub fn combined(self) -> EdgeInsets {
EdgeInsets::from_components(
self.safe_area.left.max(self.ime.left),
self.safe_area.top.max(self.ime.top),
self.safe_area.right.max(self.ime.right),
self.safe_area.bottom.max(self.ime.bottom),
)
}
}
pub fn local_safe_area_insets() -> CompositionLocal<EdgeInsets> {
thread_local! {
static LOCAL: RefCell<Option<CompositionLocal<EdgeInsets>>> = const { RefCell::new(None) };
}
LOCAL.with(|cell| {
cell.borrow_mut()
.get_or_insert_with(|| compositionLocalOf(EdgeInsets::default))
.clone()
})
}
pub fn local_ime_insets() -> CompositionLocal<EdgeInsets> {
thread_local! {
static LOCAL: RefCell<Option<CompositionLocal<EdgeInsets>>> = const { RefCell::new(None) };
}
LOCAL.with(|cell| {
cell.borrow_mut()
.get_or_insert_with(|| compositionLocalOf(EdgeInsets::default))
.clone()
})
}
pub fn window_insets() -> WindowInsets {
WindowInsets {
safe_area: local_safe_area_insets().current(),
ime: local_ime_insets().current(),
}
}
impl Modifier {
pub fn window_insets_padding(self, insets: EdgeInsets) -> Self {
self.padding_each(insets.left, insets.top, insets.right, insets.bottom)
}
pub fn safe_area_padding(self) -> Self {
self.window_insets_padding(local_safe_area_insets().current())
}
}
#[cfg(test)]
#[path = "tests/safe_area_tests.rs"]
mod tests;