Skip to main content

ratatui_widgettable/
row.rs

1use alloc::vec::Vec;
2
3use ratatui_core::style::{Style, Styled};
4
5use crate::Cell;
6
7/// A single row of data to be displayed in a [`Table`] widget.
8///
9/// A `Row` is a collection of [`Cell`]s.
10///
11/// By default, a row has a height of 1 but you can change this using [`Row::height`].
12///
13/// You can set the style of the entire row using [`Row::style`]. This [`Style`] will be combined
14/// with the [`Style`] of each individual [`Cell`] by adding the [`Style`] of the [`Cell`] to the
15/// [`Style`] of the [`Row`].
16///
17/// # Examples
18///
19/// You can create `Row`s from simple strings.
20///
21/// ```rust
22/// use ratatui_widgettable::Row;
23///
24/// Row::new(vec!["Cell1", "Cell2", "Cell3"]);
25/// ```
26///
27/// If you need a bit more control over individual cells, you can explicitly create [`Cell`]s:
28///
29/// ```rust
30/// use ratatui::style::Stylize;
31/// use ratatui_widgettable::{Cell, Row};
32///
33/// Row::new(vec![
34///     Cell::from("Cell1"),
35///     Cell::from("Cell2").red().italic(),
36/// ]);
37/// ```
38///
39/// Cells can contain any widget. Set the row [`height`](Row::height) so that there is room for
40/// the widget to render:
41///
42/// ```rust
43/// use ratatui::widgets::{Block, Paragraph, Wrap};
44/// use ratatui_widgettable::{Cell, Row};
45///
46/// Row::new(vec![
47///     Cell::from("Name"),
48///     Cell::new(
49///         Paragraph::new("A long description that wraps over multiple lines")
50///             .wrap(Wrap { trim: true })
51///             .block(Block::bordered()),
52///     ),
53/// ])
54/// .height(5);
55/// ```
56///
57/// You can also construct a row from any type that can be converted into [`Text`]:
58///
59/// ```rust
60/// use std::borrow::Cow;
61///
62/// use ratatui_widgettable::{Cell, Row};
63///
64/// Row::new(vec![
65///     Cow::Borrowed("hello"),
66///     Cow::Owned("world".to_uppercase()),
67/// ]);
68/// ```
69///
70/// An iterator whose item type is convertible into [`Text`] can be collected into a row.
71///
72/// ```rust
73/// use ratatui_widgettable::Row;
74///
75/// (0..10).map(|i| format!("{i}")).collect::<Row>();
76/// ```
77///
78/// `Row` implements [`Styled`] which means you can use style shorthands from the [`Stylize`] trait
79/// to set the style of the row concisely.
80///
81/// ```rust
82/// use ratatui::style::Stylize;
83/// use ratatui_widgettable::Row;
84///
85/// let cells = vec!["Cell1", "Cell2", "Cell3"];
86/// Row::new(cells).red().italic();
87/// ```
88///
89/// [`Table`]: crate::Table
90/// [`Text`]: ratatui_core::text::Text
91/// [`Stylize`]: ratatui_core::style::Stylize
92#[derive(Debug, Default)]
93pub struct Row<'a> {
94    pub(crate) cells: Vec<Cell<'a>>,
95    pub(crate) height: u16,
96    pub(crate) top_margin: u16,
97    pub(crate) bottom_margin: u16,
98    pub(crate) style: Style,
99}
100
101impl<'a> Row<'a> {
102    /// Creates a new [`Row`]
103    ///
104    /// The `cells` parameter accepts any value that can be converted into an iterator of anything
105    /// that can be converted into a [`Cell`] (e.g. `Vec<&str>`, `&[Cell<'a>]`, `Vec<String>`, etc.)
106    ///
107    /// # Examples
108    ///
109    /// ```rust
110    /// use ratatui_widgettable::{Cell, Row};
111    ///
112    /// let row = Row::new(vec!["Cell 1", "Cell 2", "Cell 3"]);
113    /// let row = Row::new(vec![
114    ///     Cell::from("Cell 1"),
115    ///     Cell::from("Cell 2"),
116    ///     Cell::from("Cell 3"),
117    /// ]);
118    /// ```
119    pub fn new<T>(cells: T) -> Self
120    where
121        T: IntoIterator,
122        T::Item: Into<Cell<'a>>,
123    {
124        Self {
125            cells: cells.into_iter().map(Into::into).collect(),
126            height: 1,
127            ..Default::default()
128        }
129    }
130
131    /// Set the cells of the [`Row`]
132    ///
133    /// The `cells` parameter accepts any value that can be converted into an iterator of anything
134    /// that can be converted into a [`Cell`] (e.g. `Vec<&str>`, `&[Cell<'a>]`, `Vec<String>`, etc.)
135    ///
136    /// This is a fluent setter method which must be chained or used as it consumes self
137    ///
138    /// # Examples
139    ///
140    /// ```rust
141    /// use ratatui_widgettable::{Cell, Row};
142    ///
143    /// let row = Row::default().cells(vec!["Cell 1", "Cell 2", "Cell 3"]);
144    /// let row = Row::default().cells(vec![
145    ///     Cell::from("Cell 1"),
146    ///     Cell::from("Cell 2"),
147    ///     Cell::from("Cell 3"),
148    /// ]);
149    /// ```
150    #[must_use = "method moves the value of self and returns the modified value"]
151    pub fn cells<T>(mut self, cells: T) -> Self
152    where
153        T: IntoIterator,
154        T::Item: Into<Cell<'a>>,
155    {
156        self.cells = cells.into_iter().map(Into::into).collect();
157        self
158    }
159
160    /// Set the fixed height of the [`Row`]
161    ///
162    /// Any [`Cell`] whose content has more lines than this height will see its content truncated.
163    ///
164    /// By default, the height is `1`.
165    ///
166    /// This is a fluent setter method which must be chained or used as it consumes self
167    ///
168    /// # Examples
169    ///
170    /// ```rust
171    /// use ratatui_widgettable::Row;
172    ///
173    /// let cells = vec!["Cell 1\nline 2", "Cell 2", "Cell 3"];
174    /// let row = Row::new(cells).height(2);
175    /// ```
176    #[must_use = "method moves the value of self and returns the modified value"]
177    pub const fn height(mut self, height: u16) -> Self {
178        self.height = height;
179        self
180    }
181
182    /// Set the top margin. By default, the top margin is `0`.
183    ///
184    /// The top margin is the number of blank lines to be displayed before the row.
185    ///
186    /// This is a fluent setter method which must be chained or used as it consumes self
187    ///
188    /// # Examples
189    ///
190    /// ```rust
191    /// use ratatui_widgettable::Row;
192    /// let cells = vec!["Cell 1", "Cell 2", "Cell 3"];
193    ///
194    /// let row = Row::default().top_margin(1);
195    /// ```
196    #[must_use = "method moves the value of self and returns the modified value"]
197    pub const fn top_margin(mut self, margin: u16) -> Self {
198        self.top_margin = margin;
199        self
200    }
201
202    /// Set the bottom margin. By default, the bottom margin is `0`.
203    ///
204    /// The bottom margin is the number of blank lines to be displayed after the row.
205    ///
206    /// This is a fluent setter method which must be chained or used as it consumes self
207    ///
208    /// # Examples
209    ///
210    /// ```rust
211    /// use ratatui_widgettable::Row;
212    ///
213    /// let cells = vec!["Cell 1", "Cell 2", "Cell 3"];
214    /// let row = Row::default().bottom_margin(1);
215    /// ```
216    #[must_use = "method moves the value of self and returns the modified value"]
217    pub const fn bottom_margin(mut self, margin: u16) -> Self {
218        self.bottom_margin = margin;
219        self
220    }
221
222    /// Set the [`Style`] of the entire row
223    ///
224    /// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
225    /// your own type that implements [`Into<Style>`]).
226    ///
227    /// This [`Style`] can be overridden by the [`Style`] of a any individual [`Cell`] or by their
228    /// [`Text`] content.
229    ///
230    /// This is a fluent setter method which must be chained or used as it consumes self
231    ///
232    /// # Examples
233    ///
234    /// ```rust
235    /// use ratatui::style::{Style, Stylize};
236    /// use ratatui_widgettable::Row;
237    /// let cells = vec!["Cell 1", "Cell 2", "Cell 3"];
238    /// let row = Row::new(cells).style(Style::new().red().italic());
239    /// ```
240    ///
241    /// `Row` also implements the [`Styled`] trait, which means you can use style shorthands from
242    /// the [`Stylize`] trait to set the style of the widget more concisely.
243    ///
244    /// ```rust
245    /// use ratatui::style::Stylize;
246    /// use ratatui_widgettable::Row;
247    ///
248    /// let cells = vec!["Cell 1", "Cell 2", "Cell 3"];
249    /// let row = Row::new(cells).red().italic();
250    /// ```
251    ///
252    /// [`Color`]: ratatui_core::style::Color
253    /// [`Stylize`]: ratatui_core::style::Stylize
254    /// [`Text`]: ratatui_core::text::Text
255    #[must_use = "method moves the value of self and returns the modified value"]
256    pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
257        self.style = style.into();
258        self
259    }
260}
261
262// private methods for rendering
263impl Row<'_> {
264    /// Returns the total height of the row.
265    pub(crate) const fn height_with_margin(&self) -> u16 {
266        self.height
267            .saturating_add(self.top_margin)
268            .saturating_add(self.bottom_margin)
269    }
270}
271
272impl Styled for Row<'_> {
273    type Item = Self;
274
275    fn style(&self) -> Style {
276        self.style
277    }
278
279    fn set_style<S: Into<Style>>(self, style: S) -> Self::Item {
280        self.style(style)
281    }
282}
283
284impl<'a, Item> FromIterator<Item> for Row<'a>
285where
286    Item: Into<Cell<'a>>,
287{
288    fn from_iter<IterCells: IntoIterator<Item = Item>>(cells: IterCells) -> Self {
289        Self::new(cells)
290    }
291}
292
293#[cfg(test)]
294mod tests {
295    use alloc::vec;
296
297    use ratatui_core::style::{Color, Modifier, Stylize};
298
299    use super::*;
300
301    #[test]
302    fn new() {
303        let row = Row::new(vec!["a", "b"]);
304        assert_eq!(row.cells.len(), 2);
305        assert_eq!(row.height, 1);
306    }
307
308    #[test]
309    fn collect() {
310        let row: Row = ["a", "b", "c"].into_iter().collect();
311        assert_eq!(row.cells.len(), 3);
312    }
313
314    #[test]
315    fn height_with_margin() {
316        let row = Row::default().height(2).top_margin(1).bottom_margin(3);
317        assert_eq!(row.height_with_margin(), 6);
318    }
319
320    #[test]
321    fn stylize() {
322        assert_eq!(
323            Row::new(vec![Cell::from("")])
324                .black()
325                .on_white()
326                .bold()
327                .not_italic()
328                .style,
329            Style::default()
330                .fg(Color::Black)
331                .bg(Color::White)
332                .add_modifier(Modifier::BOLD)
333                .remove_modifier(Modifier::ITALIC)
334        );
335    }
336}