5 widgets::{Block, Widget},
8 strength::{MEDIUM, REQUIRED, WEAK},
12use helix_core::unicode::width::UnicodeWidthStr;
13use helix_view::graphics::{Rect, Style};
14use std::collections::HashMap;
16/// A [`Cell`] contains the [`Text`] to be displayed in a [`Row`] of a [`Table`].
18/// It can be created from anything that can be converted to a [`Text`].
20/// # use helix_tui::widgets::Cell;
21/// # use helix_tui::text::{Span, Spans, Text};
22/// # use helix_view::graphics::{Style, Modifier};
23/// Cell::from("simple string");
25/// Cell::from(Span::from("span"));
27/// Cell::from(Spans::from(vec![
28/// Span::raw("a vec of "),
29/// Span::styled("spans", Style::default().add_modifier(Modifier::BOLD))
32/// Cell::from(Text::from("a text"));
35/// You can apply a [`Style`] on the entire [`Cell`] using [`Cell::style`] or rely on the styling
36/// capabilities of [`Text`].
37#[derive(Debug, Clone, PartialEq, Default)]
39 pub content: Text<'a>,
44 /// Set the `Style` of this cell.
45 pub fn style(mut self, style: Style) -> Self {
51impl<'a, T> From<T> for Cell<'a>
55 fn from(content: T) -> Cell<'a> {
57 content: content.into(),
58 style: Style::default(),
63/// Holds data to be displayed in a [`Table`] widget.
65/// A [`Row`] is a collection of cells. It can be created from simple strings:
67/// # use helix_tui::widgets::Row;
68/// Row::new(vec!["Cell1", "Cell2", "Cell3"]);
71/// But if you need a bit more control over individual cells, you can explicity create [`Cell`]s:
73/// # use helix_tui::widgets::{Row, Cell};
74/// # use helix_view::graphics::{Style, Color};
76/// Cell::from("Cell1"),
77/// Cell::from("Cell2").style(Style::default().fg(Color::Yellow)),
81/// By default, a row has a height of 1 but you can change this using [`Row::height`].
82#[derive(Debug, Clone, PartialEq, Default)]
84 pub cells: Vec<Cell<'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
95 T::Item: Into<Cell<'a>>,
99 cells: cells.into_iter().map(|c| c.into()).collect(),
100 style: Style::default(),
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;
112 /// Set the [`Style`] of the entire row. This [`Style`] can be overriden by the [`Style`] of a
113 /// any individual [`Cell`] or event by their [`Text`] content.
114 pub fn style(mut self, style: Style) -> Self {
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;
125 /// Returns the total height of the row.
126 fn total_height(&self) -> u16 {
127 self.height.saturating_add(self.bottom_margin)
131/// A widget to display data in formatted columns.
133/// It is a collection of [`Row`]s, themselves composed of [`Cell`]s:
135/// # use helix_tui::widgets::{Block, Borders, Table, Row, Cell};
136/// # use helix_tui::layout::Constraint;
137/// # use helix_view::graphics::{Style, Color, Modifier};
138/// # use helix_tui::text::{Text, Spans, Span};
140/// // Row can be created from simple strings.
141/// Row::new(vec!["Row11", "Row12", "Row13"]),
142/// // You can style the entire row.
143/// Row::new(vec!["Row21", "Row22", "Row23"]).style(Style::default().fg(Color::Blue)),
144/// // If you need more control over the styling you may need to create Cells directly
146/// Cell::from("Row31"),
147/// Cell::from("Row32").style(Style::default().fg(Color::Yellow)),
148/// Cell::from(Spans::from(vec![
150/// Span::styled("33", Style::default().fg(Color::Green))
153/// // If a Row need to display some content over multiple lines, you just have to change
156/// Cell::from("Row\n41"),
157/// Cell::from("Row\n42"),
158/// Cell::from("Row\n43"),
161/// // You can set the style of the entire Table.
162/// .style(Style::default().fg(Color::White))
163/// // It has an optional header, which is simply a Row always visible at the top.
165/// Row::new(vec!["Col1", "Col2", "Col3"])
166/// .style(Style::default().fg(Color::Yellow))
167/// // If you want some space between the header and the rest of the rows, you can always
168/// // specify some margin at the bottom.
171/// // As any other widget, a Table can be wrapped in a Block.
172/// .block(Block::default().title("Table"))
173/// // Columns widths are constrained in the same way as Layout...
174/// .widths(&[Constraint::Length(5), Constraint::Length(5), Constraint::Length(10)])
175/// // ...and they can be separated by a fixed spacing.
176/// .column_spacing(1)
177/// // If you wish to highlight a row in any specific way when it is selected...
178/// .highlight_style(Style::default().add_modifier(Modifier::BOLD))
179/// // ...and potentially show a symbol in front of the selection.
180/// .highlight_symbol(">>");
182#[derive(Debug, Clone, PartialEq)]
183pub struct Table<'a> {
184 /// A block to wrap the widget in
185 block: Option<Block<'a>>,
186 /// Base style for the widget
188 /// Width constraints for each column
189 widths: &'a [Constraint],
190 /// Space between each column
192 /// Style used to render the selected row
193 highlight_style: Style,
194 /// Symbol in front of the selected rom
195 highlight_symbol: Option<&'a str>,
197 header: Option<Row<'a>>,
198 /// Data to display in each row
203 pub fn new<T>(rows: T) -> Self
205 T: IntoIterator<Item = Row<'a>>,
209 style: Style::default(),
212 highlight_style: Style::default(),
213 highlight_symbol: None,
215 rows: rows.into_iter().collect(),
219 pub fn block(mut self, block: Block<'a>) -> Self {
220 self.block = Some(block);
224 pub fn header(mut self, header: Row<'a>) -> Self {
225 self.header = Some(header);
229 pub fn widths(mut self, widths: &'a [Constraint]) -> Self {
230 let between_0_and_100 = |&w| match w {
231 Constraint::Percentage(p) => p <= 100,
235 widths.iter().all(between_0_and_100),
236 "Percentages should be between 0 and 100 inclusively."
238 self.widths = widths;
242 pub fn style(mut self, style: Style) -> Self {
247 pub fn highlight_symbol(mut self, highlight_symbol: &'a str) -> Self {
248 self.highlight_symbol = Some(highlight_symbol);
252 pub fn highlight_style(mut self, highlight_style: Style) -> Self {
253 self.highlight_style = highlight_style;
257 pub fn column_spacing(mut self, spacing: u16) -> Self {
258 self.column_spacing = spacing;
262 fn get_columns_widths(&self, max_width: u16, has_selection: bool) -> Vec<u16> {
263 let mut solver = Solver::new();
264 let mut var_indices = HashMap::new();
265 let mut ccs = Vec::new();
266 let mut variables = Vec::new();
267 for i in 0..self.widths.len() {
268 let var = cassowary::Variable::new();
270 var_indices.insert(var, i);
272 let spacing_width = (variables.len() as u16).saturating_sub(1) * self.column_spacing;
273 let mut available_width = max_width.saturating_sub(spacing_width);
275 let highlight_symbol_width =
276 self.highlight_symbol.map(|s| s.width() as u16).unwrap_or(0);
277 available_width = available_width.saturating_sub(highlight_symbol_width);
279 for (i, constraint) in self.widths.iter().enumerate() {
280 ccs.push(variables[i] | GE(WEAK) | 0.);
281 ccs.push(match *constraint {
282 Constraint::Length(v) => variables[i] | EQ(MEDIUM) | f64::from(v),
283 Constraint::Percentage(v) => {
284 variables[i] | EQ(WEAK) | (f64::from(v * available_width) / 100.0)
286 Constraint::Ratio(n, d) => {
289 | (f64::from(available_width) * f64::from(n) / f64::from(d))
291 Constraint::Min(v) => variables[i] | GE(WEAK) | f64::from(v),
292 Constraint::Max(v) => variables[i] | LE(WEAK) | f64::from(v),
299 .fold(Expression::from_constant(0.), |acc, v| acc + *v)
301 | f64::from(available_width),
304 solver.add_constraints(&ccs).unwrap();
305 let mut widths = vec![0; variables.len()];
306 for &(var, value) in solver.fetch_changes() {
307 let index = var_indices[&var];
308 let value = if value.is_sign_negative() {
313 widths[index] = value;
315 // Cassowary could still return columns widths greater than the max width when there are
316 // fixed length constraints that cannot be satisfied. Therefore, we clamp the widths from
318 let mut available_width = max_width;
319 for w in &mut widths {
320 *w = available_width.min(*w);
321 available_width = available_width
323 .saturating_sub(self.column_spacing);
330 selected: Option<usize>,
333 ) -> (usize, usize) {
334 let mut start = offset;
335 let mut end = offset;
337 for item in self.rows.iter().skip(offset) {
338 if height + item.height > max_height {
341 height += item.total_height();
345 let selected = selected.unwrap_or(0).min(self.rows.len() - 1);
346 while selected >= end {
347 height = height.saturating_add(self.rows[end].total_height());
349 while height > max_height {
350 height = height.saturating_sub(self.rows[start].total_height());
354 while selected < start {
356 height = height.saturating_add(self.rows[start].total_height());
357 while height > max_height {
359 height = height.saturating_sub(self.rows[end].total_height());
366#[derive(Debug, Clone)]
367pub struct TableState {
369 pub selected: Option<usize>,
372impl Default for TableState {
373 fn default() -> TableState {
382 pub fn selected(&self) -> Option<usize> {
386 pub fn select(&mut self, index: Option<usize>) {
387 self.selected = index;
394// impl<'a> StatefulWidget for Table<'a> {
396 // type State = TableState;
398 pub fn render_table(mut self, area: Rect, buf: &mut Buffer, state: &mut TableState) {
399 if area.area() == 0 {
402 buf.set_style(area, self.style);
403 let table_area = match self.block.take() {
405 let inner_area = b.inner(area);
412 let has_selection = state.selected.is_some();
413 let columns_widths = self.get_columns_widths(table_area.width, has_selection);
414 let highlight_symbol = self.highlight_symbol.unwrap_or("");
415 let blank_symbol = " ".repeat(highlight_symbol.width());
416 let mut current_height = 0;
417 let mut rows_height = table_area.height;
420 if let Some(ref header) = self.header {
421 let max_header_height = table_area.height.min(header.total_height());
424 x: table_area.left(),
426 width: table_area.width,
427 height: table_area.height.min(header.height),
431 let mut col = table_area.left();
433 col += (highlight_symbol.width() as u16).min(table_area.width);
435 for (width, cell) in columns_widths.iter().zip(header.cells.iter()) {
443 height: max_header_height,
446 col += *width + self.column_spacing;
448 current_height += max_header_height;
449 rows_height = rows_height.saturating_sub(max_header_height);
453 if self.rows.is_empty() {
456 let (start, end) = self.get_row_bounds(state.selected, state.offset, rows_height);
457 state.offset = start;
458 for (i, table_row) in self
465 let (row, col) = (table_area.top() + current_height, table_area.left());
466 current_height += table_row.total_height();
467 let table_row_area = Rect {
470 width: table_area.width,
471 height: table_row.height,
473 buf.set_style(table_row_area, table_row.style);
474 let is_selected = state.selected.map(|s| s == i).unwrap_or(false);
475 let table_row_start_col = if has_selection {
476 let symbol = if is_selected {
482 buf.set_stringn(col, row, symbol, table_area.width as usize, table_row.style);
487 let mut col = table_row_start_col;
488 for (width, cell) in columns_widths.iter().zip(table_row.cells.iter()) {
496 height: table_row.height,
499 col += *width + self.column_spacing;
502 buf.set_style(table_row_area, self.highlight_style);
508fn render_cell(buf: &mut Buffer, cell: &Cell, area: Rect) {
509 buf.set_style(area, cell.style);
510 for (i, spans) in cell.content.lines.iter().enumerate() {
511 if i as u16 >= area.height {
514 buf.set_spans(area.x, area.y + i as u16, spans, area.width);
518impl<'a> Widget for Table<'a> {
519 fn render(self, area: Rect, buf: &mut Buffer) {
520 let mut state = TableState::default();
521 Table::render_table(self, area, buf, &mut state);
531 fn table_invalid_percentages() {
532 Table::new(vec![]).widths(&[Constraint::Percentage(110)]);
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list