Skip to main content

rusty_rich/
columns.rs

1//! Columns — render renderables side by side. Equivalent to Rich's `columns.py`.
2
3use crate::console::{ConsoleOptions, DynRenderable, RenderResult, Renderable};
4use crate::segment::Segment;
5
6/// Renders a set of renderables in side-by-side columns.
7#[derive(Clone)]
8pub struct Columns {
9    pub renderables: Vec<DynRenderable>,
10    pub equal: bool,
11    pub expand: bool,
12    pub padding: usize,
13    pub width: Option<usize>,
14}
15
16impl std::fmt::Debug for Columns {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        f.debug_struct("Columns")
19            .field("count", &self.renderables.len())
20            .field("equal", &self.equal)
21            .finish()
22    }
23}
24
25impl Columns {
26    /// Create an empty [`Columns`] container.
27    ///
28    /// # Examples
29    ///
30    /// ```rust
31    /// use rusty_rich::Columns;
32    ///
33    /// let mut cols = Columns::new();
34    /// cols.add("item 1");
35    /// cols.add("item 2");
36    /// ```
37    pub fn new() -> Self {
38        Self {
39            renderables: Vec::new(),
40            equal: false,
41            expand: false,
42            padding: 1,
43            width: None,
44        }
45    }
46
47    /// Add a renderable to the column layout.
48    pub fn add(&mut self, renderable: impl Renderable + Send + Sync + 'static) {
49        self.renderables.push(DynRenderable::new(renderable));
50    }
51
52    /// Builder: set padding between columns (in characters).
53    pub fn padding(mut self, padding: usize) -> Self { self.padding = padding; self }
54    /// Builder: force all columns to have equal width.
55    pub fn equal(mut self) -> Self { self.equal = true; self }
56    /// Builder: expand columns to fill the available width.
57    pub fn expand(mut self) -> Self { self.expand = true; self }
58}
59
60impl Renderable for Columns {
61    fn render(&self, options: &ConsoleOptions) -> RenderResult {
62        let count = self.renderables.len();
63        if count == 0 {
64            return RenderResult::new();
65        }
66
67        let available = self.width.unwrap_or(options.max_width);
68        let total_padding = (count.saturating_sub(1)) * self.padding;
69        let col_width = if self.equal {
70            (available.saturating_sub(total_padding)) / count
71        } else {
72            available.saturating_sub(total_padding) / count
73        };
74
75        // Render each column
76        let rendered: Vec<RenderResult> = self
77            .renderables
78            .iter()
79            .map(|r| r.render(&options.update_width(col_width.max(1))))
80            .collect();
81
82        // Find max lines
83        let max_lines = rendered.iter().map(|r| r.lines.len()).max().unwrap_or(0);
84
85        let mut lines: Vec<Vec<Segment>> = Vec::new();
86
87        for line_idx in 0..max_lines {
88            let mut line_segments: Vec<Segment> = Vec::new();
89
90            for (col_idx, col_result) in rendered.iter().enumerate() {
91                if col_idx > 0 {
92                    line_segments.push(Segment::new(" ".repeat(self.padding)));
93                }
94
95                if let Some(col_line) = col_result.lines.get(line_idx) {
96                    line_segments.extend(col_line.iter().cloned());
97                } else {
98                    // Fill with spaces
99                    line_segments.push(Segment::new(" ".repeat(col_width)));
100                }
101            }
102
103            if line_idx < max_lines - 1 {
104                line_segments.push(Segment::line());
105            }
106            lines.push(line_segments);
107        }
108
109        RenderResult { lines, items: Vec::new() }
110    }
111}
112
113impl Default for Columns {
114    fn default() -> Self {
115        Self::new()
116    }
117}