//! Widget wrapper for horizontal alignment. //! //! `Aligned` lets a child render left, centered, or right inside a wider //! rectangle without changing the child widget itself. It is useful for small //! layout adjustments at the edge of a composed view. use super::{Buffer, Constraint, Rect, Size, Widget}; /// Horizontal alignment for a widget inside an allocated width. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Align { /// Keep content at the left edge. Left, /// Keep content at the right edge. Right, } /// Widget wrapper that aligns its child within the parent width. #[derive(Debug)] pub struct Aligned { /// Wrapped widget. child: T, /// Horizontal alignment mode. align: Align, } impl Aligned { /// Creates an aligned wrapper around a child widget. pub fn new(child: T, align: Align) -> Self { Self { child, align } } } impl Widget for Aligned { fn size(&self, parent: Constraint) -> Size { let child = self.child.size(parent); let cols = if parent.max.cols == usize::MAX { child.cols } else { parent.max.cols.max(child.cols) }; Size::new(cols, child.rows).constrain(parent) } fn render(&mut self, area: Rect, buf: &mut Buffer) { let child = self.child.size(Constraint::max(area.size())); let cols = child.cols.min(area.cols); let x = match self.align { Align::Left => area.x, Align::Right => area.x + area.cols.saturating_sub(cols), } .min(area.right()); self.child .render(Rect::new(x, area.y, cols, area.rows), buf); } } #[cfg(test)] mod tests { use super::*; use crate::Line; #[test] fn left_alignment_pads_to_parent_width() { let mut aligned = Aligned::new(Line::new("cat"), Align::Left); assert_eq!(aligned.display(Constraint::tight(6)), "cat \n"); } #[test] fn right_alignment_pads_before_content() { let mut aligned = Aligned::new(Line::new("cat"), Align::Right); assert_eq!(aligned.display(Constraint::tight(6)), " cat\n"); } #[test] fn alignment_truncates_content_to_allocated_width() { let mut aligned = Aligned::new(Line::new("abcdef"), Align::Left); assert_eq!(aligned.display(Constraint::tight(4)), "abc…\n"); } }