1use std::fmt;
9use std::rc::Rc;
10
11use unicode_segmentation::UnicodeSegmentation;
12
13use super::model::TableModel;
14use crate::text;
15use crate::validate::Validator;
16
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
19pub enum Align {
20 #[default]
22 Left,
23 Right,
25}
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum SortDir {
30 Asc,
32 Desc,
34}
35
36impl SortDir {
37 pub fn flip(self) -> SortDir {
39 match self {
40 SortDir::Asc => SortDir::Desc,
41 SortDir::Desc => SortDir::Asc,
42 }
43 }
44
45 pub fn marker(self) -> char {
47 match self {
48 SortDir::Asc => '▲',
49 SortDir::Desc => '▼',
50 }
51 }
52}
53
54#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
60pub enum Separators {
61 #[default]
65 Off,
66 Header,
71 All,
75}
76
77impl Separators {
78 pub(crate) fn header_char(self, rule: char) -> char {
81 match self {
82 Separators::Off => ' ',
83 Separators::Header | Separators::All => rule,
84 }
85 }
86
87 pub(crate) fn row_char(self, rule: char) -> char {
90 match self {
91 Separators::All => rule,
92 Separators::Off | Separators::Header => ' ',
93 }
94 }
95}
96
97#[derive(Clone, Debug, PartialEq, Eq)]
99pub struct ColumnSpec {
100 pub label: String,
102 pub width: i32,
104 pub min_width: i32,
106 pub align: Align,
108 pub hidden: bool,
110 pub flex: u16,
114 pub resizable: bool,
117 pub movable: bool,
119 pub fixed: bool,
123 pub editable: bool,
126 pub validator: Option<ValidatorFactory>,
129}
130
131#[derive(Clone)]
135pub struct ValidatorFactory(Rc<dyn Fn() -> Box<dyn Validator>>);
136
137impl ValidatorFactory {
138 pub fn new(make: Box<dyn Fn() -> Box<dyn Validator>>) -> Self {
140 ValidatorFactory(Rc::from(make))
141 }
142
143 pub fn make(&self) -> Box<dyn Validator> {
145 (self.0)()
146 }
147}
148
149impl fmt::Debug for ValidatorFactory {
150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151 f.write_str("ValidatorFactory")
152 }
153}
154
155impl PartialEq for ValidatorFactory {
156 fn eq(&self, other: &Self) -> bool {
157 Rc::ptr_eq(&self.0, &other.0)
158 }
159}
160
161impl Eq for ValidatorFactory {}
162
163impl ColumnSpec {
164 pub fn new(label: impl Into<String>, width: i32) -> Self {
166 ColumnSpec {
167 label: label.into(),
168 width,
169 min_width: 1,
170 align: Align::Left,
171 hidden: false,
172 flex: 0,
173 resizable: true,
174 movable: true,
175 fixed: false,
176 editable: false,
177 validator: None,
178 }
179 }
180
181 pub fn min_width(mut self, min_width: i32) -> Self {
183 self.min_width = min_width;
184 self
185 }
186
187 pub fn right(mut self) -> Self {
189 self.align = Align::Right;
190 self
191 }
192
193 pub fn align(mut self, align: Align) -> Self {
195 self.align = align;
196 self
197 }
198
199 pub fn hidden(mut self, hidden: bool) -> Self {
201 self.hidden = hidden;
202 self
203 }
204
205 pub fn flex(mut self, weight: u16) -> Self {
210 self.flex = weight;
211 self
212 }
213
214 pub fn resizable(mut self, resizable: bool) -> Self {
217 self.resizable = resizable;
218 self
219 }
220
221 pub fn movable(mut self, movable: bool) -> Self {
224 self.movable = movable;
225 self
226 }
227
228 pub fn fixed(mut self, fixed: bool) -> Self {
231 self.fixed = fixed;
232 self
233 }
234
235 pub fn editable(mut self, editable: bool) -> Self {
238 self.editable = editable;
239 self
240 }
241
242 pub fn validator(mut self, make: Box<dyn Fn() -> Box<dyn Validator>>) -> Self {
247 self.validator = Some(ValidatorFactory::new(make));
248 self
249 }
250}
251
252pub const MAX_COLUMN_WIDTH: i32 = 1024;
257
258pub const CHECK_WIDTH: i32 = 3;
261
262pub fn check_column() -> ColumnSpec {
265 ColumnSpec::new("", CHECK_WIDTH).min_width(CHECK_WIDTH)
266}
267
268pub fn with_check_cell(w0: i32, check: &str, rest: String, sep: char) -> String {
272 if w0 <= 0 {
273 return rest;
274 }
275 let cell = pad_cell(check, w0, Align::Left);
276 if rest.is_empty() {
277 cell
278 } else {
279 format!("{cell}{sep}{rest}")
280 }
281}
282
283pub fn layout_widths(cols: &[ColumnSpec], avail: i32) -> Vec<i32> {
295 let mut widths: Vec<i32> = cols.iter().map(preferred_width).collect();
296 let visible = widths.iter().filter(|&&w| w > 0).count() as i32;
299 if visible == 0 || avail <= 0 {
300 return vec![0; cols.len()];
301 }
302 let budget = avail - (visible - 1);
305 let over = sum_widths(&widths).saturating_sub(budget);
306 if over > 0 {
307 shrink(cols, &mut widths, over);
308 } else if over < 0 {
309 stretch(cols, &mut widths, -over);
310 }
311 widths
312}
313
314fn shrink(cols: &[ColumnSpec], widths: &mut [i32], over: i32) {
324 let floors: Vec<i32> = cols.iter().map(shrink_floor).collect();
325 let shrinkable = |i: usize| !cols[i].hidden;
326 let cut = |widths: &[i32], level: i32| -> i64 {
329 (0..widths.len())
330 .filter(|&i| shrinkable(i))
331 .map(|i| i64::from((widths[i] - floors[i].max(level)).max(0)))
332 .sum()
333 };
334 let over = i64::from(over);
335 if over >= cut(widths, 1) {
339 for i in (0..widths.len()).filter(|&i| shrinkable(i)) {
340 widths[i] = widths[i].min(floors[i]);
341 }
342 return;
343 }
344 let (mut lo, mut hi) = (2, widths.iter().copied().max().unwrap_or(1).max(2));
347 while lo < hi {
348 let mid = lo + (hi - lo) / 2;
349 if cut(widths, mid) <= over {
350 hi = mid;
351 } else {
352 lo = mid + 1;
353 }
354 }
355 let level = lo;
356 let mut rest = over - cut(widths, level);
357 for i in (0..widths.len()).filter(|&i| shrinkable(i)) {
358 widths[i] = widths[i].min(floors[i].max(level));
359 }
360 for i in (0..widths.len()).rev() {
363 if rest == 0 {
364 break;
365 }
366 if shrinkable(i) && widths[i] == level && floors[i] < level {
367 widths[i] -= 1;
368 rest -= 1;
369 }
370 }
371}
372
373fn preferred_width(c: &ColumnSpec) -> i32 {
377 let w = match () {
378 _ if c.hidden => 0,
379 _ if c.flex > 0 => c.width.max(c.min_width).max(1),
380 _ => c.width.max(0),
381 };
382 w.min(MAX_COLUMN_WIDTH)
383}
384
385fn shrink_floor(c: &ColumnSpec) -> i32 {
388 let floor = c.min_width.max(1);
389 if c.fixed {
390 floor.max(c.width.min(MAX_COLUMN_WIDTH))
391 } else {
392 floor
393 }
394}
395
396fn sum_widths(widths: &[i32]) -> i32 {
398 widths
399 .iter()
400 .filter(|&&w| w > 0)
401 .fold(0i32, |acc, &w| acc.saturating_add(w))
402}
403
404pub fn stretch(cols: &[ColumnSpec], widths: &mut [i32], spare: i32) {
409 let flex: Vec<usize> = (0..cols.len())
410 .filter(|&i| !cols[i].hidden && cols[i].flex > 0 && widths[i] > 0)
411 .collect();
412 let total: i64 = flex.iter().map(|&i| i64::from(cols[i].flex)).sum();
413 if total == 0 || spare <= 0 {
414 return;
415 }
416 let mut left = spare;
417 for &i in &flex {
418 let share = (i64::from(spare) * i64::from(cols[i].flex) / total) as i32;
419 widths[i] += share;
420 left -= share;
421 }
422 for &i in flex.iter().take(left as usize) {
424 widths[i] += 1;
425 }
426}
427
428pub fn line_width(widths: &[i32]) -> i32 {
431 let shown = widths.iter().filter(|&&w| w > 0).count() as i32;
432 sum_widths(widths).saturating_add((shown - 1).max(0))
433}
434
435#[derive(Clone, Debug, PartialEq, Eq)]
438pub struct RowLayout {
439 pub widths: Vec<i32>,
441 pub frozen: usize,
443 pub frozen_width: i32,
445 pub content: i32,
447 pub view: i32,
449}
450
451impl RowLayout {
452 pub fn new(cols: &[ColumnSpec], frozen: usize, avail: i32) -> Self {
454 let widths = layout_widths(cols, avail);
455 let frozen = frozen.min(widths.len());
456 let content = line_width(&widths[frozen..]);
457 let mut frozen_width = line_width(&widths[..frozen]);
458 if frozen_width > 0 && content > 0 {
459 frozen_width = frozen_width.saturating_add(1);
460 }
461 RowLayout {
462 view: (avail.max(0) - frozen_width).max(0),
463 widths,
464 frozen,
465 frozen_width,
466 content,
467 }
468 }
469
470 pub fn max_offset(&self) -> i32 {
474 if self.view <= 0 {
475 return 0;
476 }
477 (self.content - self.view).max(0)
478 }
479
480 pub fn clamp(&self, offset: i32) -> i32 {
482 offset.clamp(0, self.max_offset())
483 }
484
485 pub fn compose(&self, frozen: &str, rest: &str, offset: i32, sep: char) -> String {
490 let shown = slice_cols(rest, self.clamp(offset), self.view);
491 match self.frozen {
492 0 => shown,
493 _ => with_check_cell(self.widths[0], frozen, shown, sep),
494 }
495 }
496
497 pub fn column_at(&self, x: i32, offset: i32) -> Option<usize> {
500 if x < 0 {
501 return None;
502 }
503 if x < self.frozen_width {
504 return column_at(&self.widths[..self.frozen], x);
505 }
506 let sx = x - self.frozen_width;
507 if sx >= self.view {
508 return None;
509 }
510 column_at(
511 &self.widths[self.frozen..],
512 sx.saturating_add(self.clamp(offset)),
513 )
514 .map(|c| c + self.frozen)
515 }
516
517 pub fn spans(&self) -> Vec<(usize, i32, i32)> {
520 let mut out = Vec::new();
521 let mut start = 0i32;
522 for (i, &w) in self.widths.iter().enumerate().skip(self.frozen) {
523 if w <= 0 {
524 continue;
525 }
526 let end = start.saturating_add(w);
527 out.push((i, start, end));
528 start = end.saturating_add(1);
529 }
530 out
531 }
532
533 pub fn content_x(&self, x: i32, offset: i32) -> Option<i32> {
536 let sx = x - self.frozen_width;
537 (0..self.view)
538 .contains(&sx)
539 .then(|| sx.saturating_add(self.clamp(offset)))
540 }
541
542 pub fn text_x(&self, cx: i32, offset: i32) -> i32 {
545 self.frozen_width
546 .saturating_add(cx)
547 .saturating_sub(self.clamp(offset))
548 }
549
550 pub fn separator_at(&self, x: i32, offset: i32) -> Option<usize> {
556 let cx = self.content_x(x, offset)?;
557 let spans = self.spans();
558 if let Some(&(i, _, _)) = spans.iter().find(|&&(_, _, end)| end == cx) {
559 return Some(i);
560 }
561 let &(last, _, end) = spans.last()?;
562 let on_last_cell = x - self.frozen_width == self.view - 1;
563 (on_last_cell && end == cx + 1).then_some(last)
564 }
565}
566
567pub fn slice_cols(s: &str, skip: i32, width: i32) -> String {
571 let (skip, end) = (
572 skip.max(0) as usize,
573 skip.max(0).saturating_add(width.max(0)) as usize,
574 );
575 let mut out = String::new();
576 let mut col = 0;
577 for g in s.graphemes(true) {
578 if col >= end {
579 break;
580 }
581 let gw = text::width(g);
582 let next = col + gw;
583 if col >= skip && next <= end {
584 out.push_str(g);
585 } else if next > skip {
586 out.push_str(&" ".repeat(next.min(end) - col.max(skip)));
588 }
589 col = next;
590 }
591 out
592}
593
594pub fn pad_cell(cell: &str, width: i32, align: Align) -> String {
598 let width = width.max(0) as usize;
599 if width == 0 {
600 return String::new();
601 }
602 let len = text::width(cell);
603 if len <= width {
604 let pad = " ".repeat(width - len);
605 return match align {
606 Align::Left => format!("{cell}{pad}"),
607 Align::Right => format!("{pad}{cell}"),
608 };
609 }
610 let mut head = String::new();
614 let mut used = 0;
615 for g in cell.graphemes(true) {
616 let gw = text::width(g);
617 if used + gw > width - 1 {
618 break;
619 }
620 head.push_str(g);
621 used += gw;
622 }
623 format!("{head}…{}", " ".repeat(width - 1 - used))
624}
625
626fn join_cells<'a>(
628 widths: &[i32],
629 cells: impl Iterator<Item = (usize, String)> + 'a,
630 sep: char,
631) -> String {
632 let mut line = String::new();
633 for (i, cell) in cells {
634 if widths.get(i).copied().unwrap_or(0) <= 0 {
635 continue;
636 }
637 if !line.is_empty() {
638 line.push(sep);
639 }
640 line.push_str(&cell);
641 }
642 line
643}
644
645pub fn format_line(
648 model: &dyn TableModel,
649 row: usize,
650 widths: &[i32],
651 cols: &[ColumnSpec],
652 sep: char,
653) -> String {
654 join_cells(
655 widths,
656 cols.iter().enumerate().map(|(i, c)| {
657 let w = widths.get(i).copied().unwrap_or(0);
658 (i, pad_cell(&model.cell(row, i), w, c.align))
659 }),
660 sep,
661 )
662}
663
664pub fn header_line(
668 cols: &[ColumnSpec],
669 widths: &[i32],
670 sort: Option<(usize, SortDir)>,
671 sep: char,
672) -> String {
673 join_cells(
674 widths,
675 cols.iter().enumerate().map(|(i, c)| {
676 let w = widths.get(i).copied().unwrap_or(0);
677 let cell = match sort {
678 Some((s, dir)) if s == i => {
679 let m = dir.marker();
680 let full = format!("{} {m}", c.label);
681 if text::width(&full) as i32 <= w {
682 pad_cell(&full, w, c.align)
683 } else if w >= 2 {
684 format!("{} {m}", pad_cell(&c.label, w - 2, Align::Left))
685 } else {
686 m.to_string()
687 }
688 }
689 _ => pad_cell(&c.label, w, c.align),
690 };
691 (i, cell)
692 }),
693 sep,
694 )
695}
696
697pub fn column_at(widths: &[i32], x: i32) -> Option<usize> {
700 let mut start = 0;
701 for (i, &w) in widths.iter().enumerate() {
702 if w <= 0 {
703 continue;
704 }
705 if x >= start && x < start.saturating_add(w) {
706 return Some(i);
707 }
708 start = start.saturating_add(w).saturating_add(1);
709 }
710 None
711}
712
713pub fn sort_order(model: &dyn TableModel, col: usize, dir: SortDir) -> Vec<usize> {
717 let keys: Vec<_> = (0..model.row_count())
718 .map(|r| model.sort_key(r, col))
719 .collect();
720 let mut order: Vec<usize> = (0..keys.len()).collect();
721 order.sort_by(|&a, &b| {
722 let ord = keys[a].compare(&keys[b]);
723 match dir {
725 SortDir::Desc if keys[a].same_kind(&keys[b]) => ord.reverse(),
726 _ => ord,
727 }
728 });
729 order
730}
731
732#[cfg(test)]
733mod tests {
734 use super::*;
735 use crate::widgets::table::model::{RowKey, SortKey, VecModel};
736 use std::borrow::Cow;
737
738 const RULE: char = '│';
742
743 fn col(label: &str, width: i32) -> ColumnSpec {
744 ColumnSpec::new(label, width)
745 }
746
747 fn model(rows: &[&[&str]]) -> VecModel {
748 VecModel::new(
749 rows.iter()
750 .map(|r| r.iter().map(|s| s.to_string()).collect())
751 .collect(),
752 )
753 }
754
755 #[test]
756 fn layout_widths_shrink_widest_until_it_fits() {
757 let w = layout_widths(&[col("A", 40), col("B", 20)], 30);
759 assert_eq!(w, vec![15, 14]);
760 assert_eq!(w.iter().sum::<i32>() + 1, 30, "total + separator == avail");
761 assert_eq!(layout_widths(&[col("A", 5), col("B", 5)], 30), vec![5, 5]);
763 }
764
765 #[test]
766 fn layout_widths_respects_min_width() {
767 let w = layout_widths(&[col("A", 10).min_width(8), col("B", 10)], 12);
769 assert_eq!(w, vec![8, 3]);
770 let w = layout_widths(&[col("A", 10).min_width(10), col("B", 3).min_width(3)], 8);
772 assert_eq!(w, vec![10, 3]);
773 }
774
775 #[test]
776 fn layout_widths_nonpositive_avail_yields_zeros() {
777 assert_eq!(layout_widths(&[col("A", 40)], 0), vec![0]);
778 assert_eq!(layout_widths(&[col("A", 4), col("B", 4)], -3), vec![0, 0]);
779 }
780
781 #[test]
782 fn layout_widths_without_room_for_the_separators_keeps_the_floors() {
783 assert_eq!(layout_widths(&[col("A", 4), col("B", 4)], 1), vec![1, 1]);
786 let cols = [
789 check_column(),
790 col("ID", 4),
791 col("NAME", 10),
792 col("STATE", 8),
793 col("CPU", 5),
794 ];
795 assert_eq!(layout_widths(&cols, 4), vec![3, 1, 1, 1, 1]);
796 assert_eq!(layout_widths(&cols, 1), vec![3, 1, 1, 1, 1]);
797 let cols = [
799 col("A", 6).min_width(2),
800 col("H", 5).hidden(true),
801 col("F", 4).fixed(true),
802 ];
803 assert_eq!(layout_widths(&cols, 1), vec![2, 0, 4]);
804 let l = RowLayout::new(&cols, 0, 1);
805 assert_eq!((l.content, l.view, l.max_offset()), (7, 1, 6));
806 }
807
808 #[test]
809 fn layout_widths_with_no_visible_column_yields_zeros() {
810 let cols = [col("A", 4).hidden(true), col("B", 0)];
811 assert_eq!(layout_widths(&cols, 1), vec![0, 0]);
812 assert_eq!(layout_widths(&cols, 10), vec![0, 0]);
813 }
814
815 #[test]
816 fn hidden_columns_take_no_width_and_no_separator() {
817 let cols = [col("A", 10), col("B", 12).hidden(true), col("C", 8)];
818 assert_eq!(layout_widths(&cols, 19), vec![10, 0, 8]);
820 let m = model(&[&["a", "b", "c"]]);
821 let line = format_line(&m, 0, &[10, 0, 8], &cols, ' ');
822 assert_eq!(line, "a c ");
823 assert_eq!(text::width(&line), 19);
824 assert!(layout_widths(&[col("A", 3).hidden(true)], 10) == vec![0]);
825 }
826
827 #[test]
828 fn pad_cell_uses_ellipsis_truncation() {
829 assert_eq!(pad_cell("abc", 0, Align::Left), "");
830 assert_eq!(pad_cell("abc", 1, Align::Left), "…");
831 assert_eq!(pad_cell("abc", 2, Align::Left), "a…");
832 assert_eq!(pad_cell("abc", 3, Align::Left), "abc", "exact fit");
833 assert_eq!(pad_cell("abc", 5, Align::Left), "abc ");
834 assert_eq!(pad_cell("abc", 5, Align::Right), " abc");
835 assert_eq!(
836 pad_cell("abcdef", 4, Align::Right),
837 "abc…",
838 "tail cut keeps ellipsis at the cut"
839 );
840 assert_eq!(pad_cell("ééé", 2, Align::Left), "é…");
841 }
842
843 #[test]
844 fn pad_cell_measures_display_columns() {
845 assert_eq!(pad_cell("日本語", 6, Align::Left), "日本語");
847 assert_eq!(pad_cell("日本語テキスト", 5, Align::Left), "日本…");
848 assert_eq!(pad_cell("日本語テキスト", 4, Align::Left), "日… ");
849 assert_eq!(text::width(&pad_cell("日本語テキスト", 4, Align::Left)), 4);
850 }
851
852 #[test]
853 fn format_line_pads_and_truncates_to_the_cell() {
854 let cols = [col("C1", 5), col("C2", 8), col("C3", 6)];
855 let m = model(&[&["c1", "very-long-name-here", "running"]]);
856 assert_eq!(
857 format_line(&m, 0, &[4, 7, 5], &cols, ' '),
858 "c1 very-l… runn…"
859 );
860 let cols = [col("N", 3).right()];
861 assert_eq!(format_line(&model(&[&["7"]]), 0, &[3], &cols, ' '), " 7");
862 }
863
864 #[test]
865 fn header_line_marks_sort_direction() {
866 let cols = [col("ID", 10), col("NAME", 12), col("STATE", 8)];
867 let widths = [10, 12, 8];
868 assert!(header_line(&cols, &widths, Some((1, SortDir::Asc)), ' ').contains("NAME ▲"));
869 assert!(header_line(&cols, &widths, Some((1, SortDir::Desc)), ' ').contains("NAME ▼"));
870 assert!(!header_line(&cols, &widths, None, ' ').contains('▲'));
871 }
872
873 #[test]
874 fn header_line_keeps_the_marker_when_the_label_is_cut() {
875 let cols = [col("STATUS", 5)];
876 assert_eq!(
877 header_line(&cols, &[5], Some((0, SortDir::Asc)), ' '),
878 "ST… ▲"
879 );
880 assert_eq!(header_line(&cols, &[1], Some((0, SortDir::Desc)), ' '), "▼");
881 assert_eq!(header_line(&cols, &[5], None, ' '), "STAT…");
882 }
883
884 #[test]
885 fn column_at_maps_x_to_columns_and_skips_separators() {
886 let widths = [3, 0, 4];
887 assert_eq!(column_at(&widths, 0), Some(0));
888 assert_eq!(column_at(&widths, 2), Some(0));
889 assert_eq!(column_at(&widths, 3), None, "separator");
890 assert_eq!(column_at(&widths, 4), Some(2), "hidden column skipped");
891 assert_eq!(column_at(&widths, 7), Some(2));
892 assert_eq!(column_at(&widths, 8), None, "past the end");
893 assert_eq!(column_at(&widths, -1), None);
894 }
895
896 #[test]
897 fn sort_order_orders_strings_and_is_stable_for_ties() {
898 let m = model(&[&["1", "b"], &["2", "a"], &["3", "b"]]);
899 assert_eq!(sort_order(&m, 1, SortDir::Asc), [1, 0, 2]);
900 assert_eq!(
901 sort_order(&m, 1, SortDir::Desc),
902 [0, 2, 1],
903 "ties keep model order in both directions"
904 );
905 }
906
907 #[test]
908 fn sort_order_compares_numbers_numerically() {
909 let m = model(&[&["9.9"], &["10.2"], &["1.5"]]);
910 assert_eq!(
911 sort_order(&m, 0, SortDir::Asc),
912 [2, 0, 1],
913 "numeric: 1.5 < 9.9 < 10.2 — string order would say 1.5 < 10.2 < 9.9"
914 );
915 assert_eq!(sort_order(&m, 0, SortDir::Desc), [1, 0, 2]);
916 }
917
918 #[test]
919 fn numbers_sort_before_text_in_both_directions() {
920 let m = model(&[&["n/a"], &["10"], &["9"], &["abc"]]);
921 assert_eq!(sort_order(&m, 0, SortDir::Asc), [2, 1, 3, 0]);
922 assert_eq!(
923 sort_order(&m, 0, SortDir::Desc),
924 [1, 2, 0, 3],
925 "descending reverses within each kind, numbers still first"
926 );
927 }
928
929 #[test]
930 fn check_column_is_fixed_on_a_narrow_table() {
931 let cols = [check_column(), col("A", 10), col("B", 10)];
933 let w = layout_widths(&cols, 12);
934 assert_eq!(w, vec![3, 4, 3], "the check column never shrinks");
935 let m = model(&[&["alpha", "beta"]]);
936 let line = with_check_cell(
937 w[0],
938 "[X]",
939 format_line(&m, 0, &w[1..], &cols[1..], ' '),
940 ' ',
941 );
942 assert_eq!(line, "[X] alp… be…");
943 assert_eq!(text::width(&line), 12, "fills avail exactly");
944 assert_eq!(with_check_cell(0, "[X]", "rest".into(), ' '), "rest");
945 assert_eq!(with_check_cell(3, "[ ]", String::new(), ' '), "[ ]");
946 }
947
948 #[test]
949 fn flex_columns_take_the_spare_width_by_weight() {
950 let cols = [col("A", 5).flex(2), col("B", 5), col("C", 5).flex(1)];
952 let w = layout_widths(&cols, 30);
953 assert_eq!(w, vec![5 + 8 + 1, 5, 5 + 4]);
955 assert_eq!(line_width(&w), 30, "fills avail exactly");
956 }
957
958 #[test]
959 fn flex_remainder_goes_one_cell_each_to_the_leftmost() {
960 let cols = [
962 col("A", 1).flex(1),
963 col("B", 1).flex(1),
964 col("C", 1).flex(1),
965 ];
966 assert_eq!(layout_widths(&cols, 10), vec![3, 3, 2]);
967 }
968
969 #[test]
970 fn without_flex_the_spare_stays_empty_and_hidden_flex_gets_none() {
971 assert_eq!(layout_widths(&[col("A", 5), col("B", 5)], 30), vec![5, 5]);
972 let cols = [col("A", 5).flex(1).hidden(true), col("B", 5)];
973 assert_eq!(layout_widths(&cols, 30), vec![0, 5]);
974 let cols = [col("A", 5).flex(1), col("B", 5)];
975 assert_eq!(
976 layout_widths(&cols, 8),
977 vec![4, 3],
978 "no spare: flex columns shrink like the others"
979 );
980 }
981
982 #[test]
983 fn a_zero_width_flex_column_fills_the_rest() {
984 let cols = [col("A", 5), col("X", 0).flex(1)];
986 assert_eq!(layout_widths(&cols, 20), vec![5, 14]);
987 assert_eq!(layout_widths(&cols, 7), vec![5, 1]);
989 }
990
991 #[test]
992 fn huge_widths_are_capped_and_sums_saturate() {
993 let big = i32::MAX / 2;
994 let cols = [col("A", big).min_width(big), col("B", big).min_width(big)];
995 let w = layout_widths(&cols, 10);
996 let max = MAX_COLUMN_WIDTH;
998 assert_eq!(w, vec![max, max], "nothing may shrink below the cap");
999 let flex = [col("F", big).min_width(big).flex(1)];
1000 assert_eq!(layout_widths(&flex, 10), vec![max]);
1001 let l = RowLayout::new(&cols, 0, 10);
1002 assert_eq!((l.content, l.view), (2 * max + 1, 10));
1003 assert_eq!(l.column_at(3, l.max_offset()), Some(1));
1004 assert_eq!(line_width(&[big, big]), i32::MAX);
1006 assert_eq!(column_at(&[big, big], i32::MAX - 1), Some(1));
1007 assert_eq!(slice_cols("abc", i32::MAX - 1, 10), "");
1008 }
1009
1010 #[test]
1011 fn row_layout_overflows_only_past_min_width() {
1012 let cols = [col("A", 10).min_width(8), col("B", 10).min_width(8)];
1013 let l = RowLayout::new(&cols, 0, 17);
1015 assert_eq!((l.content, l.view, l.max_offset()), (17, 17, 0));
1016 let l = RowLayout::new(&cols, 0, 12);
1018 assert_eq!((l.content, l.view, l.max_offset()), (17, 12, 5));
1019 assert_eq!(l.clamp(-3), 0);
1020 assert_eq!(l.clamp(3), 3);
1021 assert_eq!(l.clamp(99), 5, "the offset clamps to the overflow");
1022 }
1023
1024 #[test]
1025 fn row_layout_keeps_the_frozen_column_out_of_the_scroll() {
1026 let cols = [
1027 check_column(),
1028 col("A", 6).min_width(6),
1029 col("B", 6).min_width(6),
1030 ];
1031 let l = RowLayout::new(&cols, 1, 16);
1033 assert_eq!((l.frozen_width, l.content, l.view), (4, 13, 12));
1034 assert_eq!(l.max_offset(), 1);
1035 let rest = "aaaaaa bbbbbb";
1036 assert_eq!(l.compose("[X]", rest, 0, ' '), "[X] aaaaaa bbbbb");
1037 assert_eq!(l.compose("[X]", rest, 1, ' '), "[X] aaaaa bbbbbb");
1038 assert_eq!(
1039 l.compose("[X]", rest, 9, ' '),
1040 "[X] aaaaa bbbbbb",
1041 "clamped"
1042 );
1043 assert_eq!(l.compose("[X]", rest, 0, '│'), "[X]│aaaaaa bbbbb");
1045 assert_eq!(l.column_at(1, 1), Some(0));
1047 assert_eq!(l.column_at(3, 1), None, "frozen separator");
1048 assert_eq!(l.column_at(4, 0), Some(1));
1049 assert_eq!(l.column_at(9, 0), Some(1));
1050 assert_eq!(l.column_at(9, 1), None, "scrolled: now the separator");
1051 assert_eq!(l.column_at(10, 1), Some(2));
1052 assert_eq!(l.column_at(16, 1), None, "past the view");
1053 }
1054
1055 #[test]
1056 fn slice_cols_cuts_by_display_columns() {
1057 assert_eq!(slice_cols("abcdef", 2, 3), "cde");
1058 assert_eq!(slice_cols("abc", 1, 9), "bc");
1059 assert_eq!(slice_cols("abc", 5, 2), "");
1060 assert_eq!(slice_cols("日本語", 1, 4), " 本 ");
1062 assert_eq!(slice_cols("日本語", 2, 4), "本語");
1063 }
1064
1065 #[test]
1066 fn zero_width_visible_columns_get_no_separator() {
1067 let cols = [col("A", 5), col("B", 0), col("C", 5)];
1069 assert_eq!(layout_widths(&cols, 11), vec![5, 0, 5]);
1070 let m = model(&[&["a", "b", "c"]]);
1071 assert_eq!(text::width(&format_line(&m, 0, &[5, 0, 5], &cols, ' ')), 11);
1072 }
1073
1074 #[test]
1075 fn separators_choose_the_join_glyph_without_shifting_the_layout() {
1076 let cols = [col("ID", 4), col("NAME", 8), col("STATE", 6)];
1077 let widths = [4, 8, 6];
1078 let m = model(&[&["a1", "web", "running"]]);
1079
1080 assert_eq!(
1082 header_line(&cols, &widths, None, Separators::Off.header_char(RULE)),
1083 "ID NAME STATE "
1084 );
1085 assert_eq!(
1086 format_line(&m, 0, &widths, &cols, Separators::Off.row_char(RULE)),
1087 "a1 web runni…"
1088 );
1089
1090 assert_eq!(
1092 header_line(&cols, &widths, None, Separators::Header.header_char(RULE)),
1093 "ID │NAME │STATE "
1094 );
1095 assert_eq!(
1096 format_line(&m, 0, &widths, &cols, Separators::Header.row_char(RULE)),
1097 "a1 web runni…",
1098 "rows keep the blank separator"
1099 );
1100
1101 assert_eq!(
1103 header_line(&cols, &widths, None, Separators::All.header_char(RULE)),
1104 "ID │NAME │STATE "
1105 );
1106 assert_eq!(
1107 format_line(&m, 0, &widths, &cols, Separators::All.row_char(RULE)),
1108 "a1 │web │runni…"
1109 );
1110
1111 for sep in [Separators::Off, Separators::Header, Separators::All] {
1113 let head = header_line(&cols, &widths, None, sep.header_char(RULE));
1114 let row = format_line(&m, 0, &widths, &cols, sep.row_char(RULE));
1115 assert_eq!(text::width(&head) as i32, line_width(&widths));
1116 assert_eq!(text::width(&row) as i32, line_width(&widths));
1117 }
1118 }
1119
1120 #[test]
1121 fn separator_rules_take_the_glyph_from_the_theme() {
1122 const DOUBLE: char = '║';
1126 assert_eq!(Separators::Header.header_char(DOUBLE), DOUBLE);
1127 assert_eq!(Separators::All.header_char(DOUBLE), DOUBLE);
1128 assert_eq!(Separators::All.row_char(DOUBLE), DOUBLE);
1129 assert_eq!(Separators::Off.header_char(DOUBLE), ' ');
1130 assert_eq!(Separators::Header.row_char(DOUBLE), ' ', "rows stay blank");
1131 }
1132
1133 #[test]
1134 fn the_separator_rule_lands_on_the_resize_handle_cell() {
1135 let cols = [col("A", 4), col("B", 4)];
1138 let l = RowLayout::new(&cols, 0, 9);
1139 assert_eq!(l.widths, vec![4, 4]);
1140 let head = header_line(&cols, &l.widths, None, Separators::Header.header_char(RULE));
1141 assert_eq!(head.chars().nth(4), Some(RULE));
1142 assert_eq!(l.separator_at(4, 0), Some(0));
1143 let row = format_line(
1144 &model(&[&["a", "b"]]),
1145 0,
1146 &l.widths,
1147 &cols,
1148 Separators::All.row_char(RULE),
1149 );
1150 assert_eq!(row.chars().nth(4), Some(RULE));
1151 }
1152
1153 struct Percent(Vec<f64>);
1156
1157 impl TableModel for Percent {
1158 fn row_count(&self) -> usize {
1159 self.0.len()
1160 }
1161 fn cell(&self, row: usize, _col: usize) -> Cow<'_, str> {
1162 Cow::Owned(format!("{}%", self.0[row]))
1163 }
1164 fn row_key(&self, row: usize) -> RowKey {
1165 RowKey(row.to_string())
1166 }
1167 fn sort_key(&self, row: usize, _col: usize) -> SortKey {
1168 SortKey::Num(self.0[row])
1169 }
1170 }
1171
1172 #[test]
1173 fn sort_order_uses_the_model_sort_key() {
1174 let m = Percent(vec![9.9, 10.2, 1.5]);
1175 assert_eq!(sort_order(&m, 0, SortDir::Asc), [2, 0, 1]);
1176 }
1177
1178 #[test]
1179 fn nan_sort_keys_tie_and_stay_stable() {
1180 let m = Percent(vec![f64::NAN, f64::NAN]);
1181 assert_eq!(sort_order(&m, 0, SortDir::Asc), [0, 1]);
1182 }
1183
1184 fn layout_widths_reference(cols: &[ColumnSpec], avail: i32) -> Vec<i32> {
1188 let mut widths: Vec<i32> = cols.iter().map(preferred_width).collect();
1189 let visible = widths.iter().filter(|&&w| w > 0).count() as i32;
1190 if visible == 0 || avail <= 0 {
1191 return vec![0; cols.len()];
1192 }
1193 let budget = avail - (visible - 1);
1194 let mut over = sum_widths(&widths).saturating_sub(budget);
1195 while over > 0 {
1196 let widest = widths
1197 .iter()
1198 .enumerate()
1199 .filter(|(i, w)| !cols[*i].hidden && **w > shrink_floor(&cols[*i]))
1200 .max_by_key(|(_, w)| **w)
1201 .map(|(i, _)| i);
1202 let Some(i) = widest else { break };
1203 widths[i] -= 1;
1204 over -= 1;
1205 }
1206 if over < 0 {
1207 stretch(cols, &mut widths, -over);
1208 }
1209 widths
1210 }
1211
1212 #[test]
1213 fn level_shrink_matches_the_one_cell_loop() {
1214 let templates = [
1215 check_column(),
1216 col("a", 5),
1217 col("b", 9).min_width(3),
1218 col("c", 4).fixed(true),
1219 col("d", 0).flex(1),
1220 col("e", 6).flex(2).min_width(2),
1221 col("h", 7).hidden(true),
1222 col("z", 0),
1223 col("w", 2).min_width(5),
1224 col("t", 9),
1225 ];
1226 let n = templates.len();
1227 let mut checked = 0u32;
1228 for len in 0..=4u32 {
1230 for code in 0..n.pow(len) {
1231 let mut c = code;
1232 let cols: Vec<ColumnSpec> = (0..len)
1233 .map(|_| {
1234 let t = templates[c % n].clone();
1235 c /= n;
1236 t
1237 })
1238 .collect();
1239 for avail in -3..=60 {
1240 assert_eq!(
1241 layout_widths(&cols, avail),
1242 layout_widths_reference(&cols, avail),
1243 "avail {avail}, columns {:?}",
1244 cols.iter().map(|c| &c.label).collect::<Vec<_>>()
1245 );
1246 checked += 1;
1247 }
1248 }
1249 }
1250 assert_eq!(checked, 11_111 * 64);
1251 let wide = [
1253 col("p", 40),
1254 col("q", 40).min_width(30),
1255 col("r", 25),
1256 col("s", 40),
1257 col("u", 13).fixed(true),
1258 check_column(),
1259 ];
1260 for avail in -3..=200 {
1261 assert_eq!(
1262 layout_widths(&wide, avail),
1263 layout_widths_reference(&wide, avail),
1264 "avail {avail}"
1265 );
1266 }
1267 }
1268}