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