Skip to main content

cranpose_ui_layout/
alignment.rs

1//! Alignment utilities for positioning content
2
3/// Alignment across both axes used for positioning content within a box.
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub struct Alignment {
6    /// Horizontal alignment component.
7    pub horizontal: HorizontalAlignment,
8    /// Vertical alignment component.
9    pub vertical: VerticalAlignment,
10}
11
12impl Alignment {
13    /// Creates a new [`Alignment`] from explicit horizontal and vertical components.
14    pub const fn new(horizontal: HorizontalAlignment, vertical: VerticalAlignment) -> Self {
15        Self {
16            horizontal,
17            vertical,
18        }
19    }
20
21    /// Align children to the top-start corner.
22    pub const TOP_START: Self = Self::new(HorizontalAlignment::Start, VerticalAlignment::Top);
23
24    /// Align children to the center of the parent.
25    pub const CENTER: Self = Self::new(
26        HorizontalAlignment::CenterHorizontally,
27        VerticalAlignment::CenterVertically,
28    );
29
30    /// Align children to the bottom-end corner.
31    pub const BOTTOM_END: Self = Self::new(HorizontalAlignment::End, VerticalAlignment::Bottom);
32}
33
34/// Alignment along the horizontal axis.
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub enum HorizontalAlignment {
37    /// Align children to the leading edge.
38    Start,
39    /// Align children to the horizontal center.
40    CenterHorizontally,
41    /// Align children to the trailing edge.
42    End,
43}
44
45impl HorizontalAlignment {
46    /// Computes the horizontal offset for alignment.
47    pub fn align(&self, available: f32, child: f32) -> f32 {
48        match self {
49            HorizontalAlignment::Start => 0.0,
50            HorizontalAlignment::CenterHorizontally => ((available - child) / 2.0).max(0.0),
51            HorizontalAlignment::End => (available - child).max(0.0),
52        }
53    }
54}
55
56/// Alignment along the vertical axis.
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub enum VerticalAlignment {
59    /// Align children to the top edge.
60    Top,
61    /// Align children to the vertical center.
62    CenterVertically,
63    /// Align children to the bottom edge.
64    Bottom,
65}
66
67impl VerticalAlignment {
68    /// Computes the vertical offset for alignment.
69    pub fn align(&self, available: f32, child: f32) -> f32 {
70        match self {
71            VerticalAlignment::Top => 0.0,
72            VerticalAlignment::CenterVertically => ((available - child) / 2.0).max(0.0),
73            VerticalAlignment::Bottom => (available - child).max(0.0),
74        }
75    }
76}