cranpose_ui/
layout_direction.rs1use cranpose_core::{CompositionLocalProvider, StaticCompositionLocal, staticCompositionLocalOf};
9
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
12pub enum LayoutDirection {
13 #[default]
15 Ltr,
16 Rtl,
18}
19
20impl LayoutDirection {
21 pub fn place_x(self, start: f32, width: f32, item_width: f32) -> f32 {
23 if self.is_rtl() {
24 width - start - item_width
25 } else {
26 start
27 }
28 }
29 pub fn is_rtl(self) -> bool {
31 matches!(self, LayoutDirection::Rtl)
32 }
33
34 pub fn reversed(self) -> Self {
36 match self {
37 LayoutDirection::Ltr => LayoutDirection::Rtl,
38 LayoutDirection::Rtl => LayoutDirection::Ltr,
39 }
40 }
41
42 pub fn resolve(self, start: f32, end: f32) -> (f32, f32) {
44 match self {
45 LayoutDirection::Ltr => (start, end),
46 LayoutDirection::Rtl => (end, start),
47 }
48 }
49}
50
51pub fn local_layout_direction() -> StaticCompositionLocal<LayoutDirection> {
57 crate::thread_state::with_environment(|locals| {
58 locals
59 .direction
60 .get_or_init(|| staticCompositionLocalOf(LayoutDirection::default))
61 .clone()
62 })
63}
64
65pub fn layout_direction() -> LayoutDirection {
67 crate::thread_state::with_environment(|locals| {
68 locals
69 .direction
70 .get_or_init(|| staticCompositionLocalOf(LayoutDirection::default))
71 .current()
72 })
73}
74
75#[expect(non_snake_case)]
77#[track_caller]
78pub fn ProvideLayoutDirection(direction: LayoutDirection, content: impl FnOnce()) {
79 CompositionLocalProvider([local_layout_direction().provides(direction)], content);
80}
81
82#[cfg(test)]
83#[path = "tests/layout_direction_tests.rs"]
84mod tests;