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