crates/tui-core/src/aligned.rs 2.3 KiB raw
1
//! Widget wrapper for horizontal alignment.
2
//!
3
//! `Aligned` lets a child render left, centered, or right inside a wider
4
//! rectangle without changing the child widget itself. It is useful for small
5
//! layout adjustments at the edge of a composed view.
6
7
use super::{Buffer, Constraint, Rect, Size, Widget};
8
9
/// Horizontal alignment for a widget inside an allocated width.
10
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11
pub enum Align {
12
    /// Keep content at the left edge.
13
    Left,
14
    /// Keep content at the right edge.
15
    Right,
16
}
17
18
/// Widget wrapper that aligns its child within the parent width.
19
#[derive(Debug)]
20
pub struct Aligned<T> {
21
    /// Wrapped widget.
22
    child: T,
23
    /// Horizontal alignment mode.
24
    align: Align,
25
}
26
27
impl<T> Aligned<T> {
28
    /// Creates an aligned wrapper around a child widget.
29
    pub fn new(child: T, align: Align) -> Self {
30
        Self { child, align }
31
    }
32
}
33
34
impl<T: Widget> Widget for Aligned<T> {
35
    fn size(&self, parent: Constraint) -> Size {
36
        let child = self.child.size(parent);
37
        let cols = if parent.max.cols == usize::MAX {
38
            child.cols
39
        } else {
40
            parent.max.cols.max(child.cols)
41
        };
42
        Size::new(cols, child.rows).constrain(parent)
43
    }
44
45
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
46
        let child = self.child.size(Constraint::max(area.size()));
47
        let cols = child.cols.min(area.cols);
48
        let x = match self.align {
49
            Align::Left => area.x,
50
            Align::Right => area.x + area.cols.saturating_sub(cols),
51
        }
52
        .min(area.right());
53
54
        self.child
55
            .render(Rect::new(x, area.y, cols, area.rows), buf);
56
    }
57
}
58
59
#[cfg(test)]
60
mod tests {
61
    use super::*;
62
    use crate::Line;
63
64
    #[test]
65
    fn left_alignment_pads_to_parent_width() {
66
        let mut aligned = Aligned::new(Line::new("cat"), Align::Left);
67
68
        assert_eq!(aligned.display(Constraint::tight(6)), "cat   \n");
69
    }
70
71
    #[test]
72
    fn right_alignment_pads_before_content() {
73
        let mut aligned = Aligned::new(Line::new("cat"), Align::Right);
74
75
        assert_eq!(aligned.display(Constraint::tight(6)), "   cat\n");
76
    }
77
78
    #[test]
79
    fn alignment_truncates_content_to_allocated_width() {
80
        let mut aligned = Aligned::new(Line::new("abcdef"), Align::Left);
81
82
        assert_eq!(aligned.display(Constraint::tight(4)), "abc…\n");
83
    }
84
}