tui-core: Add responsive table columns

e2a68436b10df6d2a1a5cd2772d158175c72014a
Let tables flex selected columns and collapse lower-priority columns as
their available width contracts.

Assisted-by: Codex:gpt-5.6-sol
Alexis Sellier committed ago 1 parent f0d31e3a
crates/tui-core/src/lib.rs +1 -1
68 68
pub use frame::Frame;
69 69
pub use hstack::HStack;
70 70
pub use label::{Label, label};
71 71
pub use layout::{Direction, Length, Point, Rect};
72 72
pub use primitive::{Constraint, Line, Size, StyledLine};
73 -
pub use table::{Table, TableOptions};
73 +
pub use table::{Column, Table, TableOptions};
74 74
pub use terminal::Terminal;
75 75
pub use textarea::{TextArea, textarea};
76 76
pub use vstack::{VStack, VStackOptions};
77 77
pub use widget::{Block, Clear, Fill, RenderResult, StatefulWidget, Widget};
crates/tui-core/src/table.rs +172 -9
31 31
//! ``` plain
32 32
//! pest        biological control
33 33
//! aphid       lacewing
34 34
//! spider mite ladybug
35 35
//! ```
36 -
use std::fmt;
36 +
use std::{fmt, num::NonZeroUsize};
37 37
38 38
use super::cell::Text;
39 39
use super::{Border, Buffer, Constraint, Line, Size, Style, Widget, colors};
40 40
41 41
/// Rendering options for a table.
67 67
            spacing: 3,
68 68
            ..Self::default()
69 69
        }
70 70
    }
71 71
}
72 +
/// Responsive behavior for one table column.
73 +
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
74 +
pub struct Column {
75 +
    /// Relative share of horizontal space assigned to this column.
76 +
    flex: usize,
77 +
    /// Order in which this column disappears as space contracts.
78 +
    collapse: Option<usize>,
79 +
}
80 +
81 +
impl Column {
82 +
    /// Returns a column that uses its intrinsic content width.
83 +
    pub const fn auto() -> Self {
84 +
        Self {
85 +
            flex: 0,
86 +
            collapse: None,
87 +
        }
88 +
    }
89 +
90 +
    /// Returns a column that receives this relative share of available width.
91 +
    pub const fn flex(flex: usize) -> Self {
92 +
        Self {
93 +
            flex,
94 +
            collapse: None,
95 +
        }
96 +
    }
97 +
98 +
    /// Returns an intrinsic-width column that disappears at `order`.
99 +
    pub const fn collapse(order: usize) -> Self {
100 +
        Self {
101 +
            flex: 0,
102 +
            collapse: Some(order),
103 +
        }
104 +
    }
105 +
}
72 106
73 107
/// Internal row representation for table rendering.
74 108
#[derive(Debug)]
75 109
enum Row<const W: usize, T> {
76 110
    /// Header row.
96 130
    rows: Vec<Row<W, T>>,
97 131
    /// Maximum content width for each column.
98 132
    widths: [usize; W],
99 133
    /// Rendering options.
100 134
    opts: TableOptions,
135 +
    /// Responsive behavior for each column.
136 +
    layout: [Column; W],
101 137
}
102 138
103 139
impl<const W: usize, T> Default for Table<W, T> {
104 140
    fn default() -> Self {
105 141
        Self {
106 142
            rows: Vec::new(),
107 143
            widths: [0; W],
108 144
            opts: TableOptions::default(),
145 +
            layout: [Column::auto(); W],
109 146
        }
110 147
    }
111 148
}
112 149
113 150
impl<const W: usize, T: Text> FromIterator<[T; W]> for Table<W, T> {
198 235
    ) -> Line {
199 236
        let mut line = Line::default();
200 237
        if let Some(border) = border {
201 238
            line.push(border.left(1));
202 239
        }
203 -
        for (i, cell) in cells.iter().enumerate() {
204 -
            let pad = if i + 1 == W {
205 -
                0
206 -
            } else {
207 -
                self.widths[i] + self.opts.spacing
208 -
            };
209 -
            let cell_style = style.unwrap_or_else(|| Style::default().bg(cell.background()));
210 -
            line = line.extend(cell.pad(pad).into().style(cell_style));
240 +
        if self.layout == [Column::auto(); W] {
241 +
            for (i, cell) in cells.iter().enumerate() {
242 +
                let pad = if i + 1 == W {
243 +
                    0
244 +
                } else {
245 +
                    self.widths[i] + self.opts.spacing
246 +
                };
247 +
                let cell_style = style.unwrap_or_else(|| Style::default().bg(cell.background()));
248 +
                line = line.extend(cell.pad(pad).into().style(cell_style));
249 +
            }
250 +
        } else {
251 +
            let (widths, visible) = self.column_widths(cols);
252 +
            let last = visible.iter().rposition(|visible| *visible);
253 +
            for (i, cell) in cells.iter().enumerate() {
254 +
                if !visible[i] {
255 +
                    continue;
256 +
                }
257 +
                let spacing = usize::from(Some(i) != last) * self.opts.spacing;
258 +
                let cell_style = style.unwrap_or_else(|| Style::default().bg(cell.background()));
259 +
                let mut cell: Line = cell.pad(widths[i]).into();
260 +
                Line::truncate(&mut cell, widths[i], "…");
261 +
                Line::pad(&mut cell, widths[i] + spacing);
262 +
                line = line.extend(cell.style(cell_style));
263 +
            }
211 264
        }
212 265
        Line::pad(&mut line, cols);
213 266
        Line::truncate(&mut line, cols, "…");
214 267
        if let Some(row_style) = style {
215 268
            line = line.style(row_style);
217 270
        if let Some(border) = border {
218 271
            line.push(border.right(1));
219 272
        }
220 273
        line
221 274
    }
275 +
276 +
    /// Returns rendered widths and visibility under `cols`.
277 +
    fn column_widths(&self, cols: usize) -> ([usize; W], [bool; W]) {
278 +
        let mut widths = self.widths;
279 +
        let mut visible = [true; W];
280 +
        let mut visible_count = W;
281 +
        let mut natural =
282 +
            widths.iter().sum::<usize>() + visible_count.saturating_sub(1) * self.opts.spacing;
283 +
284 +
        while natural > cols {
285 +
            let Some((index, _)) = self
286 +
                .layout
287 +
                .iter()
288 +
                .enumerate()
289 +
                .filter(|(index, column)| visible[*index] && column.collapse.is_some())
290 +
                .min_by_key(|(index, column)| (column.collapse, *index))
291 +
            else {
292 +
                break;
293 +
            };
294 +
            visible[index] = false;
295 +
            natural = natural.saturating_sub(widths[index]);
296 +
            visible_count -= 1;
297 +
            if visible_count > 0 {
298 +
                natural = natural.saturating_sub(self.opts.spacing);
299 +
            }
300 +
        }
301 +
302 +
        let spacing = visible_count.saturating_sub(1) * self.opts.spacing;
303 +
        let available = cols.saturating_sub(spacing);
304 +
        let fixed = self
305 +
            .layout
306 +
            .iter()
307 +
            .enumerate()
308 +
            .filter(|(index, column)| visible[*index] && column.flex == 0)
309 +
            .map(|(index, _)| widths[index])
310 +
            .sum::<usize>();
311 +
        let flex = self
312 +
            .layout
313 +
            .iter()
314 +
            .enumerate()
315 +
            .filter(|(index, _)| visible[*index])
316 +
            .map(|(_, column)| column.flex)
317 +
            .sum::<usize>();
318 +
        let Some(flex) = NonZeroUsize::new(flex) else {
319 +
            return (widths, visible);
320 +
        };
321 +
        let available = available.saturating_sub(fixed);
322 +
        let mut assigned = 0;
323 +
        for (index, column) in self.layout.iter().enumerate() {
324 +
            if !visible[index] || column.flex == 0 {
325 +
                continue;
326 +
            }
327 +
            let width = available.saturating_mul(column.flex) / flex.get();
328 +
            widths[index] = width;
329 +
            assigned += width;
330 +
        }
331 +
        if let Some(index) = self
332 +
            .layout
333 +
            .iter()
334 +
            .enumerate()
335 +
            .rfind(|(index, column)| visible[*index] && column.flex > 0)
336 +
            .map(|(index, _)| index)
337 +
        {
338 +
            widths[index] += available - assigned;
339 +
        }
340 +
        (widths, visible)
341 +
    }
222 342
}
223 343
224 344
impl<const W: usize, T: Text> Table<W, T> {
225 345
    /// Creates an empty table with explicit options.
226 346
    pub fn new(opts: TableOptions) -> Self {
227 347
        Self {
228 348
            rows: Vec::new(),
229 349
            widths: [0; W],
230 350
            opts,
351 +
            layout: [Column::auto(); W],
231 352
        }
232 353
    }
233 354
234 355
    /// Returns the table with replacement options.
235 356
    pub fn with_opts(mut self, opts: TableOptions) -> Self {
236 357
        self.opts = opts;
237 358
        self
238 359
    }
360 +
    /// Returns the table with responsive column behavior.
361 +
    pub fn with_layout(mut self, layout: [Column; W]) -> Self {
362 +
        self.layout = layout;
363 +
        self
364 +
    }
239 365
240 366
    /// Adds a data row and returns the table.
241 367
    pub fn row(mut self, row: [T; W]) -> Self {
242 368
        self.push(row);
243 369
        self
576 702
            .collect::<Table<2, _>>();
577 703
578 704
        assert_eq!(t.display(Constraint::UNBOUNDED), "a     beta\nalpha b   \n");
579 705
    }
580 706
707 +
    #[test]
708 +
    fn responsive_columns_flex_and_collapse_in_order() {
709 +
        let mut table = Table::new(TableOptions::default()).with_layout([
710 +
            Column::auto(),
711 +
            Column::flex(1),
712 +
            Column::collapse(2),
713 +
            Column::collapse(1),
714 +
            Column::auto(),
715 +
            Column::collapse(3),
716 +
        ]);
717 +
        table.push(["id", "summarywide", "alice", "branch", "progress", "stats"]);
718 +
719 +
        let branch_hidden = table
720 +
            .lines(Constraint::tight(35))
721 +
            .pop()
722 +
            .unwrap()
723 +
            .to_string();
724 +
        let author_hidden = table
725 +
            .lines(Constraint::tight(34))
726 +
            .pop()
727 +
            .unwrap()
728 +
            .to_string();
729 +
        let stats_hidden = table
730 +
            .lines(Constraint::tight(20))
731 +
            .pop()
732 +
            .unwrap()
733 +
            .to_string();
734 +
735 +
        assert!(!branch_hidden.contains("branch"));
736 +
        assert!(branch_hidden.contains("alice"));
737 +
        assert!(!author_hidden.contains("alice"));
738 +
        assert!(author_hidden.contains("stats"));
739 +
        assert_eq!(branch_hidden, "id summarywide alice progress stats");
740 +
        assert_eq!(author_hidden, "id summarywide      progress stats");
741 +
        assert_eq!(stats_hidden, "id summary… progress");
742 +
    }
743 +
581 744
    #[test]
582 745
    fn extend_appends_data_rows_and_updates_widths() {
583 746
        let mut t = Table::default();
584 747
585 748
        t.push(["a", "b"]);