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    /// Converts a distance from the start edge to a physical horizontal position.
22    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    /// Whether the start edge is the right one.
30    pub fn is_rtl(self) -> bool {
31        matches!(self, LayoutDirection::Rtl)
32    }
33
34    /// The direction that reads the other way.
35    pub fn reversed(self) -> Self {
36        match self {
37            LayoutDirection::Ltr => LayoutDirection::Rtl,
38            LayoutDirection::Rtl => LayoutDirection::Ltr,
39        }
40    }
41
42    /// Turns start/end values into physical left/right values.
43    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
51/// The [`CompositionLocal`] carrying the current layout direction.
52pub 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
61/// The layout direction in force here.
62pub fn layout_direction() -> LayoutDirection {
63    local_layout_direction().current()
64}
65
66/// Runs `content` in `direction`.
67#[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;