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#[expect(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)]
69#[path = "tests/layout_direction_tests.rs"]
70mod tests;