Skip to main content

ratatui_table/
table.rs

1//! The [`Table`] widget is used to display multiple rows and columns in a grid and allows selecting
2//! one or multiple cells.
3
4use alloc::sync::Arc;
5use alloc::vec;
6use alloc::vec::Vec;
7use core::hash::Hasher;
8use core::panic::RefUnwindSafe;
9use core::{fmt, ptr};
10
11use itertools::Itertools;
12use ratatui_core::buffer::Buffer;
13use ratatui_core::layout::{Constraint, Flex, Layout, Rect};
14use ratatui_core::style::{Style, Styled};
15use ratatui_core::symbols::line;
16use ratatui_core::text::Text;
17use ratatui_core::widgets::{StatefulWidget, Widget};
18use ratatui_widgets::block::{Block, BlockExt};
19
20use self::border_grid::BorderGrid;
21pub use self::cell::Cell;
22pub use self::highlight_placement::HighlightPlacement;
23pub use self::highlight_spacing::HighlightSpacing;
24pub use self::row::Row;
25pub use self::state::TableState;
26pub use self::table_borders::TableBorders;
27
28mod border_grid;
29mod cell;
30mod highlight_placement;
31mod highlight_spacing;
32mod row;
33mod state;
34mod table_borders;
35
36/// Supplies the height of a lazy row *without* building it.
37///
38/// Scrolling has to know the geometry of rows that are never drawn (for instance the rows between
39/// the current offset and a selection further down the table), so heights are described separately
40/// from the rows themselves. This is what keeps variable-height lazy tables correct: the scroll
41/// calculation asks for heights, not for rows.
42enum LazyRowHeights<'a> {
43    /// Every row occupies the same number of lines.
44    Uniform(u16),
45    /// Row heights are computed on demand from the row index.
46    PerRow(Arc<dyn Fn(usize) -> u16 + Send + Sync + RefUnwindSafe + 'a>),
47}
48
49impl LazyRowHeights<'_> {
50    /// The number of lines occupied by the row at `index`.
51    fn height_of(&self, index: usize) -> u16 {
52        match self {
53            Self::Uniform(height) => *height,
54            Self::PerRow(heights) => heights(index),
55        }
56    }
57}
58
59impl fmt::Debug for LazyRowHeights<'_> {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        match self {
62            Self::Uniform(height) => f.debug_tuple("Uniform").field(height).finish(),
63            Self::PerRow(_) => f.debug_tuple("PerRow").finish(),
64        }
65    }
66}
67
68impl Clone for LazyRowHeights<'_> {
69    fn clone(&self) -> Self {
70        match self {
71            Self::Uniform(height) => Self::Uniform(*height),
72            Self::PerRow(heights) => Self::PerRow(Arc::clone(heights)),
73        }
74    }
75}
76
77impl PartialEq for LazyRowHeights<'_> {
78    fn eq(&self, other: &Self) -> bool {
79        match (self, other) {
80            (Self::Uniform(left), Self::Uniform(right)) => left == right,
81            (Self::PerRow(left), Self::PerRow(right)) => Arc::ptr_eq(left, right),
82            _ => false,
83        }
84    }
85}
86
87impl Eq for LazyRowHeights<'_> {}
88
89impl core::hash::Hash for LazyRowHeights<'_> {
90    fn hash<H: Hasher>(&self, state: &mut H) {
91        match self {
92            Self::Uniform(height) => {
93                "uniform".hash(state);
94                height.hash(state);
95            }
96            Self::PerRow(heights) => {
97                "per_row".hash(state);
98                ptr::hash(Arc::as_ptr(heights), state);
99            }
100        }
101    }
102}
103
104/// Stores the parameters needed to build rows on demand for a lazy table.
105struct LazyRowProvider<'a> {
106    count: usize,
107    heights: LazyRowHeights<'a>,
108    factory: Arc<dyn Fn(usize) -> Row<'a> + Send + Sync + RefUnwindSafe + 'a>,
109}
110
111impl LazyRowProvider<'_> {
112    /// The number of lines occupied by the row at `index`.
113    fn height_of(&self, index: usize) -> u16 {
114        self.heights.height_of(index)
115    }
116
117    fn visible_rows(
118        &self,
119        state: &TableState,
120        area: Rect,
121        borders: TableBorders,
122    ) -> (usize, usize) {
123        visible_row_range(self.count, state, area, borders, |index| {
124            let height = self.height_of(index);
125            (height, height)
126        })
127    }
128}
129
130/// Return the indexes of the visible rows, for eager and lazy rows alike.
131///
132/// `row_heights` returns two heights for a row: the lines it needs to fit, and the lines it takes
133/// with its margins. This function reads nothing else about rows, so a lazy table only builds the
134/// rows in the returned range.
135///
136/// The window starts at the offset, or at the selection if that is above the offset, and fills
137/// downwards with the rows that fit completely. When the selection is below the window, this
138/// function anchors the window at the selection and grows it upwards instead of scrolling down one
139/// row at a time. The work then depends on the height of the area, not on how far the selection
140/// moved, and a selected row taller than the area stays on screen, clipped.
141fn visible_row_range(
142    count: usize,
143    state: &TableState,
144    area: Rect,
145    borders: TableBorders,
146    row_heights: impl Fn(usize) -> (u16, u16),
147) -> (usize, usize) {
148    if count == 0 {
149        return (0, 0);
150    }
151    // The lines a row needs to fit, and the lines it takes with its margins and separator.
152    let measure = |index| {
153        let (height, height_with_margin) = row_heights(index);
154        let extent =
155            height_with_margin.saturating_add(borders.separator_height_below(index, count));
156        (height, extent)
157    };
158    let last_row = count - 1;
159    let selected = state.selected.map(|selected| selected.min(last_row));
160
161    let mut start = state.offset.min(last_row);
162    if let Some(selected) = selected {
163        start = start.min(selected);
164    }
165
166    // An area with no lines shows no rows. The offset still marks where the table resumes once
167    // the area grows, so keep it rather than reset it.
168    if area.height == 0 {
169        return (start, start);
170    }
171
172    // Fill the area downwards from the start with the rows that fit in it completely.
173    //
174    // `height` only grows by checked or saturating sums, so a row reporting `u16::MAX` lines
175    // cannot overflow it, and `end` stops at `count`.
176    let mut end = start;
177    let mut height = 0_u16;
178    while end < count {
179        let (row_height, extent) = measure(end);
180        let Some(filled) = height.checked_add(row_height) else {
181            break;
182        };
183        if filled > area.height {
184            break;
185        }
186        height = height.saturating_add(extent);
187        end += 1;
188        if window_is_full(start, end, area) {
189            break;
190        }
191    }
192
193    // Scroll down until the selected row is visible, by anchoring the window at the selection and
194    // growing it upwards until the area is full.
195    if let Some(selected) = selected
196        && selected >= end
197    {
198        // `selected <= last_row`, so `selected + 1` cannot overflow, and `start` is only
199        // decremented while it is above zero.
200        start = selected;
201        end = selected + 1;
202        height = measure(selected).1;
203        let hanging_separator = borders.separator_height_below(selected, count);
204        while start > 0 && !window_is_full(start, end, area) {
205            let Some(filled) = height.checked_add(measure(start - 1).1) else {
206                break;
207            };
208            if filled > area.height.saturating_add(hanging_separator) {
209                break;
210            }
211            height = filled;
212            start -= 1;
213        }
214    }
215
216    // Include a partial row if there is space
217    if height < area.height && end < count && !window_is_full(start, end, area) {
218        end += 1;
219    }
220
221    (start, end)
222}
223
224/// Whether a window of rows can be grown no further.
225///
226/// A window never holds more rows than the area has lines, plus one partial row. Rows are free to
227/// report a height of zero, so this bound is what keeps [`visible_row_range`] proportional to the
228/// area rather than to the number of rows.
229const fn window_is_full(start: usize, end: usize, area: Rect) -> bool {
230    end - start > area.height as usize
231}
232
233impl fmt::Debug for LazyRowProvider<'_> {
234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235        f.debug_struct("LazyRowProvider")
236            .field("count", &self.count)
237            .field("heights", &self.heights)
238            .finish_non_exhaustive()
239    }
240}
241
242impl Clone for LazyRowProvider<'_> {
243    fn clone(&self) -> Self {
244        Self {
245            count: self.count,
246            heights: self.heights.clone(),
247            factory: Arc::clone(&self.factory),
248        }
249    }
250}
251
252impl PartialEq for LazyRowProvider<'_> {
253    fn eq(&self, other: &Self) -> bool {
254        self.count == other.count
255            && self.heights == other.heights
256            && Arc::ptr_eq(&self.factory, &other.factory)
257    }
258}
259
260impl Eq for LazyRowProvider<'_> {}
261
262impl core::hash::Hash for LazyRowProvider<'_> {
263    fn hash<H: Hasher>(&self, state: &mut H) {
264        self.count.hash(state);
265        self.heights.hash(state);
266        ptr::hash(Arc::as_ptr(&self.factory), state);
267    }
268}
269
270/// A widget to display data in formatted columns.
271///
272/// A `Table` is a collection of [`Row`]s, each composed of [`Cell`]s:
273///
274/// You can construct a [`Table`] using either [`Table::new`] or [`Table::default`] and then chain
275/// builder style methods to set the desired properties.
276///
277/// Table cells can be aligned, for more details see [`Cell`].
278///
279/// Make sure to call the [`Table::widths`] method, otherwise the columns will all have a width of 0
280/// and thus not be visible.
281///
282/// [`Table`] implements [`Widget`] and so it can be drawn using `Frame::render_widget`.
283///
284/// [`Table`] is also a [`StatefulWidget`], which means you can use it with [`TableState`] to allow
285/// the user to scroll through the rows and select one of them. When rendering a [`Table`] with a
286/// [`TableState`], the selected row, column and cell will be highlighted. If the selected row is
287/// not visible (based on the offset), the table will be scrolled to make the selected row visible.
288///
289/// Note: if the `widths` field is empty, the table will be rendered with equal widths.
290/// Note: Highlight styles are applied in the following order: Row, Column, Cell.
291///
292/// # Selection and highlighting
293///
294/// What the selection draws is controlled by three independent settings:
295///
296/// - the highlight *styles* ([`Table::row_highlight_style`], [`Table::column_highlight_style`],
297///   [`Table::cell_highlight_style`]) paint the selected row, column, and their intersection. The
298///   column highlight covers the rows area only — never the header or the footer.
299/// - [`Table::highlight_symbol`] is the marker drawn in front of the selection, and
300///   [`Table::highlight_spacing`] decides *when* space is reserved for it. Because any selection
301///   reserves the space, a column-only selection widens the table the same way a row selection
302///   does.
303/// - [`Table::highlight_placement`] decides *which* columns that space is added to. The default
304///   indents the first column only, which is why a table that never selects a column lays out
305///   exactly as it did before column selection existed.
306///
307/// See the table example and the recipe and traceroute tabs in the demo2 example in the [Examples]
308/// directory for a more in depth example of the various configuration options and for how to handle
309/// state.
310///
311/// [Examples]: https://github.com/ratatui/ratatui/blob/master/examples/README.md
312///
313/// # Borders
314///
315/// [`Table::borders`] takes a [`TableBorders`] that says which lines to draw around and between the
316/// cells. [`Table::border_set`] picks their glyphs, and [`Table::border_style`] sets their style.
317/// The lines follow these rules:
318///
319/// - Outer lines sit on the edges of the table area, which is inside the [`Block`] if one is set.
320///   In an area at least two cells wide and high, [`TableBorders::OUTER`] draws the same frame as
321///   `.block(Block::bordered())`.
322/// - An inner vertical line sits in the middle of the gap between two columns, or just left of the
323///   middle when the gap is even. It needs a gap of at least one cell, so under
324///   [`TableBorders::INNER_VERTICAL`] a [`Table::column_spacing`] of 0 lays out as 1. A highlight
325///   symbol stays right of the line, inside the box of the column it precedes.
326/// - The header separator, the footer separator and each row separator take a terminal line of
327///   their own. Row margins are padding inside a row's box, and vertical lines run through them. A
328///   row separator stays blank when the row after it does not fit.
329/// - A cell spanning several columns hides the vertical lines it covers, so the lines above and
330///   below it end in `┴` and `┬`.
331/// - The table patches [`Table::border_style`] over the border cells after drawing everything else.
332///   A row highlight also covers the vertical lines inside its row. A column highlight also covers
333///   the row separators inside its column. Neither covers the outer frame.
334/// - A [`Block`] draws outside the lines and does not join them. Use [`TableBorders::OUTER`] for a
335///   frame that joins the inner lines.
336///
337/// # Constructor methods
338///
339/// - [`Table::new`] creates a new [`Table`] with the given rows.
340/// - [`Table::default`] creates an empty [`Table`]. You can then add rows using [`Table::rows`].
341///
342/// # Setter methods
343///
344/// These methods are fluent setters. They return a new `Table` with the specified property set.
345///
346/// - [`Table::rows`] sets the rows of the [`Table`].
347/// - [`Table::header`] sets the header row of the [`Table`].
348/// - [`Table::footer`] sets the footer row of the [`Table`].
349/// - [`Table::widths`] sets the width constraints of each column.
350/// - [`Table::column_spacing`] sets the spacing between each column.
351/// - [`Table::block`] wraps the table in a [`Block`] widget.
352/// - [`Table::style`] sets the base style of the widget.
353/// - [`Table::row_highlight_style`] sets the style of the selected row.
354/// - [`Table::column_highlight_style`] sets the style of the selected column.
355/// - [`Table::cell_highlight_style`] sets the style of the selected cell.
356/// - [`Table::highlight_symbol`] sets the symbol to be displayed in front of the selected row.
357/// - [`Table::highlight_spacing`] sets when to show the highlight spacing.
358/// - [`Table::highlight_placement`] sets which columns the highlight spacing is added to.
359/// - [`Table::borders`] sets which lines to draw around and between the cells.
360/// - [`Table::border_set`] sets the glyphs of those lines.
361/// - [`Table::border_style`] sets the style of those lines.
362///
363/// # Example
364///
365/// ```rust
366/// use ratatui::layout::Constraint;
367/// use ratatui::style::{Style, Stylize};
368/// use ratatui::widgets::Block;
369/// use ratatui_table::{Row, Table};
370///
371/// let rows = [Row::new(vec!["Cell1", "Cell2", "Cell3"])];
372/// // Columns widths are constrained in the same way as Layout...
373/// let widths = [
374///     Constraint::Length(5),
375///     Constraint::Length(5),
376///     Constraint::Length(10),
377/// ];
378/// let table = Table::new(rows, widths)
379///     // ...and they can be separated by a fixed spacing.
380///     .column_spacing(1)
381///     // You can set the style of the entire Table.
382///     .style(Style::new().blue())
383///     // It has an optional header, which is simply a Row always visible at the top.
384///     .header(
385///         Row::new(vec!["Col1", "Col2", "Col3"])
386///             .style(Style::new().bold())
387///             // To add space between the header and the rest of the rows, specify the margin
388///             .bottom_margin(1),
389///     )
390///     // It has an optional footer, which is simply a Row always visible at the bottom.
391///     .footer(Row::new(vec!["Updated on Dec 28"]))
392///     // As any other widget, a Table can be wrapped in a Block.
393///     .block(Block::new().title("Table"))
394///     // The selected row, column, cell and its content can also be styled.
395///     .row_highlight_style(Style::new().reversed())
396///     .column_highlight_style(Style::new().red())
397///     .cell_highlight_style(Style::new().blue())
398///     // ...and potentially show a symbol in front of the selection.
399///     .highlight_symbol(">>");
400/// ```
401///
402/// Rows can be created from an iterator of [`Cell`]s. Each row can have an associated height,
403/// bottom margin, and style. See [`Row`] for more details.
404///
405/// ```rust
406/// use ratatui::style::{Style, Stylize};
407/// use ratatui::text::{Line, Span};
408/// use ratatui_table::{Cell, Row, Table};
409///
410/// // a Row can be created from simple strings.
411/// let row = Row::new(vec!["Row11", "Row12", "Row13"]);
412///
413/// // You can style the entire row.
414/// let row = Row::new(vec!["Row21", "Row22", "Row23"]).style(Style::new().red());
415///
416/// // If you need more control over the styling, create Cells directly
417/// let row = Row::new(vec![
418///     Cell::from("Row31"),
419///     Cell::from("Row32").style(Style::new().yellow()),
420///     Cell::from(Line::from(vec![Span::raw("Row"), Span::from("33").green()])),
421/// ]);
422///
423/// // If a Row need to display some content over multiple lines, specify the height.
424/// let row = Row::new(vec![
425///     Cell::from("Row\n41"),
426///     Cell::from("Row\n42"),
427///     Cell::from("Row\n43"),
428/// ])
429/// .height(2);
430/// ```
431///
432/// Cells can be created from anything that can be converted to [`Text`]. See [`Cell`] for more
433/// details.
434///
435/// ```rust
436/// use ratatui::style::{Style, Stylize};
437/// use ratatui::text::{Line, Span, Text};
438/// use ratatui_table::Cell;
439///
440/// Cell::from("simple string");
441/// Cell::from("simple styled span".red());
442/// Cell::from(Span::raw("raw span"));
443/// Cell::from(Span::styled("styled span", Style::new().red()));
444/// Cell::from(Line::from(vec![
445///     Span::raw("a vec of "),
446///     Span::from("spans").bold(),
447/// ]));
448/// Cell::from(Text::from("text"));
449/// ```
450///
451/// Just as rows can be collected from iterators of `Cell`s, tables can be collected from iterators
452/// of `Row`s.  This will create a table with column widths evenly dividing the space available.
453/// These default columns widths can be overridden using the `Table::widths` method.
454///
455/// ```rust
456/// use ratatui::layout::Constraint;
457/// use ratatui_table::{Row, Table};
458///
459/// let text = "Mary had a\nlittle lamb.";
460///
461/// let table = text
462///     .split("\n")
463///     .map(|line: &str| -> Row { line.split_ascii_whitespace().collect() })
464///     .collect::<Table>()
465///     .widths([Constraint::Length(10); 3]);
466/// ```
467///
468/// `Table` also implements the [`Styled`] trait, which means you can use style shorthands from
469/// the [`Stylize`] trait to set the style of the widget more concisely.
470///
471/// ```rust
472/// use ratatui::layout::Constraint;
473/// use ratatui::style::Stylize;
474/// use ratatui_table::{Row, Table};
475///
476/// let rows = [Row::new(vec!["Cell1", "Cell2", "Cell3"])];
477/// let widths = [
478///     Constraint::Length(5),
479///     Constraint::Length(5),
480///     Constraint::Length(10),
481/// ];
482/// let table = Table::new(rows, widths).red().italic();
483/// ```
484///
485/// # Stateful example
486///
487/// `Table` is a [`StatefulWidget`], which means you can use it with [`TableState`] to allow the
488/// user to scroll through the rows and select one of them.
489///
490/// ```rust
491/// use ratatui::Frame;
492/// use ratatui::layout::{Constraint, Rect};
493/// use ratatui::style::{Style, Stylize};
494/// use ratatui::widgets::Block;
495/// use ratatui_table::{Row, Table, TableState};
496///
497/// # fn ui(frame: &mut Frame) {
498/// # let area = Rect::default();
499/// // Note: TableState should be stored in your application state (not constructed in your render
500/// // method) so that the selected row is preserved across renders
501/// let mut table_state = TableState::default();
502/// let rows = [
503///     Row::new(vec!["Row11", "Row12", "Row13"]),
504///     Row::new(vec!["Row21", "Row22", "Row23"]),
505///     Row::new(vec!["Row31", "Row32", "Row33"]),
506/// ];
507/// let widths = [
508///     Constraint::Length(5),
509///     Constraint::Length(5),
510///     Constraint::Length(10),
511/// ];
512/// let table = Table::new(rows, widths)
513///     .block(Block::new().title("Table"))
514///     .row_highlight_style(Style::new().reversed())
515///     .highlight_symbol(">>");
516///
517/// frame.render_stateful_widget(table, area, &mut table_state);
518/// # }
519/// ```
520///
521/// [`Stylize`]: ratatui_core::style::Stylize
522#[derive(Debug, Clone, Eq, PartialEq, Hash)]
523pub struct Table<'a> {
524    /// Data to display in each row
525    rows: Vec<Row<'a>>,
526
527    /// Optional header
528    header: Option<Row<'a>>,
529
530    /// Optional footer
531    footer: Option<Row<'a>>,
532
533    /// Width constraints for each column
534    widths: Vec<Constraint>,
535
536    /// Space between each column
537    column_spacing: u16,
538
539    /// A block to wrap the widget in
540    block: Option<Block<'a>>,
541
542    /// Base style for the widget
543    style: Style,
544
545    /// Style used to render the selected row
546    row_highlight_style: Style,
547
548    /// Style used to render the selected column
549    column_highlight_style: Style,
550
551    /// Style used to render the selected cell
552    cell_highlight_style: Style,
553
554    /// Symbol in front of the selected row
555    highlight_symbol: Text<'a>,
556
557    /// Decides when to allocate spacing for the row selection
558    highlight_spacing: HighlightSpacing,
559
560    /// Decides which columns get spacing for the highlight symbol
561    highlight_placement: HighlightPlacement,
562
563    /// Controls how to distribute extra space among the columns
564    flex: Flex,
565
566    /// Optional lazy row provider used instead of `rows` when set
567    lazy: Option<LazyRowProvider<'a>>,
568
569    /// Which lines to draw around and between the cells
570    borders: TableBorders,
571
572    /// Glyphs of the lines and their junctions
573    border_set: line::Set<'a>,
574
575    /// Style patched over the lines
576    border_style: Style,
577}
578
579impl Default for Table<'_> {
580    fn default() -> Self {
581        Self {
582            rows: Vec::new(),
583            header: None,
584            footer: None,
585            widths: Vec::new(),
586            column_spacing: 1,
587            block: None,
588            style: Style::new(),
589            row_highlight_style: Style::new(),
590            column_highlight_style: Style::new(),
591            cell_highlight_style: Style::new(),
592            highlight_symbol: Text::default(),
593            highlight_spacing: HighlightSpacing::default(),
594            highlight_placement: HighlightPlacement::default(),
595            flex: Flex::Start,
596            lazy: None,
597            borders: TableBorders::empty(),
598            border_set: line::NORMAL,
599            border_style: Style::new(),
600        }
601    }
602}
603
604impl<'a> Table<'a> {
605    /// Creates a new [`Table`] widget with the given rows.
606    ///
607    /// The `rows` parameter accepts any value that can be converted into an iterator of [`Row`]s.
608    /// This includes arrays, slices, and [`Vec`]s.
609    ///
610    /// The `widths` parameter accepts any type that implements `IntoIterator<Item =
611    /// Into<Constraint>>`. This includes arrays, slices, vectors, iterators. `Into<Constraint>` is
612    /// implemented on u16, so you can pass an array, vec, etc. of u16 to this function to create a
613    /// table with fixed width columns.
614    ///
615    /// # Examples
616    ///
617    /// ```rust
618    /// use ratatui::layout::Constraint;
619    /// use ratatui_table::{Row, Table};
620    ///
621    /// let rows = [
622    ///     Row::new(vec!["Cell1", "Cell2"]),
623    ///     Row::new(vec!["Cell3", "Cell4"]),
624    /// ];
625    /// let widths = [Constraint::Length(5), Constraint::Length(5)];
626    /// let table = Table::new(rows, widths);
627    /// ```
628    pub fn new<R, C>(rows: R, widths: C) -> Self
629    where
630        R: IntoIterator,
631        R::Item: Into<Row<'a>>,
632        C: IntoIterator,
633        C::Item: Into<Constraint>,
634    {
635        let widths = widths.into_iter().map(Into::into).collect_vec();
636        ensure_percentages_less_than_100(&widths);
637
638        let rows = rows.into_iter().map(Into::into).collect();
639        Self {
640            rows,
641            widths,
642            ..Default::default()
643        }
644    }
645
646    /// Set the rows
647    ///
648    /// The `rows` parameter accepts any value that can be converted into an iterator of [`Row`]s.
649    /// This includes arrays, slices, and [`Vec`]s.
650    ///
651    /// # Warning
652    ///
653    /// This method does not currently set the column widths. You will need to set them manually by
654    /// calling [`Table::widths`].
655    ///
656    /// Setting rows explicitly replaces the rows of a table created with [`Table::lazy_rows`].
657    ///
658    /// This is a fluent setter method which must be chained or used as it consumes self
659    ///
660    /// # Examples
661    ///
662    /// ```rust
663    /// use ratatui_table::{Row, Table};
664    ///
665    /// let rows = [
666    ///     Row::new(vec!["Cell1", "Cell2"]),
667    ///     Row::new(vec!["Cell3", "Cell4"]),
668    /// ];
669    /// let table = Table::default().rows(rows);
670    /// ```
671    #[must_use = "method moves the value of self and returns the modified value"]
672    pub fn rows<T>(mut self, rows: T) -> Self
673    where
674        T: IntoIterator<Item = Row<'a>>,
675    {
676        self.rows = rows.into_iter().collect();
677        self.lazy = None;
678        self
679    }
680
681    /// Sets the header row
682    ///
683    /// The `header` parameter is a [`Row`] which will be displayed at the top of the [`Table`]
684    ///
685    /// This is a fluent setter method which must be chained or used as it consumes self
686    ///
687    /// # Examples
688    ///
689    /// ```rust
690    /// use ratatui_table::{Cell, Row, Table};
691    ///
692    /// let header = Row::new(vec![
693    ///     Cell::from("Header Cell 1"),
694    ///     Cell::from("Header Cell 2"),
695    /// ]);
696    /// let table = Table::default().header(header);
697    /// ```
698    #[must_use = "method moves the value of self and returns the modified value"]
699    pub fn header(mut self, header: Row<'a>) -> Self {
700        self.header = Some(header);
701        self
702    }
703
704    /// Sets the footer row
705    ///
706    /// The `footer` parameter is a [`Row`] which will be displayed at the bottom of the [`Table`]
707    ///
708    /// This is a fluent setter method which must be chained or used as it consumes self
709    ///
710    /// # Examples
711    ///
712    /// ```rust
713    /// use ratatui_table::{Cell, Row, Table};
714    ///
715    /// let footer = Row::new(vec![
716    ///     Cell::from("Footer Cell 1"),
717    ///     Cell::from("Footer Cell 2"),
718    /// ]);
719    /// let table = Table::default().footer(footer);
720    /// ```
721    #[must_use = "method moves the value of self and returns the modified value"]
722    pub fn footer(mut self, footer: Row<'a>) -> Self {
723        self.footer = Some(footer);
724        self
725    }
726
727    /// Set the widths of the columns.
728    ///
729    /// The `widths` parameter accepts any type that implements `IntoIterator<Item =
730    /// Into<Constraint>>`. This includes arrays, slices, vectors, iterators. `Into<Constraint>` is
731    /// implemented on u16, so you can pass an array, vec, etc. of u16 to this function to create a
732    /// table with fixed width columns.
733    ///
734    /// If the widths are empty, the table will be rendered with equal widths.
735    ///
736    /// This is a fluent setter method which must be chained or used as it consumes self
737    ///
738    /// # Examples
739    ///
740    /// ```rust
741    /// use ratatui::layout::Constraint;
742    /// use ratatui_table::{Cell, Row, Table};
743    ///
744    /// let table = Table::default().widths([Constraint::Length(5), Constraint::Length(5)]);
745    /// let table = Table::default().widths(vec![Constraint::Length(5); 2]);
746    ///
747    /// // widths could also be computed at runtime
748    /// let widths = [10, 10, 20].into_iter().map(|c| Constraint::Length(c));
749    /// let table = Table::default().widths(widths);
750    /// ```
751    #[must_use = "method moves the value of self and returns the modified value"]
752    pub fn widths<I>(mut self, widths: I) -> Self
753    where
754        I: IntoIterator,
755        I::Item: Into<Constraint>,
756    {
757        let widths = widths.into_iter().map(Into::into).collect_vec();
758        ensure_percentages_less_than_100(&widths);
759        self.widths = widths;
760        self
761    }
762
763    /// Set the spacing between columns
764    ///
765    /// This is a fluent setter method which must be chained or used as it consumes self
766    ///
767    /// # Examples
768    ///
769    /// ```rust
770    /// use ratatui::layout::Constraint;
771    /// use ratatui_table::{Row, Table};
772    ///
773    /// let rows = [Row::new(vec!["Cell1", "Cell2"])];
774    /// let widths = [Constraint::Length(5), Constraint::Length(5)];
775    /// let table = Table::new(rows, widths).column_spacing(1);
776    /// ```
777    ///
778    /// Under [`TableBorders::INNER_VERTICAL`], a spacing of 0 lays out as 1 so that the line has a
779    /// cell to sit in.
780    #[must_use = "method moves the value of self and returns the modified value"]
781    pub const fn column_spacing(mut self, spacing: u16) -> Self {
782        self.column_spacing = spacing;
783        self
784    }
785
786    /// Wraps the table with a custom [`Block`] widget.
787    ///
788    /// The `block` parameter is of type [`Block`]. This holds the specified block to be
789    /// created around the [`Table`]
790    ///
791    /// The block's border does not join the table's lines. See [`Table::borders`] for lines
792    /// between the cells and a frame that joins them.
793    ///
794    /// This is a fluent setter method which must be chained or used as it consumes self
795    ///
796    /// # Examples
797    ///
798    /// ```rust
799    /// use ratatui::layout::Constraint;
800    /// use ratatui::widgets::Block;
801    /// use ratatui_table::{Cell, Row, Table};
802    ///
803    /// let rows = [Row::new(vec!["Cell1", "Cell2"])];
804    /// let widths = [Constraint::Length(5), Constraint::Length(5)];
805    /// let block = Block::bordered().title("Table");
806    /// let table = Table::new(rows, widths).block(block);
807    /// ```
808    #[must_use = "method moves the value of self and returns the modified value"]
809    pub fn block(mut self, block: Block<'a>) -> Self {
810        self.block = Some(block);
811        self
812    }
813
814    /// Sets the base style of the widget
815    ///
816    /// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
817    /// your own type that implements [`Into<Style>`]).
818    ///
819    /// All text rendered by the widget will use this style, unless overridden by [`Block::style`],
820    /// [`Row::style`], [`Cell::style`], or the styles of cell's content.
821    ///
822    /// This is a fluent setter method which must be chained or used as it consumes self
823    ///
824    /// # Examples
825    ///
826    /// ```rust
827    /// use ratatui::layout::Constraint;
828    /// use ratatui::style::{Style, Stylize};
829    /// use ratatui_table::{Row, Table};
830    ///
831    /// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
832    /// # let widths = [Constraint::Length(5), Constraint::Length(5)];
833    /// let table = Table::new(rows, widths).style(Style::new().red().italic());
834    /// ```
835    ///
836    /// `Table` also implements the [`Styled`] trait, which means you can use style shorthands from
837    /// the [`Stylize`] trait to set the style of the widget more concisely.
838    ///
839    /// ```rust
840    /// use ratatui::layout::Constraint;
841    /// use ratatui::style::Stylize;
842    /// use ratatui_table::{Cell, Row, Table};
843    ///
844    /// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
845    /// # let widths = vec![Constraint::Length(5), Constraint::Length(5)];
846    /// let table = Table::new(rows, widths).red().italic();
847    /// ```
848    ///
849    /// [`Color`]: ratatui_core::style::Color
850    /// [`Stylize`]: ratatui_core::style::Stylize
851    #[must_use = "method moves the value of self and returns the modified value"]
852    pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
853        self.style = style.into();
854        self
855    }
856
857    /// Set the style of the selected row
858    ///
859    /// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
860    /// your own type that implements [`Into<Style>`]).
861    ///
862    /// This style will be applied to the entire row, including the selection symbol if it is
863    /// displayed, and will override any style set on the row or on the individual cells.
864    ///
865    /// This is a fluent setter method which must be chained or used as it consumes self
866    ///
867    /// # Examples
868    ///
869    /// ```rust
870    /// use ratatui::layout::Constraint;
871    /// use ratatui::style::{Style, Stylize};
872    /// use ratatui_table::{Cell, Row, Table};
873    ///
874    /// let rows = [Row::new(vec!["Cell1", "Cell2"])];
875    /// let widths = [Constraint::Length(5), Constraint::Length(5)];
876    /// let table = Table::new(rows, widths).highlight_style(Style::new().red().italic());
877    /// ```
878    ///
879    /// [`Color`]: ratatui_core::style::Color
880    #[must_use = "method moves the value of self and returns the modified value"]
881    #[deprecated(note = "use `row_highlight_style()` instead", since = "0.2.1")]
882    pub fn highlight_style<S: Into<Style>>(self, highlight_style: S) -> Self {
883        self.row_highlight_style(highlight_style)
884    }
885
886    /// Set the style of the selected row
887    ///
888    /// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
889    /// your own type that implements [`Into<Style>`]).
890    ///
891    /// This style will be applied to the entire row, including the selection symbol if it is
892    /// displayed, and will override any style set on the row or on the individual cells.
893    ///
894    /// This is a fluent setter method which must be chained or used as it consumes self
895    ///
896    /// # Examples
897    ///
898    /// ```rust
899    /// # use ratatui::{layout::Constraint, style::{Style, Stylize}, widgets::{Row, Table}};
900    /// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
901    /// # let widths = [Constraint::Length(5), Constraint::Length(5)];
902    /// let table = Table::new(rows, widths).row_highlight_style(Style::new().red().italic());
903    /// ```
904    /// [`Color`]: ratatui_core::style::Color
905    #[must_use = "method moves the value of self and returns the modified value"]
906    pub fn row_highlight_style<S: Into<Style>>(mut self, highlight_style: S) -> Self {
907        self.row_highlight_style = highlight_style.into();
908        self
909    }
910
911    /// Set the style of the selected column
912    ///
913    /// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
914    /// your own type that implements [`Into<Style>`]).
915    ///
916    /// This style will be applied to the entire column, and will override any style set on the
917    /// row or on the individual cells.
918    ///
919    /// This is a fluent setter method which must be chained or used as it consumes self
920    ///
921    /// # Examples
922    ///
923    /// ```rust
924    /// # use ratatui::{layout::Constraint, style::{Style, Stylize}, widgets::{Row, Table}};
925    /// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
926    /// # let widths = [Constraint::Length(5), Constraint::Length(5)];
927    /// let table = Table::new(rows, widths).column_highlight_style(Style::new().red().italic());
928    /// ```
929    /// [`Color`]: ratatui_core::style::Color
930    #[must_use = "method moves the value of self and returns the modified value"]
931    pub fn column_highlight_style<S: Into<Style>>(mut self, highlight_style: S) -> Self {
932        self.column_highlight_style = highlight_style.into();
933        self
934    }
935
936    /// Set the style of the selected cell
937    ///
938    /// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
939    /// your own type that implements [`Into<Style>`]).
940    ///
941    /// This style will be applied to the selected cell, and will override any style set on the
942    /// row or on the individual cells.
943    ///
944    /// This is a fluent setter method which must be chained or used as it consumes self
945    ///
946    /// # Examples
947    ///
948    /// ```rust
949    /// # use ratatui::{layout::Constraint, style::{Style, Stylize}, widgets::{Row, Table}};
950    /// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
951    /// # let widths = [Constraint::Length(5), Constraint::Length(5)];
952    /// let table = Table::new(rows, widths).cell_highlight_style(Style::new().red().italic());
953    /// ```
954    /// [`Color`]: ratatui_core::style::Color
955    #[must_use = "method moves the value of self and returns the modified value"]
956    pub fn cell_highlight_style<S: Into<Style>>(mut self, highlight_style: S) -> Self {
957        self.cell_highlight_style = highlight_style.into();
958        self
959    }
960
961    /// Set the symbol to be displayed in front of the selected row
962    ///
963    /// This is a fluent setter method which must be chained or used as it consumes self
964    ///
965    /// # Examples
966    ///
967    /// ```rust
968    /// use ratatui::layout::Constraint;
969    /// use ratatui_table::{Cell, Row, Table};
970    ///
971    /// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
972    /// # let widths = [Constraint::Length(5), Constraint::Length(5)];
973    /// let table = Table::new(rows, widths).highlight_symbol(">>");
974    /// ```
975    #[must_use = "method moves the value of self and returns the modified value"]
976    pub fn highlight_symbol<T: Into<Text<'a>>>(mut self, highlight_symbol: T) -> Self {
977        self.highlight_symbol = highlight_symbol.into();
978        self
979    }
980
981    /// Set when to show the highlight spacing
982    ///
983    /// The highlight spacing is the spacing that is allocated for the selection symbol column (if
984    /// enabled) and is used to shift the table when a row is selected. This method allows you to
985    /// configure when this spacing is allocated.
986    ///
987    /// - [`HighlightSpacing::Always`] will always allocate the spacing, regardless of whether a row
988    ///   is selected or not. This means that the table will never change size, regardless of if a
989    ///   row is selected or not.
990    /// - [`HighlightSpacing::WhenSelected`] will only allocate the spacing if a row is selected.
991    ///   This means that the table will shift when a row is selected. This is the default setting
992    ///   for backwards compatibility, but it is recommended to use `HighlightSpacing::Always` for a
993    ///   better user experience.
994    /// - [`HighlightSpacing::Never`] will never allocate the spacing, regardless of whether a row
995    ///   is selected or not. This means that the highlight symbol will never be drawn.
996    ///
997    /// This is a fluent setter method which must be chained or used as it consumes self
998    ///
999    /// # Examples
1000    ///
1001    /// ```rust
1002    /// use ratatui::layout::Constraint;
1003    /// use ratatui_table::{HighlightSpacing, Row, Table};
1004    ///
1005    /// let rows = [Row::new(vec!["Cell1", "Cell2"])];
1006    /// let widths = [Constraint::Length(5), Constraint::Length(5)];
1007    /// let table = Table::new(rows, widths).highlight_spacing(HighlightSpacing::Always);
1008    /// ```
1009    #[must_use = "method moves the value of self and returns the modified value"]
1010    pub const fn highlight_spacing(mut self, value: HighlightSpacing) -> Self {
1011        self.highlight_spacing = value;
1012        self
1013    }
1014
1015    /// Set which columns get space for the highlight symbol.
1016    ///
1017    /// Reads as a pair with [`Table::highlight_spacing`]: that one decides *when* the symbol
1018    /// column is allocated, this one decides *where*. Defaults to
1019    /// [`HighlightPlacement::FirstColumn`], which reproduces the layout of a table without column
1020    /// selection.
1021    ///
1022    /// See [`HighlightPlacement`] for how the columns shift as the selection moves.
1023    ///
1024    /// This is a fluent setter method which must be chained or used as it consumes self
1025    ///
1026    /// # Examples
1027    ///
1028    /// ```rust
1029    /// use ratatui::layout::Constraint;
1030    /// use ratatui_table::{HighlightPlacement, Row, Table};
1031    ///
1032    /// let rows = [Row::new(vec!["Cell1", "Cell2"])];
1033    /// let widths = [Constraint::Length(5), Constraint::Length(5)];
1034    /// let table = Table::new(rows, widths).highlight_placement(HighlightPlacement::SelectedColumn);
1035    /// ```
1036    #[must_use = "method moves the value of self and returns the modified value"]
1037    pub fn highlight_placement(mut self, value: HighlightPlacement) -> Self {
1038        self.highlight_placement = value;
1039        self
1040    }
1041
1042    /// Sets which lines to draw around and between the cells.
1043    ///
1044    /// Defaults to [`TableBorders::empty`], which draws no lines. See [Borders](Table#borders) for
1045    /// where the lines go.
1046    ///
1047    /// This is a fluent setter method which must be chained or used as it consumes self
1048    ///
1049    /// # Examples
1050    ///
1051    /// ```rust
1052    /// use ratatui::buffer::Buffer;
1053    /// use ratatui::layout::{Constraint, Rect};
1054    /// use ratatui::widgets::Widget;
1055    /// use ratatui_table::{Row, Table, TableBorders};
1056    ///
1057    /// let rows = [Row::new(["1", "2"]), Row::new(["3", "4"])];
1058    /// let table = Table::new(rows, [Constraint::Length(1); 2])
1059    ///     .header(Row::new(["A", "B"]))
1060    ///     .borders(TableBorders::ALL);
1061    ///
1062    /// let mut buf = Buffer::empty(Rect::new(0, 0, 5, 7));
1063    /// Widget::render(table, buf.area, &mut buf);
1064    /// let expected = Buffer::with_lines([
1065    ///     "┌─┬─┐",
1066    ///     "│A│B│",
1067    ///     "├─┼─┤",
1068    ///     "│1│2│",
1069    ///     "├─┼─┤",
1070    ///     "│3│4│",
1071    ///     "└─┴─┘",
1072    /// ]);
1073    /// assert_eq!(buf, expected);
1074    /// ```
1075    #[must_use = "method moves the value of self and returns the modified value"]
1076    pub const fn borders(mut self, borders: TableBorders) -> Self {
1077        self.borders = borders;
1078        self
1079    }
1080
1081    /// Sets the glyphs of the lines and of the junctions where they meet.
1082    ///
1083    /// Defaults to [`line::NORMAL`]. Any [`line::Set`] works, including one of your own. Each
1084    /// junction takes the field that matches the lines meeting there, such as `cross` where four
1085    /// lines meet or `horizontal_down` for a `┬`.
1086    ///
1087    /// This is a fluent setter method which must be chained or used as it consumes self
1088    ///
1089    /// # Examples
1090    ///
1091    /// ```rust
1092    /// use ratatui::layout::Constraint;
1093    /// use ratatui::symbols::line;
1094    /// use ratatui_table::{Row, Table, TableBorders};
1095    ///
1096    /// let rows = [Row::new(vec!["Cell1", "Cell2"])];
1097    /// let widths = [Constraint::Length(5), Constraint::Length(5)];
1098    /// let table = Table::new(rows, widths)
1099    ///     .borders(TableBorders::ALL)
1100    ///     .border_set(line::ROUNDED);
1101    /// ```
1102    #[must_use = "method moves the value of self and returns the modified value"]
1103    pub const fn border_set(mut self, border_set: line::Set<'a>) -> Self {
1104        self.border_set = border_set;
1105        self
1106    }
1107
1108    /// Sets the style of the lines.
1109    ///
1110    /// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
1111    /// your own type that implements [`Into<Style>`]).
1112    ///
1113    /// The table patches this style over the border cells after drawing everything else, so any
1114    /// property it leaves unset shows the table, row or highlight style underneath. To keep a
1115    /// highlight off the lines, set every property that highlight style sets.
1116    ///
1117    /// This is a fluent setter method which must be chained or used as it consumes self
1118    ///
1119    /// # Examples
1120    ///
1121    /// ```rust
1122    /// use ratatui::layout::Constraint;
1123    /// use ratatui::style::{Style, Stylize};
1124    /// use ratatui_table::{Row, Table, TableBorders};
1125    ///
1126    /// let rows = [Row::new(vec!["Cell1", "Cell2"])];
1127    /// let widths = [Constraint::Length(5), Constraint::Length(5)];
1128    /// let table = Table::new(rows, widths)
1129    ///     .borders(TableBorders::OUTER | TableBorders::INNER_VERTICAL)
1130    ///     .border_style(Style::new().dark_gray());
1131    /// ```
1132    ///
1133    /// [`Color`]: ratatui_core::style::Color
1134    #[must_use = "method moves the value of self and returns the modified value"]
1135    pub fn border_style<S: Into<Style>>(mut self, style: S) -> Self {
1136        self.border_style = style.into();
1137        self
1138    }
1139
1140    /// Set how extra space is distributed amongst columns.
1141    ///
1142    /// This determines how the space is distributed when the constraints are satisfied. By default,
1143    /// the extra space is not distributed at all.  But this can be changed to distribute all extra
1144    /// space to the last column or to distribute it equally.
1145    ///
1146    /// This is a fluent setter method which must be chained or used as it consumes self
1147    ///
1148    /// # Examples
1149    ///
1150    /// Create a table that needs at least 30 columns to display.  Any extra space will be assigned
1151    /// to the last column.
1152    /// ```
1153    /// use ratatui::layout::{Constraint, Flex};
1154    /// use ratatui_table::{Row, Table};
1155    ///
1156    /// let widths = [
1157    ///     Constraint::Min(10),
1158    ///     Constraint::Min(10),
1159    ///     Constraint::Min(10),
1160    /// ];
1161    /// let table = Table::new(Vec::<Row>::new(), widths).flex(Flex::Legacy);
1162    /// ```
1163    #[must_use = "method moves the value of self and returns the modified value"]
1164    pub const fn flex(mut self, flex: Flex) -> Self {
1165        self.flex = flex;
1166        self
1167    }
1168
1169    /// Creates a [`Table`] that builds rows lazily, calling the factory only for visible rows.
1170    ///
1171    /// Unlike [`Table::new`], which eagerly collects all rows into a `Vec`, this constructor stores
1172    /// only the total row count and a factory closure. During rendering the factory is called
1173    /// exclusively for the rows that fall within the visible viewport, so memory allocation and
1174    /// processing work scale with the visible area rather than the total dataset size.
1175    ///
1176    /// Rows are one line tall by default. Use [`Table::lazy_row_height`] for taller rows, or
1177    /// [`Table::lazy_row_height_with`] when rows have individual heights.
1178    ///
1179    /// The `widths` parameter works exactly like [`Table::widths`] and must be provided because
1180    /// column layout cannot be inferred from rows that have not yet been built.
1181    ///
1182    /// # Row geometry
1183    ///
1184    /// The height configured on the table is authoritative: [`Row::height`], [`Row::top_margin`]
1185    /// and [`Row::bottom_margin`] set on rows returned by the factory are ignored, because
1186    /// scrolling has to reason about rows that are never built. Include any spacing you want in
1187    /// the row height.
1188    ///
1189    /// # Examples
1190    ///
1191    /// ```rust
1192    /// use ratatui::layout::Constraint;
1193    /// use ratatui_table::{Row, Table};
1194    ///
1195    /// let table = Table::lazy_rows(
1196    ///     10_000,
1197    ///     [Constraint::Length(20), Constraint::Fill(1)],
1198    ///     |index| Row::new([format!("item {index}"), format!("value {index}")]),
1199    /// );
1200    /// ```
1201    pub fn lazy_rows<C, F>(row_count: usize, widths: C, row: F) -> Self
1202    where
1203        C: IntoIterator,
1204        C::Item: Into<Constraint>,
1205        F: Fn(usize) -> Row<'a> + Send + Sync + RefUnwindSafe + 'a,
1206    {
1207        let widths: Vec<Constraint> = widths.into_iter().map(Into::into).collect();
1208        ensure_percentages_less_than_100(&widths);
1209        Self {
1210            lazy: Some(LazyRowProvider {
1211                count: row_count,
1212                heights: LazyRowHeights::Uniform(1),
1213                factory: Arc::new(row),
1214            }),
1215            widths,
1216            ..Default::default()
1217        }
1218    }
1219
1220    /// Set the height, in lines, of every lazily built row.
1221    ///
1222    /// Use [`Table::lazy_row_height_with`] when rows have individual heights.
1223    ///
1224    /// This is a fluent setter method which must be chained or used as it consumes self
1225    ///
1226    /// # Note
1227    ///
1228    /// This only affects rows built by [`Table::lazy_rows`]; rows set with [`Table::new`] or
1229    /// [`Table::rows`] carry their own [`Row::height`].
1230    ///
1231    /// # Examples
1232    ///
1233    /// ```rust
1234    /// use ratatui::layout::Constraint;
1235    /// use ratatui_table::{Row, Table};
1236    ///
1237    /// let table = Table::lazy_rows(10_000, [Constraint::Length(20)], |index| {
1238    ///     Row::new([format!("item {index}")])
1239    /// })
1240    /// .lazy_row_height(2);
1241    /// ```
1242    #[must_use = "method moves the value of self and returns the modified value"]
1243    pub fn lazy_row_height(mut self, height: u16) -> Self {
1244        if let Some(ref mut lazy) = self.lazy {
1245            lazy.heights = LazyRowHeights::Uniform(height);
1246        }
1247        self
1248    }
1249
1250    /// Set the height, in lines, of each lazily built row individually.
1251    ///
1252    /// This is the varying-height counterpart of [`Table::lazy_row_height`].
1253    ///
1254    /// Scrolling needs the geometry of rows that are not on screen — for instance to work out how
1255    /// far to scroll back when the selection is below the viewport — which is why heights are
1256    /// supplied separately from the rows. `height` should therefore be cheap: it is called for the
1257    /// rows in the viewport (and, while anchoring a selection, for a viewport's worth of rows
1258    /// around it), but never allocates a [`Row`]. The row factory itself is still only called for
1259    /// rows that are actually drawn.
1260    ///
1261    /// This is a fluent setter method which must be chained or used as it consumes self
1262    ///
1263    /// # Note
1264    ///
1265    /// This only affects rows built by [`Table::lazy_rows`]; rows set with [`Table::new`] or
1266    /// [`Table::rows`] carry their own [`Row::height`].
1267    ///
1268    /// # Examples
1269    ///
1270    /// ```rust
1271    /// use ratatui::layout::Constraint;
1272    /// use ratatui_table::{Row, Table};
1273    ///
1274    /// // Every tenth row is a double-height separator.
1275    /// let table = Table::lazy_rows(10_000, [Constraint::Length(20)], |index| {
1276    ///     Row::new([format!("item {index}")])
1277    /// })
1278    /// .lazy_row_height_with(|index| if index % 10 == 0 { 2 } else { 1 });
1279    /// ```
1280    #[must_use = "method moves the value of self and returns the modified value"]
1281    pub fn lazy_row_height_with<H>(mut self, height: H) -> Self
1282    where
1283        H: Fn(usize) -> u16 + Send + Sync + RefUnwindSafe + 'a,
1284    {
1285        if let Some(ref mut lazy) = self.lazy {
1286            lazy.heights = LazyRowHeights::PerRow(Arc::new(height));
1287        }
1288        self
1289    }
1290}
1291
1292impl Widget for Table<'_> {
1293    fn render(self, area: Rect, buf: &mut Buffer) {
1294        Widget::render(&self, area, buf);
1295    }
1296}
1297
1298impl Widget for &Table<'_> {
1299    fn render(self, area: Rect, buf: &mut Buffer) {
1300        let mut state = TableState::default();
1301        StatefulWidget::render(self, area, buf, &mut state);
1302    }
1303}
1304
1305impl StatefulWidget for Table<'_> {
1306    type State = TableState;
1307
1308    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
1309        StatefulWidget::render(&self, area, buf, state);
1310    }
1311}
1312
1313impl StatefulWidget for &Table<'_> {
1314    type State = TableState;
1315
1316    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
1317        buf.set_style(area, self.style);
1318        self.block.as_ref().render(area, buf);
1319        let frame = self.block.inner_if_some(area);
1320        let table_area = self.borders.inner(frame);
1321        let mut grid = BorderGrid::new(self.borders, frame);
1322        if table_area.is_empty() {
1323            grid.render(buf, &self.border_set, self.border_style);
1324            return;
1325        }
1326
1327        let row_count = self.row_count();
1328        if state.selected.is_some_and(|s| s >= row_count) {
1329            state.select(Some(row_count.saturating_sub(1)));
1330        }
1331
1332        if row_count == 0 {
1333            state.select(None);
1334        }
1335
1336        let column_count = self.column_count();
1337        if state.selected_column.is_some_and(|s| s >= column_count) {
1338            state.select_column(Some(column_count.saturating_sub(1)));
1339        }
1340        if column_count == 0 {
1341            state.select_column(None);
1342        }
1343
1344        let selection_width = self.selection_width(state);
1345        let symbol_columns = self
1346            .highlight_placement
1347            .column_mask(state.selected_column(), column_count);
1348        let column_widths = self.get_column_widths(
1349            table_area.width,
1350            selection_width,
1351            column_count,
1352            &symbol_columns,
1353        );
1354        grid.add_columns(table_area, &column_widths, &symbol_columns, selection_width);
1355        let [
1356            header_top,
1357            header_area,
1358            header_bottom,
1359            header_line,
1360            rows_area,
1361            footer_line,
1362            footer_top,
1363            footer_area,
1364            footer_bottom,
1365        ] = self.layout(table_area);
1366
1367        self.render_fixed_row(self.header.as_ref(), header_area, buf, &column_widths);
1368        if let Some(header) = &self.header {
1369            grid.add_spans(header_top.y..header_bottom.bottom(), header);
1370        }
1371        if !header_line.is_empty() {
1372            grid.add_horizontal(header_line.y);
1373        }
1374
1375        self.render_rows(
1376            rows_area,
1377            buf,
1378            selection_width,
1379            state,
1380            &column_widths,
1381            &symbol_columns,
1382            &mut grid,
1383        );
1384
1385        if !footer_line.is_empty() {
1386            grid.add_horizontal(footer_line.y);
1387        }
1388        self.render_fixed_row(self.footer.as_ref(), footer_area, buf, &column_widths);
1389        if let Some(footer) = &self.footer {
1390            grid.add_spans(footer_top.y..footer_bottom.bottom(), footer);
1391        }
1392
1393        grid.render(buf, &self.border_set, self.border_style);
1394    }
1395}
1396
1397// private methods for rendering
1398impl Table<'_> {
1399    fn layout(&self, area: Rect) -> [Rect; 9] {
1400        let header_top_margin = self.header.as_ref().map_or(0, |h| h.top_margin);
1401        let header_height = self.header.as_ref().map_or(0, |h| h.height);
1402        let header_bottom_margin = self.header.as_ref().map_or(0, |h| h.bottom_margin);
1403        let footer_top_margin = self.footer.as_ref().map_or(0, |h| h.top_margin);
1404        let footer_height = self.footer.as_ref().map_or(0, |f| f.height);
1405        let footer_bottom_margin = self.footer.as_ref().map_or(0, |h| h.bottom_margin);
1406        let header_line = u16::from(
1407            self.header.is_some() && self.borders.contains(TableBorders::HEADER_SEPARATOR),
1408        );
1409        let footer_line = u16::from(
1410            self.footer.is_some() && self.borders.contains(TableBorders::FOOTER_SEPARATOR),
1411        );
1412        Layout::vertical([
1413            Constraint::Length(header_top_margin),
1414            Constraint::Length(header_height),
1415            Constraint::Length(header_bottom_margin),
1416            Constraint::Length(header_line),
1417            Constraint::Min(0),
1418            Constraint::Length(footer_line),
1419            Constraint::Length(footer_top_margin),
1420            Constraint::Length(footer_height),
1421            Constraint::Length(footer_bottom_margin),
1422        ])
1423        .areas(area)
1424    }
1425
1426    /// The `x` and `width` fields of each `Rect` in `column_widths` denote the starting
1427    /// x-coordinate and width of each column in the table.
1428    fn render_fixed_row(
1429        &self,
1430        row: Option<&Row>,
1431        area: Rect,
1432        buf: &mut Buffer,
1433        column_widths: &[Rect],
1434    ) {
1435        if let Some(row) = row {
1436            buf.set_style(area, row.style);
1437            self.render_row_cells(buf, column_widths, &row.cells, area);
1438        }
1439    }
1440
1441    /// Render the table rows
1442    ///
1443    /// The `x` and `width` fields of each `Rect` in `column_widths` denote the starting
1444    /// x-coordinate and width of each column in the table.
1445    #[expect(clippy::too_many_arguments)]
1446    fn render_rows(
1447        &self,
1448        area: Rect,
1449        buf: &mut Buffer,
1450        selection_width: u16,
1451        state: &mut TableState,
1452        columns_widths: &[Rect],
1453        symbol_columns: &[bool],
1454        grid: &mut BorderGrid,
1455    ) {
1456        if let Some(ref provider) = self.lazy {
1457            self.render_lazy_rows(
1458                area,
1459                buf,
1460                selection_width,
1461                state,
1462                columns_widths,
1463                symbol_columns,
1464                provider,
1465                grid,
1466            );
1467            return;
1468        }
1469
1470        if self.rows.is_empty() {
1471            return;
1472        }
1473
1474        let (start_index, end_index) = self.visible_rows(state, area);
1475        state.offset = start_index;
1476
1477        let mut y_offset = 0_u16;
1478
1479        let mut selected_row_area = None;
1480        for (i, row) in self
1481            .rows
1482            .iter()
1483            .enumerate()
1484            .skip(start_index)
1485            .take(end_index - start_index)
1486        {
1487            let top = area.y.saturating_add(y_offset);
1488            let y = top.saturating_add(row.top_margin);
1489            let height = (y + row.height).min(area.bottom()).saturating_sub(y);
1490            let row_area = Rect { y, height, ..area };
1491            buf.set_style(row_area, row.style);
1492
1493            let is_selected = state.selected() == Some(i);
1494            self.render_highlight_symbol(
1495                buf,
1496                row_area,
1497                row,
1498                i,
1499                start_index,
1500                state,
1501                columns_widths,
1502                symbol_columns,
1503                selection_width,
1504            );
1505            self.render_row_cells(buf, columns_widths, &row.cells, row_area);
1506            if is_selected {
1507                selected_row_area = Some(row_area);
1508            }
1509            y_offset = y_offset.saturating_add(row.height_with_margin());
1510            let line_y = area.y.saturating_add(y_offset);
1511            grid.add_spans(top..line_y.min(area.bottom()), row);
1512            let below = self.borders.separator_height_below(i, self.rows.len());
1513            if below > 0 && i + 1 < end_index && line_y < area.bottom() {
1514                grid.add_horizontal(line_y);
1515            }
1516            y_offset = y_offset.saturating_add(below);
1517        }
1518
1519        self.apply_highlight_styles(buf, area, selected_row_area, state, columns_widths);
1520    }
1521
1522    /// Render visible rows from a lazy provider, calling the factory only for the visible range.
1523    #[expect(clippy::too_many_arguments)]
1524    fn render_lazy_rows(
1525        &self,
1526        area: Rect,
1527        buf: &mut Buffer,
1528        selection_width: u16,
1529        state: &mut TableState,
1530        columns_widths: &[Rect],
1531        symbol_columns: &[bool],
1532        provider: &LazyRowProvider,
1533        grid: &mut BorderGrid,
1534    ) {
1535        if provider.count == 0 {
1536            return;
1537        }
1538
1539        let (start_index, end_index) = provider.visible_rows(state, area, self.borders);
1540        state.offset = start_index;
1541
1542        let mut y = area.y;
1543        let mut selected_row_area = None;
1544
1545        for index in start_index..end_index {
1546            let row = (provider.factory)(index);
1547            // The provider owns the geometry: a height or margin set on the row would make what is
1548            // drawn disagree with the scroll calculation, which never sees the row itself.
1549            let row_height = provider.height_of(index);
1550            let height = y
1551                .saturating_add(row_height)
1552                .min(area.bottom())
1553                .saturating_sub(y);
1554            let row_area = Rect { y, height, ..area };
1555            buf.set_style(row_area, row.style);
1556
1557            let is_selected = state.selected() == Some(index);
1558            self.render_highlight_symbol(
1559                buf,
1560                row_area,
1561                &row,
1562                index,
1563                start_index,
1564                state,
1565                columns_widths,
1566                symbol_columns,
1567                selection_width,
1568            );
1569            self.render_row_cells(buf, columns_widths, &row.cells, row_area);
1570            if is_selected {
1571                selected_row_area = Some(row_area);
1572            }
1573            grid.add_spans(y..y.saturating_add(row_height).min(area.bottom()), &row);
1574            y = y.saturating_add(row_height);
1575            let below = self.borders.separator_height_below(index, provider.count);
1576            if below > 0 && index + 1 < end_index && y < area.bottom() {
1577                grid.add_horizontal(y);
1578            }
1579            y = y.saturating_add(below);
1580        }
1581
1582        self.apply_highlight_styles(buf, area, selected_row_area, state, columns_widths);
1583    }
1584
1585    /// Apply row, column, and cell highlight styles after rows have been rendered.
1586    fn apply_highlight_styles(
1587        &self,
1588        buf: &mut Buffer,
1589        area: Rect,
1590        selected_row_area: Option<Rect>,
1591        state: &TableState,
1592        columns_widths: &[Rect],
1593    ) {
1594        let selected_column_area = state.selected_column().and_then(|s| {
1595            // The selection is clamped by the column count. Since a user can manually specify an
1596            // incorrect number of widths, we should use panic free methods.
1597            columns_widths.get(s).map(|cell_area| Rect {
1598                x: cell_area.x + area.x,
1599                width: cell_area.width,
1600                ..area
1601            })
1602        });
1603
1604        match (selected_row_area, selected_column_area) {
1605            (Some(row_area), Some(col_area)) => {
1606                buf.set_style(row_area, self.row_highlight_style);
1607                buf.set_style(col_area, self.column_highlight_style);
1608                let cell_area = row_area.intersection(col_area);
1609                buf.set_style(cell_area, self.cell_highlight_style);
1610            }
1611            (Some(row_area), None) => {
1612                buf.set_style(row_area, self.row_highlight_style);
1613            }
1614            (None, Some(col_area)) => {
1615                buf.set_style(col_area, self.column_highlight_style);
1616            }
1617            (None, None) => (),
1618        }
1619    }
1620
1621    /// Render cells into the columns of a row
1622    ///
1623    /// Render `Cell`s from `cells` into columns specified by `column_widths`, stopping
1624    /// if either of these iterators are finished.  Each `Cell` gets rendered across
1625    /// [`Cell::get_column_span`] columns plus the gaps between them, if this value is > 1.
1626    fn render_row_cells(
1627        &self,
1628        buf: &mut Buffer,
1629        column_widths: &[Rect],
1630        cells: &[Cell],
1631        row_area: Rect,
1632    ) {
1633        let mut column_widths_iterator = column_widths.iter();
1634        for current_cell in cells {
1635            if let Some(cell_area) = Self::get_cell_area(
1636                &mut column_widths_iterator,
1637                current_cell.column_span,
1638                self.borders.column_spacing(self.column_spacing),
1639            ) {
1640                let new_x = row_area.x + cell_area.x;
1641                let area_to_render = Rect::new(new_x, row_area.y, cell_area.width, row_area.height);
1642                current_cell.render(area_to_render, buf);
1643            }
1644        }
1645    }
1646
1647    /// Render the highlight symbol into every slot of the selected row.
1648    ///
1649    /// The two axes are anchored independently: [`HighlightPlacement`] alone decides which columns
1650    /// have a slot, and the selection alone decides which row the symbols land on. Requiring the
1651    /// slot to sit at the *selected* column instead would erase the symbol under the default
1652    /// [`HighlightPlacement::FirstColumn`] whenever a column other than the first is selected.
1653    ///
1654    /// A column-only selection has no row to anchor to, so it uses the topmost visible row —
1655    /// pinning it to row 0 would hide the symbol as soon as the table scrolls.
1656    ///
1657    /// Slots are per *column index*, not per [`Cell`]: [`Cell::column_span`] makes the two differ,
1658    /// so folding this into `render_row_cells` would misplace the symbol on spanned rows.
1659    #[expect(clippy::too_many_arguments)]
1660    fn render_highlight_symbol(
1661        &self,
1662        buf: &mut Buffer,
1663        row_area: Rect,
1664        row: &Row,
1665        row_index: usize,
1666        first_visible_row: usize,
1667        state: &TableState,
1668        columns_widths: &[Rect],
1669        symbol_columns: &[bool],
1670        selection_width: u16,
1671    ) {
1672        if selection_width == 0 {
1673            return;
1674        }
1675        if state.selected().is_none() && state.selected_column().is_none() {
1676            return;
1677        }
1678        if row_index != state.selected().unwrap_or(first_visible_row) {
1679            return;
1680        }
1681
1682        for (column_index, cell_area) in columns_widths.iter().enumerate() {
1683            if !symbol_columns.get(column_index).copied().unwrap_or(false) {
1684                continue;
1685            }
1686            let symbol_area = Rect {
1687                x: (row_area.x + cell_area.x).saturating_sub(selection_width),
1688                width: selection_width,
1689                ..row_area
1690            };
1691            buf.set_style(symbol_area, row.style);
1692            (&self.highlight_symbol).render(symbol_area, buf);
1693        }
1694    }
1695
1696    /// Return the area that a [`Cell`] should occupy, taking into account its
1697    /// [`Cell::column_span`].
1698    ///
1699    /// Returns `None` when there are no more columns for the [`Cell`] to occupy.
1700    ///
1701    /// Otherwise, returns `Some(Rect{x, y = 0, width, height = 0})`, representing the start
1702    /// x-coordinate and width of the [`Cell`].
1703    ///
1704    /// This function consumes `cell_column_span` `Rect`s from `column_widths_iterator` (or all the
1705    /// `Rects` if the iterator is less than `cell_column_span` `Rect`s long). This function adds
1706    /// the width of each `Rect` plus `column_spacing` to a running total of the final width.  The
1707    /// return value is the original x coordinate and the final width, or `None` if
1708    /// `column_widths_iterator` is empty or `cell_column_span` is `0`.
1709    fn get_cell_area<'a, T>(
1710        column_widths_iterator: &mut T,
1711        cell_column_span: u16,
1712        column_spacing: u16,
1713    ) -> Option<Rect>
1714    where
1715        T: Iterator<Item = &'a Rect>,
1716    {
1717        if cell_column_span == 0 {
1718            return None;
1719        }
1720        let first = column_widths_iterator.next()?;
1721        let (n_columns_taken, all_columns_width) = column_widths_iterator
1722            .take((cell_column_span - 1).into())
1723            .map(|rect| (1, rect.width))
1724            .fold((1, first.width), |so_far, next_column| {
1725                (next_column.0 + so_far.0, next_column.1 + so_far.1)
1726            });
1727        let width = all_columns_width + (n_columns_taken - 1) * column_spacing;
1728        Some(Rect::new(first.x, first.y, width, 1))
1729    }
1730
1731    fn visible_rows(&self, state: &TableState, area: Rect) -> (usize, usize) {
1732        visible_row_range(self.rows.len(), state, area, self.borders, |index| {
1733            let row = &self.rows[index];
1734            (row.height, row.height_with_margin())
1735        })
1736    }
1737
1738    /// Get all offsets and widths of all user specified columns.
1739    ///
1740    /// Returns (x, width). When self.widths is empty, it is assumed `.widths()` has not been called
1741    /// and a default of equal widths is returned.
1742    fn get_column_widths(
1743        &self,
1744        max_width: u16,
1745        selection_width: u16,
1746        col_count: usize,
1747        symbol_columns: &[bool],
1748    ) -> Vec<Rect> {
1749        let widths = if self.widths.is_empty() {
1750            // Divide the space between each column equally
1751            vec![Constraint::Length(max_width / col_count.max(1) as u16); col_count]
1752        } else {
1753            self.widths.clone()
1754        };
1755
1756        // Reserve one symbol slot per qualifying column up front, lay the columns out in what is
1757        // left, then push each column right past the slots that precede it. Two passes rather
1758        // than interleaving the slots into the constraints, so `flex` and `column_spacing` keep
1759        // acting on the columns alone.
1760        let slots = symbol_columns.iter().filter(|slot| **slot).count() as u16;
1761        let content_width = max_width.saturating_sub(selection_width * slots);
1762        let rects = Layout::horizontal(widths)
1763            .flex(self.flex)
1764            .spacing(self.borders.column_spacing(self.column_spacing))
1765            .split(Rect::new(0, 0, content_width, 1));
1766
1767        let mut shift = 0;
1768        rects
1769            .iter()
1770            .enumerate()
1771            .map(|(index, rect)| {
1772                if symbol_columns.get(index).copied().unwrap_or(false) {
1773                    shift += selection_width;
1774                }
1775                Rect::new(rect.x + shift, 0, rect.width, 1)
1776            })
1777            .collect()
1778    }
1779
1780    /// The number of rows in the table, whether they are stored eagerly or built lazily.
1781    fn row_count(&self) -> usize {
1782        self.lazy
1783            .as_ref()
1784            .map_or(self.rows.len(), |provider| provider.count)
1785    }
1786
1787    fn column_count(&self) -> usize {
1788        // Lazy rows cannot be inspected without building them, so the column count comes from the
1789        // widths (which `Table::lazy_rows` requires) and from the header and footer.
1790        let lazy_columns = if self.lazy.is_some() {
1791            self.widths.len()
1792        } else {
1793            0
1794        };
1795        self.rows
1796            .iter()
1797            .chain(self.footer.iter())
1798            .chain(self.header.iter())
1799            .map(|row| {
1800                row.cells
1801                    .iter()
1802                    .map(|cell| usize::from(cell.column_span))
1803                    .sum()
1804            })
1805            .chain(Some(lazy_columns))
1806            .max()
1807            .unwrap_or_default()
1808    }
1809
1810    /// Returns the width of the selection column if anything is selected, or the
1811    /// `highlight_spacing` is set to show the column always, otherwise 0.
1812    ///
1813    /// Any selection counts, not just a row: `HighlightPlacement::SelectedColumn` would have
1814    /// nowhere to draw if a column-only selection reserved no space.
1815    fn selection_width(&self, state: &TableState) -> u16 {
1816        let has_selection = state.selected().is_some() || state.selected_column().is_some();
1817        if self.highlight_spacing.should_add(has_selection) {
1818            self.highlight_symbol.width() as u16
1819        } else {
1820            0
1821        }
1822    }
1823}
1824
1825fn ensure_percentages_less_than_100(widths: &[Constraint]) {
1826    for w in widths {
1827        if let Constraint::Percentage(p) = w {
1828            assert!(
1829                *p <= 100,
1830                "Percentages should be between 0 and 100 inclusively."
1831            );
1832        }
1833    }
1834}
1835
1836impl Styled for Table<'_> {
1837    type Item = Self;
1838
1839    fn style(&self) -> Style {
1840        self.style
1841    }
1842
1843    fn set_style<S: Into<Style>>(self, style: S) -> Self::Item {
1844        self.style(style)
1845    }
1846}
1847
1848impl<'a, Item> FromIterator<Item> for Table<'a>
1849where
1850    Item: Into<Row<'a>>,
1851{
1852    /// Collects an iterator of rows into a table.
1853    ///
1854    /// When collecting from an iterator into a table, the user must provide the widths using
1855    /// `Table::widths` after construction.
1856    fn from_iter<Iter: IntoIterator<Item = Item>>(rows: Iter) -> Self {
1857        let widths: [Constraint; 0] = [];
1858        Self::new(rows, widths)
1859    }
1860}
1861
1862#[cfg(test)]
1863mod tests {
1864    use alloc::string::ToString;
1865    use alloc::{format, vec};
1866
1867    use ratatui_core::layout::Constraint::*;
1868    use ratatui_core::style::{Color, Modifier, Style, Stylize};
1869    use ratatui_core::text::Line;
1870    use rstest::{fixture, rstest};
1871
1872    use super::*;
1873    use crate::table::Cell;
1874
1875    /// A row taller than the remaining space must end the window instead of wrapping the
1876    /// running line total, which needs an area tall enough for that total to reach `u16::MAX`.
1877    #[test]
1878    fn lazy_visible_rows_do_not_overflow_the_line_total() {
1879        let table = Table::lazy_rows(4, [Constraint::Length(1)], |_| Row::new(["x"]))
1880            .lazy_row_height_with(|index| if index == 0 { u16::MAX } else { 1 });
1881        let lazy = table.lazy.as_ref().expect("lazy rows");
1882        let area = Rect::new(0, 0, 1, u16::MAX);
1883
1884        let state = TableState::default();
1885        assert_eq!(
1886            lazy.visible_rows(&state, area, TableBorders::empty()),
1887            (0, 1)
1888        );
1889
1890        let state = TableState::default().with_selected(3);
1891        assert_eq!(
1892            lazy.visible_rows(&state, area, TableBorders::empty()),
1893            (1, 4)
1894        );
1895    }
1896
1897    #[test]
1898    fn new() {
1899        let rows = [Row::new(vec![Cell::from("")])];
1900        let widths = [Constraint::Percentage(100)];
1901        let table = Table::new(rows.clone(), widths);
1902        assert_eq!(table.rows, rows);
1903        assert_eq!(table.header, None);
1904        assert_eq!(table.footer, None);
1905        assert_eq!(table.widths, widths);
1906        assert_eq!(table.column_spacing, 1);
1907        assert_eq!(table.block, None);
1908        assert_eq!(table.style, Style::default());
1909        assert_eq!(table.row_highlight_style, Style::default());
1910        assert_eq!(table.highlight_symbol, Text::default());
1911        assert_eq!(table.highlight_spacing, HighlightSpacing::WhenSelected);
1912        assert_eq!(table.flex, Flex::Start);
1913    }
1914
1915    #[test]
1916    fn default() {
1917        let table = Table::default();
1918        assert_eq!(table.rows, []);
1919        assert_eq!(table.header, None);
1920        assert_eq!(table.footer, None);
1921        assert_eq!(table.widths, []);
1922        assert_eq!(table.column_spacing, 1);
1923        assert_eq!(table.block, None);
1924        assert_eq!(table.style, Style::default());
1925        assert_eq!(table.row_highlight_style, Style::default());
1926        assert_eq!(table.highlight_symbol, Text::default());
1927        assert_eq!(table.highlight_spacing, HighlightSpacing::WhenSelected);
1928        assert_eq!(table.flex, Flex::Start);
1929    }
1930
1931    #[test]
1932    fn collect() {
1933        let table = (0..4)
1934            .map(|i| -> Row { (0..4).map(|j| format!("{i}*{j} = {}", i * j)).collect() })
1935            .collect::<Table>()
1936            .widths([Constraint::Percentage(25); 4]);
1937
1938        let expected_rows: Vec<Row> = vec![
1939            Row::new(["0*0 = 0", "0*1 = 0", "0*2 = 0", "0*3 = 0"]),
1940            Row::new(["1*0 = 0", "1*1 = 1", "1*2 = 2", "1*3 = 3"]),
1941            Row::new(["2*0 = 0", "2*1 = 2", "2*2 = 4", "2*3 = 6"]),
1942            Row::new(["3*0 = 0", "3*1 = 3", "3*2 = 6", "3*3 = 9"]),
1943        ];
1944
1945        assert_eq!(table.rows, expected_rows);
1946        assert_eq!(table.widths, [Constraint::Percentage(25); 4]);
1947    }
1948
1949    #[test]
1950    fn widths() {
1951        let table = Table::default().widths([Constraint::Length(100)]);
1952        assert_eq!(table.widths, [Constraint::Length(100)]);
1953
1954        // ensure that code that uses &[] continues to work as there is a large amount of code that
1955        // uses this pattern
1956        #[expect(clippy::needless_borrows_for_generic_args)]
1957        let table = Table::default().widths(&[Constraint::Length(100)]);
1958        assert_eq!(table.widths, [Constraint::Length(100)]);
1959
1960        let table = Table::default().widths(vec![Constraint::Length(100)]);
1961        assert_eq!(table.widths, [Constraint::Length(100)]);
1962
1963        // ensure that code that uses &some_vec continues to work as there is a large amount of code
1964        // that uses this pattern
1965        #[expect(clippy::needless_borrows_for_generic_args)]
1966        let table = Table::default().widths(&vec![Constraint::Length(100)]);
1967        assert_eq!(table.widths, [Constraint::Length(100)]);
1968
1969        let table = Table::default().widths([100].into_iter().map(Constraint::Length));
1970        assert_eq!(table.widths, [Constraint::Length(100)]);
1971    }
1972
1973    #[test]
1974    fn rows() {
1975        let rows = [Row::new(vec![Cell::from("")])];
1976        let table = Table::default().rows(rows.clone());
1977        assert_eq!(table.rows, rows);
1978    }
1979
1980    #[test]
1981    fn column_spacing() {
1982        let table = Table::default().column_spacing(2);
1983        assert_eq!(table.column_spacing, 2);
1984    }
1985
1986    #[test]
1987    fn block() {
1988        let block = Block::bordered().title("Table");
1989        let table = Table::default().block(block.clone());
1990        assert_eq!(table.block, Some(block));
1991    }
1992
1993    #[test]
1994    fn header() {
1995        let header = Row::new(vec![Cell::from("")]);
1996        let table = Table::default().header(header.clone());
1997        assert_eq!(table.header, Some(header));
1998    }
1999
2000    #[test]
2001    fn footer() {
2002        let footer = Row::new(vec![Cell::from("")]);
2003        let table = Table::default().footer(footer.clone());
2004        assert_eq!(table.footer, Some(footer));
2005    }
2006
2007    #[test]
2008    #[expect(deprecated)]
2009    fn highlight_style() {
2010        let style = Style::default().red().italic();
2011        let table = Table::default().highlight_style(style);
2012        assert_eq!(table.row_highlight_style, style);
2013    }
2014
2015    #[test]
2016    fn row_highlight_style() {
2017        let style = Style::default().red().italic();
2018        let table = Table::default().row_highlight_style(style);
2019        assert_eq!(table.row_highlight_style, style);
2020    }
2021
2022    #[test]
2023    fn column_highlight_style() {
2024        let style = Style::default().red().italic();
2025        let table = Table::default().column_highlight_style(style);
2026        assert_eq!(table.column_highlight_style, style);
2027    }
2028
2029    #[test]
2030    fn cell_highlight_style() {
2031        let style = Style::default().red().italic();
2032        let table = Table::default().cell_highlight_style(style);
2033        assert_eq!(table.cell_highlight_style, style);
2034    }
2035
2036    #[test]
2037    fn highlight_symbol() {
2038        let table = Table::default().highlight_symbol(">>");
2039        assert_eq!(table.highlight_symbol, Text::from(">>"));
2040    }
2041
2042    #[test]
2043    fn highlight_spacing() {
2044        let table = Table::default().highlight_spacing(HighlightSpacing::Always);
2045        assert_eq!(table.highlight_spacing, HighlightSpacing::Always);
2046    }
2047
2048    #[test]
2049    #[should_panic = "Percentages should be between 0 and 100 inclusively"]
2050    fn table_invalid_percentages() {
2051        let _ = Table::default().widths([Constraint::Percentage(110)]);
2052    }
2053
2054    #[test]
2055    fn widths_conversions() {
2056        let array = [Constraint::Percentage(100)];
2057        let table = Table::new(Vec::<Row>::new(), array);
2058        assert_eq!(table.widths, [Constraint::Percentage(100)], "array");
2059
2060        let array_ref = &[Constraint::Percentage(100)];
2061        let table = Table::new(Vec::<Row>::new(), array_ref);
2062        assert_eq!(table.widths, [Constraint::Percentage(100)], "array ref");
2063
2064        let vec = vec![Constraint::Percentage(100)];
2065        let slice = vec.as_slice();
2066        let table = Table::new(Vec::<Row>::new(), slice);
2067        assert_eq!(table.widths, [Constraint::Percentage(100)], "slice");
2068
2069        let vec = vec![Constraint::Percentage(100)];
2070        let table = Table::new(Vec::<Row>::new(), vec);
2071        assert_eq!(table.widths, [Constraint::Percentage(100)], "vec");
2072
2073        let vec_ref = &vec![Constraint::Percentage(100)];
2074        let table = Table::new(Vec::<Row>::new(), vec_ref);
2075        assert_eq!(table.widths, [Constraint::Percentage(100)], "vec ref");
2076    }
2077
2078    #[cfg(test)]
2079    mod state {
2080        use ratatui_core::buffer::Buffer;
2081        use ratatui_core::layout::{Constraint, Rect};
2082        use ratatui_core::widgets::StatefulWidget;
2083
2084        use super::*;
2085        use crate::table::{Row, Table, TableState};
2086
2087        #[fixture]
2088        fn table_buf() -> Buffer {
2089            Buffer::empty(Rect::new(0, 0, 10, 10))
2090        }
2091
2092        #[rstest]
2093        fn test_list_state_empty_list(mut table_buf: Buffer) {
2094            let mut state = TableState::default();
2095
2096            let rows: Vec<Row> = Vec::new();
2097            let widths = vec![Constraint::Percentage(100)];
2098            let table = Table::new(rows, widths);
2099            state.select_first();
2100            StatefulWidget::render(table, table_buf.area, &mut table_buf, &mut state);
2101            assert_eq!(state.selected(), None);
2102            assert_eq!(state.selected_column(), None);
2103        }
2104
2105        #[rstest]
2106        fn test_list_state_single_item(mut table_buf: Buffer) {
2107            let mut state = TableState::default();
2108
2109            let widths = vec![Constraint::Percentage(100)];
2110
2111            let items = vec![Row::new(vec!["Item 1"])];
2112            let table = Table::new(items, widths);
2113            state.select_first();
2114            StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
2115            assert_eq!(state.selected(), Some(0));
2116            assert_eq!(state.selected_column(), None);
2117
2118            state.select_last();
2119            StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
2120            assert_eq!(state.selected(), Some(0));
2121            assert_eq!(state.selected_column(), None);
2122
2123            state.select_previous();
2124            StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
2125            assert_eq!(state.selected(), Some(0));
2126            assert_eq!(state.selected_column(), None);
2127
2128            state.select_next();
2129            StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
2130            assert_eq!(state.selected(), Some(0));
2131            assert_eq!(state.selected_column(), None);
2132
2133            let mut state = TableState::default();
2134
2135            state.select_first_column();
2136            StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
2137            assert_eq!(state.selected_column(), Some(0));
2138            assert_eq!(state.selected(), None);
2139
2140            state.select_last_column();
2141            StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
2142            assert_eq!(state.selected_column(), Some(0));
2143            assert_eq!(state.selected(), None);
2144
2145            state.select_previous_column();
2146            StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
2147            assert_eq!(state.selected_column(), Some(0));
2148            assert_eq!(state.selected(), None);
2149
2150            state.select_next_column();
2151            StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
2152            assert_eq!(state.selected_column(), Some(0));
2153            assert_eq!(state.selected(), None);
2154        }
2155    }
2156
2157    #[cfg(test)]
2158    mod render {
2159        use ratatui_core::layout::Alignment;
2160
2161        use super::*;
2162
2163        #[test]
2164        fn render_empty_area() {
2165            let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2166            let rows = vec![Row::new(vec!["Cell1", "Cell2"])];
2167            let table = Table::new(rows, vec![Constraint::Length(5); 2]);
2168            Widget::render(table, Rect::new(0, 0, 0, 0), &mut buf);
2169            assert_eq!(buf, Buffer::empty(Rect::new(0, 0, 15, 3)));
2170        }
2171
2172        #[test]
2173        fn render_default() {
2174            let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2175            let table = Table::default();
2176            Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
2177            assert_eq!(buf, Buffer::empty(Rect::new(0, 0, 15, 3)));
2178        }
2179
2180        #[test]
2181        fn render_with_block() {
2182            let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2183            let rows = vec![
2184                Row::new(vec!["Cell1", "Cell2"]),
2185                Row::new(vec!["Cell3", "Cell4"]),
2186            ];
2187            let block = Block::bordered().title("Block");
2188            let table = Table::new(rows, vec![Constraint::Length(5); 2]).block(block);
2189            Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
2190            #[rustfmt::skip]
2191            let expected = Buffer::with_lines([
2192                "┌Block────────┐",
2193                "│Cell1 Cell2  │",
2194                "└─────────────┘",
2195            ]);
2196            assert_eq!(buf, expected);
2197        }
2198
2199        #[rstest]
2200        #[case(15, 5, vec![
2201                Row::new(vec![
2202                    Cell::new("Cell1").column_span(1),
2203                    Cell::new("Cell2").column_span(1),
2204                ]),
2205                Row::new(vec![
2206                    Cell::new("Cell3").column_span(1),
2207                    Cell::new("Cell4").column_span(1),
2208                ]),
2209            ],
2210            &Buffer::with_lines(["Cell1 Cell2    ", "Cell3 Cell4    "]))]
2211        #[case(15, 5, vec![
2212                Row::new(vec![
2213                    Cell::new("Cell1").column_span(0),
2214                    Cell::new("Cell2").column_span(1),
2215                ]),
2216                Row::new(vec![
2217                    Cell::new("Cell3").column_span(1),
2218                    Cell::new("Cell4").column_span(1),
2219                ]),
2220            ], &Buffer::with_lines(["Cell2          ", "Cell3 Cell4    "]))]
2221        #[case(15, 5, vec![
2222                Row::new(vec![
2223                    Cell::new("Cell1").column_span(2),
2224                    Cell::new("Cell2").column_span(1),
2225                ]),
2226                Row::new(vec![
2227                    Cell::new("Cell3").column_span(1),
2228                    Cell::new("Cell4").column_span(1),
2229                ]),
2230            ], &Buffer::with_lines(["Cell1          ", "Cell3 Cell4    "]))]
2231        fn test_colspans_2_cols<'rows, Rows>(
2232            #[case] width: u16,
2233            #[case] column_width: u16,
2234            #[case] rows: Rows,
2235            #[case] expected: &Buffer,
2236        ) where
2237            Rows: IntoIterator<Item = Row<'rows>>,
2238        {
2239            let mut buf = Buffer::empty(Rect::new(0, 0, width, 2));
2240            let table = Table::new(rows, [Constraint::Length(column_width); 2]);
2241            Widget::render(table, Rect::new(0, 0, width, 2), &mut buf);
2242            assert_eq!(buf, *expected);
2243        }
2244
2245        #[rstest]
2246        #[case(17, 5, vec![
2247                Row::new(vec![
2248                    Cell::new("Cell1").column_span(2),
2249                    Cell::new("Cell2").column_span(1),
2250                ]),
2251                Row::new(vec![
2252                    Cell::new("Cell3").column_span(1),
2253                    Cell::new("Cell4").column_span(1),
2254                    Cell::new("Cell5").column_span(1),
2255                ]),
2256            ], &Buffer::with_lines(["Cell1       Cell2", "Cell3 Cell4 Cell5"]))]
2257        #[case(17, 5, vec![
2258                Row::new(vec![
2259                    Cell::new("Cell1").column_span(1),
2260                    Cell::new("Cell2").column_span(2),
2261                    Cell::new("Cell3").column_span(1),
2262                ]),
2263                Row::new(vec![
2264                    Cell::new("Cell4").column_span(1),
2265                    Cell::new("Cell5").column_span(1),
2266                    Cell::new("Cell6").column_span(1),
2267                ]),
2268            ], &Buffer::with_lines(["Cell1 Cell2      ", "Cell4 Cell5 Cell6"]))]
2269        #[case(15, 5, vec![
2270                Row::new(vec![
2271                    Cell::new("11111111111111111111").column_span(2),
2272                    Cell::new("22222222222222222222").column_span(1),
2273                ]),
2274                Row::new(vec![
2275                    Cell::new("33333333333333333333").column_span(1),
2276                    Cell::new("44444444444444444444").column_span(2),
2277                    Cell::new("55555555555555555555").column_span(1),
2278                ]),
2279            ], &Buffer::with_lines(["1111111111 2222", "3333 4444444444"]))]
2280        fn test_colspans_3_cols<'rows, Rows>(
2281            #[case] width: u16,
2282            #[case] column_width: u16,
2283            #[case] rows: Rows,
2284            #[case] expected: &Buffer,
2285        ) where
2286            Rows: IntoIterator<Item = Row<'rows>>,
2287        {
2288            let mut buf = Buffer::empty(Rect::new(0, 0, width, 2));
2289            let table = Table::new(rows, [Constraint::Length(column_width); 3]);
2290            Widget::render(table, Rect::new(0, 0, width, 2), &mut buf);
2291            assert_eq!(buf, *expected);
2292        }
2293
2294        #[test]
2295        fn render_with_header() {
2296            let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2297            let header = Row::new(vec!["Head1", "Head2"]);
2298            let rows = vec![
2299                Row::new(vec!["Cell1", "Cell2"]),
2300                Row::new(vec!["Cell3", "Cell4"]),
2301            ];
2302            let table = Table::new(rows, [Constraint::Length(5); 2]).header(header);
2303            Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
2304            #[rustfmt::skip]
2305            let expected = Buffer::with_lines([
2306                "Head1 Head2    ",
2307                "Cell1 Cell2    ",
2308                "Cell3 Cell4    ",
2309            ]);
2310            assert_eq!(buf, expected);
2311        }
2312
2313        #[test]
2314        fn render_with_footer() {
2315            let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2316            let footer = Row::new(vec!["Foot1", "Foot2"]);
2317            let rows = vec![
2318                Row::new(vec!["Cell1", "Cell2"]),
2319                Row::new(vec!["Cell3", "Cell4"]),
2320            ];
2321            let table = Table::new(rows, [Constraint::Length(5); 2]).footer(footer);
2322            Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
2323            #[rustfmt::skip]
2324            let expected = Buffer::with_lines([
2325                "Cell1 Cell2    ",
2326                "Cell3 Cell4    ",
2327                "Foot1 Foot2    ",
2328            ]);
2329            assert_eq!(buf, expected);
2330        }
2331
2332        #[test]
2333        fn render_with_header_and_footer() {
2334            let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2335            let header = Row::new(vec!["Head1", "Head2"]);
2336            let footer = Row::new(vec!["Foot1", "Foot2"]);
2337            let rows = vec![Row::new(vec!["Cell1", "Cell2"])];
2338            let table = Table::new(rows, [Constraint::Length(5); 2])
2339                .header(header)
2340                .footer(footer);
2341            Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
2342            #[rustfmt::skip]
2343            let expected = Buffer::with_lines([
2344                "Head1 Head2    ",
2345                "Cell1 Cell2    ",
2346                "Foot1 Foot2    ",
2347            ]);
2348            assert_eq!(buf, expected);
2349        }
2350
2351        #[test]
2352        fn render_header_and_footer_cells_across_their_column_span() {
2353            let mut buf = Buffer::empty(Rect::new(0, 0, 11, 3));
2354            let table = Table::new([Row::new(["a", "b"])], [Constraint::Length(5); 2])
2355                .header(Row::new([Cell::new("Header spans").column_span(2)]))
2356                .footer(Row::new([Cell::new("Footer spans").column_span(2)]));
2357            Widget::render(table, buf.area, &mut buf);
2358            #[rustfmt::skip]
2359            let expected = Buffer::with_lines([
2360                "Header span",
2361                "a     b    ",
2362                "Footer span",
2363            ]);
2364            assert_eq!(buf, expected);
2365        }
2366
2367        #[test]
2368        fn render_default_widths_split_between_every_spanned_column() {
2369            let mut buf = Buffer::empty(Rect::new(0, 0, 11, 1));
2370            let rows = [Row::new([Cell::new("AB").column_span(2), Cell::new("C")])];
2371            Widget::render(Table::default().rows(rows), buf.area, &mut buf);
2372            assert_eq!(buf, Buffer::with_lines(["AB      C  "]));
2373        }
2374
2375        #[test]
2376        fn render_keeps_selected_column_covered_by_a_spanned_cell() {
2377            let mut buf = Buffer::empty(Rect::new(0, 0, 5, 1));
2378            let rows = [Row::new([Cell::new("AB").column_span(2), Cell::new("C")])];
2379            let table = Table::new(rows, [Constraint::Length(1); 3]);
2380            let mut state = TableState::new().with_selected_column(Some(2));
2381            StatefulWidget::render(table, buf.area, &mut buf, &mut state);
2382            assert_eq!(state.selected_column(), Some(2));
2383        }
2384
2385        #[test]
2386        fn render_with_header_margin() {
2387            let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2388            let header = Row::new(vec!["Head1", "Head2"]).bottom_margin(1);
2389            let rows = vec![
2390                Row::new(vec!["Cell1", "Cell2"]),
2391                Row::new(vec!["Cell3", "Cell4"]),
2392            ];
2393            let table = Table::new(rows, [Constraint::Length(5); 2]).header(header);
2394            Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
2395            #[rustfmt::skip]
2396            let expected = Buffer::with_lines([
2397                "Head1 Head2    ",
2398                "               ",
2399                "Cell1 Cell2    ",
2400            ]);
2401            assert_eq!(buf, expected);
2402        }
2403
2404        #[test]
2405        fn render_with_footer_margin() {
2406            let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2407            let footer = Row::new(vec!["Foot1", "Foot2"]).top_margin(1);
2408            let rows = vec![Row::new(vec!["Cell1", "Cell2"])];
2409            let table = Table::new(rows, [Constraint::Length(5); 2]).footer(footer);
2410            Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
2411            #[rustfmt::skip]
2412            let expected = Buffer::with_lines([
2413                "Cell1 Cell2    ",
2414                "               ",
2415                "Foot1 Foot2    ",
2416            ]);
2417            assert_eq!(buf, expected);
2418        }
2419
2420        #[test]
2421        fn render_with_row_margin() {
2422            let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2423            let rows = vec![
2424                Row::new(vec!["Cell1", "Cell2"]).bottom_margin(1),
2425                Row::new(vec!["Cell3", "Cell4"]),
2426            ];
2427            let table = Table::new(rows, [Constraint::Length(5); 2]);
2428            Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
2429            #[rustfmt::skip]
2430            let expected = Buffer::with_lines([
2431                "Cell1 Cell2    ",
2432                "               ",
2433                "Cell3 Cell4    ",
2434            ]);
2435            assert_eq!(buf, expected);
2436        }
2437
2438        #[test]
2439        fn render_with_tall_row() {
2440            let mut buf = Buffer::empty(Rect::new(0, 0, 23, 3));
2441            let rows = vec![
2442                Row::new(vec!["Cell1", "Cell2"]),
2443                Row::new(vec![
2444                    Text::raw("Cell3-Line1\nCell3-Line2\nCell3-Line3"),
2445                    Text::raw("Cell4-Line1\nCell4-Line2\nCell4-Line3"),
2446                ])
2447                .height(3),
2448            ];
2449            let table = Table::new(rows, [Constraint::Length(11); 2]);
2450            Widget::render(table, Rect::new(0, 0, 23, 3), &mut buf);
2451            #[rustfmt::skip]
2452            let expected = Buffer::with_lines([
2453                "Cell1       Cell2      ",
2454                "Cell3-Line1 Cell4-Line1",
2455                "Cell3-Line2 Cell4-Line2",
2456            ]);
2457            assert_eq!(buf, expected);
2458        }
2459
2460        #[test]
2461        fn render_with_alignment() {
2462            let mut buf = Buffer::empty(Rect::new(0, 0, 10, 3));
2463            let rows = vec![
2464                Row::new(vec![Line::from("Left").alignment(Alignment::Left)]),
2465                Row::new(vec![Line::from("Center").alignment(Alignment::Center)]),
2466                Row::new(vec![Line::from("Right").alignment(Alignment::Right)]),
2467            ];
2468            let table = Table::new(rows, [Percentage(100)]);
2469            Widget::render(table, Rect::new(0, 0, 10, 3), &mut buf);
2470            let expected = Buffer::with_lines(["Left      ", "  Center  ", "     Right"]);
2471            assert_eq!(buf, expected);
2472        }
2473
2474        #[test]
2475        fn render_with_overflow_does_not_panic() {
2476            let mut buf = Buffer::empty(Rect::new(0, 0, 20, 3));
2477            let table = Table::new(Vec::<Row>::new(), [Constraint::Min(20); 1])
2478                .header(Row::new([Line::from("").alignment(Alignment::Right)]))
2479                .footer(Row::new([Line::from("").alignment(Alignment::Right)]));
2480            Widget::render(table, Rect::new(0, 0, 20, 3), &mut buf);
2481        }
2482
2483        #[test]
2484        fn render_with_selected_column_and_incorrect_width_count_does_not_panic() {
2485            let mut buf = Buffer::empty(Rect::new(0, 0, 20, 3));
2486            let table = Table::new(
2487                vec![Row::new(vec!["Row1", "Row2", "Row3"])],
2488                [Constraint::Length(10); 1],
2489            );
2490            let mut state = TableState::new().with_selected_column(2);
2491            StatefulWidget::render(table, Rect::new(0, 0, 20, 3), &mut buf, &mut state);
2492        }
2493
2494        #[test]
2495        fn render_with_selected() {
2496            let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2497            let rows = vec![
2498                Row::new(vec!["Cell1", "Cell2"]),
2499                Row::new(vec!["Cell3", "Cell4"]),
2500            ];
2501            let table = Table::new(rows, [Constraint::Length(5); 2])
2502                .row_highlight_style(Style::new().red())
2503                .highlight_symbol(">>");
2504            let mut state = TableState::new().with_selected(Some(0));
2505            StatefulWidget::render(table, Rect::new(0, 0, 15, 3), &mut buf, &mut state);
2506            let expected = Buffer::with_lines([
2507                ">>Cell1 Cell2  ".red(),
2508                "  Cell3 Cell4  ".into(),
2509                "               ".into(),
2510            ]);
2511            assert_eq!(buf, expected);
2512        }
2513
2514        #[test]
2515        fn render_with_selected_column() {
2516            let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2517            let rows = vec![
2518                Row::new(vec!["Cell1", "Cell2"]),
2519                Row::new(vec!["Cell3", "Cell4"]),
2520            ];
2521            let table = Table::new(rows, [Constraint::Length(5); 2])
2522                .column_highlight_style(Style::new().blue())
2523                .highlight_symbol(">>");
2524            let mut state = TableState::new().with_selected_column(Some(1));
2525            StatefulWidget::render(table, Rect::new(0, 0, 15, 3), &mut buf, &mut state);
2526            let expected = Buffer::with_lines::<[Line; 3]>([
2527                Line::from(vec![
2528                    ">>Cell1".into(),
2529                    " ".into(),
2530                    "Cell2".blue(),
2531                    "  ".into(),
2532                ]),
2533                Line::from(vec![
2534                    "  Cell3".into(),
2535                    " ".into(),
2536                    "Cell4".blue(),
2537                    "  ".into(),
2538                ]),
2539                Line::from(vec!["        ".into(), "     ".blue(), "  ".into()]),
2540            ]);
2541            assert_eq!(buf, expected);
2542        }
2543
2544        #[test]
2545        fn render_with_selected_cell() {
2546            let mut buf = Buffer::empty(Rect::new(0, 0, 20, 4));
2547            let rows = vec![
2548                Row::new(vec!["Cell1", "Cell2", "Cell3"]),
2549                Row::new(vec!["Cell4", "Cell5", "Cell6"]),
2550                Row::new(vec!["Cell7", "Cell8", "Cell9"]),
2551            ];
2552            let table = Table::new(rows, [Constraint::Length(5); 3])
2553                .highlight_symbol(">>")
2554                .cell_highlight_style(Style::new().green());
2555            let mut state = TableState::new().with_selected_cell((1, 2));
2556            StatefulWidget::render(table, Rect::new(0, 0, 20, 4), &mut buf, &mut state);
2557            let expected = Buffer::with_lines::<[Line; 4]>([
2558                Line::from(vec!["  Cell1 ".into(), "Cell2 ".into(), "Cell3".into()]),
2559                Line::from(vec![">>Cell4 Cell5 ".into(), "Cell6".green(), " ".into()]),
2560                Line::from(vec!["  Cell7 ".into(), "Cell8 ".into(), "Cell9".into()]),
2561                Line::from(vec!["                    ".into()]),
2562            ]);
2563            assert_eq!(buf, expected);
2564        }
2565
2566        #[test]
2567        fn render_with_selected_row_and_column() {
2568            let mut buf = Buffer::empty(Rect::new(0, 0, 20, 4));
2569            let rows = vec![
2570                Row::new(vec!["Cell1", "Cell2", "Cell3"]),
2571                Row::new(vec!["Cell4", "Cell5", "Cell6"]),
2572                Row::new(vec!["Cell7", "Cell8", "Cell9"]),
2573            ];
2574            let table = Table::new(rows, [Constraint::Length(5); 3])
2575                .highlight_symbol(">>")
2576                .row_highlight_style(Style::new().red())
2577                .column_highlight_style(Style::new().blue());
2578            let mut state = TableState::new().with_selected(1).with_selected_column(2);
2579            StatefulWidget::render(table, Rect::new(0, 0, 20, 4), &mut buf, &mut state);
2580            let expected = Buffer::with_lines::<[Line; 4]>([
2581                Line::from(vec!["  Cell1 ".into(), "Cell2 ".into(), "Cell3".blue()]),
2582                Line::from(vec![">>Cell4 Cell5 ".red(), "Cell6".blue(), " ".red()]),
2583                Line::from(vec!["  Cell7 ".into(), "Cell8 ".into(), "Cell9".blue()]),
2584                Line::from(vec!["              ".into(), "     ".blue(), " ".into()]),
2585            ]);
2586            assert_eq!(buf, expected);
2587        }
2588
2589        #[test]
2590        fn render_with_selected_row_and_column_and_cell() {
2591            let mut buf = Buffer::empty(Rect::new(0, 0, 20, 4));
2592            let rows = vec![
2593                Row::new(vec!["Cell1", "Cell2", "Cell3"]),
2594                Row::new(vec!["Cell4", "Cell5", "Cell6"]),
2595                Row::new(vec!["Cell7", "Cell8", "Cell9"]),
2596            ];
2597            let table = Table::new(rows, [Constraint::Length(5); 3])
2598                .highlight_symbol(">>")
2599                .row_highlight_style(Style::new().red())
2600                .column_highlight_style(Style::new().blue())
2601                .cell_highlight_style(Style::new().green());
2602            let mut state = TableState::new().with_selected(1).with_selected_column(2);
2603            StatefulWidget::render(table, Rect::new(0, 0, 20, 4), &mut buf, &mut state);
2604            let expected = Buffer::with_lines::<[Line; 4]>([
2605                Line::from(vec!["  Cell1 ".into(), "Cell2 ".into(), "Cell3".blue()]),
2606                Line::from(vec![">>Cell4 Cell5 ".red(), "Cell6".green(), " ".red()]),
2607                Line::from(vec!["  Cell7 ".into(), "Cell8 ".into(), "Cell9".blue()]),
2608                Line::from(vec!["              ".into(), "     ".blue(), " ".into()]),
2609            ]);
2610            assert_eq!(buf, expected);
2611        }
2612
2613        /// Note that this includes a regression test for a bug where the table would not render the
2614        /// correct rows when there is no selection.
2615        /// <https://github.com/ratatui/ratatui/issues/1179>
2616        #[rstest]
2617        #[case::no_selection(None, 50, ["50", "51", "52", "53", "54"])]
2618        #[case::selection_before_offset(20, 20, ["20", "21", "22", "23", "24"])]
2619        #[case::selection_immediately_before_offset(49, 49, ["49", "50", "51", "52", "53"])]
2620        #[case::selection_at_start_of_offset(50, 50, ["50", "51", "52", "53", "54"])]
2621        #[case::selection_at_end_of_offset(54, 50, ["50", "51", "52", "53", "54"])]
2622        #[case::selection_immediately_after_offset(55, 51, ["51", "52", "53", "54", "55"])]
2623        #[case::selection_after_offset(80, 76, ["76", "77", "78", "79", "80"])]
2624        fn render_with_selection_and_offset<T: Into<Option<usize>>>(
2625            #[case] selected_row: T,
2626            #[case] expected_offset: usize,
2627            #[case] expected_items: [&str; 5],
2628        ) {
2629            // render 100 rows offset at 50, with a selected row
2630            let rows = (0..100).map(|i| Row::new([i.to_string()]));
2631            let table = Table::new(rows, [Constraint::Length(2)]);
2632            let mut buf = Buffer::empty(Rect::new(0, 0, 2, 5));
2633            let mut state = TableState::new()
2634                .with_offset(50)
2635                .with_selected(selected_row.into());
2636
2637            StatefulWidget::render(table.clone(), Rect::new(0, 0, 5, 5), &mut buf, &mut state);
2638
2639            assert_eq!(buf, Buffer::with_lines(expected_items));
2640            assert_eq!(state.offset, expected_offset);
2641        }
2642    }
2643
2644    mod highlight_placement {
2645        use super::*;
2646
2647        /// Renders a 3x3 table of `A1`..`C3` in a 24x3 area and compares the lines.
2648        #[track_caller]
2649        fn assert_render(
2650            placement: HighlightPlacement,
2651            selected_row: Option<usize>,
2652            selected_column: Option<usize>,
2653            expected: [&str; 3],
2654        ) {
2655            let rows = [
2656                Row::new(["A1", "A2", "A3"]),
2657                Row::new(["B1", "B2", "B3"]),
2658                Row::new(["C1", "C2", "C3"]),
2659            ];
2660            let table = Table::new(rows, [Constraint::Length(2); 3])
2661                .highlight_symbol(">>")
2662                .highlight_placement(placement);
2663            let mut state = TableState::new()
2664                .with_selected(selected_row)
2665                .with_selected_column(selected_column);
2666            let area = Rect::new(0, 0, 24, 3);
2667            let mut buf = Buffer::empty(area);
2668            StatefulWidget::render(table, area, &mut buf, &mut state);
2669            assert_eq!(buf, Buffer::with_lines(expected));
2670        }
2671
2672        #[test]
2673        fn first_column_with_row_selection() {
2674            assert_render(
2675                HighlightPlacement::FirstColumn,
2676                Some(1),
2677                None,
2678                [
2679                    "  A1 A2 A3              ",
2680                    ">>B1 B2 B3              ",
2681                    "  C1 C2 C3              ",
2682                ],
2683            );
2684        }
2685
2686        #[test]
2687        fn first_column_keeps_symbol_when_a_later_column_is_selected() {
2688            // The slot is at column 0, the selection is at column 2. The symbol still shows.
2689            assert_render(
2690                HighlightPlacement::FirstColumn,
2691                Some(1),
2692                Some(2),
2693                [
2694                    "  A1 A2 A3              ",
2695                    ">>B1 B2 B3              ",
2696                    "  C1 C2 C3              ",
2697                ],
2698            );
2699        }
2700
2701        #[test]
2702        fn selected_column_moves_the_slot() {
2703            assert_render(
2704                HighlightPlacement::SelectedColumn,
2705                Some(1),
2706                Some(1),
2707                [
2708                    "A1   A2 A3              ",
2709                    "B1 >>B2 B3              ",
2710                    "C1   C2 C3              ",
2711                ],
2712            );
2713        }
2714
2715        #[test]
2716        fn selected_column_without_a_column_falls_back_to_first() {
2717            assert_render(
2718                HighlightPlacement::SelectedColumn,
2719                Some(0),
2720                None,
2721                [
2722                    ">>A1 A2 A3              ",
2723                    "  B1 B2 B3              ",
2724                    "  C1 C2 C3              ",
2725                ],
2726            );
2727        }
2728
2729        #[test]
2730        fn columns_indents_each_listed_column() {
2731            assert_render(
2732                HighlightPlacement::Columns(vec![1, 2]),
2733                Some(0),
2734                None,
2735                [
2736                    "A1 >>A2 >>A3            ",
2737                    "B1   B2   B3            ",
2738                    "C1   C2   C3            ",
2739                ],
2740            );
2741        }
2742
2743        #[test]
2744        fn columns_ignores_out_of_range_indices() {
2745            // Index 9 does not exist: no panic, and no slot allocated for it.
2746            assert_render(
2747                HighlightPlacement::Columns(vec![1, 9]),
2748                Some(0),
2749                None,
2750                [
2751                    "A1 >>A2 A3              ",
2752                    "B1   B2 B3              ",
2753                    "C1   C2 C3              ",
2754                ],
2755            );
2756        }
2757
2758        #[test]
2759        fn all_columns() {
2760            assert_render(
2761                HighlightPlacement::AllColumns,
2762                Some(2),
2763                None,
2764                [
2765                    "  A1   A2   A3          ",
2766                    "  B1   B2   B3          ",
2767                    ">>C1 >>C2 >>C3          ",
2768                ],
2769            );
2770        }
2771
2772        #[test]
2773        fn column_only_selection_anchors_to_the_first_visible_row() {
2774            // Scrolled past row 0: the symbol must follow the viewport, not stay on row 0 where
2775            // nobody can see it.
2776            let rows = ["A", "B", "C", "D"].map(|label| Row::new([label, label]));
2777            let table = Table::new(rows, [Constraint::Length(1); 2])
2778                .highlight_symbol(">>")
2779                .highlight_placement(HighlightPlacement::SelectedColumn);
2780            let mut state = TableState::new().with_offset(2).with_selected_column(1);
2781            let area = Rect::new(0, 0, 8, 2);
2782            let mut buf = Buffer::empty(area);
2783            StatefulWidget::render(table, area, &mut buf, &mut state);
2784            assert_eq!(buf, Buffer::with_lines(["C >>C   ", "D   D   "]));
2785        }
2786
2787        #[test]
2788        fn never_spacing_allocates_no_slot() {
2789            let rows = [Row::new(["A1", "A2"]), Row::new(["B1", "B2"])];
2790            let table = Table::new(rows, [Constraint::Length(2); 2])
2791                .highlight_symbol(">>")
2792                .highlight_spacing(HighlightSpacing::Never)
2793                .highlight_placement(HighlightPlacement::AllColumns);
2794            let mut state = TableState::new().with_selected(0);
2795            let area = Rect::new(0, 0, 12, 2);
2796            let mut buf = Buffer::empty(area);
2797            StatefulWidget::render(table, area, &mut buf, &mut state);
2798            assert_eq!(buf, Buffer::with_lines(["A1 A2       ", "B1 B2       "]));
2799        }
2800
2801        #[test]
2802        fn symbol_follows_columns_not_spanned_cells() {
2803            // The first cell spans two columns, so cell index 1 is column index 2. With a slot on
2804            // every column the symbols must still land on column boundaries.
2805            let rows = [Row::new([
2806                Cell::from("A1").column_span(2),
2807                Cell::from("A3"),
2808            ])];
2809            let table = Table::new(rows, [Constraint::Length(2); 3])
2810                .header(Row::new(["H1", "H2", "H3"]))
2811                .highlight_symbol(">>")
2812                .highlight_placement(HighlightPlacement::AllColumns);
2813            let mut state = TableState::new().with_selected(0);
2814            let area = Rect::new(0, 0, 20, 2);
2815            let mut buf = Buffer::empty(area);
2816            StatefulWidget::render(table, area, &mut buf, &mut state);
2817            assert_eq!(
2818                buf,
2819                Buffer::with_lines(["  H1   H2   H3      ", ">>A1 >>   >>A3      "])
2820            );
2821        }
2822
2823        #[test]
2824        fn column_highlight_does_not_reach_header_or_footer() {
2825            let rows = [Row::new(["A1", "A2"])];
2826            let table = Table::new(rows, [Constraint::Length(2); 2])
2827                .header(Row::new(["H1", "H2"]))
2828                .footer(Row::new(["F1", "F2"]))
2829                .column_highlight_style(Style::new().blue());
2830            let mut state = TableState::new().with_selected_column(1);
2831            let area = Rect::new(0, 0, 6, 3);
2832            let mut buf = Buffer::empty(area);
2833            StatefulWidget::render(table, area, &mut buf, &mut state);
2834
2835            let mut expected = Buffer::with_lines(["H1 H2 ", "A1 A2 ", "F1 F2 "]);
2836            expected.set_style(Rect::new(3, 1, 2, 1), Style::new().blue());
2837            assert_eq!(buf, expected);
2838        }
2839    }
2840
2841    // test how constraints interact with table column width allocation
2842    mod column_widths {
2843        use super::*;
2844
2845        #[test]
2846        fn length_constraint() {
2847            // without selection, more than needed width
2848            let table = Table::default().widths([Length(4), Length(4)]);
2849            assert_eq!(
2850                table.get_column_widths(20, 0, 0, &[]),
2851                [Rect::new(0, 0, 4, 1), Rect::new(5, 0, 4, 1),]
2852            );
2853
2854            // with selection, more than needed width
2855            let table = Table::default().widths([Length(4), Length(4)]);
2856            assert_eq!(
2857                table.get_column_widths(20, 3, 0, &[true]),
2858                [Rect::new(3, 0, 4, 1), Rect::new(8, 0, 4, 1)]
2859            );
2860
2861            // without selection, less than needed width
2862            let table = Table::default().widths([Length(4), Length(4)]);
2863            assert_eq!(
2864                table.get_column_widths(7, 0, 0, &[]),
2865                [Rect::new(0, 0, 3, 1), Rect::new(4, 0, 3, 1)]
2866            );
2867
2868            // with selection, less than needed width
2869            // <--------7px-------->
2870            // ┌────────┐x┌────────┐
2871            // │ (3, 2) │x│ (6, 1) │
2872            // └────────┘x└────────┘
2873            // column spacing (i.e. `x`) is always prioritized
2874            let table = Table::default().widths([Length(4), Length(4)]);
2875            assert_eq!(
2876                table.get_column_widths(7, 3, 0, &[true]),
2877                [Rect::new(3, 0, 2, 1), Rect::new(6, 0, 1, 1)]
2878            );
2879        }
2880
2881        #[test]
2882        fn max_constraint() {
2883            // without selection, more than needed width
2884            let table = Table::default().widths([Max(4), Max(4)]);
2885            assert_eq!(
2886                table.get_column_widths(20, 0, 0, &[]),
2887                [Rect::new(0, 0, 4, 1), Rect::new(5, 0, 4, 1)]
2888            );
2889
2890            // with selection, more than needed width
2891            let table = Table::default().widths([Max(4), Max(4)]);
2892            assert_eq!(
2893                table.get_column_widths(20, 3, 0, &[true]),
2894                [Rect::new(3, 0, 4, 1), Rect::new(8, 0, 4, 1)]
2895            );
2896
2897            // without selection, less than needed width
2898            let table = Table::default().widths([Max(4), Max(4)]);
2899            assert_eq!(
2900                table.get_column_widths(7, 0, 0, &[]),
2901                [Rect::new(0, 0, 3, 1), Rect::new(4, 0, 3, 1)]
2902            );
2903
2904            // with selection, less than needed width
2905            let table = Table::default().widths([Max(4), Max(4)]);
2906            assert_eq!(
2907                table.get_column_widths(7, 3, 0, &[true]),
2908                [Rect::new(3, 0, 2, 1), Rect::new(6, 0, 1, 1)]
2909            );
2910        }
2911
2912        #[test]
2913        fn min_constraint() {
2914            // in its currently stage, the "Min" constraint does not grow to use the possible
2915            // available length and enabling "expand_to_fill" will just stretch the last
2916            // constraint and not split it with all available constraints
2917
2918            // without selection, more than needed width
2919            let table = Table::default().widths([Min(4), Min(4)]);
2920            assert_eq!(
2921                table.get_column_widths(20, 0, 0, &[]),
2922                [Rect::new(0, 0, 10, 1), Rect::new(11, 0, 9, 1)]
2923            );
2924
2925            // with selection, more than needed width
2926            let table = Table::default().widths([Min(4), Min(4)]);
2927            assert_eq!(
2928                table.get_column_widths(20, 3, 0, &[true]),
2929                [Rect::new(3, 0, 8, 1), Rect::new(12, 0, 8, 1)]
2930            );
2931
2932            // without selection, less than needed width
2933            // allocates spacer
2934            let table = Table::default().widths([Min(4), Min(4)]);
2935            assert_eq!(
2936                table.get_column_widths(7, 0, 0, &[]),
2937                [Rect::new(0, 0, 3, 1), Rect::new(4, 0, 3, 1)]
2938            );
2939
2940            // with selection, less than needed width
2941            // always allocates selection and spacer
2942            let table = Table::default().widths([Min(4), Min(4)]);
2943            assert_eq!(
2944                table.get_column_widths(7, 3, 0, &[true]),
2945                [Rect::new(3, 0, 2, 1), Rect::new(6, 0, 1, 1)]
2946            );
2947        }
2948
2949        #[test]
2950        fn percentage_constraint() {
2951            // without selection, more than needed width
2952            let table = Table::default().widths([Percentage(30), Percentage(30)]);
2953            assert_eq!(
2954                table.get_column_widths(20, 0, 0, &[]),
2955                [Rect::new(0, 0, 6, 1), Rect::new(7, 0, 6, 1)]
2956            );
2957
2958            // with selection, more than needed width
2959            let table = Table::default().widths([Percentage(30), Percentage(30)]);
2960            assert_eq!(
2961                table.get_column_widths(20, 3, 0, &[true]),
2962                [Rect::new(3, 0, 5, 1), Rect::new(9, 0, 5, 1)]
2963            );
2964
2965            // without selection, less than needed width
2966            // rounds from positions: [0.0, 0.0, 2.1, 3.1, 5.2, 7.0]
2967            let table = Table::default().widths([Percentage(30), Percentage(30)]);
2968            assert_eq!(
2969                table.get_column_widths(7, 0, 0, &[]),
2970                [Rect::new(0, 0, 2, 1), Rect::new(3, 0, 2, 1)]
2971            );
2972
2973            // with selection, less than needed width
2974            // rounds from positions: [0.0, 3.0, 5.1, 6.1, 7.0, 7.0]
2975            let table = Table::default().widths([Percentage(30), Percentage(30)]);
2976            assert_eq!(
2977                table.get_column_widths(7, 3, 0, &[true]),
2978                [Rect::new(3, 0, 1, 1), Rect::new(5, 0, 1, 1)]
2979            );
2980        }
2981
2982        #[test]
2983        fn ratio_constraint() {
2984            // without selection, more than needed width
2985            // rounds from positions: [0.00, 0.00, 6.67, 7.67, 14.33]
2986            let table = Table::default().widths([Ratio(1, 3), Ratio(1, 3)]);
2987            assert_eq!(
2988                table.get_column_widths(20, 0, 0, &[]),
2989                [Rect::new(0, 0, 7, 1), Rect::new(8, 0, 6, 1)]
2990            );
2991
2992            // with selection, more than needed width
2993            // rounds from positions: [0.00, 3.00, 10.67, 17.33, 20.00]
2994            let table = Table::default().widths([Ratio(1, 3), Ratio(1, 3)]);
2995            assert_eq!(
2996                table.get_column_widths(20, 3, 0, &[true]),
2997                [Rect::new(3, 0, 6, 1), Rect::new(10, 0, 5, 1)]
2998            );
2999
3000            // without selection, less than needed width
3001            // rounds from positions: [0.00, 2.33, 3.33, 5.66, 7.00]
3002            let table = Table::default().widths([Ratio(1, 3), Ratio(1, 3)]);
3003            assert_eq!(
3004                table.get_column_widths(7, 0, 0, &[]),
3005                [Rect::new(0, 0, 2, 1), Rect::new(3, 0, 3, 1)]
3006            );
3007
3008            // with selection, less than needed width
3009            // rounds from positions: [0.00, 3.00, 5.33, 6.33, 7.00, 7.00]
3010            let table = Table::default().widths([Ratio(1, 3), Ratio(1, 3)]);
3011            assert_eq!(
3012                table.get_column_widths(7, 3, 0, &[true]),
3013                [Rect::new(3, 0, 1, 1), Rect::new(5, 0, 2, 1)]
3014            );
3015        }
3016
3017        /// When more width is available than requested, the behavior is controlled by flex
3018        #[test]
3019        fn underconstrained_flex() {
3020            let table = Table::default().widths([Min(10), Min(10), Min(1)]);
3021            assert_eq!(
3022                table.get_column_widths(62, 0, 0, &[]),
3023                &[
3024                    Rect::new(0, 0, 20, 1),
3025                    Rect::new(21, 0, 20, 1),
3026                    Rect::new(42, 0, 20, 1)
3027                ]
3028            );
3029
3030            let table = Table::default()
3031                .widths([Min(10), Min(10), Min(1)])
3032                .flex(Flex::Legacy);
3033            assert_eq!(
3034                table.get_column_widths(62, 0, 0, &[]),
3035                &[
3036                    Rect::new(0, 0, 10, 1),
3037                    Rect::new(11, 0, 10, 1),
3038                    Rect::new(22, 0, 40, 1)
3039                ]
3040            );
3041
3042            let table = Table::default()
3043                .widths([Min(10), Min(10), Min(1)])
3044                .flex(Flex::SpaceBetween);
3045            assert_eq!(
3046                table.get_column_widths(62, 0, 0, &[]),
3047                &[
3048                    Rect::new(0, 0, 20, 1),
3049                    Rect::new(21, 0, 20, 1),
3050                    Rect::new(42, 0, 20, 1)
3051                ]
3052            );
3053        }
3054
3055        #[test]
3056        fn underconstrained_segment_size() {
3057            let table = Table::default().widths([Min(10), Min(10), Min(1)]);
3058            assert_eq!(
3059                table.get_column_widths(62, 0, 0, &[]),
3060                &[
3061                    Rect::new(0, 0, 20, 1),
3062                    Rect::new(21, 0, 20, 1),
3063                    Rect::new(42, 0, 20, 1)
3064                ]
3065            );
3066
3067            let table = Table::default()
3068                .widths([Min(10), Min(10), Min(1)])
3069                .flex(Flex::Legacy);
3070            assert_eq!(
3071                table.get_column_widths(62, 0, 0, &[]),
3072                &[
3073                    Rect::new(0, 0, 10, 1),
3074                    Rect::new(11, 0, 10, 1),
3075                    Rect::new(22, 0, 40, 1)
3076                ]
3077            );
3078        }
3079
3080        #[test]
3081        fn no_constraint_with_rows() {
3082            let table = Table::default()
3083                .rows(vec![
3084                    Row::new(vec!["a", "b"]),
3085                    Row::new(vec!["c", "d", "e"]),
3086                ])
3087                // rows should get precedence over header
3088                .header(Row::new(vec!["f", "g"]))
3089                .footer(Row::new(vec!["h", "i"]))
3090                .column_spacing(0);
3091            assert_eq!(
3092                table.get_column_widths(30, 0, 3, &[]),
3093                &[
3094                    Rect::new(0, 0, 10, 1),
3095                    Rect::new(10, 0, 10, 1),
3096                    Rect::new(20, 0, 10, 1)
3097                ]
3098            );
3099        }
3100
3101        #[test]
3102        fn no_constraint_with_header() {
3103            let table = Table::default()
3104                .rows(vec![])
3105                .header(Row::new(vec!["f", "g"]))
3106                .column_spacing(0);
3107            assert_eq!(
3108                table.get_column_widths(10, 0, 2, &[]),
3109                [Rect::new(0, 0, 5, 1), Rect::new(5, 0, 5, 1)]
3110            );
3111        }
3112
3113        #[test]
3114        fn no_constraint_with_footer() {
3115            let table = Table::default()
3116                .rows(vec![])
3117                .footer(Row::new(vec!["h", "i"]))
3118                .column_spacing(0);
3119            assert_eq!(
3120                table.get_column_widths(10, 0, 2, &[]),
3121                [Rect::new(0, 0, 5, 1), Rect::new(5, 0, 5, 1)]
3122            );
3123        }
3124
3125        #[track_caller]
3126        fn test_table_with_selection<'line, Lines>(
3127            highlight_spacing: HighlightSpacing,
3128            columns: u16,
3129            spacing: u16,
3130            selection: Option<usize>,
3131            expected: Lines,
3132        ) where
3133            Lines: IntoIterator,
3134            Lines::Item: Into<Line<'line>>,
3135        {
3136            let table = Table::default()
3137                .rows(vec![Row::new(vec!["ABCDE", "12345"])])
3138                .highlight_spacing(highlight_spacing)
3139                .highlight_symbol(">>>")
3140                .column_spacing(spacing);
3141            let area = Rect::new(0, 0, columns, 3);
3142            let mut buf = Buffer::empty(area);
3143            let mut state = TableState::default().with_selected(selection);
3144            StatefulWidget::render(table, area, &mut buf, &mut state);
3145            assert_eq!(buf, Buffer::with_lines(expected));
3146        }
3147
3148        #[test]
3149        fn excess_area_highlight_symbol_and_column_spacing_allocation() {
3150            // no highlight_symbol rendered ever
3151            test_table_with_selection(
3152                HighlightSpacing::Never,
3153                15,   // width
3154                0,    // spacing
3155                None, // selection
3156                [
3157                    "ABCDE  12345   ", /* default layout is Flex::Start but columns length
3158                                        * constraints are calculated as `max_area / n_columns`,
3159                                        * i.e. they are distributed amongst available space */
3160                    "               ", // row 2
3161                    "               ", // row 3
3162                ],
3163            );
3164
3165            let table = Table::default()
3166                .rows(vec![Row::new(vec!["ABCDE", "12345"])])
3167                .widths([5, 5])
3168                .column_spacing(0);
3169            let area = Rect::new(0, 0, 15, 3);
3170            let mut buf = Buffer::empty(area);
3171            Widget::render(table, area, &mut buf);
3172            let expected = Buffer::with_lines([
3173                "ABCDE12345     ", /* As reference, this is what happens when you manually
3174                                    * specify widths */
3175                "               ", // row 2
3176                "               ", // row 3
3177            ]);
3178            assert_eq!(buf, expected);
3179
3180            // no highlight_symbol rendered ever
3181            test_table_with_selection(
3182                HighlightSpacing::Never,
3183                15,      // width
3184                0,       // spacing
3185                Some(0), // selection
3186                [
3187                    "ABCDE  12345   ", // row 1
3188                    "               ", // row 2
3189                    "               ", // row 3
3190                ],
3191            );
3192
3193            // no highlight_symbol rendered because no selection is made
3194            test_table_with_selection(
3195                HighlightSpacing::WhenSelected,
3196                15,   // width
3197                0,    // spacing
3198                None, // selection
3199                [
3200                    "ABCDE  12345   ", // row 1
3201                    "               ", // row 2
3202                    "               ", // row 3
3203                ],
3204            );
3205            // highlight_symbol rendered because selection is made
3206            test_table_with_selection(
3207                HighlightSpacing::WhenSelected,
3208                15,      // width
3209                0,       // spacing
3210                Some(0), // selection
3211                [
3212                    ">>>ABCDE 12345 ", // row 1
3213                    "               ", // row 2
3214                    "               ", // row 3
3215                ],
3216            );
3217
3218            // highlight_symbol always rendered even no selection is made
3219            test_table_with_selection(
3220                HighlightSpacing::Always,
3221                15,   // width
3222                0,    // spacing
3223                None, // selection
3224                [
3225                    "   ABCDE 12345 ", // row 1
3226                    "               ", // row 2
3227                    "               ", // row 3
3228                ],
3229            );
3230
3231            // no highlight_symbol rendered because no selection is made
3232            test_table_with_selection(
3233                HighlightSpacing::Always,
3234                15,      // width
3235                0,       // spacing
3236                Some(0), // selection
3237                [
3238                    ">>>ABCDE 12345 ", // row 1
3239                    "               ", // row 2
3240                    "               ", // row 3
3241                ],
3242            );
3243        }
3244
3245        #[expect(clippy::too_many_lines)]
3246        #[test]
3247        fn insufficient_area_highlight_symbol_and_column_spacing_allocation() {
3248            // column spacing is prioritized over every other constraint
3249            test_table_with_selection(
3250                HighlightSpacing::Never,
3251                10,   // width
3252                1,    // spacing
3253                None, // selection
3254                [
3255                    "ABCDE 1234", // spacing is prioritized and column is cut
3256                    "          ", // row 2
3257                    "          ", // row 3
3258                ],
3259            );
3260            test_table_with_selection(
3261                HighlightSpacing::WhenSelected,
3262                10,   // width
3263                1,    // spacing
3264                None, // selection
3265                [
3266                    "ABCDE 1234", // spacing is prioritized and column is cut
3267                    "          ", // row 2
3268                    "          ", // row 3
3269                ],
3270            );
3271
3272            // this test checks that space for highlight_symbol space is always allocated.
3273            // this test also checks that space for column is allocated.
3274            //
3275            // Space for highlight_symbol is allocated first by splitting horizontal space
3276            // into highlight_symbol area and column area.
3277            // Then in a separate step, column widths are calculated.
3278            // column spacing is prioritized when column widths are calculated and last column here
3279            // ends up with just 1 wide
3280            test_table_with_selection(
3281                HighlightSpacing::Always,
3282                10,   // width
3283                1,    // spacing
3284                None, // selection
3285                [
3286                    "   ABC 123", // highlight_symbol and spacing are prioritized
3287                    "          ", // row 2
3288                    "          ", // row 3
3289                ],
3290            );
3291
3292            // the following are specification tests
3293            test_table_with_selection(
3294                HighlightSpacing::Always,
3295                9,    // width
3296                1,    // spacing
3297                None, // selection
3298                [
3299                    "   ABC 12", // highlight_symbol and spacing are prioritized
3300                    "         ", // row 2
3301                    "         ", // row 3
3302                ],
3303            );
3304            test_table_with_selection(
3305                HighlightSpacing::Always,
3306                8,    // width
3307                1,    // spacing
3308                None, // selection
3309                [
3310                    "   AB 12", // highlight_symbol and spacing are prioritized
3311                    "        ", // row 2
3312                    "        ", // row 3
3313                ],
3314            );
3315            test_table_with_selection(
3316                HighlightSpacing::Always,
3317                7,    // width
3318                1,    // spacing
3319                None, // selection
3320                [
3321                    "   AB 1", // highlight_symbol and spacing are prioritized
3322                    "       ", // row 2
3323                    "       ", // row 3
3324                ],
3325            );
3326
3327            let table = Table::default()
3328                .rows(vec![Row::new(vec!["ABCDE", "12345"])])
3329                .highlight_spacing(HighlightSpacing::Always)
3330                .flex(Flex::Legacy)
3331                .highlight_symbol(">>>")
3332                .column_spacing(1);
3333            let area = Rect::new(0, 0, 10, 3);
3334            let mut buf = Buffer::empty(area);
3335            Widget::render(table, area, &mut buf);
3336            // highlight_symbol and spacing are prioritized but columns are evenly distributed
3337            #[rustfmt::skip]
3338            let expected = Buffer::with_lines([
3339                "   ABCDE 1",
3340                "          ",
3341                "          ",
3342            ]);
3343            assert_eq!(buf, expected);
3344
3345            let table = Table::default()
3346                .rows(vec![Row::new(vec!["ABCDE", "12345"])])
3347                .highlight_spacing(HighlightSpacing::Always)
3348                .flex(Flex::Start)
3349                .highlight_symbol(">>>")
3350                .column_spacing(1);
3351            let area = Rect::new(0, 0, 10, 3);
3352            let mut buf = Buffer::empty(area);
3353            Widget::render(table, area, &mut buf);
3354            // highlight_symbol and spacing are prioritized but columns are evenly distributed
3355            #[rustfmt::skip]
3356            let expected = Buffer::with_lines([
3357                "   ABC 123",
3358                "          ",
3359                "          ",
3360            ]);
3361            assert_eq!(buf, expected);
3362
3363            test_table_with_selection(
3364                HighlightSpacing::Never,
3365                10,      // width
3366                1,       // spacing
3367                Some(0), // selection
3368                [
3369                    "ABCDE 1234", // spacing is prioritized
3370                    "          ",
3371                    "          ",
3372                ],
3373            );
3374
3375            test_table_with_selection(
3376                HighlightSpacing::WhenSelected,
3377                10,      // width
3378                1,       // spacing
3379                Some(0), // selection
3380                [
3381                    ">>>ABC 123", // row 1
3382                    "          ", // row 2
3383                    "          ", // row 3
3384                ],
3385            );
3386
3387            test_table_with_selection(
3388                HighlightSpacing::Always,
3389                10,      // width
3390                1,       // spacing
3391                Some(0), // selection
3392                [
3393                    ">>>ABC 123", // highlight column and spacing are prioritized
3394                    "          ", // row 2
3395                    "          ", // row 3
3396                ],
3397            );
3398        }
3399
3400        #[test]
3401        fn insufficient_area_highlight_symbol_allocation_with_no_column_spacing() {
3402            test_table_with_selection(
3403                HighlightSpacing::Never,
3404                10,   // width
3405                0,    // spacing
3406                None, // selection
3407                [
3408                    "ABCDE12345", // row 1
3409                    "          ", // row 2
3410                    "          ", // row 3
3411                ],
3412            );
3413            test_table_with_selection(
3414                HighlightSpacing::WhenSelected,
3415                10,   // width
3416                0,    // spacing
3417                None, // selection
3418                [
3419                    "ABCDE12345", // row 1
3420                    "          ", // row 2
3421                    "          ", // row 3
3422                ],
3423            );
3424            // highlight symbol spacing is prioritized over all constraints
3425            // even if the constraints are fixed length
3426            // this is because highlight_symbol column is separated _before_ any of the constraint
3427            // widths are calculated
3428            test_table_with_selection(
3429                HighlightSpacing::Always,
3430                10,   // width
3431                0,    // spacing
3432                None, // selection
3433                [
3434                    "   ABCD123", // highlight column and spacing are prioritized
3435                    "          ", // row 2
3436                    "          ", // row 3
3437                ],
3438            );
3439            test_table_with_selection(
3440                HighlightSpacing::Never,
3441                10,      // width
3442                0,       // spacing
3443                Some(0), // selection
3444                [
3445                    "ABCDE12345", // row 1
3446                    "          ", // row 2
3447                    "          ", // row 3
3448                ],
3449            );
3450            test_table_with_selection(
3451                HighlightSpacing::WhenSelected,
3452                10,      // width
3453                0,       // spacing
3454                Some(0), // selection
3455                [
3456                    ">>>ABCD123", // highlight column and spacing are prioritized
3457                    "          ", // row 2
3458                    "          ", // row 3
3459                ],
3460            );
3461            test_table_with_selection(
3462                HighlightSpacing::Always,
3463                10,      // width
3464                0,       // spacing
3465                Some(0), // selection
3466                [
3467                    ">>>ABCD123", // highlight column and spacing are prioritized
3468                    "          ", // row 2
3469                    "          ", // row 3
3470                ],
3471            );
3472        }
3473    }
3474
3475    #[test]
3476    fn stylize() {
3477        assert_eq!(
3478            Table::new(vec![Row::new(vec![Cell::from("")])], [Percentage(100)])
3479                .black()
3480                .on_white()
3481                .bold()
3482                .not_crossed_out()
3483                .style,
3484            Style::default()
3485                .fg(Color::Black)
3486                .bg(Color::White)
3487                .add_modifier(Modifier::BOLD)
3488                .remove_modifier(Modifier::CROSSED_OUT)
3489        );
3490    }
3491
3492    #[rstest]
3493    #[case::no_columns(vec![], vec![], vec![], 0)]
3494    #[case::only_header(vec!["H1", "H2"], vec![], vec![], 2)]
3495    #[case::only_rows(
3496        vec![],
3497        vec![vec!["C1", "C2"], vec!["C1", "C2", "C3"]],
3498        vec![],
3499        3
3500    )]
3501    #[case::only_footer(vec![], vec![], vec!["F1", "F2", "F3", "F4"], 4)]
3502    #[case::rows_longer(
3503        vec!["H1", "H2", "H3", "H4"],
3504        vec![vec!["C1", "C2"],vec!["C1", "C2", "C3"]],
3505        vec!["F1", "F2"],
3506        4
3507    )]
3508    #[case::rows_longer(
3509        vec!["H1", "H2"],
3510        vec![vec!["C1", "C2"], vec!["C1", "C2", "C3", "C4"]],
3511        vec!["F1", "F2"],
3512        4
3513    )]
3514    #[case::footer_longer(
3515        vec!["H1", "H2"],
3516        vec![vec!["C1", "C2"], vec!["C1", "C2", "C3"]],
3517        vec!["F1", "F2", "F3", "F4"],
3518        4
3519    )]
3520
3521    fn column_count(
3522        #[case] header: Vec<&str>,
3523        #[case] rows: Vec<Vec<&str>>,
3524        #[case] footer: Vec<&str>,
3525        #[case] expected: usize,
3526    ) {
3527        let header = Row::new(header);
3528        let footer = Row::new(footer);
3529        let rows: Vec<Row> = rows.into_iter().map(Row::new).collect();
3530        let table = Table::new(rows, Vec::<Constraint>::new())
3531            .header(header)
3532            .footer(footer);
3533        let column_count = table.column_count();
3534        assert_eq!(column_count, expected);
3535    }
3536
3537    #[rstest]
3538    #[case::spanned_cell_counts_every_column(
3539        Row::new([Cell::new("AB").column_span(2), Cell::new("C")]),
3540        3
3541    )]
3542    #[case::zero_span_cell_counts_no_column(
3543        Row::new([Cell::new("hidden").column_span(0), Cell::new("C")]),
3544        1
3545    )]
3546    fn column_count_counts_spanned_columns(#[case] row: Row, #[case] expected: usize) {
3547        let table = Table::new([row], Vec::<Constraint>::new());
3548        assert_eq!(table.column_count(), expected);
3549    }
3550
3551    #[test]
3552    fn column_count_counts_header_and_footer_spans() {
3553        let table = Table::new([Row::new(["a"])], Vec::<Constraint>::new())
3554            .header(Row::new([Cell::new("H").column_span(3)]))
3555            .footer(Row::new([Cell::new("F").column_span(2)]));
3556        assert_eq!(table.column_count(), 3);
3557    }
3558
3559    #[test]
3560    fn render_in_minimal_buffer() {
3561        let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 1));
3562        let rows = vec![
3563            Row::new(vec!["Cell1", "Cell2", "Cell3"]),
3564            Row::new(vec!["Cell4", "Cell5", "Cell6"]),
3565        ];
3566        let table = Table::new(rows, [Constraint::Length(10); 3])
3567            .header(Row::new(vec!["Header1", "Header2", "Header3"]))
3568            .footer(Row::new(vec!["Footer1", "Footer2", "Footer3"]));
3569        // This should not panic, even if the buffer is too small to render the table.
3570        Widget::render(table, buffer.area, &mut buffer);
3571        assert_eq!(buffer, Buffer::with_lines([" "]));
3572    }
3573
3574    #[test]
3575    fn render_in_zero_size_buffer() {
3576        let mut buffer = Buffer::empty(Rect::ZERO);
3577        let rows = vec![
3578            Row::new(vec!["Cell1", "Cell2", "Cell3"]),
3579            Row::new(vec!["Cell4", "Cell5", "Cell6"]),
3580        ];
3581        let table = Table::new(rows, [Constraint::Length(10); 3])
3582            .header(Row::new(vec!["Header1", "Header2", "Header3"]))
3583            .footer(Row::new(vec!["Footer1", "Footer2", "Footer3"]));
3584        // This should not panic, even if the buffer has zero size.
3585        Widget::render(table, buffer.area, &mut buffer);
3586    }
3587
3588    #[test]
3589    fn get_area_for_column_span_one_no_more_columns() {
3590        let columns = [];
3591        let column_span = Table::get_cell_area(&mut columns.iter(), 1, 1);
3592        assert!(column_span.is_none());
3593    }
3594
3595    #[test]
3596    fn get_area_for_column_span_two_no_more_columns() {
3597        let columns = [];
3598        let column_span = Table::get_cell_area(&mut columns.iter(), 2, 1);
3599        assert!(column_span.is_none());
3600    }
3601
3602    #[rstest]
3603    #[case(&[Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}], 2, 5)]
3604    #[case(&[Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}], 2, 5,)]
3605    #[case(&[Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}], 1, 2)]
3606    #[case(&[Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}], 3, 5)]
3607    #[case(&[Rect{x: 3, width: 2, y: 0, height: 1}], 1, 2)]
3608    #[case(&[Rect{x: 3, width: 2, y: 0, height: 1}], 2, 2)]
3609    #[case(&[
3610        Rect{x: 3, width: 2, y: 0, height: 1},
3611        Rect{x: 3, width: 2, y: 0, height: 1},
3612        Rect{x: 3, width: 2, y: 0, height: 1},
3613        Rect{x: 3, width: 2, y: 0, height: 1},
3614            ], 3, 8)]
3615    #[case(&[
3616        Rect{x: 3, width: 2, y: 0, height: 1},
3617        Rect{x: 3, width: 2, y: 0, height: 1},
3618        Rect{x: 3, width: 2, y: 0, height: 1},
3619            ], 3, 8)]
3620    fn test_colspan_width_single_column_spacing(
3621        #[case] columns: &[Rect],
3622        #[case] column_span: u16,
3623        #[case] expected_column_width: u16,
3624    ) {
3625        let column_span = Table::get_cell_area(&mut columns.iter(), column_span, 1);
3626        assert!(column_span.is_some());
3627        assert_eq!(column_span.unwrap().width, expected_column_width);
3628    }
3629
3630    #[rstest]
3631    #[case(&[Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}], 3, 10)]
3632    #[case(&[Rect{x: 3, width: 2, y: 0, height: 1}], 3, 2)]
3633    fn test_colspan_width_two_column_spacing(
3634        #[case] columns: &[Rect],
3635        #[case] column_span: u16,
3636        #[case] expected_column_width: u16,
3637    ) {
3638        let column_span = Table::get_cell_area(&mut columns.iter(), column_span, 2);
3639        assert!(column_span.is_some());
3640        assert_eq!(column_span.unwrap().width, expected_column_width);
3641    }
3642
3643    #[rstest]
3644    #[case(
3645        HighlightSpacing::Always,
3646        15,   // width
3647        1,    // spacing
3648        None, // selection
3649        [
3650            Cell::new("ABCDEFGHIJK").column_span(2),
3651            Cell::new("12345678901"),
3652            Cell::new("XYZXYZXYZXY"),
3653        ],
3654        [
3655            "   ABCDEF 12 XY",
3656            "               ", // row 2
3657            "               ", // row 3
3658        ])]
3659    #[case(
3660        HighlightSpacing::Always,
3661        15,      // width
3662        1,       // spacing
3663        Some(0), // selection
3664        [
3665            Cell::new("ABCDEFGHIJK").column_span(2),
3666            Cell::new("12345678901"),
3667            Cell::new("XYZXYZXYZXY"),
3668        ],
3669        [
3670            ">>>ABCDEF 12 XY",
3671            "               ", // row 2
3672            "               ", // row 3
3673        ])]
3674    #[case(
3675        HighlightSpacing::WhenSelected,
3676        15,   // width
3677        1,    // spacing
3678        None, // selection
3679        [
3680            Cell::new("ABCDEFGHIJK").column_span(2),
3681            Cell::new("12345678901"),
3682            Cell::new("XYZXYZXYZXY"),
3683        ],
3684        [
3685            "ABCDEFG 123 XYZ",
3686            "               ", // row 2
3687            "               ", // row 3
3688        ])]
3689    #[case(
3690        HighlightSpacing::WhenSelected,
3691        15,      // width
3692        1,       // spacing
3693        Some(0), // selection
3694        [
3695            Cell::new("ABCDEFGHIJK").column_span(2),
3696            Cell::new("12345678901"),
3697            Cell::new("XYZXYZXYZXY"),
3698        ],
3699        [
3700            ">>>ABCDEF 12 XY",
3701            "               ", // row 2
3702            "               ", // row 3
3703        ])]
3704    fn test_table_with_selection_and_column_spans<'line, 'cell, Lines, Cells>(
3705        #[case] highlight_spacing: HighlightSpacing,
3706        #[case] columns: u16,
3707        #[case] spacing: u16,
3708        #[case] selection: Option<usize>,
3709        #[case] cells: Cells,
3710        #[case] expected: Lines,
3711    ) where
3712        Cells: IntoIterator,
3713        Cells::Item: Into<Cell<'cell>>,
3714        Lines: IntoIterator,
3715        Lines::Item: Into<Line<'line>>,
3716    {
3717        let table = Table::default()
3718            .rows(vec![Row::new(cells)])
3719            .highlight_spacing(highlight_spacing)
3720            .highlight_symbol(">>>")
3721            .column_spacing(spacing);
3722        let area = Rect::new(0, 0, columns, 3);
3723        let mut buf = Buffer::empty(area);
3724        let mut state = TableState::default().with_selected(selection);
3725        StatefulWidget::render(table, area, &mut buf, &mut state);
3726        assert_eq!(buf, Buffer::with_lines(expected));
3727    }
3728}