use cranpose_core::{CompositionLocal, CompositionLocalProvider, compositionLocalOf};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum LayoutDirection {
#[default]
Ltr,
Rtl,
}
impl LayoutDirection {
pub fn place_x(self, start: f32, width: f32, item_width: f32) -> f32 {
if self.is_rtl() {
width - start - item_width
} else {
start
}
}
pub fn is_rtl(self) -> bool {
matches!(self, LayoutDirection::Rtl)
}
pub fn reversed(self) -> Self {
match self {
LayoutDirection::Ltr => LayoutDirection::Rtl,
LayoutDirection::Rtl => LayoutDirection::Ltr,
}
}
pub fn resolve(self, start: f32, end: f32) -> (f32, f32) {
match self {
LayoutDirection::Ltr => (start, end),
LayoutDirection::Rtl => (end, start),
}
}
}
pub fn local_layout_direction() -> CompositionLocal<LayoutDirection> {
crate::environment_locals::ENVIRONMENT_LOCALS.with(|locals| {
locals
.direction
.get_or_init(|| compositionLocalOf(LayoutDirection::default))
.clone()
})
}
pub fn layout_direction() -> LayoutDirection {
crate::environment_locals::ENVIRONMENT_LOCALS.with(|locals| {
locals
.direction
.get_or_init(|| compositionLocalOf(LayoutDirection::default))
.current()
})
}
#[expect(non_snake_case)]
#[track_caller]
pub fn ProvideLayoutDirection(direction: LayoutDirection, content: impl FnOnce()) {
CompositionLocalProvider([local_layout_direction().provides(direction)], content);
}
#[cfg(test)]
#[path = "tests/layout_direction_tests.rs"]
mod tests;