Debian Codegraph @

helix-tui/src/widgets/table.rs

raw symbols SCIP
1 use crate::{
2 buffer::Buffer,
3 layout::Constraint,
4 text::Text,
5 widgets::{Block, Widget},
6 };
7 use helix_core::unicode::width::UnicodeWidthStr;
8 use helix_view::graphics::{Rect, Style};
9
10 /// A [`Cell`] contains the [`Text`] to be displayed in a [`Row`] of a [`Table`].
11 ///
12 /// It can be created from anything that can be converted to a [`Text`].
13 /// ```rust
14 /// # use helix_tui::widgets::Cell;
15 /// # use helix_tui::text::{Span, Spans, Text};
16 /// # use helix_view::graphics::{Style, Modifier};
17 /// Cell::from("simple string");
18 ///
19 /// Cell::from(Span::from("span"));
20 ///
21 /// Cell::from(Spans::from(vec![
22 /// Span::raw("a vec of "),
23 /// Span::styled("spans", Style::default().add_modifier(Modifier::BOLD))
24 /// ]));
25 ///
26 /// Cell::from(Text::from("a text"));
27 /// ```
28 ///
29 /// You can apply a [`Style`] on the entire [`Cell`] using [`Cell::style`] or rely on the styling
30 /// capabilities of [`Text`].
31 #[derive(Debug, Clone, PartialEq, Eq, Default)]
32 pub struct Cell<'a> {
33 pub content: Text<'a>,
34 style: Style,
35 }
36
37 impl Cell<'_> {
38 /// Set the `Style` of this cell.
39 pub fn style(mut self, style: Style) -> Self {
40 self.set_style(style);
41 self
42 }
43
44 /// Set the `Style` of this cell.
45 pub fn set_style(&mut self, style: Style) {
46 self.style = style;
47 self.content.patch_style(style);
48 }
49 }
50
51 impl<'a, T> From<T> for Cell<'a>
52 where
53 T: Into<Text<'a>>,
54 {
55 fn from(content: T) -> Cell<'a> {
56 Cell {
57 content: content.into(),
58 style: Style::default(),
59 }
60 }
61 }
62
63 /// Holds data to be displayed in a [`Table`] widget.
64 ///
65 /// A [`Row`] is a collection of cells. It can be created from simple strings:
66 /// ```rust
67 /// # use helix_tui::widgets::Row;
68 /// Row::new(vec!["Cell1", "Cell2", "Cell3"]);
69 /// ```
70 ///
71 /// But if you need a bit more control over individual cells, you can explicitly create [`Cell`]s:
72 /// ```rust
73 /// # use helix_tui::widgets::{Row, Cell};
74 /// # use helix_view::graphics::{Style, Color};
75 /// Row::new(vec![
76 /// Cell::from("Cell1"),
77 /// Cell::from("Cell2").style(Style::default().fg(Color::Yellow)),
78 /// ]);
79 /// ```
80 ///
81 /// By default, a row has a height of 1 but you can change this using [`Row::height`].
82 #[derive(Debug, Clone, PartialEq, Eq, Default)]
83 pub struct Row<'a> {
84 pub cells: Vec<Cell<'a>>,
85 height: u16,
86 style: Style,
87 bottom_margin: u16,
88 }
89
90 impl<'a> Row<'a> {
91 /// Creates a new [`Row`] from an iterator where items can be converted to a [`Cell`].
92 pub fn new<T>(cells: T) -> Self
93 where
94 T: IntoIterator,
95 T::Item: Into<Cell<'a>>,
96 {
97 Self {
98 height: 1,
99 cells: cells.into_iter().map(|c| c.into()).collect(),
100 style: Style::default(),
101 bottom_margin: 0,
102 }
103 }
104
105 /// Set the fixed height of the [`Row`]. Any [`Cell`] whose content has more lines than this
106 /// height will see its content truncated.
107 pub fn height(mut self, height: u16) -> Self {
108 self.height = height;
109 self
110 }
111
112 /// Set the [`Style`] of the entire row. This [`Style`] can be overridden by the [`Style`] of a
113 /// any individual [`Cell`] or event by their [`Text`] content.
114 pub fn style(mut self, style: Style) -> Self {
115 self.style = style;
116 self
117 }
118
119 /// Set the bottom margin. By default, the bottom margin is `0`.
120 pub fn bottom_margin(mut self, margin: u16) -> Self {
121 self.bottom_margin = margin;
122 self
123 }
124
125 /// Returns the total height of the row.
126 fn total_height(&self) -> u16 {
127 self.height.saturating_add(self.bottom_margin)
128 }
129
130 /// Returns the contents of cells as plain text, without styles and colors.
131 pub fn cell_text(&self) -> impl Iterator<Item = String> + '_ {
132 self.cells.iter().map(|cell| String::from(&cell.content))
133 }
134 }
135
136 impl<'a, T: Into<Cell<'a>>> From<T> for Row<'a> {
137 fn from(cell: T) -> Self {
138 Row::new(vec![cell.into()])
139 }
140 }
141
142 /// A widget to display data in formatted columns.
143 ///
144 /// It is a collection of [`Row`]s, themselves composed of [`Cell`]s:
145 /// ```rust
146 /// # use helix_tui::widgets::{Block, Borders, Table, Row, Cell};
147 /// # use helix_tui::layout::Constraint;
148 /// # use helix_view::graphics::{Style, Color, Modifier};
149 /// # use helix_tui::text::{Text, Spans, Span};
150 /// Table::new(vec![
151 /// // Row can be created from simple strings.
152 /// Row::new(vec!["Row11", "Row12", "Row13"]),
153 /// // You can style the entire row.
154 /// Row::new(vec!["Row21", "Row22", "Row23"]).style(Style::default().fg(Color::Blue)),
155 /// // If you need more control over the styling you may need to create Cells directly
156 /// Row::new(vec![
157 /// Cell::from("Row31"),
158 /// Cell::from("Row32").style(Style::default().fg(Color::Yellow)),
159 /// Cell::from(Spans::from(vec![
160 /// Span::raw("Row"),
161 /// Span::styled("33", Style::default().fg(Color::Green))
162 /// ])),
163 /// ]),
164 /// // If a Row need to display some content over multiple lines, you just have to change
165 /// // its height.
166 /// Row::new(vec![
167 /// Cell::from("Row\n41"),
168 /// Cell::from("Row\n42"),
169 /// Cell::from("Row\n43"),
170 /// ]).height(2),
171 /// ])
172 /// // You can set the style of the entire Table.
173 /// .style(Style::default().fg(Color::White))
174 /// // It has an optional header, which is simply a Row always visible at the top.
175 /// .header(
176 /// Row::new(vec!["Col1", "Col2", "Col3"])
177 /// .style(Style::default().fg(Color::Yellow))
178 /// // If you want some space between the header and the rest of the rows, you can always
179 /// // specify some margin at the bottom.
180 /// .bottom_margin(1)
181 /// )
182 /// // As any other widget, a Table can be wrapped in a Block.
183 /// .block(Block::default().title("Table"))
184 /// // Columns widths are constrained in the same way as Layout...
185 /// .widths(&[Constraint::Length(5), Constraint::Length(5), Constraint::Length(10)])
186 /// // ...and they can be separated by a fixed spacing.
187 /// .column_spacing(1)
188 /// // If you wish to highlight a row in any specific way when it is selected...
189 /// .highlight_style(Style::default().add_modifier(Modifier::BOLD))
190 /// // ...and potentially show a symbol in front of the selection.
191 /// .highlight_symbol(">>");
192 /// ```
193 #[derive(Debug, Clone, PartialEq, Eq)]
194 pub struct Table<'a> {
195 /// A block to wrap the widget in
196 block: Option<Block<'a>>,
197 /// Base style for the widget
198 style: Style,
199 /// Width constraints for each column
200 widths: &'a [Constraint],
201 /// Space between each column
202 column_spacing: u16,
203 /// Style used to render the selected row
204 highlight_style: Style,
205 /// Symbol in front of the selected rom
206 highlight_symbol: Option<&'a str>,
207 /// Optional header
208 header: Option<Row<'a>>,
209 /// Data to display in each row
210 rows: Vec<Row<'a>>,
211 }
212
213 impl<'a> Table<'a> {
214 pub fn new<T>(rows: T) -> Self
215 where
216 T: IntoIterator<Item = Row<'a>>,
217 {
218 Self {
219 block: None,
220 style: Style::default(),
221 widths: &[],
222 column_spacing: 1,
223 highlight_style: Style::default(),
224 highlight_symbol: None,
225 header: None,
226 rows: rows.into_iter().collect(),
227 }
228 }
229
230 pub fn block(mut self, block: Block<'a>) -> Self {
231 self.block = Some(block);
232 self
233 }
234
235 pub fn header(mut self, header: Row<'a>) -> Self {
236 self.header = Some(header);
237 self
238 }
239
240 pub fn widths(mut self, widths: &'a [Constraint]) -> Self {
241 let between_0_and_100 = |&w| match w {
242 Constraint::Percentage(p) => p <= 100,
243 _ => true,
244 };
245 assert!(
246 widths.iter().all(between_0_and_100),
247 "Percentages should be between 0 and 100 inclusively."
248 );
249 self.widths = widths;
250 self
251 }
252
253 pub fn style(mut self, style: Style) -> Self {
254 self.style = style;
255 self
256 }
257
258 pub fn highlight_symbol(mut self, highlight_symbol: &'a str) -> Self {
259 self.highlight_symbol = Some(highlight_symbol);
260 self
261 }
262
263 pub fn highlight_style(mut self, highlight_style: Style) -> Self {
264 self.highlight_style = highlight_style;
265 self
266 }
267
268 pub fn column_spacing(mut self, spacing: u16) -> Self {
269 self.column_spacing = spacing;
270 self
271 }
272
273 fn get_columns_widths(&self, max_width: u16, has_selection: bool) -> Vec<u16> {
274 let mut constraints = Vec::with_capacity(self.widths.len() * 2 + 1);
275 if has_selection {
276 let highlight_symbol_width =
277 self.highlight_symbol.map(|s| s.width() as u16).unwrap_or(0);
278 constraints.push(Constraint::Length(highlight_symbol_width));
279 }
280 for constraint in self.widths {
281 constraints.push(*constraint);
282 constraints.push(Constraint::Length(self.column_spacing));
283 }
284 if !self.widths.is_empty() {
285 constraints.pop();
286 }
287 let mut chunks = crate::layout::Layout::default()
288 .direction(crate::layout::Direction::Horizontal)
289 .constraints(constraints)
290 .split(Rect {
291 x: 0,
292 y: 0,
293 width: max_width,
294 height: 1,
295 });
296 if has_selection {
297 chunks.remove(0);
298 }
299 chunks.iter().step_by(2).map(|c| c.width).collect()
300 }
301
302 fn get_row_bounds(
303 &self,
304 selected: Option<usize>,
305 offset: usize,
306 max_height: u16,
307 ) -> (usize, usize) {
308 let mut start = offset;
309 let mut end = offset;
310 let mut height = 0;
311 for item in self.rows.iter().skip(offset) {
312 if height + item.height > max_height {
313 break;
314 }
315 height += item.total_height();
316 end += 1;
317 }
318
319 let selected = selected.unwrap_or(0).min(self.rows.len() - 1);
320 while selected >= end {
321 height = height.saturating_add(self.rows[end].total_height());
322 end += 1;
323 while height > max_height {
324 height = height.saturating_sub(self.rows[start].total_height());
325 start += 1;
326 }
327 }
328 while selected < start {
329 start -= 1;
330 height = height.saturating_add(self.rows[start].total_height());
331 while height > max_height {
332 end -= 1;
333 height = height.saturating_sub(self.rows[end].total_height());
334 }
335 }
336 (start, end)
337 }
338 }
339
340 /// Track [Table] scroll offset and selection
341 #[derive(Debug, Default, Clone)]
342 pub struct TableState {
343 pub offset: usize,
344 pub selected: Option<usize>,
345 }
346
347 impl TableState {
348 pub fn selected(&self) -> Option<usize> {
349 self.selected
350 }
351
352 pub fn select(&mut self, index: Option<usize>) {
353 self.selected = index;
354 if index.is_none() {
355 self.offset = 0;
356 }
357 }
358 }
359
360 // impl<'a> StatefulWidget for Table<'a> {
361 impl Table<'_> {
362 // type State = TableState;
363
364 pub fn render_table(
365 mut self,
366 area: Rect,
367 buf: &mut Buffer,
368 state: &mut TableState,
369 truncate: bool,
370 ) {
371 if area.area() == 0 {
372 return;
373 }
374 buf.set_style(area, self.style);
375 let table_area = match self.block.take() {
376 Some(b) => {
377 let inner_area = b.inner(area);
378 b.render(area, buf);
379 inner_area
380 }
381 None => area,
382 };
383
384 let has_selection = state.selected.is_some();
385 let columns_widths = self.get_columns_widths(table_area.width, has_selection);
386 let highlight_symbol = self.highlight_symbol.unwrap_or("");
387 let blank_symbol = " ".repeat(highlight_symbol.width());
388 let mut current_height = 0;
389 let mut rows_height = table_area.height;
390
391 // Draw header
392 if let Some(ref header) = self.header {
393 let max_header_height = table_area.height.min(header.total_height());
394 buf.set_style(
395 Rect {
396 x: table_area.left(),
397 y: table_area.top(),
398 width: table_area.width,
399 height: table_area.height.min(header.height),
400 },
401 header.style,
402 );
403 let mut col = table_area.left();
404 if has_selection {
405 col += (highlight_symbol.width() as u16).min(table_area.width);
406 }
407 for (width, cell) in columns_widths.iter().zip(header.cells.iter()) {
408 render_cell(
409 buf,
410 cell,
411 Rect {
412 x: col,
413 y: table_area.top(),
414 width: *width,
415 height: max_header_height,
416 },
417 truncate,
418 );
419 col += *width + self.column_spacing;
420 }
421 current_height += max_header_height;
422 rows_height = rows_height.saturating_sub(max_header_height);
423 }
424
425 // Draw rows
426 if self.rows.is_empty() {
427 return;
428 }
429 let (start, end) = self.get_row_bounds(state.selected, state.offset, rows_height);
430 state.offset = start;
431 for (i, table_row) in self
432 .rows
433 .iter_mut()
434 .enumerate()
435 .skip(state.offset)
436 .take(end - start)
437 {
438 let (row, col) = (table_area.top() + current_height, table_area.left());
439 current_height += table_row.total_height();
440 let table_row_area = Rect {
441 x: col,
442 y: row,
443 width: table_area.width,
444 height: table_row.height,
445 };
446 buf.set_style(table_row_area, table_row.style);
447 let is_selected = state.selected.map(|s| s == i).unwrap_or(false);
448 let table_row_start_col = if has_selection {
449 let symbol = if is_selected {
450 highlight_symbol
451 } else {
452 &blank_symbol
453 };
454 let (col, _) =
455 buf.set_stringn(col, row, symbol, table_area.width as usize, table_row.style);
456 col
457 } else {
458 col
459 };
460 if is_selected {
461 buf.set_style(table_row_area, self.highlight_style);
462 for cell in &mut table_row.cells {
463 cell.set_style(self.highlight_style);
464 }
465 }
466 let mut col = table_row_start_col;
467 for (width, cell) in columns_widths.iter().zip(table_row.cells.iter()) {
468 render_cell(
469 buf,
470 cell,
471 Rect {
472 x: col,
473 y: row,
474 width: *width,
475 height: table_row.height,
476 },
477 truncate,
478 );
479 col += *width + self.column_spacing;
480 }
481 }
482 }
483 }
484
485 fn render_cell(buf: &mut Buffer, cell: &Cell, area: Rect, truncate: bool) {
486 buf.set_style(area, cell.style);
487 for (i, spans) in cell.content.lines.iter().enumerate() {
488 if i as u16 >= area.height {
489 break;
490 }
491 if truncate {
492 buf.set_spans_truncated(area.x, area.y + i as u16, spans, area.width);
493 } else {
494 buf.set_spans(area.x, area.y + i as u16, spans, area.width);
495 }
496 }
497 }
498
499 impl Widget for Table<'_> {
500 fn render(self, area: Rect, buf: &mut Buffer) {
501 let mut state = TableState::default();
502 Table::render_table(self, area, buf, &mut state, false);
503 }
504 }
505
506 #[cfg(test)]
507 mod tests {
508 use super::*;
509
510 #[test]
511 #[should_panic]
512 fn table_invalid_percentages() {
513 Table::new(vec![]).widths(&[Constraint::Percentage(110)]);
514 }
515 }