1use alloc::sync::Arc;
5use alloc::vec;
6use alloc::vec::Vec;
7use core::hash::Hasher;
8use core::panic::RefUnwindSafe;
9use core::{fmt, ptr};
10
11use itertools::Itertools;
12use ratatui_core::buffer::Buffer;
13use ratatui_core::layout::{Constraint, Flex, Layout, Rect};
14use ratatui_core::style::{Style, Styled};
15use ratatui_core::text::Text;
16use ratatui_core::widgets::{StatefulWidget, Widget};
17use ratatui_widgets::block::{Block, BlockExt};
18
19pub use self::cell::Cell;
20pub use self::highlight_placement::HighlightPlacement;
21pub use self::highlight_spacing::HighlightSpacing;
22pub use self::row::Row;
23pub use self::state::TableState;
24
25mod cell;
26mod highlight_placement;
27mod highlight_spacing;
28mod row;
29mod state;
30
31enum LazyRowHeights<'a> {
38 Uniform(u16),
40 PerRow(Arc<dyn Fn(usize) -> u16 + Send + Sync + RefUnwindSafe + 'a>),
42}
43
44impl LazyRowHeights<'_> {
45 fn height_of(&self, index: usize) -> u16 {
47 match self {
48 Self::Uniform(height) => *height,
49 Self::PerRow(heights) => heights(index),
50 }
51 }
52}
53
54impl fmt::Debug for LazyRowHeights<'_> {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 match self {
57 Self::Uniform(height) => f.debug_tuple("Uniform").field(height).finish(),
58 Self::PerRow(_) => f.debug_tuple("PerRow").finish(),
59 }
60 }
61}
62
63impl Clone for LazyRowHeights<'_> {
64 fn clone(&self) -> Self {
65 match self {
66 Self::Uniform(height) => Self::Uniform(*height),
67 Self::PerRow(heights) => Self::PerRow(Arc::clone(heights)),
68 }
69 }
70}
71
72impl PartialEq for LazyRowHeights<'_> {
73 fn eq(&self, other: &Self) -> bool {
74 match (self, other) {
75 (Self::Uniform(left), Self::Uniform(right)) => left == right,
76 (Self::PerRow(left), Self::PerRow(right)) => Arc::ptr_eq(left, right),
77 _ => false,
78 }
79 }
80}
81
82impl Eq for LazyRowHeights<'_> {}
83
84impl core::hash::Hash for LazyRowHeights<'_> {
85 fn hash<H: Hasher>(&self, state: &mut H) {
86 match self {
87 Self::Uniform(height) => {
88 "uniform".hash(state);
89 height.hash(state);
90 }
91 Self::PerRow(heights) => {
92 "per_row".hash(state);
93 ptr::hash(Arc::as_ptr(heights), state);
94 }
95 }
96 }
97}
98
99struct LazyRowProvider<'a> {
101 count: usize,
102 heights: LazyRowHeights<'a>,
103 factory: Arc<dyn Fn(usize) -> Row<'a> + Send + Sync + RefUnwindSafe + 'a>,
104}
105
106impl LazyRowProvider<'_> {
107 fn height_of(&self, index: usize) -> u16 {
109 self.heights.height_of(index)
110 }
111
112 fn visible_rows(&self, state: &TableState, area: Rect) -> (usize, usize) {
124 if self.count == 0 {
125 return (0, 0);
126 }
127 let last_row = self.count - 1;
128 let selected = state.selected.map(|selected| selected.min(last_row));
129
130 let mut start = state.offset.min(last_row);
131 if let Some(selected) = selected {
132 start = start.min(selected);
133 }
134
135 if area.height == 0 {
138 return (start, start);
139 }
140
141 let mut end = start;
146 let mut height = 0_u16;
147 while end < self.count {
148 let Some(filled) = height.checked_add(self.height_of(end)) else {
149 break;
150 };
151 if filled > area.height {
152 break;
153 }
154 height = filled;
155 end += 1;
156 if window_is_full(start, end, area) {
157 break;
158 }
159 }
160
161 if let Some(selected) = selected
164 && selected >= end
165 {
166 start = selected;
169 end = selected + 1;
170 height = self.height_of(selected);
171 while start > 0 && !window_is_full(start, end, area) {
172 let Some(filled) = height.checked_add(self.height_of(start - 1)) else {
173 break;
174 };
175 if filled > area.height {
176 break;
177 }
178 height = filled;
179 start -= 1;
180 }
181 }
182
183 if height < area.height && end < self.count && !window_is_full(start, end, area) {
185 end += 1;
186 }
187
188 (start, end)
189 }
190}
191
192const fn window_is_full(start: usize, end: usize, area: Rect) -> bool {
198 end - start > area.height as usize
199}
200
201impl fmt::Debug for LazyRowProvider<'_> {
202 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
203 f.debug_struct("LazyRowProvider")
204 .field("count", &self.count)
205 .field("heights", &self.heights)
206 .finish_non_exhaustive()
207 }
208}
209
210impl Clone for LazyRowProvider<'_> {
211 fn clone(&self) -> Self {
212 Self {
213 count: self.count,
214 heights: self.heights.clone(),
215 factory: Arc::clone(&self.factory),
216 }
217 }
218}
219
220impl PartialEq for LazyRowProvider<'_> {
221 fn eq(&self, other: &Self) -> bool {
222 self.count == other.count
223 && self.heights == other.heights
224 && Arc::ptr_eq(&self.factory, &other.factory)
225 }
226}
227
228impl Eq for LazyRowProvider<'_> {}
229
230impl core::hash::Hash for LazyRowProvider<'_> {
231 fn hash<H: Hasher>(&self, state: &mut H) {
232 self.count.hash(state);
233 self.heights.hash(state);
234 ptr::hash(Arc::as_ptr(&self.factory), state);
235 }
236}
237
238#[derive(Debug, Clone, Eq, PartialEq, Hash)]
464pub struct Table<'a> {
465 rows: Vec<Row<'a>>,
467
468 header: Option<Row<'a>>,
470
471 footer: Option<Row<'a>>,
473
474 widths: Vec<Constraint>,
476
477 column_spacing: u16,
479
480 block: Option<Block<'a>>,
482
483 style: Style,
485
486 row_highlight_style: Style,
488
489 column_highlight_style: Style,
491
492 cell_highlight_style: Style,
494
495 highlight_symbol: Text<'a>,
497
498 highlight_spacing: HighlightSpacing,
500
501 highlight_placement: HighlightPlacement,
503
504 flex: Flex,
506
507 lazy: Option<LazyRowProvider<'a>>,
509}
510
511impl Default for Table<'_> {
512 fn default() -> Self {
513 Self {
514 rows: Vec::new(),
515 header: None,
516 footer: None,
517 widths: Vec::new(),
518 column_spacing: 1,
519 block: None,
520 style: Style::new(),
521 row_highlight_style: Style::new(),
522 column_highlight_style: Style::new(),
523 cell_highlight_style: Style::new(),
524 highlight_symbol: Text::default(),
525 highlight_spacing: HighlightSpacing::default(),
526 highlight_placement: HighlightPlacement::default(),
527 flex: Flex::Start,
528 lazy: None,
529 }
530 }
531}
532
533impl<'a> Table<'a> {
534 pub fn new<R, C>(rows: R, widths: C) -> Self
558 where
559 R: IntoIterator,
560 R::Item: Into<Row<'a>>,
561 C: IntoIterator,
562 C::Item: Into<Constraint>,
563 {
564 let widths = widths.into_iter().map(Into::into).collect_vec();
565 ensure_percentages_less_than_100(&widths);
566
567 let rows = rows.into_iter().map(Into::into).collect();
568 Self {
569 rows,
570 widths,
571 ..Default::default()
572 }
573 }
574
575 #[must_use = "method moves the value of self and returns the modified value"]
601 pub fn rows<T>(mut self, rows: T) -> Self
602 where
603 T: IntoIterator<Item = Row<'a>>,
604 {
605 self.rows = rows.into_iter().collect();
606 self.lazy = None;
607 self
608 }
609
610 #[must_use = "method moves the value of self and returns the modified value"]
628 pub fn header(mut self, header: Row<'a>) -> Self {
629 self.header = Some(header);
630 self
631 }
632
633 #[must_use = "method moves the value of self and returns the modified value"]
651 pub fn footer(mut self, footer: Row<'a>) -> Self {
652 self.footer = Some(footer);
653 self
654 }
655
656 #[must_use = "method moves the value of self and returns the modified value"]
681 pub fn widths<I>(mut self, widths: I) -> Self
682 where
683 I: IntoIterator,
684 I::Item: Into<Constraint>,
685 {
686 let widths = widths.into_iter().map(Into::into).collect_vec();
687 ensure_percentages_less_than_100(&widths);
688 self.widths = widths;
689 self
690 }
691
692 #[must_use = "method moves the value of self and returns the modified value"]
707 pub const fn column_spacing(mut self, spacing: u16) -> Self {
708 self.column_spacing = spacing;
709 self
710 }
711
712 #[must_use = "method moves the value of self and returns the modified value"]
732 pub fn block(mut self, block: Block<'a>) -> Self {
733 self.block = Some(block);
734 self
735 }
736
737 #[must_use = "method moves the value of self and returns the modified value"]
775 pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
776 self.style = style.into();
777 self
778 }
779
780 #[must_use = "method moves the value of self and returns the modified value"]
804 #[deprecated(note = "use `row_highlight_style()` instead")]
805 pub fn highlight_style<S: Into<Style>>(self, highlight_style: S) -> Self {
806 self.row_highlight_style(highlight_style)
807 }
808
809 #[must_use = "method moves the value of self and returns the modified value"]
829 pub fn row_highlight_style<S: Into<Style>>(mut self, highlight_style: S) -> Self {
830 self.row_highlight_style = highlight_style.into();
831 self
832 }
833
834 #[must_use = "method moves the value of self and returns the modified value"]
854 pub fn column_highlight_style<S: Into<Style>>(mut self, highlight_style: S) -> Self {
855 self.column_highlight_style = highlight_style.into();
856 self
857 }
858
859 #[must_use = "method moves the value of self and returns the modified value"]
879 pub fn cell_highlight_style<S: Into<Style>>(mut self, highlight_style: S) -> Self {
880 self.cell_highlight_style = highlight_style.into();
881 self
882 }
883
884 #[must_use = "method moves the value of self and returns the modified value"]
899 pub fn highlight_symbol<T: Into<Text<'a>>>(mut self, highlight_symbol: T) -> Self {
900 self.highlight_symbol = highlight_symbol.into();
901 self
902 }
903
904 #[must_use = "method moves the value of self and returns the modified value"]
933 pub const fn highlight_spacing(mut self, value: HighlightSpacing) -> Self {
934 self.highlight_spacing = value;
935 self
936 }
937
938 #[must_use = "method moves the value of self and returns the modified value"]
960 pub fn highlight_placement(mut self, value: HighlightPlacement) -> Self {
961 self.highlight_placement = value;
962 self
963 }
964
965 #[must_use = "method moves the value of self and returns the modified value"]
989 pub const fn flex(mut self, flex: Flex) -> Self {
990 self.flex = flex;
991 self
992 }
993
994 pub fn lazy_rows<C, F>(row_count: usize, widths: C, row: F) -> Self
1027 where
1028 C: IntoIterator,
1029 C::Item: Into<Constraint>,
1030 F: Fn(usize) -> Row<'a> + Send + Sync + RefUnwindSafe + 'a,
1031 {
1032 let widths: Vec<Constraint> = widths.into_iter().map(Into::into).collect();
1033 ensure_percentages_less_than_100(&widths);
1034 Self {
1035 lazy: Some(LazyRowProvider {
1036 count: row_count,
1037 heights: LazyRowHeights::Uniform(1),
1038 factory: Arc::new(row),
1039 }),
1040 widths,
1041 ..Default::default()
1042 }
1043 }
1044
1045 #[must_use = "method moves the value of self and returns the modified value"]
1068 pub fn lazy_row_height(mut self, height: u16) -> Self {
1069 if let Some(ref mut lazy) = self.lazy {
1070 lazy.heights = LazyRowHeights::Uniform(height);
1071 }
1072 self
1073 }
1074
1075 #[must_use = "method moves the value of self and returns the modified value"]
1106 pub fn lazy_row_height_with<H>(mut self, height: H) -> Self
1107 where
1108 H: Fn(usize) -> u16 + Send + Sync + RefUnwindSafe + 'a,
1109 {
1110 if let Some(ref mut lazy) = self.lazy {
1111 lazy.heights = LazyRowHeights::PerRow(Arc::new(height));
1112 }
1113 self
1114 }
1115}
1116
1117impl Widget for Table<'_> {
1118 fn render(self, area: Rect, buf: &mut Buffer) {
1119 Widget::render(&self, area, buf);
1120 }
1121}
1122
1123impl Widget for &Table<'_> {
1124 fn render(self, area: Rect, buf: &mut Buffer) {
1125 let mut state = TableState::default();
1126 StatefulWidget::render(self, area, buf, &mut state);
1127 }
1128}
1129
1130impl StatefulWidget for Table<'_> {
1131 type State = TableState;
1132
1133 fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
1134 StatefulWidget::render(&self, area, buf, state);
1135 }
1136}
1137
1138impl StatefulWidget for &Table<'_> {
1139 type State = TableState;
1140
1141 fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
1142 buf.set_style(area, self.style);
1143 self.block.as_ref().render(area, buf);
1144 let table_area = self.block.inner_if_some(area);
1145 if table_area.is_empty() {
1146 return;
1147 }
1148
1149 let row_count = self.row_count();
1150 if state.selected.is_some_and(|s| s >= row_count) {
1151 state.select(Some(row_count.saturating_sub(1)));
1152 }
1153
1154 if row_count == 0 {
1155 state.select(None);
1156 }
1157
1158 let column_count = self.column_count();
1159 if state.selected_column.is_some_and(|s| s >= column_count) {
1160 state.select_column(Some(column_count.saturating_sub(1)));
1161 }
1162 if column_count == 0 {
1163 state.select_column(None);
1164 }
1165
1166 let selection_width = self.selection_width(state);
1167 let symbol_columns = self
1168 .highlight_placement
1169 .column_mask(state.selected_column(), column_count);
1170 let column_widths = self.get_column_widths(
1171 table_area.width,
1172 selection_width,
1173 column_count,
1174 &symbol_columns,
1175 );
1176 let (header_area, rows_area, footer_area) = self.layout(table_area);
1177
1178 self.render_header(header_area, buf, &column_widths);
1179
1180 self.render_rows(
1181 rows_area,
1182 buf,
1183 selection_width,
1184 state,
1185 &column_widths,
1186 &symbol_columns,
1187 );
1188
1189 self.render_footer(footer_area, buf, &column_widths);
1190 }
1191}
1192
1193impl Table<'_> {
1195 fn layout(&self, area: Rect) -> (Rect, Rect, Rect) {
1197 let header_top_margin = self.header.as_ref().map_or(0, |h| h.top_margin);
1198 let header_height = self.header.as_ref().map_or(0, |h| h.height);
1199 let header_bottom_margin = self.header.as_ref().map_or(0, |h| h.bottom_margin);
1200 let footer_top_margin = self.footer.as_ref().map_or(0, |h| h.top_margin);
1201 let footer_height = self.footer.as_ref().map_or(0, |f| f.height);
1202 let footer_bottom_margin = self.footer.as_ref().map_or(0, |h| h.bottom_margin);
1203 let layout = Layout::vertical([
1204 Constraint::Length(header_top_margin),
1205 Constraint::Length(header_height),
1206 Constraint::Length(header_bottom_margin),
1207 Constraint::Min(0),
1208 Constraint::Length(footer_top_margin),
1209 Constraint::Length(footer_height),
1210 Constraint::Length(footer_bottom_margin),
1211 ])
1212 .split(area);
1213 let (header_area, rows_area, footer_area) = (layout[1], layout[3], layout[5]);
1214 (header_area, rows_area, footer_area)
1215 }
1216
1217 fn render_header(&self, area: Rect, buf: &mut Buffer, column_widths: &[Rect]) {
1222 if let Some(ref header) = self.header {
1223 buf.set_style(area, header.style);
1224 for (cell_area, cell) in column_widths.iter().zip(header.cells.iter()) {
1225 let new_x = area.x + cell_area.x;
1226 let area_to_render = Rect::new(new_x, area.y, cell_area.width, area.height);
1227 cell.render(area_to_render, buf);
1228 }
1229 }
1230 }
1231
1232 fn render_footer(&self, area: Rect, buf: &mut Buffer, column_widths: &[Rect]) {
1237 if let Some(ref footer) = self.footer {
1238 buf.set_style(area, footer.style);
1239 for (cell_area, cell) in column_widths.iter().zip(footer.cells.iter()) {
1240 let new_x = area.x + cell_area.x;
1241 let area_to_render = Rect::new(new_x, area.y, cell_area.width, area.height);
1242 cell.render(area_to_render, buf);
1243 }
1244 }
1245 }
1246
1247 fn render_rows(
1252 &self,
1253 area: Rect,
1254 buf: &mut Buffer,
1255 selection_width: u16,
1256 state: &mut TableState,
1257 columns_widths: &[Rect],
1258 symbol_columns: &[bool],
1259 ) {
1260 if let Some(ref provider) = self.lazy {
1261 self.render_lazy_rows(
1262 area,
1263 buf,
1264 selection_width,
1265 state,
1266 columns_widths,
1267 symbol_columns,
1268 provider,
1269 );
1270 return;
1271 }
1272
1273 if self.rows.is_empty() {
1274 return;
1275 }
1276
1277 let (start_index, end_index) = self.visible_rows(state, area);
1278 state.offset = start_index;
1279
1280 let mut y_offset = 0;
1281
1282 let mut selected_row_area = None;
1283 for (i, row) in self
1284 .rows
1285 .iter()
1286 .enumerate()
1287 .skip(start_index)
1288 .take(end_index - start_index)
1289 {
1290 let y = area.y + y_offset + row.top_margin;
1291 let height = (y + row.height).min(area.bottom()).saturating_sub(y);
1292 let row_area = Rect { y, height, ..area };
1293 buf.set_style(row_area, row.style);
1294
1295 let is_selected = state.selected() == Some(i);
1296 self.render_highlight_symbol(
1297 buf,
1298 row_area,
1299 row,
1300 i,
1301 start_index,
1302 state,
1303 columns_widths,
1304 symbol_columns,
1305 selection_width,
1306 );
1307 self.render_row_cells(buf, columns_widths.iter().collect(), &row.cells, row_area);
1308 if is_selected {
1309 selected_row_area = Some(row_area);
1310 }
1311 y_offset += row.height_with_margin();
1312 }
1313
1314 self.apply_highlight_styles(buf, area, selected_row_area, state, columns_widths);
1315 }
1316
1317 #[expect(clippy::too_many_arguments)]
1319 fn render_lazy_rows(
1320 &self,
1321 area: Rect,
1322 buf: &mut Buffer,
1323 selection_width: u16,
1324 state: &mut TableState,
1325 columns_widths: &[Rect],
1326 symbol_columns: &[bool],
1327 provider: &LazyRowProvider,
1328 ) {
1329 if provider.count == 0 {
1330 return;
1331 }
1332
1333 let (start_index, end_index) = provider.visible_rows(state, area);
1334 state.offset = start_index;
1335
1336 let mut y = area.y;
1337 let mut selected_row_area = None;
1338
1339 for index in start_index..end_index {
1340 let row = (provider.factory)(index);
1341 let row_height = provider.height_of(index);
1344 let height = y
1345 .saturating_add(row_height)
1346 .min(area.bottom())
1347 .saturating_sub(y);
1348 let row_area = Rect { y, height, ..area };
1349 buf.set_style(row_area, row.style);
1350
1351 let is_selected = state.selected() == Some(index);
1352 self.render_highlight_symbol(
1353 buf,
1354 row_area,
1355 &row,
1356 index,
1357 start_index,
1358 state,
1359 columns_widths,
1360 symbol_columns,
1361 selection_width,
1362 );
1363 self.render_row_cells(buf, columns_widths.iter().collect(), &row.cells, row_area);
1364 if is_selected {
1365 selected_row_area = Some(row_area);
1366 }
1367 y = y.saturating_add(row_height);
1368 }
1369
1370 self.apply_highlight_styles(buf, area, selected_row_area, state, columns_widths);
1371 }
1372
1373 fn apply_highlight_styles(
1375 &self,
1376 buf: &mut Buffer,
1377 area: Rect,
1378 selected_row_area: Option<Rect>,
1379 state: &TableState,
1380 columns_widths: &[Rect],
1381 ) {
1382 let selected_column_area = state.selected_column().and_then(|s| {
1383 columns_widths.get(s).map(|cell_area| Rect {
1386 x: cell_area.x + area.x,
1387 width: cell_area.width,
1388 ..area
1389 })
1390 });
1391
1392 match (selected_row_area, selected_column_area) {
1393 (Some(row_area), Some(col_area)) => {
1394 buf.set_style(row_area, self.row_highlight_style);
1395 buf.set_style(col_area, self.column_highlight_style);
1396 let cell_area = row_area.intersection(col_area);
1397 buf.set_style(cell_area, self.cell_highlight_style);
1398 }
1399 (Some(row_area), None) => {
1400 buf.set_style(row_area, self.row_highlight_style);
1401 }
1402 (None, Some(col_area)) => {
1403 buf.set_style(col_area, self.column_highlight_style);
1404 }
1405 (None, None) => (),
1406 }
1407 }
1408
1409 fn render_row_cells(
1415 &self,
1416 buf: &mut Buffer,
1417 column_widths: Vec<&Rect>,
1418 cells: &Vec<Cell>,
1419 row_area: Rect,
1420 ) {
1421 let mut column_widths_iterator = column_widths.into_iter();
1422 for current_cell in cells {
1423 if let Some(cell_area) = Self::get_cell_area(
1424 &mut column_widths_iterator,
1425 current_cell.column_span,
1426 self.column_spacing,
1427 ) {
1428 let new_x = row_area.x + cell_area.x;
1429 let area_to_render = Rect::new(new_x, row_area.y, cell_area.width, row_area.height);
1430 current_cell.render(area_to_render, buf);
1431 }
1432 }
1433 }
1434
1435 #[expect(clippy::too_many_arguments)]
1448 fn render_highlight_symbol(
1449 &self,
1450 buf: &mut Buffer,
1451 row_area: Rect,
1452 row: &Row,
1453 row_index: usize,
1454 first_visible_row: usize,
1455 state: &TableState,
1456 columns_widths: &[Rect],
1457 symbol_columns: &[bool],
1458 selection_width: u16,
1459 ) {
1460 if selection_width == 0 {
1461 return;
1462 }
1463 if state.selected().is_none() && state.selected_column().is_none() {
1464 return;
1465 }
1466 if row_index != state.selected().unwrap_or(first_visible_row) {
1467 return;
1468 }
1469
1470 for (column_index, cell_area) in columns_widths.iter().enumerate() {
1471 if !symbol_columns.get(column_index).copied().unwrap_or(false) {
1472 continue;
1473 }
1474 let symbol_area = Rect {
1475 x: (row_area.x + cell_area.x).saturating_sub(selection_width),
1476 width: selection_width,
1477 ..row_area
1478 };
1479 buf.set_style(symbol_area, row.style);
1480 (&self.highlight_symbol).render(symbol_area, buf);
1481 }
1482 }
1483
1484 fn get_cell_area<'a, T>(
1498 column_widths_iterator: &mut T,
1499 cell_column_span: u16,
1500 column_spacing: u16,
1501 ) -> Option<Rect>
1502 where
1503 T: Iterator<Item = &'a Rect>,
1504 {
1505 if cell_column_span == 0 {
1506 return None;
1507 }
1508 let first = column_widths_iterator.next()?;
1509 let (n_columns_taken, all_columns_width) = column_widths_iterator
1510 .take((cell_column_span - 1).into())
1511 .map(|rect| (1, rect.width))
1512 .fold((1, first.width), |so_far, next_column| {
1513 (next_column.0 + so_far.0, next_column.1 + so_far.1)
1514 });
1515 let width = all_columns_width + (n_columns_taken - 1) * column_spacing;
1516 Some(Rect::new(first.x, first.y, width, 1))
1517 }
1518
1519 fn visible_rows(&self, state: &TableState, area: Rect) -> (usize, usize) {
1528 let last_row = self.rows.len().saturating_sub(1);
1529 let mut start = state.offset.min(last_row);
1530
1531 if let Some(selected) = state.selected {
1532 start = start.min(selected);
1533 }
1534
1535 let mut end = start;
1536 let mut height = 0;
1537
1538 for item in self.rows.iter().skip(start) {
1539 if height + item.height > area.height {
1540 break;
1541 }
1542 height += item.height_with_margin();
1543 end += 1;
1544 }
1545
1546 if let Some(selected) = state.selected {
1547 let selected = selected.min(last_row);
1548
1549 while selected >= end {
1551 height = height.saturating_add(self.rows[end].height_with_margin());
1552 end += 1;
1553 while height > area.height {
1554 height = height.saturating_sub(self.rows[start].height_with_margin());
1555 start += 1;
1556 }
1557 }
1558 }
1559
1560 if height < area.height && end < self.rows.len() {
1562 end += 1;
1563 }
1564
1565 (start, end)
1566 }
1567
1568 fn get_column_widths(
1573 &self,
1574 max_width: u16,
1575 selection_width: u16,
1576 col_count: usize,
1577 symbol_columns: &[bool],
1578 ) -> Vec<Rect> {
1579 let widths = if self.widths.is_empty() {
1580 vec![Constraint::Length(max_width / col_count.max(1) as u16); col_count]
1582 } else {
1583 self.widths.clone()
1584 };
1585
1586 let slots = symbol_columns.iter().filter(|slot| **slot).count() as u16;
1591 let content_width = max_width.saturating_sub(selection_width * slots);
1592 let rects = Layout::horizontal(widths)
1593 .flex(self.flex)
1594 .spacing(self.column_spacing)
1595 .split(Rect::new(0, 0, content_width, 1));
1596
1597 let mut shift = 0;
1598 rects
1599 .iter()
1600 .enumerate()
1601 .map(|(index, rect)| {
1602 if symbol_columns.get(index).copied().unwrap_or(false) {
1603 shift += selection_width;
1604 }
1605 Rect::new(rect.x + shift, 0, rect.width, 1)
1606 })
1607 .collect()
1608 }
1609
1610 fn row_count(&self) -> usize {
1612 self.lazy
1613 .as_ref()
1614 .map_or_else(|| self.rows.len(), |provider| provider.count)
1615 }
1616
1617 fn column_count(&self) -> usize {
1618 let lazy_columns = if self.lazy.is_some() {
1621 self.widths.len()
1622 } else {
1623 0
1624 };
1625 self.rows
1626 .iter()
1627 .chain(self.footer.iter())
1628 .chain(self.header.iter())
1629 .map(|r| r.cells.len())
1630 .chain(Some(lazy_columns))
1631 .max()
1632 .unwrap_or_default()
1633 }
1634
1635 fn selection_width(&self, state: &TableState) -> u16 {
1641 let has_selection = state.selected().is_some() || state.selected_column().is_some();
1642 if self.highlight_spacing.should_add(has_selection) {
1643 self.highlight_symbol.width() as u16
1644 } else {
1645 0
1646 }
1647 }
1648}
1649
1650fn ensure_percentages_less_than_100(widths: &[Constraint]) {
1651 for w in widths {
1652 if let Constraint::Percentage(p) = w {
1653 assert!(
1654 *p <= 100,
1655 "Percentages should be between 0 and 100 inclusively."
1656 );
1657 }
1658 }
1659}
1660
1661impl Styled for Table<'_> {
1662 type Item = Self;
1663
1664 fn style(&self) -> Style {
1665 self.style
1666 }
1667
1668 fn set_style<S: Into<Style>>(self, style: S) -> Self::Item {
1669 self.style(style)
1670 }
1671}
1672
1673impl<'a, Item> FromIterator<Item> for Table<'a>
1674where
1675 Item: Into<Row<'a>>,
1676{
1677 fn from_iter<Iter: IntoIterator<Item = Item>>(rows: Iter) -> Self {
1682 let widths: [Constraint; 0] = [];
1683 Self::new(rows, widths)
1684 }
1685}
1686
1687#[cfg(test)]
1688mod tests {
1689 use alloc::string::ToString;
1690 use alloc::{format, vec};
1691
1692 use ratatui_core::layout::Constraint::*;
1693 use ratatui_core::style::{Color, Modifier, Style, Stylize};
1694 use ratatui_core::text::Line;
1695 use rstest::{fixture, rstest};
1696
1697 use super::*;
1698 use crate::table::Cell;
1699
1700 #[test]
1703 fn lazy_visible_rows_do_not_overflow_the_line_total() {
1704 let table = Table::lazy_rows(4, [Constraint::Length(1)], |_| Row::new(["x"]))
1705 .lazy_row_height_with(|index| if index == 0 { u16::MAX } else { 1 });
1706 let lazy = table.lazy.as_ref().expect("lazy rows");
1707 let area = Rect::new(0, 0, 1, u16::MAX);
1708
1709 let state = TableState::default();
1710 assert_eq!(lazy.visible_rows(&state, area), (0, 1));
1711
1712 let state = TableState::default().with_selected(3);
1713 assert_eq!(lazy.visible_rows(&state, area), (1, 4));
1714 }
1715
1716 #[test]
1717 fn new() {
1718 let rows = [Row::new(vec![Cell::from("")])];
1719 let widths = [Constraint::Percentage(100)];
1720 let table = Table::new(rows.clone(), widths);
1721 assert_eq!(table.rows, rows);
1722 assert_eq!(table.header, None);
1723 assert_eq!(table.footer, None);
1724 assert_eq!(table.widths, widths);
1725 assert_eq!(table.column_spacing, 1);
1726 assert_eq!(table.block, None);
1727 assert_eq!(table.style, Style::default());
1728 assert_eq!(table.row_highlight_style, Style::default());
1729 assert_eq!(table.highlight_symbol, Text::default());
1730 assert_eq!(table.highlight_spacing, HighlightSpacing::WhenSelected);
1731 assert_eq!(table.flex, Flex::Start);
1732 }
1733
1734 #[test]
1735 fn default() {
1736 let table = Table::default();
1737 assert_eq!(table.rows, []);
1738 assert_eq!(table.header, None);
1739 assert_eq!(table.footer, None);
1740 assert_eq!(table.widths, []);
1741 assert_eq!(table.column_spacing, 1);
1742 assert_eq!(table.block, None);
1743 assert_eq!(table.style, Style::default());
1744 assert_eq!(table.row_highlight_style, Style::default());
1745 assert_eq!(table.highlight_symbol, Text::default());
1746 assert_eq!(table.highlight_spacing, HighlightSpacing::WhenSelected);
1747 assert_eq!(table.flex, Flex::Start);
1748 }
1749
1750 #[test]
1751 fn collect() {
1752 let table = (0..4)
1753 .map(|i| -> Row { (0..4).map(|j| format!("{i}*{j} = {}", i * j)).collect() })
1754 .collect::<Table>()
1755 .widths([Constraint::Percentage(25); 4]);
1756
1757 let expected_rows: Vec<Row> = vec![
1758 Row::new(["0*0 = 0", "0*1 = 0", "0*2 = 0", "0*3 = 0"]),
1759 Row::new(["1*0 = 0", "1*1 = 1", "1*2 = 2", "1*3 = 3"]),
1760 Row::new(["2*0 = 0", "2*1 = 2", "2*2 = 4", "2*3 = 6"]),
1761 Row::new(["3*0 = 0", "3*1 = 3", "3*2 = 6", "3*3 = 9"]),
1762 ];
1763
1764 assert_eq!(table.rows, expected_rows);
1765 assert_eq!(table.widths, [Constraint::Percentage(25); 4]);
1766 }
1767
1768 #[test]
1769 fn widths() {
1770 let table = Table::default().widths([Constraint::Length(100)]);
1771 assert_eq!(table.widths, [Constraint::Length(100)]);
1772
1773 #[expect(clippy::needless_borrows_for_generic_args)]
1776 let table = Table::default().widths(&[Constraint::Length(100)]);
1777 assert_eq!(table.widths, [Constraint::Length(100)]);
1778
1779 let table = Table::default().widths(vec![Constraint::Length(100)]);
1780 assert_eq!(table.widths, [Constraint::Length(100)]);
1781
1782 #[expect(clippy::needless_borrows_for_generic_args)]
1785 let table = Table::default().widths(&vec![Constraint::Length(100)]);
1786 assert_eq!(table.widths, [Constraint::Length(100)]);
1787
1788 let table = Table::default().widths([100].into_iter().map(Constraint::Length));
1789 assert_eq!(table.widths, [Constraint::Length(100)]);
1790 }
1791
1792 #[test]
1793 fn rows() {
1794 let rows = [Row::new(vec![Cell::from("")])];
1795 let table = Table::default().rows(rows.clone());
1796 assert_eq!(table.rows, rows);
1797 }
1798
1799 #[test]
1800 fn column_spacing() {
1801 let table = Table::default().column_spacing(2);
1802 assert_eq!(table.column_spacing, 2);
1803 }
1804
1805 #[test]
1806 fn block() {
1807 let block = Block::bordered().title("Table");
1808 let table = Table::default().block(block.clone());
1809 assert_eq!(table.block, Some(block));
1810 }
1811
1812 #[test]
1813 fn header() {
1814 let header = Row::new(vec![Cell::from("")]);
1815 let table = Table::default().header(header.clone());
1816 assert_eq!(table.header, Some(header));
1817 }
1818
1819 #[test]
1820 fn footer() {
1821 let footer = Row::new(vec![Cell::from("")]);
1822 let table = Table::default().footer(footer.clone());
1823 assert_eq!(table.footer, Some(footer));
1824 }
1825
1826 #[test]
1827 #[expect(deprecated)]
1828 fn highlight_style() {
1829 let style = Style::default().red().italic();
1830 let table = Table::default().highlight_style(style);
1831 assert_eq!(table.row_highlight_style, style);
1832 }
1833
1834 #[test]
1835 fn row_highlight_style() {
1836 let style = Style::default().red().italic();
1837 let table = Table::default().row_highlight_style(style);
1838 assert_eq!(table.row_highlight_style, style);
1839 }
1840
1841 #[test]
1842 fn column_highlight_style() {
1843 let style = Style::default().red().italic();
1844 let table = Table::default().column_highlight_style(style);
1845 assert_eq!(table.column_highlight_style, style);
1846 }
1847
1848 #[test]
1849 fn cell_highlight_style() {
1850 let style = Style::default().red().italic();
1851 let table = Table::default().cell_highlight_style(style);
1852 assert_eq!(table.cell_highlight_style, style);
1853 }
1854
1855 #[test]
1856 fn highlight_symbol() {
1857 let table = Table::default().highlight_symbol(">>");
1858 assert_eq!(table.highlight_symbol, Text::from(">>"));
1859 }
1860
1861 #[test]
1862 fn highlight_spacing() {
1863 let table = Table::default().highlight_spacing(HighlightSpacing::Always);
1864 assert_eq!(table.highlight_spacing, HighlightSpacing::Always);
1865 }
1866
1867 #[test]
1868 #[should_panic = "Percentages should be between 0 and 100 inclusively"]
1869 fn table_invalid_percentages() {
1870 let _ = Table::default().widths([Constraint::Percentage(110)]);
1871 }
1872
1873 #[test]
1874 fn widths_conversions() {
1875 let array = [Constraint::Percentage(100)];
1876 let table = Table::new(Vec::<Row>::new(), array);
1877 assert_eq!(table.widths, [Constraint::Percentage(100)], "array");
1878
1879 let array_ref = &[Constraint::Percentage(100)];
1880 let table = Table::new(Vec::<Row>::new(), array_ref);
1881 assert_eq!(table.widths, [Constraint::Percentage(100)], "array ref");
1882
1883 let vec = vec![Constraint::Percentage(100)];
1884 let slice = vec.as_slice();
1885 let table = Table::new(Vec::<Row>::new(), slice);
1886 assert_eq!(table.widths, [Constraint::Percentage(100)], "slice");
1887
1888 let vec = vec![Constraint::Percentage(100)];
1889 let table = Table::new(Vec::<Row>::new(), vec);
1890 assert_eq!(table.widths, [Constraint::Percentage(100)], "vec");
1891
1892 let vec_ref = &vec![Constraint::Percentage(100)];
1893 let table = Table::new(Vec::<Row>::new(), vec_ref);
1894 assert_eq!(table.widths, [Constraint::Percentage(100)], "vec ref");
1895 }
1896
1897 #[cfg(test)]
1898 mod state {
1899 use ratatui_core::buffer::Buffer;
1900 use ratatui_core::layout::{Constraint, Rect};
1901 use ratatui_core::widgets::StatefulWidget;
1902
1903 use super::*;
1904 use crate::table::{Row, Table, TableState};
1905
1906 #[fixture]
1907 fn table_buf() -> Buffer {
1908 Buffer::empty(Rect::new(0, 0, 10, 10))
1909 }
1910
1911 #[rstest]
1912 fn test_list_state_empty_list(mut table_buf: Buffer) {
1913 let mut state = TableState::default();
1914
1915 let rows: Vec<Row> = Vec::new();
1916 let widths = vec![Constraint::Percentage(100)];
1917 let table = Table::new(rows, widths);
1918 state.select_first();
1919 StatefulWidget::render(table, table_buf.area, &mut table_buf, &mut state);
1920 assert_eq!(state.selected(), None);
1921 assert_eq!(state.selected_column(), None);
1922 }
1923
1924 #[rstest]
1925 fn test_list_state_single_item(mut table_buf: Buffer) {
1926 let mut state = TableState::default();
1927
1928 let widths = vec![Constraint::Percentage(100)];
1929
1930 let items = vec![Row::new(vec!["Item 1"])];
1931 let table = Table::new(items, widths);
1932 state.select_first();
1933 StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
1934 assert_eq!(state.selected(), Some(0));
1935 assert_eq!(state.selected_column(), None);
1936
1937 state.select_last();
1938 StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
1939 assert_eq!(state.selected(), Some(0));
1940 assert_eq!(state.selected_column(), None);
1941
1942 state.select_previous();
1943 StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
1944 assert_eq!(state.selected(), Some(0));
1945 assert_eq!(state.selected_column(), None);
1946
1947 state.select_next();
1948 StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
1949 assert_eq!(state.selected(), Some(0));
1950 assert_eq!(state.selected_column(), None);
1951
1952 let mut state = TableState::default();
1953
1954 state.select_first_column();
1955 StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
1956 assert_eq!(state.selected_column(), Some(0));
1957 assert_eq!(state.selected(), None);
1958
1959 state.select_last_column();
1960 StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
1961 assert_eq!(state.selected_column(), Some(0));
1962 assert_eq!(state.selected(), None);
1963
1964 state.select_previous_column();
1965 StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
1966 assert_eq!(state.selected_column(), Some(0));
1967 assert_eq!(state.selected(), None);
1968
1969 state.select_next_column();
1970 StatefulWidget::render(&table, table_buf.area, &mut table_buf, &mut state);
1971 assert_eq!(state.selected_column(), Some(0));
1972 assert_eq!(state.selected(), None);
1973 }
1974 }
1975
1976 #[cfg(test)]
1977 mod render {
1978 use ratatui_core::layout::Alignment;
1979
1980 use super::*;
1981
1982 #[test]
1983 fn render_empty_area() {
1984 let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
1985 let rows = vec![Row::new(vec!["Cell1", "Cell2"])];
1986 let table = Table::new(rows, vec![Constraint::Length(5); 2]);
1987 Widget::render(table, Rect::new(0, 0, 0, 0), &mut buf);
1988 assert_eq!(buf, Buffer::empty(Rect::new(0, 0, 15, 3)));
1989 }
1990
1991 #[test]
1992 fn render_default() {
1993 let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
1994 let table = Table::default();
1995 Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
1996 assert_eq!(buf, Buffer::empty(Rect::new(0, 0, 15, 3)));
1997 }
1998
1999 #[test]
2000 fn render_with_block() {
2001 let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2002 let rows = vec![
2003 Row::new(vec!["Cell1", "Cell2"]),
2004 Row::new(vec!["Cell3", "Cell4"]),
2005 ];
2006 let block = Block::bordered().title("Block");
2007 let table = Table::new(rows, vec![Constraint::Length(5); 2]).block(block);
2008 Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
2009 #[rustfmt::skip]
2010 let expected = Buffer::with_lines([
2011 "┌Block────────┐",
2012 "│Cell1 Cell2 │",
2013 "└─────────────┘",
2014 ]);
2015 assert_eq!(buf, expected);
2016 }
2017
2018 #[rstest]
2019 #[case(15, 5, vec![
2020 Row::new(vec![
2021 Cell::new("Cell1").column_span(1),
2022 Cell::new("Cell2").column_span(1),
2023 ]),
2024 Row::new(vec![
2025 Cell::new("Cell3").column_span(1),
2026 Cell::new("Cell4").column_span(1),
2027 ]),
2028 ],
2029 &Buffer::with_lines(["Cell1 Cell2 ", "Cell3 Cell4 "]))]
2030 #[case(15, 5, vec![
2031 Row::new(vec![
2032 Cell::new("Cell1").column_span(0),
2033 Cell::new("Cell2").column_span(1),
2034 ]),
2035 Row::new(vec![
2036 Cell::new("Cell3").column_span(1),
2037 Cell::new("Cell4").column_span(1),
2038 ]),
2039 ], &Buffer::with_lines(["Cell2 ", "Cell3 Cell4 "]))]
2040 #[case(15, 5, vec![
2041 Row::new(vec![
2042 Cell::new("Cell1").column_span(2),
2043 Cell::new("Cell2").column_span(1),
2044 ]),
2045 Row::new(vec![
2046 Cell::new("Cell3").column_span(1),
2047 Cell::new("Cell4").column_span(1),
2048 ]),
2049 ], &Buffer::with_lines(["Cell1 ", "Cell3 Cell4 "]))]
2050 fn test_colspans_2_cols<'rows, Rows>(
2051 #[case] width: u16,
2052 #[case] column_width: u16,
2053 #[case] rows: Rows,
2054 #[case] expected: &Buffer,
2055 ) where
2056 Rows: IntoIterator<Item = Row<'rows>>,
2057 {
2058 let mut buf = Buffer::empty(Rect::new(0, 0, width, 2));
2059 let table = Table::new(rows, [Constraint::Length(column_width); 2]);
2060 Widget::render(table, Rect::new(0, 0, width, 2), &mut buf);
2061 assert_eq!(buf, *expected);
2062 }
2063
2064 #[rstest]
2065 #[case(17, 5, vec![
2066 Row::new(vec![
2067 Cell::new("Cell1").column_span(2),
2068 Cell::new("Cell2").column_span(1),
2069 ]),
2070 Row::new(vec![
2071 Cell::new("Cell3").column_span(1),
2072 Cell::new("Cell4").column_span(1),
2073 Cell::new("Cell5").column_span(1),
2074 ]),
2075 ], &Buffer::with_lines(["Cell1 Cell2", "Cell3 Cell4 Cell5"]))]
2076 #[case(17, 5, vec![
2077 Row::new(vec![
2078 Cell::new("Cell1").column_span(1),
2079 Cell::new("Cell2").column_span(2),
2080 Cell::new("Cell3").column_span(1),
2081 ]),
2082 Row::new(vec![
2083 Cell::new("Cell4").column_span(1),
2084 Cell::new("Cell5").column_span(1),
2085 Cell::new("Cell6").column_span(1),
2086 ]),
2087 ], &Buffer::with_lines(["Cell1 Cell2 ", "Cell4 Cell5 Cell6"]))]
2088 #[case(15, 5, vec![
2089 Row::new(vec![
2090 Cell::new("11111111111111111111").column_span(2),
2091 Cell::new("22222222222222222222").column_span(1),
2092 ]),
2093 Row::new(vec![
2094 Cell::new("33333333333333333333").column_span(1),
2095 Cell::new("44444444444444444444").column_span(2),
2096 Cell::new("55555555555555555555").column_span(1),
2097 ]),
2098 ], &Buffer::with_lines(["1111111111 2222", "3333 4444444444"]))]
2099 fn test_colspans_3_cols<'rows, Rows>(
2100 #[case] width: u16,
2101 #[case] column_width: u16,
2102 #[case] rows: Rows,
2103 #[case] expected: &Buffer,
2104 ) where
2105 Rows: IntoIterator<Item = Row<'rows>>,
2106 {
2107 let mut buf = Buffer::empty(Rect::new(0, 0, width, 2));
2108 let table = Table::new(rows, [Constraint::Length(column_width); 3]);
2109 Widget::render(table, Rect::new(0, 0, width, 2), &mut buf);
2110 assert_eq!(buf, *expected);
2111 }
2112
2113 #[test]
2114 fn render_with_header() {
2115 let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2116 let header = Row::new(vec!["Head1", "Head2"]);
2117 let rows = vec![
2118 Row::new(vec!["Cell1", "Cell2"]),
2119 Row::new(vec!["Cell3", "Cell4"]),
2120 ];
2121 let table = Table::new(rows, [Constraint::Length(5); 2]).header(header);
2122 Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
2123 #[rustfmt::skip]
2124 let expected = Buffer::with_lines([
2125 "Head1 Head2 ",
2126 "Cell1 Cell2 ",
2127 "Cell3 Cell4 ",
2128 ]);
2129 assert_eq!(buf, expected);
2130 }
2131
2132 #[test]
2133 fn render_with_footer() {
2134 let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2135 let footer = Row::new(vec!["Foot1", "Foot2"]);
2136 let rows = vec![
2137 Row::new(vec!["Cell1", "Cell2"]),
2138 Row::new(vec!["Cell3", "Cell4"]),
2139 ];
2140 let table = Table::new(rows, [Constraint::Length(5); 2]).footer(footer);
2141 Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
2142 #[rustfmt::skip]
2143 let expected = Buffer::with_lines([
2144 "Cell1 Cell2 ",
2145 "Cell3 Cell4 ",
2146 "Foot1 Foot2 ",
2147 ]);
2148 assert_eq!(buf, expected);
2149 }
2150
2151 #[test]
2152 fn render_with_header_and_footer() {
2153 let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2154 let header = Row::new(vec!["Head1", "Head2"]);
2155 let footer = Row::new(vec!["Foot1", "Foot2"]);
2156 let rows = vec![Row::new(vec!["Cell1", "Cell2"])];
2157 let table = Table::new(rows, [Constraint::Length(5); 2])
2158 .header(header)
2159 .footer(footer);
2160 Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
2161 #[rustfmt::skip]
2162 let expected = Buffer::with_lines([
2163 "Head1 Head2 ",
2164 "Cell1 Cell2 ",
2165 "Foot1 Foot2 ",
2166 ]);
2167 assert_eq!(buf, expected);
2168 }
2169
2170 #[test]
2171 fn render_with_header_margin() {
2172 let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2173 let header = Row::new(vec!["Head1", "Head2"]).bottom_margin(1);
2174 let rows = vec![
2175 Row::new(vec!["Cell1", "Cell2"]),
2176 Row::new(vec!["Cell3", "Cell4"]),
2177 ];
2178 let table = Table::new(rows, [Constraint::Length(5); 2]).header(header);
2179 Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
2180 #[rustfmt::skip]
2181 let expected = Buffer::with_lines([
2182 "Head1 Head2 ",
2183 " ",
2184 "Cell1 Cell2 ",
2185 ]);
2186 assert_eq!(buf, expected);
2187 }
2188
2189 #[test]
2190 fn render_with_footer_margin() {
2191 let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2192 let footer = Row::new(vec!["Foot1", "Foot2"]).top_margin(1);
2193 let rows = vec![Row::new(vec!["Cell1", "Cell2"])];
2194 let table = Table::new(rows, [Constraint::Length(5); 2]).footer(footer);
2195 Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
2196 #[rustfmt::skip]
2197 let expected = Buffer::with_lines([
2198 "Cell1 Cell2 ",
2199 " ",
2200 "Foot1 Foot2 ",
2201 ]);
2202 assert_eq!(buf, expected);
2203 }
2204
2205 #[test]
2206 fn render_with_row_margin() {
2207 let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2208 let rows = vec![
2209 Row::new(vec!["Cell1", "Cell2"]).bottom_margin(1),
2210 Row::new(vec!["Cell3", "Cell4"]),
2211 ];
2212 let table = Table::new(rows, [Constraint::Length(5); 2]);
2213 Widget::render(table, Rect::new(0, 0, 15, 3), &mut buf);
2214 #[rustfmt::skip]
2215 let expected = Buffer::with_lines([
2216 "Cell1 Cell2 ",
2217 " ",
2218 "Cell3 Cell4 ",
2219 ]);
2220 assert_eq!(buf, expected);
2221 }
2222
2223 #[test]
2224 fn render_with_tall_row() {
2225 let mut buf = Buffer::empty(Rect::new(0, 0, 23, 3));
2226 let rows = vec![
2227 Row::new(vec!["Cell1", "Cell2"]),
2228 Row::new(vec![
2229 Text::raw("Cell3-Line1\nCell3-Line2\nCell3-Line3"),
2230 Text::raw("Cell4-Line1\nCell4-Line2\nCell4-Line3"),
2231 ])
2232 .height(3),
2233 ];
2234 let table = Table::new(rows, [Constraint::Length(11); 2]);
2235 Widget::render(table, Rect::new(0, 0, 23, 3), &mut buf);
2236 #[rustfmt::skip]
2237 let expected = Buffer::with_lines([
2238 "Cell1 Cell2 ",
2239 "Cell3-Line1 Cell4-Line1",
2240 "Cell3-Line2 Cell4-Line2",
2241 ]);
2242 assert_eq!(buf, expected);
2243 }
2244
2245 #[test]
2246 fn render_with_alignment() {
2247 let mut buf = Buffer::empty(Rect::new(0, 0, 10, 3));
2248 let rows = vec![
2249 Row::new(vec![Line::from("Left").alignment(Alignment::Left)]),
2250 Row::new(vec![Line::from("Center").alignment(Alignment::Center)]),
2251 Row::new(vec![Line::from("Right").alignment(Alignment::Right)]),
2252 ];
2253 let table = Table::new(rows, [Percentage(100)]);
2254 Widget::render(table, Rect::new(0, 0, 10, 3), &mut buf);
2255 let expected = Buffer::with_lines(["Left ", " Center ", " Right"]);
2256 assert_eq!(buf, expected);
2257 }
2258
2259 #[test]
2260 fn render_with_overflow_does_not_panic() {
2261 let mut buf = Buffer::empty(Rect::new(0, 0, 20, 3));
2262 let table = Table::new(Vec::<Row>::new(), [Constraint::Min(20); 1])
2263 .header(Row::new([Line::from("").alignment(Alignment::Right)]))
2264 .footer(Row::new([Line::from("").alignment(Alignment::Right)]));
2265 Widget::render(table, Rect::new(0, 0, 20, 3), &mut buf);
2266 }
2267
2268 #[test]
2269 fn render_with_selected_column_and_incorrect_width_count_does_not_panic() {
2270 let mut buf = Buffer::empty(Rect::new(0, 0, 20, 3));
2271 let table = Table::new(
2272 vec![Row::new(vec!["Row1", "Row2", "Row3"])],
2273 [Constraint::Length(10); 1],
2274 );
2275 let mut state = TableState::new().with_selected_column(2);
2276 StatefulWidget::render(table, Rect::new(0, 0, 20, 3), &mut buf, &mut state);
2277 }
2278
2279 #[test]
2280 fn render_with_selected() {
2281 let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2282 let rows = vec![
2283 Row::new(vec!["Cell1", "Cell2"]),
2284 Row::new(vec!["Cell3", "Cell4"]),
2285 ];
2286 let table = Table::new(rows, [Constraint::Length(5); 2])
2287 .row_highlight_style(Style::new().red())
2288 .highlight_symbol(">>");
2289 let mut state = TableState::new().with_selected(Some(0));
2290 StatefulWidget::render(table, Rect::new(0, 0, 15, 3), &mut buf, &mut state);
2291 let expected = Buffer::with_lines([
2292 ">>Cell1 Cell2 ".red(),
2293 " Cell3 Cell4 ".into(),
2294 " ".into(),
2295 ]);
2296 assert_eq!(buf, expected);
2297 }
2298
2299 #[test]
2300 fn render_with_selected_column() {
2301 let mut buf = Buffer::empty(Rect::new(0, 0, 15, 3));
2302 let rows = vec![
2303 Row::new(vec!["Cell1", "Cell2"]),
2304 Row::new(vec!["Cell3", "Cell4"]),
2305 ];
2306 let table = Table::new(rows, [Constraint::Length(5); 2])
2307 .column_highlight_style(Style::new().blue())
2308 .highlight_symbol(">>");
2309 let mut state = TableState::new().with_selected_column(Some(1));
2310 StatefulWidget::render(table, Rect::new(0, 0, 15, 3), &mut buf, &mut state);
2311 let expected = Buffer::with_lines::<[Line; 3]>([
2312 Line::from(vec![
2313 ">>Cell1".into(),
2314 " ".into(),
2315 "Cell2".blue(),
2316 " ".into(),
2317 ]),
2318 Line::from(vec![
2319 " Cell3".into(),
2320 " ".into(),
2321 "Cell4".blue(),
2322 " ".into(),
2323 ]),
2324 Line::from(vec![" ".into(), " ".blue(), " ".into()]),
2325 ]);
2326 assert_eq!(buf, expected);
2327 }
2328
2329 #[test]
2330 fn render_with_selected_cell() {
2331 let mut buf = Buffer::empty(Rect::new(0, 0, 20, 4));
2332 let rows = vec![
2333 Row::new(vec!["Cell1", "Cell2", "Cell3"]),
2334 Row::new(vec!["Cell4", "Cell5", "Cell6"]),
2335 Row::new(vec!["Cell7", "Cell8", "Cell9"]),
2336 ];
2337 let table = Table::new(rows, [Constraint::Length(5); 3])
2338 .highlight_symbol(">>")
2339 .cell_highlight_style(Style::new().green());
2340 let mut state = TableState::new().with_selected_cell((1, 2));
2341 StatefulWidget::render(table, Rect::new(0, 0, 20, 4), &mut buf, &mut state);
2342 let expected = Buffer::with_lines::<[Line; 4]>([
2343 Line::from(vec![" Cell1 ".into(), "Cell2 ".into(), "Cell3".into()]),
2344 Line::from(vec![">>Cell4 Cell5 ".into(), "Cell6".green(), " ".into()]),
2345 Line::from(vec![" Cell7 ".into(), "Cell8 ".into(), "Cell9".into()]),
2346 Line::from(vec![" ".into()]),
2347 ]);
2348 assert_eq!(buf, expected);
2349 }
2350
2351 #[test]
2352 fn render_with_selected_row_and_column() {
2353 let mut buf = Buffer::empty(Rect::new(0, 0, 20, 4));
2354 let rows = vec![
2355 Row::new(vec!["Cell1", "Cell2", "Cell3"]),
2356 Row::new(vec!["Cell4", "Cell5", "Cell6"]),
2357 Row::new(vec!["Cell7", "Cell8", "Cell9"]),
2358 ];
2359 let table = Table::new(rows, [Constraint::Length(5); 3])
2360 .highlight_symbol(">>")
2361 .row_highlight_style(Style::new().red())
2362 .column_highlight_style(Style::new().blue());
2363 let mut state = TableState::new().with_selected(1).with_selected_column(2);
2364 StatefulWidget::render(table, Rect::new(0, 0, 20, 4), &mut buf, &mut state);
2365 let expected = Buffer::with_lines::<[Line; 4]>([
2366 Line::from(vec![" Cell1 ".into(), "Cell2 ".into(), "Cell3".blue()]),
2367 Line::from(vec![">>Cell4 Cell5 ".red(), "Cell6".blue(), " ".red()]),
2368 Line::from(vec![" Cell7 ".into(), "Cell8 ".into(), "Cell9".blue()]),
2369 Line::from(vec![" ".into(), " ".blue(), " ".into()]),
2370 ]);
2371 assert_eq!(buf, expected);
2372 }
2373
2374 #[test]
2375 fn render_with_selected_row_and_column_and_cell() {
2376 let mut buf = Buffer::empty(Rect::new(0, 0, 20, 4));
2377 let rows = vec![
2378 Row::new(vec!["Cell1", "Cell2", "Cell3"]),
2379 Row::new(vec!["Cell4", "Cell5", "Cell6"]),
2380 Row::new(vec!["Cell7", "Cell8", "Cell9"]),
2381 ];
2382 let table = Table::new(rows, [Constraint::Length(5); 3])
2383 .highlight_symbol(">>")
2384 .row_highlight_style(Style::new().red())
2385 .column_highlight_style(Style::new().blue())
2386 .cell_highlight_style(Style::new().green());
2387 let mut state = TableState::new().with_selected(1).with_selected_column(2);
2388 StatefulWidget::render(table, Rect::new(0, 0, 20, 4), &mut buf, &mut state);
2389 let expected = Buffer::with_lines::<[Line; 4]>([
2390 Line::from(vec![" Cell1 ".into(), "Cell2 ".into(), "Cell3".blue()]),
2391 Line::from(vec![">>Cell4 Cell5 ".red(), "Cell6".green(), " ".red()]),
2392 Line::from(vec![" Cell7 ".into(), "Cell8 ".into(), "Cell9".blue()]),
2393 Line::from(vec![" ".into(), " ".blue(), " ".into()]),
2394 ]);
2395 assert_eq!(buf, expected);
2396 }
2397
2398 #[rstest]
2402 #[case::no_selection(None, 50, ["50", "51", "52", "53", "54"])]
2403 #[case::selection_before_offset(20, 20, ["20", "21", "22", "23", "24"])]
2404 #[case::selection_immediately_before_offset(49, 49, ["49", "50", "51", "52", "53"])]
2405 #[case::selection_at_start_of_offset(50, 50, ["50", "51", "52", "53", "54"])]
2406 #[case::selection_at_end_of_offset(54, 50, ["50", "51", "52", "53", "54"])]
2407 #[case::selection_immediately_after_offset(55, 51, ["51", "52", "53", "54", "55"])]
2408 #[case::selection_after_offset(80, 76, ["76", "77", "78", "79", "80"])]
2409 fn render_with_selection_and_offset<T: Into<Option<usize>>>(
2410 #[case] selected_row: T,
2411 #[case] expected_offset: usize,
2412 #[case] expected_items: [&str; 5],
2413 ) {
2414 let rows = (0..100).map(|i| Row::new([i.to_string()]));
2416 let table = Table::new(rows, [Constraint::Length(2)]);
2417 let mut buf = Buffer::empty(Rect::new(0, 0, 2, 5));
2418 let mut state = TableState::new()
2419 .with_offset(50)
2420 .with_selected(selected_row.into());
2421
2422 StatefulWidget::render(table.clone(), Rect::new(0, 0, 5, 5), &mut buf, &mut state);
2423
2424 assert_eq!(buf, Buffer::with_lines(expected_items));
2425 assert_eq!(state.offset, expected_offset);
2426 }
2427 }
2428
2429 mod highlight_placement {
2430 use super::*;
2431
2432 #[track_caller]
2434 fn assert_render(
2435 placement: HighlightPlacement,
2436 selected_row: Option<usize>,
2437 selected_column: Option<usize>,
2438 expected: [&str; 3],
2439 ) {
2440 let rows = [
2441 Row::new(["A1", "A2", "A3"]),
2442 Row::new(["B1", "B2", "B3"]),
2443 Row::new(["C1", "C2", "C3"]),
2444 ];
2445 let table = Table::new(rows, [Constraint::Length(2); 3])
2446 .highlight_symbol(">>")
2447 .highlight_placement(placement);
2448 let mut state = TableState::new()
2449 .with_selected(selected_row)
2450 .with_selected_column(selected_column);
2451 let area = Rect::new(0, 0, 24, 3);
2452 let mut buf = Buffer::empty(area);
2453 StatefulWidget::render(table, area, &mut buf, &mut state);
2454 assert_eq!(buf, Buffer::with_lines(expected));
2455 }
2456
2457 #[test]
2458 fn first_column_with_row_selection() {
2459 assert_render(
2460 HighlightPlacement::FirstColumn,
2461 Some(1),
2462 None,
2463 [
2464 " A1 A2 A3 ",
2465 ">>B1 B2 B3 ",
2466 " C1 C2 C3 ",
2467 ],
2468 );
2469 }
2470
2471 #[test]
2472 fn first_column_keeps_symbol_when_a_later_column_is_selected() {
2473 assert_render(
2475 HighlightPlacement::FirstColumn,
2476 Some(1),
2477 Some(2),
2478 [
2479 " A1 A2 A3 ",
2480 ">>B1 B2 B3 ",
2481 " C1 C2 C3 ",
2482 ],
2483 );
2484 }
2485
2486 #[test]
2487 fn selected_column_moves_the_slot() {
2488 assert_render(
2489 HighlightPlacement::SelectedColumn,
2490 Some(1),
2491 Some(1),
2492 [
2493 "A1 A2 A3 ",
2494 "B1 >>B2 B3 ",
2495 "C1 C2 C3 ",
2496 ],
2497 );
2498 }
2499
2500 #[test]
2501 fn selected_column_without_a_column_falls_back_to_first() {
2502 assert_render(
2503 HighlightPlacement::SelectedColumn,
2504 Some(0),
2505 None,
2506 [
2507 ">>A1 A2 A3 ",
2508 " B1 B2 B3 ",
2509 " C1 C2 C3 ",
2510 ],
2511 );
2512 }
2513
2514 #[test]
2515 fn columns_indents_each_listed_column() {
2516 assert_render(
2517 HighlightPlacement::Columns(vec![1, 2]),
2518 Some(0),
2519 None,
2520 [
2521 "A1 >>A2 >>A3 ",
2522 "B1 B2 B3 ",
2523 "C1 C2 C3 ",
2524 ],
2525 );
2526 }
2527
2528 #[test]
2529 fn columns_ignores_out_of_range_indices() {
2530 assert_render(
2532 HighlightPlacement::Columns(vec![1, 9]),
2533 Some(0),
2534 None,
2535 [
2536 "A1 >>A2 A3 ",
2537 "B1 B2 B3 ",
2538 "C1 C2 C3 ",
2539 ],
2540 );
2541 }
2542
2543 #[test]
2544 fn all_columns() {
2545 assert_render(
2546 HighlightPlacement::AllColumns,
2547 Some(2),
2548 None,
2549 [
2550 " A1 A2 A3 ",
2551 " B1 B2 B3 ",
2552 ">>C1 >>C2 >>C3 ",
2553 ],
2554 );
2555 }
2556
2557 #[test]
2558 fn column_only_selection_anchors_to_the_first_visible_row() {
2559 let rows = ["A", "B", "C", "D"].map(|label| Row::new([label, label]));
2562 let table = Table::new(rows, [Constraint::Length(1); 2])
2563 .highlight_symbol(">>")
2564 .highlight_placement(HighlightPlacement::SelectedColumn);
2565 let mut state = TableState::new().with_offset(2).with_selected_column(1);
2566 let area = Rect::new(0, 0, 8, 2);
2567 let mut buf = Buffer::empty(area);
2568 StatefulWidget::render(table, area, &mut buf, &mut state);
2569 assert_eq!(buf, Buffer::with_lines(["C >>C ", "D D "]));
2570 }
2571
2572 #[test]
2573 fn never_spacing_allocates_no_slot() {
2574 let rows = [Row::new(["A1", "A2"]), Row::new(["B1", "B2"])];
2575 let table = Table::new(rows, [Constraint::Length(2); 2])
2576 .highlight_symbol(">>")
2577 .highlight_spacing(HighlightSpacing::Never)
2578 .highlight_placement(HighlightPlacement::AllColumns);
2579 let mut state = TableState::new().with_selected(0);
2580 let area = Rect::new(0, 0, 12, 2);
2581 let mut buf = Buffer::empty(area);
2582 StatefulWidget::render(table, area, &mut buf, &mut state);
2583 assert_eq!(buf, Buffer::with_lines(["A1 A2 ", "B1 B2 "]));
2584 }
2585
2586 #[test]
2587 fn symbol_follows_columns_not_spanned_cells() {
2588 let rows = [Row::new([
2591 Cell::from("A1").column_span(2),
2592 Cell::from("A3"),
2593 ])];
2594 let table = Table::new(rows, [Constraint::Length(2); 3])
2595 .header(Row::new(["H1", "H2", "H3"]))
2596 .highlight_symbol(">>")
2597 .highlight_placement(HighlightPlacement::AllColumns);
2598 let mut state = TableState::new().with_selected(0);
2599 let area = Rect::new(0, 0, 20, 2);
2600 let mut buf = Buffer::empty(area);
2601 StatefulWidget::render(table, area, &mut buf, &mut state);
2602 assert_eq!(
2603 buf,
2604 Buffer::with_lines([" H1 H2 H3 ", ">>A1 >> >>A3 "])
2605 );
2606 }
2607
2608 #[test]
2609 fn column_highlight_does_not_reach_header_or_footer() {
2610 let rows = [Row::new(["A1", "A2"])];
2611 let table = Table::new(rows, [Constraint::Length(2); 2])
2612 .header(Row::new(["H1", "H2"]))
2613 .footer(Row::new(["F1", "F2"]))
2614 .column_highlight_style(Style::new().blue());
2615 let mut state = TableState::new().with_selected_column(1);
2616 let area = Rect::new(0, 0, 6, 3);
2617 let mut buf = Buffer::empty(area);
2618 StatefulWidget::render(table, area, &mut buf, &mut state);
2619
2620 let mut expected = Buffer::with_lines(["H1 H2 ", "A1 A2 ", "F1 F2 "]);
2621 expected.set_style(Rect::new(3, 1, 2, 1), Style::new().blue());
2622 assert_eq!(buf, expected);
2623 }
2624 }
2625
2626 mod column_widths {
2628 use super::*;
2629
2630 #[test]
2631 fn length_constraint() {
2632 let table = Table::default().widths([Length(4), Length(4)]);
2634 assert_eq!(
2635 table.get_column_widths(20, 0, 0, &[]),
2636 [Rect::new(0, 0, 4, 1), Rect::new(5, 0, 4, 1),]
2637 );
2638
2639 let table = Table::default().widths([Length(4), Length(4)]);
2641 assert_eq!(
2642 table.get_column_widths(20, 3, 0, &[true]),
2643 [Rect::new(3, 0, 4, 1), Rect::new(8, 0, 4, 1)]
2644 );
2645
2646 let table = Table::default().widths([Length(4), Length(4)]);
2648 assert_eq!(
2649 table.get_column_widths(7, 0, 0, &[]),
2650 [Rect::new(0, 0, 3, 1), Rect::new(4, 0, 3, 1)]
2651 );
2652
2653 let table = Table::default().widths([Length(4), Length(4)]);
2660 assert_eq!(
2661 table.get_column_widths(7, 3, 0, &[true]),
2662 [Rect::new(3, 0, 2, 1), Rect::new(6, 0, 1, 1)]
2663 );
2664 }
2665
2666 #[test]
2667 fn max_constraint() {
2668 let table = Table::default().widths([Max(4), Max(4)]);
2670 assert_eq!(
2671 table.get_column_widths(20, 0, 0, &[]),
2672 [Rect::new(0, 0, 4, 1), Rect::new(5, 0, 4, 1)]
2673 );
2674
2675 let table = Table::default().widths([Max(4), Max(4)]);
2677 assert_eq!(
2678 table.get_column_widths(20, 3, 0, &[true]),
2679 [Rect::new(3, 0, 4, 1), Rect::new(8, 0, 4, 1)]
2680 );
2681
2682 let table = Table::default().widths([Max(4), Max(4)]);
2684 assert_eq!(
2685 table.get_column_widths(7, 0, 0, &[]),
2686 [Rect::new(0, 0, 3, 1), Rect::new(4, 0, 3, 1)]
2687 );
2688
2689 let table = Table::default().widths([Max(4), Max(4)]);
2691 assert_eq!(
2692 table.get_column_widths(7, 3, 0, &[true]),
2693 [Rect::new(3, 0, 2, 1), Rect::new(6, 0, 1, 1)]
2694 );
2695 }
2696
2697 #[test]
2698 fn min_constraint() {
2699 let table = Table::default().widths([Min(4), Min(4)]);
2705 assert_eq!(
2706 table.get_column_widths(20, 0, 0, &[]),
2707 [Rect::new(0, 0, 10, 1), Rect::new(11, 0, 9, 1)]
2708 );
2709
2710 let table = Table::default().widths([Min(4), Min(4)]);
2712 assert_eq!(
2713 table.get_column_widths(20, 3, 0, &[true]),
2714 [Rect::new(3, 0, 8, 1), Rect::new(12, 0, 8, 1)]
2715 );
2716
2717 let table = Table::default().widths([Min(4), Min(4)]);
2720 assert_eq!(
2721 table.get_column_widths(7, 0, 0, &[]),
2722 [Rect::new(0, 0, 3, 1), Rect::new(4, 0, 3, 1)]
2723 );
2724
2725 let table = Table::default().widths([Min(4), Min(4)]);
2728 assert_eq!(
2729 table.get_column_widths(7, 3, 0, &[true]),
2730 [Rect::new(3, 0, 2, 1), Rect::new(6, 0, 1, 1)]
2731 );
2732 }
2733
2734 #[test]
2735 fn percentage_constraint() {
2736 let table = Table::default().widths([Percentage(30), Percentage(30)]);
2738 assert_eq!(
2739 table.get_column_widths(20, 0, 0, &[]),
2740 [Rect::new(0, 0, 6, 1), Rect::new(7, 0, 6, 1)]
2741 );
2742
2743 let table = Table::default().widths([Percentage(30), Percentage(30)]);
2745 assert_eq!(
2746 table.get_column_widths(20, 3, 0, &[true]),
2747 [Rect::new(3, 0, 5, 1), Rect::new(9, 0, 5, 1)]
2748 );
2749
2750 let table = Table::default().widths([Percentage(30), Percentage(30)]);
2753 assert_eq!(
2754 table.get_column_widths(7, 0, 0, &[]),
2755 [Rect::new(0, 0, 2, 1), Rect::new(3, 0, 2, 1)]
2756 );
2757
2758 let table = Table::default().widths([Percentage(30), Percentage(30)]);
2761 assert_eq!(
2762 table.get_column_widths(7, 3, 0, &[true]),
2763 [Rect::new(3, 0, 1, 1), Rect::new(5, 0, 1, 1)]
2764 );
2765 }
2766
2767 #[test]
2768 fn ratio_constraint() {
2769 let table = Table::default().widths([Ratio(1, 3), Ratio(1, 3)]);
2772 assert_eq!(
2773 table.get_column_widths(20, 0, 0, &[]),
2774 [Rect::new(0, 0, 7, 1), Rect::new(8, 0, 6, 1)]
2775 );
2776
2777 let table = Table::default().widths([Ratio(1, 3), Ratio(1, 3)]);
2780 assert_eq!(
2781 table.get_column_widths(20, 3, 0, &[true]),
2782 [Rect::new(3, 0, 6, 1), Rect::new(10, 0, 5, 1)]
2783 );
2784
2785 let table = Table::default().widths([Ratio(1, 3), Ratio(1, 3)]);
2788 assert_eq!(
2789 table.get_column_widths(7, 0, 0, &[]),
2790 [Rect::new(0, 0, 2, 1), Rect::new(3, 0, 3, 1)]
2791 );
2792
2793 let table = Table::default().widths([Ratio(1, 3), Ratio(1, 3)]);
2796 assert_eq!(
2797 table.get_column_widths(7, 3, 0, &[true]),
2798 [Rect::new(3, 0, 1, 1), Rect::new(5, 0, 2, 1)]
2799 );
2800 }
2801
2802 #[test]
2804 fn underconstrained_flex() {
2805 let table = Table::default().widths([Min(10), Min(10), Min(1)]);
2806 assert_eq!(
2807 table.get_column_widths(62, 0, 0, &[]),
2808 &[
2809 Rect::new(0, 0, 20, 1),
2810 Rect::new(21, 0, 20, 1),
2811 Rect::new(42, 0, 20, 1)
2812 ]
2813 );
2814
2815 let table = Table::default()
2816 .widths([Min(10), Min(10), Min(1)])
2817 .flex(Flex::Legacy);
2818 assert_eq!(
2819 table.get_column_widths(62, 0, 0, &[]),
2820 &[
2821 Rect::new(0, 0, 10, 1),
2822 Rect::new(11, 0, 10, 1),
2823 Rect::new(22, 0, 40, 1)
2824 ]
2825 );
2826
2827 let table = Table::default()
2828 .widths([Min(10), Min(10), Min(1)])
2829 .flex(Flex::SpaceBetween);
2830 assert_eq!(
2831 table.get_column_widths(62, 0, 0, &[]),
2832 &[
2833 Rect::new(0, 0, 20, 1),
2834 Rect::new(21, 0, 20, 1),
2835 Rect::new(42, 0, 20, 1)
2836 ]
2837 );
2838 }
2839
2840 #[test]
2841 fn underconstrained_segment_size() {
2842 let table = Table::default().widths([Min(10), Min(10), Min(1)]);
2843 assert_eq!(
2844 table.get_column_widths(62, 0, 0, &[]),
2845 &[
2846 Rect::new(0, 0, 20, 1),
2847 Rect::new(21, 0, 20, 1),
2848 Rect::new(42, 0, 20, 1)
2849 ]
2850 );
2851
2852 let table = Table::default()
2853 .widths([Min(10), Min(10), Min(1)])
2854 .flex(Flex::Legacy);
2855 assert_eq!(
2856 table.get_column_widths(62, 0, 0, &[]),
2857 &[
2858 Rect::new(0, 0, 10, 1),
2859 Rect::new(11, 0, 10, 1),
2860 Rect::new(22, 0, 40, 1)
2861 ]
2862 );
2863 }
2864
2865 #[test]
2866 fn no_constraint_with_rows() {
2867 let table = Table::default()
2868 .rows(vec![
2869 Row::new(vec!["a", "b"]),
2870 Row::new(vec!["c", "d", "e"]),
2871 ])
2872 .header(Row::new(vec!["f", "g"]))
2874 .footer(Row::new(vec!["h", "i"]))
2875 .column_spacing(0);
2876 assert_eq!(
2877 table.get_column_widths(30, 0, 3, &[]),
2878 &[
2879 Rect::new(0, 0, 10, 1),
2880 Rect::new(10, 0, 10, 1),
2881 Rect::new(20, 0, 10, 1)
2882 ]
2883 );
2884 }
2885
2886 #[test]
2887 fn no_constraint_with_header() {
2888 let table = Table::default()
2889 .rows(vec![])
2890 .header(Row::new(vec!["f", "g"]))
2891 .column_spacing(0);
2892 assert_eq!(
2893 table.get_column_widths(10, 0, 2, &[]),
2894 [Rect::new(0, 0, 5, 1), Rect::new(5, 0, 5, 1)]
2895 );
2896 }
2897
2898 #[test]
2899 fn no_constraint_with_footer() {
2900 let table = Table::default()
2901 .rows(vec![])
2902 .footer(Row::new(vec!["h", "i"]))
2903 .column_spacing(0);
2904 assert_eq!(
2905 table.get_column_widths(10, 0, 2, &[]),
2906 [Rect::new(0, 0, 5, 1), Rect::new(5, 0, 5, 1)]
2907 );
2908 }
2909
2910 #[track_caller]
2911 fn test_table_with_selection<'line, Lines>(
2912 highlight_spacing: HighlightSpacing,
2913 columns: u16,
2914 spacing: u16,
2915 selection: Option<usize>,
2916 expected: Lines,
2917 ) where
2918 Lines: IntoIterator,
2919 Lines::Item: Into<Line<'line>>,
2920 {
2921 let table = Table::default()
2922 .rows(vec![Row::new(vec!["ABCDE", "12345"])])
2923 .highlight_spacing(highlight_spacing)
2924 .highlight_symbol(">>>")
2925 .column_spacing(spacing);
2926 let area = Rect::new(0, 0, columns, 3);
2927 let mut buf = Buffer::empty(area);
2928 let mut state = TableState::default().with_selected(selection);
2929 StatefulWidget::render(table, area, &mut buf, &mut state);
2930 assert_eq!(buf, Buffer::with_lines(expected));
2931 }
2932
2933 #[test]
2934 fn excess_area_highlight_symbol_and_column_spacing_allocation() {
2935 test_table_with_selection(
2937 HighlightSpacing::Never,
2938 15, 0, None, [
2942 "ABCDE 12345 ", " ", " ", ],
2948 );
2949
2950 let table = Table::default()
2951 .rows(vec![Row::new(vec!["ABCDE", "12345"])])
2952 .widths([5, 5])
2953 .column_spacing(0);
2954 let area = Rect::new(0, 0, 15, 3);
2955 let mut buf = Buffer::empty(area);
2956 Widget::render(table, area, &mut buf);
2957 let expected = Buffer::with_lines([
2958 "ABCDE12345 ", " ", " ", ]);
2963 assert_eq!(buf, expected);
2964
2965 test_table_with_selection(
2967 HighlightSpacing::Never,
2968 15, 0, Some(0), [
2972 "ABCDE 12345 ", " ", " ", ],
2976 );
2977
2978 test_table_with_selection(
2980 HighlightSpacing::WhenSelected,
2981 15, 0, None, [
2985 "ABCDE 12345 ", " ", " ", ],
2989 );
2990 test_table_with_selection(
2992 HighlightSpacing::WhenSelected,
2993 15, 0, Some(0), [
2997 ">>>ABCDE 12345 ", " ", " ", ],
3001 );
3002
3003 test_table_with_selection(
3005 HighlightSpacing::Always,
3006 15, 0, None, [
3010 " ABCDE 12345 ", " ", " ", ],
3014 );
3015
3016 test_table_with_selection(
3018 HighlightSpacing::Always,
3019 15, 0, Some(0), [
3023 ">>>ABCDE 12345 ", " ", " ", ],
3027 );
3028 }
3029
3030 #[expect(clippy::too_many_lines)]
3031 #[test]
3032 fn insufficient_area_highlight_symbol_and_column_spacing_allocation() {
3033 test_table_with_selection(
3035 HighlightSpacing::Never,
3036 10, 1, None, [
3040 "ABCDE 1234", " ", " ", ],
3044 );
3045 test_table_with_selection(
3046 HighlightSpacing::WhenSelected,
3047 10, 1, None, [
3051 "ABCDE 1234", " ", " ", ],
3055 );
3056
3057 test_table_with_selection(
3066 HighlightSpacing::Always,
3067 10, 1, None, [
3071 " ABC 123", " ", " ", ],
3075 );
3076
3077 test_table_with_selection(
3079 HighlightSpacing::Always,
3080 9, 1, None, [
3084 " ABC 12", " ", " ", ],
3088 );
3089 test_table_with_selection(
3090 HighlightSpacing::Always,
3091 8, 1, None, [
3095 " AB 12", " ", " ", ],
3099 );
3100 test_table_with_selection(
3101 HighlightSpacing::Always,
3102 7, 1, None, [
3106 " AB 1", " ", " ", ],
3110 );
3111
3112 let table = Table::default()
3113 .rows(vec![Row::new(vec!["ABCDE", "12345"])])
3114 .highlight_spacing(HighlightSpacing::Always)
3115 .flex(Flex::Legacy)
3116 .highlight_symbol(">>>")
3117 .column_spacing(1);
3118 let area = Rect::new(0, 0, 10, 3);
3119 let mut buf = Buffer::empty(area);
3120 Widget::render(table, area, &mut buf);
3121 #[rustfmt::skip]
3123 let expected = Buffer::with_lines([
3124 " ABCDE 1",
3125 " ",
3126 " ",
3127 ]);
3128 assert_eq!(buf, expected);
3129
3130 let table = Table::default()
3131 .rows(vec![Row::new(vec!["ABCDE", "12345"])])
3132 .highlight_spacing(HighlightSpacing::Always)
3133 .flex(Flex::Start)
3134 .highlight_symbol(">>>")
3135 .column_spacing(1);
3136 let area = Rect::new(0, 0, 10, 3);
3137 let mut buf = Buffer::empty(area);
3138 Widget::render(table, area, &mut buf);
3139 #[rustfmt::skip]
3141 let expected = Buffer::with_lines([
3142 " ABC 123",
3143 " ",
3144 " ",
3145 ]);
3146 assert_eq!(buf, expected);
3147
3148 test_table_with_selection(
3149 HighlightSpacing::Never,
3150 10, 1, Some(0), [
3154 "ABCDE 1234", " ",
3156 " ",
3157 ],
3158 );
3159
3160 test_table_with_selection(
3161 HighlightSpacing::WhenSelected,
3162 10, 1, Some(0), [
3166 ">>>ABC 123", " ", " ", ],
3170 );
3171
3172 test_table_with_selection(
3173 HighlightSpacing::Always,
3174 10, 1, Some(0), [
3178 ">>>ABC 123", " ", " ", ],
3182 );
3183 }
3184
3185 #[test]
3186 fn insufficient_area_highlight_symbol_allocation_with_no_column_spacing() {
3187 test_table_with_selection(
3188 HighlightSpacing::Never,
3189 10, 0, None, [
3193 "ABCDE12345", " ", " ", ],
3197 );
3198 test_table_with_selection(
3199 HighlightSpacing::WhenSelected,
3200 10, 0, None, [
3204 "ABCDE12345", " ", " ", ],
3208 );
3209 test_table_with_selection(
3214 HighlightSpacing::Always,
3215 10, 0, None, [
3219 " ABCD123", " ", " ", ],
3223 );
3224 test_table_with_selection(
3225 HighlightSpacing::Never,
3226 10, 0, Some(0), [
3230 "ABCDE12345", " ", " ", ],
3234 );
3235 test_table_with_selection(
3236 HighlightSpacing::WhenSelected,
3237 10, 0, Some(0), [
3241 ">>>ABCD123", " ", " ", ],
3245 );
3246 test_table_with_selection(
3247 HighlightSpacing::Always,
3248 10, 0, Some(0), [
3252 ">>>ABCD123", " ", " ", ],
3256 );
3257 }
3258 }
3259
3260 #[test]
3261 fn stylize() {
3262 assert_eq!(
3263 Table::new(vec![Row::new(vec![Cell::from("")])], [Percentage(100)])
3264 .black()
3265 .on_white()
3266 .bold()
3267 .not_crossed_out()
3268 .style,
3269 Style::default()
3270 .fg(Color::Black)
3271 .bg(Color::White)
3272 .add_modifier(Modifier::BOLD)
3273 .remove_modifier(Modifier::CROSSED_OUT)
3274 );
3275 }
3276
3277 #[rstest]
3278 #[case::no_columns(vec![], vec![], vec![], 0)]
3279 #[case::only_header(vec!["H1", "H2"], vec![], vec![], 2)]
3280 #[case::only_rows(
3281 vec![],
3282 vec![vec!["C1", "C2"], vec!["C1", "C2", "C3"]],
3283 vec![],
3284 3
3285 )]
3286 #[case::only_footer(vec![], vec![], vec!["F1", "F2", "F3", "F4"], 4)]
3287 #[case::rows_longer(
3288 vec!["H1", "H2", "H3", "H4"],
3289 vec![vec!["C1", "C2"],vec!["C1", "C2", "C3"]],
3290 vec!["F1", "F2"],
3291 4
3292 )]
3293 #[case::rows_longer(
3294 vec!["H1", "H2"],
3295 vec![vec!["C1", "C2"], vec!["C1", "C2", "C3", "C4"]],
3296 vec!["F1", "F2"],
3297 4
3298 )]
3299 #[case::footer_longer(
3300 vec!["H1", "H2"],
3301 vec![vec!["C1", "C2"], vec!["C1", "C2", "C3"]],
3302 vec!["F1", "F2", "F3", "F4"],
3303 4
3304 )]
3305
3306 fn column_count(
3307 #[case] header: Vec<&str>,
3308 #[case] rows: Vec<Vec<&str>>,
3309 #[case] footer: Vec<&str>,
3310 #[case] expected: usize,
3311 ) {
3312 let header = Row::new(header);
3313 let footer = Row::new(footer);
3314 let rows: Vec<Row> = rows.into_iter().map(Row::new).collect();
3315 let table = Table::new(rows, Vec::<Constraint>::new())
3316 .header(header)
3317 .footer(footer);
3318 let column_count = table.column_count();
3319 assert_eq!(column_count, expected);
3320 }
3321
3322 #[test]
3323 fn render_in_minimal_buffer() {
3324 let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 1));
3325 let rows = vec![
3326 Row::new(vec!["Cell1", "Cell2", "Cell3"]),
3327 Row::new(vec!["Cell4", "Cell5", "Cell6"]),
3328 ];
3329 let table = Table::new(rows, [Constraint::Length(10); 3])
3330 .header(Row::new(vec!["Header1", "Header2", "Header3"]))
3331 .footer(Row::new(vec!["Footer1", "Footer2", "Footer3"]));
3332 Widget::render(table, buffer.area, &mut buffer);
3334 assert_eq!(buffer, Buffer::with_lines([" "]));
3335 }
3336
3337 #[test]
3338 fn render_in_zero_size_buffer() {
3339 let mut buffer = Buffer::empty(Rect::ZERO);
3340 let rows = vec![
3341 Row::new(vec!["Cell1", "Cell2", "Cell3"]),
3342 Row::new(vec!["Cell4", "Cell5", "Cell6"]),
3343 ];
3344 let table = Table::new(rows, [Constraint::Length(10); 3])
3345 .header(Row::new(vec!["Header1", "Header2", "Header3"]))
3346 .footer(Row::new(vec!["Footer1", "Footer2", "Footer3"]));
3347 Widget::render(table, buffer.area, &mut buffer);
3349 }
3350
3351 #[test]
3352 fn get_area_for_column_span_one_no_more_columns() {
3353 let columns = [];
3354 let column_span = Table::get_cell_area(&mut columns.iter(), 1, 1);
3355 assert!(column_span.is_none());
3356 }
3357
3358 #[test]
3359 fn get_area_for_column_span_two_no_more_columns() {
3360 let columns = [];
3361 let column_span = Table::get_cell_area(&mut columns.iter(), 2, 1);
3362 assert!(column_span.is_none());
3363 }
3364
3365 #[rstest]
3366 #[case(&[Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}], 2, 5)]
3367 #[case(&[Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}], 2, 5,)]
3368 #[case(&[Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}], 1, 2)]
3369 #[case(&[Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}], 3, 5)]
3370 #[case(&[Rect{x: 3, width: 2, y: 0, height: 1}], 1, 2)]
3371 #[case(&[Rect{x: 3, width: 2, y: 0, height: 1}], 2, 2)]
3372 #[case(&[
3373 Rect{x: 3, width: 2, y: 0, height: 1},
3374 Rect{x: 3, width: 2, y: 0, height: 1},
3375 Rect{x: 3, width: 2, y: 0, height: 1},
3376 Rect{x: 3, width: 2, y: 0, height: 1},
3377 ], 3, 8)]
3378 #[case(&[
3379 Rect{x: 3, width: 2, y: 0, height: 1},
3380 Rect{x: 3, width: 2, y: 0, height: 1},
3381 Rect{x: 3, width: 2, y: 0, height: 1},
3382 ], 3, 8)]
3383 fn test_colspan_width_single_column_spacing(
3384 #[case] columns: &[Rect],
3385 #[case] column_span: u16,
3386 #[case] expected_column_width: u16,
3387 ) {
3388 let column_span = Table::get_cell_area(&mut columns.iter(), column_span, 1);
3389 assert!(column_span.is_some());
3390 assert_eq!(column_span.unwrap().width, expected_column_width);
3391 }
3392
3393 #[rstest]
3394 #[case(&[Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}, Rect{x: 3, width: 2, y: 0, height: 1}], 3, 10)]
3395 #[case(&[Rect{x: 3, width: 2, y: 0, height: 1}], 3, 2)]
3396 fn test_colspan_width_two_column_spacing(
3397 #[case] columns: &[Rect],
3398 #[case] column_span: u16,
3399 #[case] expected_column_width: u16,
3400 ) {
3401 let column_span = Table::get_cell_area(&mut columns.iter(), column_span, 2);
3402 assert!(column_span.is_some());
3403 assert_eq!(column_span.unwrap().width, expected_column_width);
3404 }
3405
3406 #[rstest]
3407 #[case(
3408 HighlightSpacing::Always,
3409 15, 1, None, [
3413 Cell::new("ABCDEFGHIJK").column_span(2),
3414 Cell::new("12345678901"),
3415 Cell::new("XYZXYZXYZXY"),
3416 ],
3417 [
3418 " ABCDEFGH 123",
3419 " ", " ", ])]
3422 #[case(
3423 HighlightSpacing::Always,
3424 15, 1, Some(0), [
3428 Cell::new("ABCDEFGHIJK").column_span(2),
3429 Cell::new("12345678901"),
3430 Cell::new("XYZXYZXYZXY"),
3431 ],
3432 [
3433 ">>>ABCDEFGH 123",
3434 " ", " ", ])]
3437 #[case(
3438 HighlightSpacing::WhenSelected,
3439 15, 1, None, [
3443 Cell::new("ABCDEFGHIJK").column_span(2),
3444 Cell::new("12345678901"),
3445 Cell::new("XYZXYZXYZXY"),
3446 ],
3447 [
3448 "ABCDEFGHIJ 1234",
3449 " ", " ", ])]
3452 #[case(
3453 HighlightSpacing::WhenSelected,
3454 15, 1, Some(0), [
3458 Cell::new("ABCDEFGHIJK").column_span(2),
3459 Cell::new("12345678901"),
3460 Cell::new("XYZXYZXYZXY"),
3461 ],
3462 [
3463 ">>>ABCDEFGH 123",
3464 " ", " ", ])]
3467 fn test_table_with_selection_and_column_spans<'line, 'cell, Lines, Cells>(
3468 #[case] highlight_spacing: HighlightSpacing,
3469 #[case] columns: u16,
3470 #[case] spacing: u16,
3471 #[case] selection: Option<usize>,
3472 #[case] cells: Cells,
3473 #[case] expected: Lines,
3474 ) where
3475 Cells: IntoIterator,
3476 Cells::Item: Into<Cell<'cell>>,
3477 Lines: IntoIterator,
3478 Lines::Item: Into<Line<'line>>,
3479 {
3480 let table = Table::default()
3481 .rows(vec![Row::new(cells)])
3482 .highlight_spacing(highlight_spacing)
3483 .highlight_symbol(">>>")
3484 .column_spacing(spacing);
3485 let area = Rect::new(0, 0, columns, 3);
3486 let mut buf = Buffer::empty(area);
3487 let mut state = TableState::default().with_selected(selection);
3488 StatefulWidget::render(table, area, &mut buf, &mut state);
3489 assert_eq!(buf, Buffer::with_lines(expected));
3490 }
3491}