Skip to main content

cranpose_ui/
layout_direction.rs

1//! Which way the interface reads.
2//!
3//! Layout direction is what turns "start" and "end" into "left" and "right".
4//! It is a composition local rather than a global so a screen can pin a
5//! direction — a code block, a phone number, a language picker — without
6//! reversing the rest of the interface with it.
7
8use cranpose_core::{CompositionLocal, CompositionLocalProvider, compositionLocalOf};
9
10/// Which side of the interface is the start.
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
12pub enum LayoutDirection {
13    /// Start is the left edge — Latin, Cyrillic, CJK.
14    #[default]
15    Ltr,
16    /// Start is the right edge — Arabic, Hebrew.
17    Rtl,
18}
19
20impl LayoutDirection {
21    /// Whether the start edge is the right one.
22    pub fn is_rtl(self) -> bool {
23        matches!(self, LayoutDirection::Rtl)
24    }
25
26    /// The direction that reads the other way.
27    pub fn reversed(self) -> Self {
28        match self {
29            LayoutDirection::Ltr => LayoutDirection::Rtl,
30            LayoutDirection::Rtl => LayoutDirection::Ltr,
31        }
32    }
33
34    /// Turns start/end values into physical left/right values.
35    pub fn resolve(self, start: f32, end: f32) -> (f32, f32) {
36        match self {
37            LayoutDirection::Ltr => (start, end),
38            LayoutDirection::Rtl => (end, start),
39        }
40    }
41}
42
43/// The [`CompositionLocal`] carrying the current layout direction.
44pub fn local_layout_direction() -> CompositionLocal<LayoutDirection> {
45    thread_local! {
46        static LOCAL: std::cell::RefCell<Option<CompositionLocal<LayoutDirection>>> =
47            const { std::cell::RefCell::new(None) };
48    }
49    LOCAL.with(|cell| {
50        cell.borrow_mut()
51            .get_or_insert_with(|| compositionLocalOf(LayoutDirection::default))
52            .clone()
53    })
54}
55
56/// The layout direction in force here.
57pub fn layout_direction() -> LayoutDirection {
58    local_layout_direction().current()
59}
60
61/// Runs `content` in `direction`.
62#[allow(non_snake_case)]
63#[track_caller]
64pub fn ProvideLayoutDirection(direction: LayoutDirection, content: impl FnOnce()) {
65    CompositionLocalProvider(vec![local_layout_direction().provides(direction)], content);
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71
72    #[test]
73    fn resolving_start_and_end_follows_the_direction() {
74        assert_eq!(LayoutDirection::Ltr.resolve(4.0, 12.0), (4.0, 12.0));
75        assert_eq!(LayoutDirection::Rtl.resolve(4.0, 12.0), (12.0, 4.0));
76    }
77
78    #[test]
79    fn a_direction_knows_its_opposite() {
80        assert_eq!(LayoutDirection::Ltr.reversed(), LayoutDirection::Rtl);
81        assert!(!LayoutDirection::Ltr.is_rtl());
82        assert!(LayoutDirection::Rtl.is_rtl());
83    }
84
85    #[test]
86    fn a_provided_direction_reaches_the_content_and_ends_with_it() {
87        use std::{cell::Cell, rc::Rc};
88
89        use cranpose_core::{Composition, MemoryApplier, location_key};
90
91        let mut composition = Composition::new(MemoryApplier::new());
92        let outer = Rc::new(Cell::new(LayoutDirection::Rtl));
93        let inside = Rc::new(Cell::new(LayoutDirection::Ltr));
94        let nested = Rc::new(Cell::new(LayoutDirection::Rtl));
95        let after = Rc::new(Cell::new(LayoutDirection::Rtl));
96
97        let key = location_key(file!(), line!(), column!());
98        {
99            let (outer, inside, nested, after) = (
100                Rc::clone(&outer),
101                Rc::clone(&inside),
102                Rc::clone(&nested),
103                Rc::clone(&after),
104            );
105            let mut render = move || {
106                outer.set(layout_direction());
107                ProvideLayoutDirection(LayoutDirection::Rtl, || {
108                    inside.set(layout_direction());
109                    ProvideLayoutDirection(LayoutDirection::Ltr, || nested.set(layout_direction()));
110                });
111                after.set(layout_direction());
112            };
113            composition.render(key, &mut render).expect("render");
114        }
115
116        assert_eq!(outer.get(), LayoutDirection::Ltr);
117        assert_eq!(inside.get(), LayoutDirection::Rtl);
118        assert_eq!(nested.get(), LayoutDirection::Ltr);
119        assert_eq!(after.get(), LayoutDirection::Ltr);
120    }
121
122    #[test]
123    fn the_composition_local_is_one_instance_per_thread() {
124        use std::{cell::Cell, rc::Rc};
125
126        use cranpose_core::{Composition, MemoryApplier, location_key};
127
128        let mut composition = Composition::new(MemoryApplier::new());
129        let seen = Rc::new(Cell::new(LayoutDirection::Ltr));
130        let recorder = Rc::clone(&seen);
131        let key = location_key(file!(), line!(), column!());
132        let mut render = move || {
133            CompositionLocalProvider(
134                vec![local_layout_direction().provides(LayoutDirection::Rtl)],
135                || recorder.set(local_layout_direction().current()),
136            );
137        };
138        composition.render(key, &mut render).expect("render");
139
140        assert_eq!(seen.get(), LayoutDirection::Rtl);
141    }
142}