Skip to main content

ratatui_widgettable/
lib.rs

1//! A [Ratatui] table widget whose cells can contain any widget.
2//!
3//! This crate provides a [`Table`] that works exactly like the `Table` widget built into Ratatui,
4//! except that each [`Cell`] can hold any widget (e.g. `Paragraph`, `Block`, `Gauge`, `List`, or
5//! even another [`Table`]) rather than only [`Text`].
6//!
7//! The API mirrors the built-in table, and it uses the same [`TableState`] and
8//! [`HighlightSpacing`] types, so switching over is usually just a matter of changing imports:
9//!
10//! ```diff
11//! -use ratatui::widgets::{Cell, Row, Table, TableState};
12//! +use ratatui::widgets::TableState;
13//! +use ratatui_widgettable::{Cell, Row, Table};
14//! ```
15//!
16//! # Example
17//!
18//! ```rust
19//! use ratatui::layout::Constraint;
20//! use ratatui::widgets::{Block, Gauge, Paragraph, Wrap};
21//! use ratatui_widgettable::{Cell, Row, Table};
22//!
23//! let rows = [Row::new(vec![
24//!     Cell::from("Build"),
25//!     Cell::new(
26//!         Paragraph::new("Compiling a very long list of crates, this might take a while")
27//!             .wrap(Wrap { trim: true }),
28//!     ),
29//!     Cell::new(Gauge::default().percent(42)),
30//! ])
31//! .height(3)];
32//! let widths = [
33//!     Constraint::Length(8),
34//!     Constraint::Fill(1),
35//!     Constraint::Length(20),
36//! ];
37//! let table = Table::new(rows, widths)
38//!     .header(Row::new(vec!["Step", "Details", "Progress"]))
39//!     .block(Block::bordered().title("Jobs"));
40//! ```
41//!
42//! [Ratatui]: https://ratatui.rs
43#![no_std]
44
45extern crate alloc;
46
47use alloc::vec;
48use alloc::vec::Vec;
49
50use ratatui_core::buffer::Buffer;
51use ratatui_core::layout::{Constraint, Flex, Layout, Rect};
52use ratatui_core::style::{Style, Styled};
53use ratatui_core::text::Text;
54use ratatui_core::widgets::{StatefulWidget, Widget};
55use ratatui_widgets::block::{Block, BlockExt};
56pub use ratatui_widgets::table::{HighlightSpacing, TableState};
57
58pub use self::cell::Cell;
59pub use self::row::Row;
60
61mod cell;
62mod row;
63
64/// Ensures that the examples in the README compile.
65#[cfg(doctest)]
66#[doc = include_str!("../README.md")]
67struct ReadmeDoctests;
68
69/// A widget to display data in formatted columns, where each cell can contain any widget.
70///
71/// A `Table` is a collection of [`Row`]s, each composed of [`Cell`]s. Each [`Cell`] can hold any
72/// widget which implements [`Widget`] for a reference to itself, or a closure (see
73/// [`Cell::from_fn`]). Widgets are rendered into the area of the cell, which is the width of the
74/// column and the [`height`](Row::height) of the row.
75///
76/// You can construct a [`Table`] using either [`Table::new`] or [`Table::default`] and then chain
77/// builder style methods to set the desired properties.
78///
79/// Table cells can be aligned, for more details see [`Cell`].
80///
81/// Make sure to call the [`Table::widths`] method, otherwise the columns will all have a width of 0
82/// and thus not be visible.
83///
84/// [`Table`] implements [`Widget`] and so it can be drawn using `Frame::render_widget`.
85///
86/// [`Table`] is also a [`StatefulWidget`], which means you can use it with [`TableState`] to allow
87/// the user to scroll through the rows and select one of them. When rendering a [`Table`] with a
88/// [`TableState`], the selected row, column and cell will be highlighted. If the selected row is
89/// not visible (based on the offset), the table will be scrolled to make the selected row visible.
90///
91/// Note: if the `widths` field is empty, the table will be rendered with equal widths.
92/// Note: Highlight styles are applied in the following order: Row, Column, Cell.
93///
94///
95/// # Constructor methods
96///
97/// - [`Table::new`] creates a new [`Table`] with the given rows.
98/// - [`Table::default`] creates an empty [`Table`]. You can then add rows using [`Table::rows`].
99///
100/// # Setter methods
101///
102/// These methods are fluent setters. They return a new `Table` with the specified property set.
103///
104/// - [`Table::rows`] sets the rows of the [`Table`].
105/// - [`Table::header`] sets the header row of the [`Table`].
106/// - [`Table::footer`] sets the footer row of the [`Table`].
107/// - [`Table::widths`] sets the width constraints of each column.
108/// - [`Table::column_spacing`] sets the spacing between each column.
109/// - [`Table::block`] wraps the table in a [`Block`] widget.
110/// - [`Table::style`] sets the base style of the widget.
111/// - [`Table::row_highlight_style`] sets the style of the selected row.
112/// - [`Table::column_highlight_style`] sets the style of the selected column.
113/// - [`Table::cell_highlight_style`] sets the style of the selected cell.
114/// - [`Table::highlight_symbol`] sets the symbol to be displayed in front of the selected row.
115/// - [`Table::highlight_spacing`] sets when to show the highlight spacing.
116/// - [`Table::scroll_padding`] sets the number of rows to keep visible before and after the
117///   selected row.
118///
119/// # Example
120///
121/// ```rust
122/// use ratatui::layout::Constraint;
123/// use ratatui::style::{Style, Stylize};
124/// use ratatui::widgets::Block;
125/// use ratatui_widgettable::{Row, Table};
126///
127/// let rows = [Row::new(vec!["Cell1", "Cell2", "Cell3"])];
128/// // Columns widths are constrained in the same way as Layout...
129/// let widths = [
130///     Constraint::Length(5),
131///     Constraint::Length(5),
132///     Constraint::Length(10),
133/// ];
134/// let table = Table::new(rows, widths)
135///     // ...and they can be separated by a fixed spacing.
136///     .column_spacing(1)
137///     // You can set the style of the entire Table.
138///     .style(Style::new().blue())
139///     // It has an optional header, which is simply a Row always visible at the top.
140///     .header(
141///         Row::new(vec!["Col1", "Col2", "Col3"])
142///             .style(Style::new().bold())
143///             // To add space between the header and the rest of the rows, specify the margin
144///             .bottom_margin(1),
145///     )
146///     // It has an optional footer, which is simply a Row always visible at the bottom.
147///     .footer(Row::new(vec!["Updated on Dec 28"]))
148///     // As any other widget, a Table can be wrapped in a Block.
149///     .block(Block::new().title("Table"))
150///     // The selected row, column, cell and its content can also be styled.
151///     .row_highlight_style(Style::new().reversed())
152///     .column_highlight_style(Style::new().red())
153///     .cell_highlight_style(Style::new().blue())
154///     // ...and potentially show a symbol in front of the selection.
155///     .highlight_symbol(">>");
156/// ```
157///
158/// Rows can be created from an iterator of [`Cell`]s. Each row can have an associated height,
159/// bottom margin, and style. See [`Row`] for more details.
160///
161/// ```rust
162/// use ratatui::style::{Style, Stylize};
163/// use ratatui::text::{Line, Span};
164/// use ratatui_widgettable::{Cell, Row, Table};
165///
166/// // a Row can be created from simple strings.
167/// let row = Row::new(vec!["Row11", "Row12", "Row13"]);
168///
169/// // You can style the entire row.
170/// let row = Row::new(vec!["Row21", "Row22", "Row23"]).style(Style::new().red());
171///
172/// // If you need more control over the styling, create Cells directly
173/// let row = Row::new(vec![
174///     Cell::from("Row31"),
175///     Cell::from("Row32").style(Style::new().yellow()),
176///     Cell::from(Line::from(vec![Span::raw("Row"), Span::from("33").green()])),
177/// ]);
178///
179/// // If a Row need to display some content over multiple lines, specify the height.
180/// let row = Row::new(vec![
181///     Cell::from("Row\n41"),
182///     Cell::from("Row\n42"),
183///     Cell::from("Row\n43"),
184/// ])
185/// .height(2);
186/// ```
187///
188/// Cells can be created from anything that can be converted to [`Text`], or from any widget. See
189/// [`Cell`] for more details.
190///
191/// ```rust
192/// use ratatui::style::{Style, Stylize};
193/// use ratatui::text::{Line, Span, Text};
194/// use ratatui::widgets::Paragraph;
195/// use ratatui_widgettable::Cell;
196///
197/// Cell::from("simple string");
198/// Cell::from("simple styled span".red());
199/// Cell::from(Span::raw("raw span"));
200/// Cell::from(Span::styled("styled span", Style::new().red()));
201/// Cell::from(Line::from(vec![
202///     Span::raw("a vec of "),
203///     Span::from("spans").bold(),
204/// ]));
205/// Cell::from(Text::from("text"));
206/// Cell::new(Paragraph::new("a paragraph").centered());
207/// ```
208///
209/// Just as rows can be collected from iterators of `Cell`s, tables can be collected from iterators
210/// of `Row`s.  This will create a table with column widths evenly dividing the space available.
211/// These default columns widths can be overridden using the `Table::widths` method.
212///
213/// ```rust
214/// use ratatui::layout::Constraint;
215/// use ratatui_widgettable::{Row, Table};
216///
217/// let text = "Mary had a\nlittle lamb.";
218///
219/// let table = text
220///     .split("\n")
221///     .map(|line: &str| -> Row { line.split_ascii_whitespace().collect() })
222///     .collect::<Table>()
223///     .widths([Constraint::Length(10); 3]);
224/// ```
225///
226/// `Table` also implements the [`Styled`] trait, which means you can use style shorthands from
227/// the [`Stylize`] trait to set the style of the widget more concisely.
228///
229/// ```rust
230/// use ratatui::layout::Constraint;
231/// use ratatui::style::Stylize;
232/// use ratatui_widgettable::{Row, Table};
233///
234/// let rows = [Row::new(vec!["Cell1", "Cell2", "Cell3"])];
235/// let widths = [
236///     Constraint::Length(5),
237///     Constraint::Length(5),
238///     Constraint::Length(10),
239/// ];
240/// let table = Table::new(rows, widths).red().italic();
241/// ```
242///
243/// # Stateful example
244///
245/// `Table` is a [`StatefulWidget`], which means you can use it with [`TableState`] to allow the
246/// user to scroll through the rows and select one of them.
247///
248/// ```rust
249/// use ratatui::Frame;
250/// use ratatui::layout::{Constraint, Rect};
251/// use ratatui::style::{Style, Stylize};
252/// use ratatui::widgets::Block;
253/// use ratatui_widgettable::{Row, Table, TableState};
254///
255/// # fn ui(frame: &mut Frame) {
256/// # let area = Rect::default();
257/// // Note: TableState should be stored in your application state (not constructed in your render
258/// // method) so that the selected row is preserved across renders
259/// let mut table_state = TableState::default();
260/// let rows = [
261///     Row::new(vec!["Row11", "Row12", "Row13"]),
262///     Row::new(vec!["Row21", "Row22", "Row23"]),
263///     Row::new(vec!["Row31", "Row32", "Row33"]),
264/// ];
265/// let widths = [
266///     Constraint::Length(5),
267///     Constraint::Length(5),
268///     Constraint::Length(10),
269/// ];
270/// let table = Table::new(rows, widths)
271///     .block(Block::new().title("Table"))
272///     .row_highlight_style(Style::new().reversed())
273///     .highlight_symbol(">>");
274///
275/// frame.render_stateful_widget(table, area, &mut table_state);
276/// # }
277/// ```
278///
279/// [`Stylize`]: ratatui_core::style::Stylize
280#[derive(Debug)]
281pub struct Table<'a> {
282    /// Data to display in each row
283    rows: Vec<Row<'a>>,
284
285    /// Optional header
286    header: Option<Row<'a>>,
287
288    /// Optional footer
289    footer: Option<Row<'a>>,
290
291    /// Width constraints for each column
292    widths: Vec<Constraint>,
293
294    /// Space between each column
295    column_spacing: u16,
296
297    /// A block to wrap the widget in
298    block: Option<Block<'a>>,
299
300    /// Base style for the widget
301    style: Style,
302
303    /// Style used to render the selected row
304    row_highlight_style: Style,
305
306    /// Style used to render the selected column
307    column_highlight_style: Style,
308
309    /// Style used to render the selected cell
310    cell_highlight_style: Style,
311
312    /// Symbol in front of the selected row
313    highlight_symbol: Text<'a>,
314
315    /// Decides when to allocate spacing for the row selection
316    highlight_spacing: HighlightSpacing,
317
318    /// Controls how to distribute extra space among the columns
319    flex: Flex,
320
321    /// How many rows to try to keep visible before and after the selected row
322    scroll_padding: usize,
323}
324
325impl Default for Table<'_> {
326    fn default() -> Self {
327        Self {
328            rows: Vec::new(),
329            header: None,
330            footer: None,
331            widths: Vec::new(),
332            column_spacing: 1,
333            block: None,
334            style: Style::new(),
335            row_highlight_style: Style::new(),
336            column_highlight_style: Style::new(),
337            cell_highlight_style: Style::new(),
338            highlight_symbol: Text::default(),
339            highlight_spacing: HighlightSpacing::default(),
340            flex: Flex::Start,
341            scroll_padding: 0,
342        }
343    }
344}
345
346impl<'a> Table<'a> {
347    /// Creates a new [`Table`] widget with the given rows.
348    ///
349    /// The `rows` parameter accepts any value that can be converted into an iterator of [`Row`]s.
350    /// This includes arrays, slices, and [`Vec`]s.
351    ///
352    /// The `widths` parameter accepts any type that implements `IntoIterator<Item =
353    /// Into<Constraint>>`. This includes arrays, slices, vectors, iterators. `Into<Constraint>` is
354    /// implemented on u16, so you can pass an array, vec, etc. of u16 to this function to create a
355    /// table with fixed width columns.
356    ///
357    /// # Examples
358    ///
359    /// ```rust
360    /// use ratatui::layout::Constraint;
361    /// use ratatui_widgettable::{Row, Table};
362    ///
363    /// let rows = [
364    ///     Row::new(vec!["Cell1", "Cell2"]),
365    ///     Row::new(vec!["Cell3", "Cell4"]),
366    /// ];
367    /// let widths = [Constraint::Length(5), Constraint::Length(5)];
368    /// let table = Table::new(rows, widths);
369    /// ```
370    pub fn new<R, C>(rows: R, widths: C) -> Self
371    where
372        R: IntoIterator,
373        R::Item: Into<Row<'a>>,
374        C: IntoIterator,
375        C::Item: Into<Constraint>,
376    {
377        let widths = widths.into_iter().map(Into::into).collect::<Vec<_>>();
378        ensure_percentages_less_than_100(&widths);
379
380        let rows = rows.into_iter().map(Into::into).collect();
381        Self {
382            rows,
383            widths,
384            ..Default::default()
385        }
386    }
387
388    /// Set the rows
389    ///
390    /// The `rows` parameter accepts any value that can be converted into an iterator of [`Row`]s.
391    /// This includes arrays, slices, and [`Vec`]s.
392    ///
393    /// # Warning
394    ///
395    /// This method does not currently set the column widths. You will need to set them manually by
396    /// calling [`Table::widths`].
397    ///
398    /// This is a fluent setter method which must be chained or used as it consumes self
399    ///
400    /// # Examples
401    ///
402    /// ```rust
403    /// use ratatui_widgettable::{Row, Table};
404    ///
405    /// let rows = [
406    ///     Row::new(vec!["Cell1", "Cell2"]),
407    ///     Row::new(vec!["Cell3", "Cell4"]),
408    /// ];
409    /// let table = Table::default().rows(rows);
410    /// ```
411    #[must_use = "method moves the value of self and returns the modified value"]
412    pub fn rows<T>(mut self, rows: T) -> Self
413    where
414        T: IntoIterator<Item = Row<'a>>,
415    {
416        self.rows = rows.into_iter().collect();
417        self
418    }
419
420    /// Sets the header row
421    ///
422    /// The `header` parameter is a [`Row`] which will be displayed at the top of the [`Table`]
423    ///
424    /// This is a fluent setter method which must be chained or used as it consumes self
425    ///
426    /// # Examples
427    ///
428    /// ```rust
429    /// use ratatui_widgettable::{Cell, Row, Table};
430    ///
431    /// let header = Row::new(vec![
432    ///     Cell::from("Header Cell 1"),
433    ///     Cell::from("Header Cell 2"),
434    /// ]);
435    /// let table = Table::default().header(header);
436    /// ```
437    #[must_use = "method moves the value of self and returns the modified value"]
438    pub fn header(mut self, header: Row<'a>) -> Self {
439        self.header = Some(header);
440        self
441    }
442
443    /// Sets the footer row
444    ///
445    /// The `footer` parameter is a [`Row`] which will be displayed at the bottom of the [`Table`]
446    ///
447    /// This is a fluent setter method which must be chained or used as it consumes self
448    ///
449    /// # Examples
450    ///
451    /// ```rust
452    /// use ratatui_widgettable::{Cell, Row, Table};
453    ///
454    /// let footer = Row::new(vec![
455    ///     Cell::from("Footer Cell 1"),
456    ///     Cell::from("Footer Cell 2"),
457    /// ]);
458    /// let table = Table::default().footer(footer);
459    /// ```
460    #[must_use = "method moves the value of self and returns the modified value"]
461    pub fn footer(mut self, footer: Row<'a>) -> Self {
462        self.footer = Some(footer);
463        self
464    }
465
466    /// Set the widths of the columns.
467    ///
468    /// The `widths` parameter accepts any type that implements `IntoIterator<Item =
469    /// Into<Constraint>>`. This includes arrays, slices, vectors, iterators. `Into<Constraint>` is
470    /// implemented on u16, so you can pass an array, vec, etc. of u16 to this function to create a
471    /// table with fixed width columns.
472    ///
473    /// If the widths are empty, the table will be rendered with equal widths.
474    ///
475    /// This is a fluent setter method which must be chained or used as it consumes self
476    ///
477    /// # Examples
478    ///
479    /// ```rust
480    /// use ratatui::layout::Constraint;
481    /// use ratatui_widgettable::{Cell, Row, Table};
482    ///
483    /// let table = Table::default().widths([Constraint::Length(5), Constraint::Length(5)]);
484    /// let table = Table::default().widths(vec![Constraint::Length(5); 2]);
485    ///
486    /// // widths could also be computed at runtime
487    /// let widths = [10, 10, 20].into_iter().map(|c| Constraint::Length(c));
488    /// let table = Table::default().widths(widths);
489    /// ```
490    #[must_use = "method moves the value of self and returns the modified value"]
491    pub fn widths<I>(mut self, widths: I) -> Self
492    where
493        I: IntoIterator,
494        I::Item: Into<Constraint>,
495    {
496        let widths = widths.into_iter().map(Into::into).collect::<Vec<_>>();
497        ensure_percentages_less_than_100(&widths);
498        self.widths = widths;
499        self
500    }
501
502    /// Set the spacing between columns
503    ///
504    /// This is a fluent setter method which must be chained or used as it consumes self
505    ///
506    /// # Examples
507    ///
508    /// ```rust
509    /// use ratatui::layout::Constraint;
510    /// use ratatui_widgettable::{Row, Table};
511    ///
512    /// let rows = [Row::new(vec!["Cell1", "Cell2"])];
513    /// let widths = [Constraint::Length(5), Constraint::Length(5)];
514    /// let table = Table::new(rows, widths).column_spacing(1);
515    /// ```
516    #[must_use = "method moves the value of self and returns the modified value"]
517    pub const fn column_spacing(mut self, spacing: u16) -> Self {
518        self.column_spacing = spacing;
519        self
520    }
521
522    /// Wraps the table with a custom [`Block`] widget.
523    ///
524    /// The `block` parameter is of type [`Block`]. This holds the specified block to be
525    /// created around the [`Table`]
526    ///
527    /// This is a fluent setter method which must be chained or used as it consumes self
528    ///
529    /// # Examples
530    ///
531    /// ```rust
532    /// use ratatui::layout::Constraint;
533    /// use ratatui::widgets::Block;
534    /// use ratatui_widgettable::{Cell, Row, Table};
535    ///
536    /// let rows = [Row::new(vec!["Cell1", "Cell2"])];
537    /// let widths = [Constraint::Length(5), Constraint::Length(5)];
538    /// let block = Block::bordered().title("Table");
539    /// let table = Table::new(rows, widths).block(block);
540    /// ```
541    #[must_use = "method moves the value of self and returns the modified value"]
542    pub fn block(mut self, block: Block<'a>) -> Self {
543        self.block = Some(block);
544        self
545    }
546
547    /// Sets the base style of the widget
548    ///
549    /// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
550    /// your own type that implements [`Into<Style>`]).
551    ///
552    /// All text rendered by the widget will use this style, unless overridden by [`Block::style`],
553    /// [`Row::style`], [`Cell::style`], or the styles of cell's content.
554    ///
555    /// This is a fluent setter method which must be chained or used as it consumes self
556    ///
557    /// # Examples
558    ///
559    /// ```rust
560    /// use ratatui::layout::Constraint;
561    /// use ratatui::style::{Style, Stylize};
562    /// use ratatui_widgettable::{Row, Table};
563    ///
564    /// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
565    /// # let widths = [Constraint::Length(5), Constraint::Length(5)];
566    /// let table = Table::new(rows, widths).style(Style::new().red().italic());
567    /// ```
568    ///
569    /// `Table` also implements the [`Styled`] trait, which means you can use style shorthands from
570    /// the [`Stylize`] trait to set the style of the widget more concisely.
571    ///
572    /// ```rust
573    /// use ratatui::layout::Constraint;
574    /// use ratatui::style::Stylize;
575    /// use ratatui_widgettable::{Cell, Row, Table};
576    ///
577    /// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
578    /// # let widths = vec![Constraint::Length(5), Constraint::Length(5)];
579    /// let table = Table::new(rows, widths).red().italic();
580    /// ```
581    ///
582    /// [`Color`]: ratatui_core::style::Color
583    /// [`Stylize`]: ratatui_core::style::Stylize
584    #[must_use = "method moves the value of self and returns the modified value"]
585    pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
586        self.style = style.into();
587        self
588    }
589
590    /// Set the style of the selected row
591    ///
592    /// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
593    /// your own type that implements [`Into<Style>`]).
594    ///
595    /// This style will be applied to the entire row, including the selection symbol if it is
596    /// displayed, and will override any style set on the row or on the individual cells.
597    ///
598    /// This is a fluent setter method which must be chained or used as it consumes self
599    ///
600    /// # Examples
601    ///
602    /// ```rust
603    /// # use ratatui::{layout::Constraint, style::{Style, Stylize}};
604    /// # use ratatui_widgettable::{Row, Table};
605    /// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
606    /// # let widths = [Constraint::Length(5), Constraint::Length(5)];
607    /// let table = Table::new(rows, widths).row_highlight_style(Style::new().red().italic());
608    /// ```
609    /// [`Color`]: ratatui_core::style::Color
610    #[must_use = "method moves the value of self and returns the modified value"]
611    pub fn row_highlight_style<S: Into<Style>>(mut self, highlight_style: S) -> Self {
612        self.row_highlight_style = highlight_style.into();
613        self
614    }
615
616    /// Set the style of the selected column
617    ///
618    /// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
619    /// your own type that implements [`Into<Style>`]).
620    ///
621    /// This style will be applied to the entire column, and will override any style set on the
622    /// row or on the individual cells.
623    ///
624    /// This is a fluent setter method which must be chained or used as it consumes self
625    ///
626    /// # Examples
627    ///
628    /// ```rust
629    /// # use ratatui::{layout::Constraint, style::{Style, Stylize}};
630    /// # use ratatui_widgettable::{Row, Table};
631    /// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
632    /// # let widths = [Constraint::Length(5), Constraint::Length(5)];
633    /// let table = Table::new(rows, widths).column_highlight_style(Style::new().red().italic());
634    /// ```
635    /// [`Color`]: ratatui_core::style::Color
636    #[must_use = "method moves the value of self and returns the modified value"]
637    pub fn column_highlight_style<S: Into<Style>>(mut self, highlight_style: S) -> Self {
638        self.column_highlight_style = highlight_style.into();
639        self
640    }
641
642    /// Set the style of the selected cell
643    ///
644    /// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
645    /// your own type that implements [`Into<Style>`]).
646    ///
647    /// This style will be applied to the selected cell, and will override any style set on the
648    /// row or on the individual cells.
649    ///
650    /// This is a fluent setter method which must be chained or used as it consumes self
651    ///
652    /// # Examples
653    ///
654    /// ```rust
655    /// # use ratatui::{layout::Constraint, style::{Style, Stylize}};
656    /// # use ratatui_widgettable::{Row, Table};
657    /// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
658    /// # let widths = [Constraint::Length(5), Constraint::Length(5)];
659    /// let table = Table::new(rows, widths).cell_highlight_style(Style::new().red().italic());
660    /// ```
661    /// [`Color`]: ratatui_core::style::Color
662    #[must_use = "method moves the value of self and returns the modified value"]
663    pub fn cell_highlight_style<S: Into<Style>>(mut self, highlight_style: S) -> Self {
664        self.cell_highlight_style = highlight_style.into();
665        self
666    }
667
668    /// Set the symbol to be displayed in front of the selected row
669    ///
670    /// This is a fluent setter method which must be chained or used as it consumes self
671    ///
672    /// # Examples
673    ///
674    /// ```rust
675    /// use ratatui::layout::Constraint;
676    /// use ratatui_widgettable::{Cell, Row, Table};
677    ///
678    /// # let rows = [Row::new(vec!["Cell1", "Cell2"])];
679    /// # let widths = [Constraint::Length(5), Constraint::Length(5)];
680    /// let table = Table::new(rows, widths).highlight_symbol(">>");
681    /// ```
682    #[must_use = "method moves the value of self and returns the modified value"]
683    pub fn highlight_symbol<T: Into<Text<'a>>>(mut self, highlight_symbol: T) -> Self {
684        self.highlight_symbol = highlight_symbol.into();
685        self
686    }
687
688    /// Set when to show the highlight spacing
689    ///
690    /// The highlight spacing is the spacing that is allocated for the selection symbol column (if
691    /// enabled) and is used to shift the table when a row is selected. This method allows you to
692    /// configure when this spacing is allocated.
693    ///
694    /// - [`HighlightSpacing::Always`] will always allocate the spacing, regardless of whether a row
695    ///   is selected or not. This means that the table will never change size, regardless of if a
696    ///   row is selected or not.
697    /// - [`HighlightSpacing::WhenSelected`] will only allocate the spacing if a row is selected.
698    ///   This means that the table will shift when a row is selected. This is the default setting
699    ///   for backwards compatibility, but it is recommended to use `HighlightSpacing::Always` for a
700    ///   better user experience.
701    /// - [`HighlightSpacing::Never`] will never allocate the spacing, regardless of whether a row
702    ///   is selected or not. This means that the highlight symbol will never be drawn.
703    ///
704    /// This is a fluent setter method which must be chained or used as it consumes self
705    ///
706    /// # Examples
707    ///
708    /// ```rust
709    /// use ratatui::layout::Constraint;
710    /// use ratatui_widgettable::{HighlightSpacing, Row, Table};
711    ///
712    /// let rows = [Row::new(vec!["Cell1", "Cell2"])];
713    /// let widths = [Constraint::Length(5), Constraint::Length(5)];
714    /// let table = Table::new(rows, widths).highlight_spacing(HighlightSpacing::Always);
715    /// ```
716    #[must_use = "method moves the value of self and returns the modified value"]
717    pub const fn highlight_spacing(mut self, value: HighlightSpacing) -> Self {
718        self.highlight_spacing = value;
719        self
720    }
721
722    /// Set how extra space is distributed amongst columns.
723    ///
724    /// This determines how the space is distributed when the constraints are satisfied. By default,
725    /// the extra space is not distributed at all.  But this can be changed to distribute all extra
726    /// space to the last column or to distribute it equally.
727    ///
728    /// This is a fluent setter method which must be chained or used as it consumes self
729    ///
730    /// # Examples
731    ///
732    /// Create a table that needs at least 30 columns to display.  Any extra space will be assigned
733    /// to the last column.
734    /// ```
735    /// use ratatui::layout::{Constraint, Flex};
736    /// use ratatui_widgettable::{Row, Table};
737    ///
738    /// let widths = [
739    ///     Constraint::Min(10),
740    ///     Constraint::Min(10),
741    ///     Constraint::Min(10),
742    /// ];
743    /// let table = Table::new(Vec::<Row>::new(), widths).flex(Flex::Legacy);
744    /// ```
745    #[must_use = "method moves the value of self and returns the modified value"]
746    pub const fn flex(mut self, flex: Flex) -> Self {
747        self.flex = flex;
748        self
749    }
750
751    /// Set the number of rows to keep visible before and after the selected row when scrolling.
752    ///
753    /// This is similar to the `scrolloff` option in Vim, and ensures context around the selected
754    /// row is visible. If the padding value is too large for the visible area, it will be
755    /// automatically reduced to keep the selected row visible.
756    ///
757    /// This is a fluent setter method which must be chained or used as it consumes self
758    ///
759    /// # Examples
760    ///
761    /// ```rust
762    /// use ratatui_widgettable::Table;
763    ///
764    /// let table = Table::default().scroll_padding(1);
765    /// ```
766    #[must_use = "method moves the value of self and returns the modified value"]
767    pub const fn scroll_padding(mut self, padding: usize) -> Self {
768        self.scroll_padding = padding;
769        self
770    }
771}
772
773impl Widget for Table<'_> {
774    fn render(self, area: Rect, buf: &mut Buffer) {
775        Widget::render(&self, area, buf);
776    }
777}
778
779impl Widget for &Table<'_> {
780    fn render(self, area: Rect, buf: &mut Buffer) {
781        let mut state = TableState::default();
782        StatefulWidget::render(self, area, buf, &mut state);
783    }
784}
785
786impl StatefulWidget for Table<'_> {
787    type State = TableState;
788
789    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
790        StatefulWidget::render(&self, area, buf, state);
791    }
792}
793
794impl StatefulWidget for &Table<'_> {
795    type State = TableState;
796
797    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
798        buf.set_style(area, self.style);
799        self.block.as_ref().render(area, buf);
800        let table_area = self.block.inner_if_some(area);
801        if table_area.is_empty() {
802            return;
803        }
804
805        if state.selected().is_some_and(|s| s >= self.rows.len()) {
806            state.select(Some(self.rows.len().saturating_sub(1)));
807        }
808
809        if self.rows.is_empty() {
810            state.select(None);
811        }
812
813        let column_count = self.column_count();
814        if state.selected_column().is_some_and(|s| s >= column_count) {
815            state.select_column(Some(column_count.saturating_sub(1)));
816        }
817        if column_count == 0 {
818            state.select_column(None);
819        }
820
821        let selection_width = self.selection_width(state);
822        let column_widths = self.get_column_widths(table_area.width, selection_width, column_count);
823        let (header_area, rows_area, footer_area) = self.layout(table_area);
824
825        self.render_header(header_area, buf, &column_widths);
826
827        self.render_rows(rows_area, buf, selection_width, state, &column_widths);
828
829        self.render_footer(footer_area, buf, &column_widths);
830    }
831}
832
833// private methods for rendering
834impl Table<'_> {
835    /// Splits the table area into a header, rows area and a footer
836    fn layout(&self, area: Rect) -> (Rect, Rect, Rect) {
837        let header_top_margin = self.header.as_ref().map_or(0, |h| h.top_margin);
838        let header_height = self.header.as_ref().map_or(0, |h| h.height);
839        let header_bottom_margin = self.header.as_ref().map_or(0, |h| h.bottom_margin);
840        let footer_top_margin = self.footer.as_ref().map_or(0, |h| h.top_margin);
841        let footer_height = self.footer.as_ref().map_or(0, |f| f.height);
842        let footer_bottom_margin = self.footer.as_ref().map_or(0, |h| h.bottom_margin);
843        let layout = Layout::vertical([
844            Constraint::Length(header_top_margin),
845            Constraint::Length(header_height),
846            Constraint::Length(header_bottom_margin),
847            Constraint::Min(0),
848            Constraint::Length(footer_top_margin),
849            Constraint::Length(footer_height),
850            Constraint::Length(footer_bottom_margin),
851        ])
852        .split(area);
853        let (header_area, rows_area, footer_area) = (layout[1], layout[3], layout[5]);
854        (header_area, rows_area, footer_area)
855    }
856
857    /// Render the header cells, if they are not `None`
858    ///
859    /// The `x` and `width` fields of each `Rect` in `column_widths` denote the starting
860    /// x-coordinate and width of each column in the table.
861    fn render_header(&self, area: Rect, buf: &mut Buffer, column_widths: &[Rect]) {
862        if let Some(ref header) = self.header {
863            buf.set_style(area, header.style);
864            for (cell_area, cell) in column_widths.iter().zip(header.cells.iter()) {
865                let new_x = area.x + cell_area.x;
866                let area_to_render = Rect::new(new_x, area.y, cell_area.width, area.height);
867                cell.render(area_to_render, buf);
868            }
869        }
870    }
871
872    /// Render the footer cells, if they are not `None`
873    ///
874    /// The `x` and `width` fields of each `Rect` in `column_widths` denote the starting
875    /// x-coordinate and width of each column in the table.
876    fn render_footer(&self, area: Rect, buf: &mut Buffer, column_widths: &[Rect]) {
877        if let Some(ref footer) = self.footer {
878            buf.set_style(area, footer.style);
879            for (cell_area, cell) in column_widths.iter().zip(footer.cells.iter()) {
880                let new_x = area.x + cell_area.x;
881                let area_to_render = Rect::new(new_x, area.y, cell_area.width, area.height);
882                cell.render(area_to_render, buf);
883            }
884        }
885    }
886
887    /// Render the table rows
888    ///
889    /// The `x` and `width` fields of each `Rect` in `column_widths` denote the starting
890    /// x-coordinate and width of each column in the table.
891    fn render_rows(
892        &self,
893        area: Rect,
894        buf: &mut Buffer,
895        selection_width: u16,
896        state: &mut TableState,
897        columns_widths: &[Rect],
898    ) {
899        if self.rows.is_empty() {
900            return;
901        }
902
903        let (start_index, end_index) = self.visible_rows(state, area);
904        *state.offset_mut() = start_index;
905
906        let mut y_offset = 0;
907
908        let mut selected_row_area = None;
909        for (i, row) in self
910            .rows
911            .iter()
912            .enumerate()
913            .skip(start_index)
914            .take(end_index - start_index)
915        {
916            // saturating, as rows can extend past the end of the coordinate space
917            let y = area
918                .y
919                .saturating_add(y_offset)
920                .saturating_add(row.top_margin);
921            let height = y
922                .saturating_add(row.height)
923                .min(area.bottom())
924                .saturating_sub(y);
925            let row_area = Rect { y, height, ..area };
926            buf.set_style(row_area, row.style);
927
928            let is_selected = state.selected().is_some_and(|index| index == i);
929            if selection_width > 0 && is_selected {
930                self.set_selection_style(buf, selection_width, row_area, row);
931            }
932            self.render_row_cells(buf, columns_widths.iter().collect(), &row.cells, row_area);
933            if is_selected {
934                selected_row_area = Some(row_area);
935            }
936            y_offset = y_offset.saturating_add(row.height_with_margin());
937        }
938
939        let selected_column_area = state.selected_column().and_then(|s| {
940            // The selection is clamped by the column count. Since a user can manually specify an
941            // incorrect number of widths, we should use panic free methods.
942            columns_widths.get(s).map(|cell_area| Rect {
943                x: cell_area.x + area.x,
944                width: cell_area.width,
945                ..area
946            })
947        });
948
949        match (selected_row_area, selected_column_area) {
950            (Some(row_area), Some(col_area)) => {
951                buf.set_style(row_area, self.row_highlight_style);
952                buf.set_style(col_area, self.column_highlight_style);
953                let cell_area = row_area.intersection(col_area);
954                buf.set_style(cell_area, self.cell_highlight_style);
955            }
956            (Some(row_area), None) => {
957                buf.set_style(row_area, self.row_highlight_style);
958            }
959            (None, Some(col_area)) => {
960                buf.set_style(col_area, self.column_highlight_style);
961            }
962            (None, None) => (),
963        }
964    }
965
966    /// Render cells into the columns of a row
967    ///
968    /// Render `Cell`s from `cells` into columns specified by `column_widths`, stopping
969    /// if either of these iterators are finished.  Each `Cell` gets rendered across
970    /// [`Cell::get_column_span`] columns plus the gaps between them, if this value is > 1.
971    fn render_row_cells(
972        &self,
973        buf: &mut Buffer,
974        column_widths: Vec<&Rect>,
975        cells: &Vec<Cell>,
976        row_area: Rect,
977    ) {
978        let mut column_widths_iterator = column_widths.into_iter();
979        for current_cell in cells {
980            if let Some(cell_area) = Self::get_cell_area(
981                &mut column_widths_iterator,
982                current_cell.column_span,
983                self.column_spacing,
984            ) {
985                let new_x = row_area.x + cell_area.x;
986                // A cell spanning multiple columns can extend past the right edge of the table
987                // when the columns are squeezed, so it is clipped to the row
988                let area_to_render = Rect::new(new_x, row_area.y, cell_area.width, row_area.height)
989                    .intersection(row_area);
990                current_cell.render(area_to_render, buf);
991            }
992        }
993    }
994
995    /// Set the row style and render the highlight symbol
996    fn set_selection_style(
997        &self,
998        buf: &mut Buffer,
999        selection_width: u16,
1000        row_area: Rect,
1001        row: &Row,
1002    ) {
1003        // clipped to the row, in case the highlight symbol is wider than the table
1004        let selection_area = Rect {
1005            width: selection_width,
1006            ..row_area
1007        }
1008        .intersection(row_area);
1009        buf.set_style(selection_area, row.style);
1010        (&self.highlight_symbol).render(selection_area, buf);
1011    }
1012
1013    /// Return the area that a [`Cell`] should occupy, taking into account its
1014    /// [`Cell::column_span`].
1015    ///
1016    /// Returns `None` when there are no more columns for the [`Cell`] to occupy.
1017    ///
1018    /// Otherwise, returns `Some(Rect{x, y = 0, width, height = 0})`, representing the start
1019    /// x-coordinate and width of the [`Cell`].
1020    ///
1021    /// This function consumes `cell_column_span` `Rect`s from `column_widths_iterator` (or all the
1022    /// `Rects` if the iterator is less than `cell_column_span` `Rect`s long). This function adds
1023    /// the width of each `Rect` plus `column_spacing` to a running total of the final width.  The
1024    /// return value is the original x coordinate and the final width, or `None` if
1025    /// `column_widths_iterator` is empty or `cell_column_span` is `0`.
1026    fn get_cell_area<'a, T>(
1027        column_widths_iterator: &mut T,
1028        cell_column_span: u16,
1029        column_spacing: u16,
1030    ) -> Option<Rect>
1031    where
1032        T: Iterator<Item = &'a Rect>,
1033    {
1034        if cell_column_span == 0 {
1035            return None;
1036        }
1037        let first = column_widths_iterator.next()?;
1038        let (n_columns_taken, all_columns_width) = column_widths_iterator
1039            .take((cell_column_span - 1).into())
1040            .map(|rect| (1, u32::from(rect.width)))
1041            .fold((1, u32::from(first.width)), |so_far, next_column| {
1042                (next_column.0 + so_far.0, next_column.1 + so_far.1)
1043            });
1044        // computed as u32 and clamped, as a large column spacing can overflow u16
1045        let width = all_columns_width + (n_columns_taken - 1) * u32::from(column_spacing);
1046        let width = u16::try_from(width).unwrap_or(u16::MAX);
1047        Some(Rect::new(first.x, first.y, width, 1))
1048    }
1049
1050    /// Return the indexes of the visible rows.
1051    ///
1052    /// The algorithm works as follows:
1053    /// - start at the offset and calculate the height of the rows that can be displayed within the
1054    ///   area.
1055    /// - if the selected row is not visible, scroll the table to ensure it is visible.
1056    /// - if scroll padding is set, ensure the padding number of rows are visible before and after
1057    ///   the selected row, adjusting the padding down when items of inconsistent sizes make it
1058    ///   impossible.
1059    /// - if there is still space to fill then there's a partial row at the end which should be
1060    ///   included in the view.
1061    fn visible_rows(&self, state: &TableState, area: Rect) -> (usize, usize) {
1062        let last_row = self.rows.len().saturating_sub(1);
1063        let mut start = state.offset().min(last_row);
1064
1065        if let Some(selected) = state.selected() {
1066            start = start.min(selected);
1067        }
1068
1069        let mut end = start;
1070        let mut height: u16 = 0;
1071
1072        for item in self.rows.iter().skip(start) {
1073            if height.saturating_add(item.height) > area.height {
1074                break;
1075            }
1076            height = height.saturating_add(item.height_with_margin());
1077            end += 1;
1078        }
1079
1080        if let Some(selected) = state.selected() {
1081            let selected = selected.min(last_row);
1082
1083            let index_to_display = self.apply_scroll_padding_to_selected_index(
1084                selected,
1085                area.height as usize,
1086                start,
1087                end,
1088            );
1089
1090            // scroll down until the target index is visible
1091            while index_to_display >= end {
1092                height = height.saturating_add(self.rows[end].height_with_margin());
1093                end += 1;
1094                while height > area.height {
1095                    height = height.saturating_sub(self.rows[start].height_with_margin());
1096                    start += 1;
1097                }
1098            }
1099
1100            // scroll up until the target index is visible
1101            while index_to_display < start {
1102                start -= 1;
1103                height = height.saturating_add(self.rows[start].height_with_margin());
1104                while height > area.height {
1105                    end -= 1;
1106                    height = height.saturating_sub(self.rows[end].height_with_margin());
1107                }
1108            }
1109        }
1110
1111        // Include a partial row if there is space
1112        if height < area.height && end < self.rows.len() {
1113            end += 1;
1114        }
1115
1116        (start, end)
1117    }
1118
1119    /// Applies scroll padding to the selected index, reducing the padding value to keep the
1120    /// selected row on screen even with rows of inconsistent sizes
1121    fn apply_scroll_padding_to_selected_index(
1122        &self,
1123        selected: usize,
1124        max_height: usize,
1125        first_visible_index: usize,
1126        last_visible_index: usize,
1127    ) -> usize {
1128        let last_valid_index = self.rows.len().saturating_sub(1);
1129        if self.scroll_padding == 0 {
1130            return selected;
1131        }
1132
1133        let mut scroll_padding = self.scroll_padding.min(last_valid_index);
1134        let pad_start = selected.saturating_sub(scroll_padding);
1135        let pad_end = selected
1136            .saturating_add(scroll_padding)
1137            .min(last_valid_index);
1138        let mut height_around_selected = self.rows[pad_start..=pad_end]
1139            .iter()
1140            .map(|row| row.height_with_margin() as usize)
1141            .sum::<usize>();
1142
1143        while scroll_padding > 0 && height_around_selected > max_height {
1144            if let Some(index) = selected.checked_sub(scroll_padding) {
1145                height_around_selected = height_around_selected
1146                    .saturating_sub(self.rows[index].height_with_margin() as usize);
1147            }
1148            if let Some(index) = selected
1149                .checked_add(scroll_padding)
1150                .filter(|&index| index <= last_valid_index)
1151            {
1152                height_around_selected = height_around_selected
1153                    .saturating_sub(self.rows[index].height_with_margin() as usize);
1154            }
1155            scroll_padding -= 1;
1156        }
1157
1158        let selected_after_padding = selected
1159            .saturating_add(scroll_padding)
1160            .min(last_valid_index);
1161        if selected_after_padding >= last_visible_index {
1162            selected_after_padding
1163        } else if selected.saturating_sub(scroll_padding) < first_visible_index {
1164            selected.saturating_sub(scroll_padding)
1165        } else {
1166            selected
1167        }
1168    }
1169
1170    /// Get all offsets and widths of all user specified columns.
1171    ///
1172    /// Returns (x, width). When self.widths is empty, it is assumed `.widths()` has not been called
1173    /// and a default of equal widths is returned.
1174    fn get_column_widths(
1175        &self,
1176        max_width: u16,
1177        selection_width: u16,
1178        col_count: usize,
1179    ) -> Vec<Rect> {
1180        let widths = if self.widths.is_empty() {
1181            // Divide the space between each column equally
1182            vec![Constraint::Length(max_width / col_count.max(1) as u16); col_count]
1183        } else {
1184            self.widths.clone()
1185        };
1186        // this will always allocate a selection area
1187        let [_selection_area, columns_area] =
1188            Layout::horizontal([Constraint::Length(selection_width), Constraint::Fill(0)])
1189                .areas(Rect::new(0, 0, max_width, 1));
1190        let rects = Layout::horizontal(widths)
1191            .flex(self.flex)
1192            .spacing(self.column_spacing)
1193            .split(columns_area);
1194        rects
1195            .iter()
1196            .map(|c| Rect::new(c.x, 0, c.width, 1))
1197            .collect()
1198    }
1199
1200    fn column_count(&self) -> usize {
1201        self.rows
1202            .iter()
1203            .chain(self.footer.iter())
1204            .chain(self.header.iter())
1205            .map(|r| r.cells.len())
1206            .max()
1207            .unwrap_or_default()
1208    }
1209
1210    /// Returns the width of the selection column if a row is selected, or the `highlight_spacing`
1211    /// is set to show the column always, otherwise 0.
1212    fn selection_width(&self, state: &TableState) -> u16 {
1213        let should_add = match self.highlight_spacing {
1214            HighlightSpacing::Always => true,
1215            HighlightSpacing::WhenSelected => state.selected().is_some(),
1216            HighlightSpacing::Never => false,
1217        };
1218        if should_add {
1219            self.highlight_symbol.width() as u16
1220        } else {
1221            0
1222        }
1223    }
1224}
1225
1226fn ensure_percentages_less_than_100(widths: &[Constraint]) {
1227    for w in widths {
1228        if let Constraint::Percentage(p) = w {
1229            assert!(
1230                *p <= 100,
1231                "Percentages should be between 0 and 100 inclusively."
1232            );
1233        }
1234    }
1235}
1236
1237impl Styled for Table<'_> {
1238    type Item = Self;
1239
1240    fn style(&self) -> Style {
1241        self.style
1242    }
1243
1244    fn set_style<S: Into<Style>>(self, style: S) -> Self::Item {
1245        self.style(style)
1246    }
1247}
1248
1249impl<'a, Item> FromIterator<Item> for Table<'a>
1250where
1251    Item: Into<Row<'a>>,
1252{
1253    /// Collects an iterator of rows into a table.
1254    ///
1255    /// When collecting from an iterator into a table, the user must provide the widths using
1256    /// `Table::widths` after construction.
1257    fn from_iter<Iter: IntoIterator<Item = Item>>(rows: Iter) -> Self {
1258        let widths: [Constraint; 0] = [];
1259        Self::new(rows, widths)
1260    }
1261}