cranpose_ui/
layout_direction.rs1use cranpose_core::{CompositionLocal, CompositionLocalProvider, compositionLocalOf};
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() -> CompositionLocal<LayoutDirection> {
53 crate::environment_locals::ENVIRONMENT_LOCALS.with(|locals| {
54 locals
55 .direction
56 .get_or_init(|| compositionLocalOf(LayoutDirection::default))
57 .clone()
58 })
59}
60
61pub fn layout_direction() -> LayoutDirection {
63 local_layout_direction().current()
64}
65
66#[expect(non_snake_case)]
68#[track_caller]
69pub fn ProvideLayoutDirection(direction: LayoutDirection, content: impl FnOnce()) {
70 CompositionLocalProvider([local_layout_direction().provides(direction)], content);
71}
72
73#[cfg(test)]
74#[path = "tests/layout_direction_tests.rs"]
75mod tests;