-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtable.rs
More file actions
1270 lines (1082 loc) · 38.4 KB
/
table.rs
File metadata and controls
1270 lines (1082 loc) · 38.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! ASCII Table Renderer
//!
//! Provides complete ASCII box-drawing table rendering with:
//! - Full box-drawing border characters
//! - Column alignment (left, center, right)
//! - Unicode-aware width calculation
//! - Automatic column width distribution
//! - Content truncation with ellipsis
//!
//! ## Example Output
//!
//! ```text
//! ┌──────────┬───────────┬─────────┐
//! │ Header 1 │ Header 2 │ Header 3│
//! ├──────────┼───────────┼─────────┤
//! │ Cell 1 │ Cell 2 │ Cell 3 │
//! │ Cell 4 │ Cell 5 │ Cell 6 │
//! └──────────┴───────────┴─────────┘
//! ```
//!
//! ## Usage
//!
//! ```rust,ignore
//! use cortex_engine::markdown::table::{TableBuilder, render_table, Alignment};
//! use ratatui::style::{Style, Color};
//!
//! let mut builder = TableBuilder::new();
//! builder.start_header();
//! builder.add_cell("Name".to_string());
//! builder.add_cell("Value".to_string());
//! builder.end_header();
//!
//! builder.start_row();
//! builder.add_cell("foo".to_string());
//! builder.add_cell("bar".to_string());
//! builder.end_row();
//!
//! builder.set_alignments(vec![Alignment::Left, Alignment::Right]);
//! let table = builder.build();
//!
//! let lines = render_table(
//! &table,
//! Color::Gray,
//! Style::default().fg(Color::White),
//! Style::default(),
//! 80,
//! );
//! ```
use ratatui::style::{Color, Style};
use ratatui::text::{Line, Span};
use unicode_width::UnicodeWidthStr;
// ============================================================
// BORDER CHARACTERS MODULE
// ============================================================
/// ASCII box-drawing border characters for table rendering.
pub mod border {
/// Top-left corner: ┌
pub const TOP_LEFT: char = '\u{250C}';
/// Top-right corner: ┐
pub const TOP_RIGHT: char = '\u{2510}';
/// Bottom-left corner: └
pub const BOTTOM_LEFT: char = '\u{2514}';
/// Bottom-right corner: ┘
pub const BOTTOM_RIGHT: char = '\u{2518}';
/// Horizontal line: ─
pub const HORIZONTAL: char = '\u{2500}';
/// Vertical line: │
pub const VERTICAL: char = '\u{2502}';
/// Cross intersection: ┼
pub const CROSS: char = '\u{253C}';
/// T-down (top tee): ┬
pub const T_DOWN: char = '\u{252C}';
/// T-up (bottom tee): ┴
pub const T_UP: char = '\u{2534}';
/// T-right (left tee): ├
pub const T_RIGHT: char = '\u{251C}';
/// T-left (right tee): ┤
pub const T_LEFT: char = '\u{2524}';
}
// ============================================================
// ALIGNMENT ENUM
// ============================================================
/// Alignment for table columns.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Alignment {
/// Left-align content (default)
#[default]
Left,
/// Center content
Center,
/// Right-align content
Right,
}
// ============================================================
// TABLE CELL
// ============================================================
/// A single table cell containing text content and optional styled spans.
#[derive(Debug, Clone)]
pub struct TableCell {
/// Raw text content of the cell
pub content: String,
/// Styled spans for rendering (if different from plain content)
pub spans: Vec<Span<'static>>,
}
impl TableCell {
/// Creates a new table cell with the given content.
///
/// The spans will be set to a single unstyled span containing the content.
pub fn new(content: impl Into<String>) -> Self {
let content = content.into();
let spans = vec![Span::raw(content.clone())];
Self { content, spans }
}
/// Creates a new table cell with pre-styled spans.
///
/// # Arguments
/// * `content` - The raw text content (used for width calculation)
/// * `spans` - Pre-styled spans for rendering
pub fn with_spans(content: String, spans: Vec<Span<'static>>) -> Self {
Self { content, spans }
}
/// Returns the display width of the cell content.
///
/// Uses unicode-width for proper handling of:
/// - Multi-byte UTF-8 characters
/// - Wide characters (CJK, emoji)
/// - Zero-width characters
#[inline]
pub fn width(&self) -> usize {
UnicodeWidthStr::width(self.content.as_str())
}
}
impl Default for TableCell {
fn default() -> Self {
Self::new("")
}
}
// ============================================================
// TABLE
// ============================================================
/// Minimum column width (excluding borders)
const MIN_COLUMN_WIDTH: usize = 3;
/// Padding on each side of cell content
const CELL_PADDING: usize = 1;
/// A complete table with headers, rows, alignments, and calculated widths.
#[derive(Debug, Clone)]
pub struct Table {
/// Header cells
pub headers: Vec<TableCell>,
/// Data rows (each row is a vector of cells)
pub rows: Vec<Vec<TableCell>>,
/// Column alignments
pub alignments: Vec<Alignment>,
/// Calculated column widths (content width, excluding borders/padding)
pub column_widths: Vec<usize>,
}
impl Table {
/// Creates a new table with the given headers, rows, and alignments.
///
/// Column widths are initialized to zero and should be calculated
/// using `calculate_column_widths` before rendering.
pub fn new(
headers: Vec<TableCell>,
rows: Vec<Vec<TableCell>>,
alignments: Vec<Alignment>,
) -> Self {
let num_cols = headers
.len()
.max(rows.iter().map(|r| r.len()).max().unwrap_or(0));
// Extend alignments to match column count
let mut alignments = alignments;
alignments.resize(num_cols, Alignment::default());
Self {
headers,
rows,
alignments,
column_widths: vec![0; num_cols],
}
}
/// Returns true if the table has no content.
#[inline]
pub fn is_empty(&self) -> bool {
self.headers.is_empty() && self.rows.is_empty()
}
/// Returns the number of columns in the table.
#[inline]
pub fn num_columns(&self) -> usize {
self.column_widths.len()
}
/// Calculates optimal column widths based on content and max_width.
///
/// The algorithm:
/// 1. Calculate minimum width per column (longest word or MIN_COLUMN_WIDTH)
/// 2. Calculate preferred width (full content width)
/// 3. Distribute available space proportionally
/// 4. Respect max_width parameter
///
/// # Arguments
/// * `max_width` - Maximum total table width including borders
pub fn calculate_column_widths(&mut self, max_width: u16) {
let num_cols = self.num_columns();
if num_cols == 0 {
return;
}
// Calculate minimum and preferred widths for each column
let mut min_widths = vec![MIN_COLUMN_WIDTH; num_cols];
let mut pref_widths = vec![MIN_COLUMN_WIDTH; num_cols];
// Process headers
for (i, cell) in self.headers.iter().enumerate() {
if i < num_cols {
let cell_width = cell.width();
let min_word = longest_word_width(&cell.content);
min_widths[i] = min_widths[i].max(min_word).max(MIN_COLUMN_WIDTH);
pref_widths[i] = pref_widths[i].max(cell_width);
}
}
// Process data rows
for row in &self.rows {
for (i, cell) in row.iter().enumerate() {
if i < num_cols {
let cell_width = cell.width();
let min_word = longest_word_width(&cell.content);
min_widths[i] = min_widths[i].max(min_word).max(MIN_COLUMN_WIDTH);
pref_widths[i] = pref_widths[i].max(cell_width);
}
}
}
// Calculate available width for content
// Border chars: │ at start, │ between each column, │ at end = num_cols + 1
// Padding: CELL_PADDING on each side of content = 2 * CELL_PADDING * num_cols
let border_overhead = num_cols + 1;
let padding_overhead = 2 * CELL_PADDING * num_cols;
let total_overhead = border_overhead + padding_overhead;
let available_width = if (max_width as usize) > total_overhead {
(max_width as usize) - total_overhead
} else {
// Not enough space, use minimum possible
num_cols * MIN_COLUMN_WIDTH
};
// Calculate total minimum and preferred widths
let total_min: usize = min_widths.iter().sum();
let total_pref: usize = pref_widths.iter().sum();
if total_pref <= available_width {
// All preferred widths fit
self.column_widths = pref_widths;
} else if total_min <= available_width {
// Distribute extra space proportionally
let extra_space = available_width - total_min;
let pref_extra: usize = pref_widths
.iter()
.zip(min_widths.iter())
.map(|(p, m)| p.saturating_sub(*m))
.sum();
self.column_widths = min_widths.clone();
if pref_extra > 0 {
for i in 0..num_cols {
let col_extra = pref_widths[i].saturating_sub(min_widths[i]);
let allocated =
(col_extra as f64 / pref_extra as f64 * extra_space as f64) as usize;
self.column_widths[i] += allocated;
}
}
} else {
// Not enough space even for minimums, use minimums anyway
self.column_widths = min_widths;
}
}
}
impl Default for Table {
fn default() -> Self {
Self {
headers: Vec::new(),
rows: Vec::new(),
alignments: Vec::new(),
column_widths: Vec::new(),
}
}
}
// ============================================================
// TABLE BUILDER
// ============================================================
/// Builder for constructing tables incrementally.
///
/// Useful when parsing markdown tables where content arrives piece by piece.
#[derive(Debug, Default)]
pub struct TableBuilder {
headers: Vec<TableCell>,
rows: Vec<Vec<TableCell>>,
alignments: Vec<Alignment>,
current_row: Vec<TableCell>,
in_header: bool,
}
impl TableBuilder {
/// Creates a new empty table builder.
pub fn new() -> Self {
Self::default()
}
/// Starts building the header row.
///
/// Cells added after this call will be added to the header.
pub fn start_header(&mut self) {
self.in_header = true;
self.current_row.clear();
}
/// Ends the header row.
///
/// The accumulated cells become the table headers.
pub fn end_header(&mut self) {
if self.in_header {
self.headers = std::mem::take(&mut self.current_row);
self.in_header = false;
}
}
/// Starts a new data row.
///
/// Cells added after this call will be added to the current row.
pub fn start_row(&mut self) {
self.current_row.clear();
}
/// Ends the current data row.
///
/// The accumulated cells are added as a new row.
pub fn end_row(&mut self) {
if !self.in_header && !self.current_row.is_empty() {
self.rows.push(std::mem::take(&mut self.current_row));
}
}
/// Adds a cell to the current row (header or data).
///
/// # Arguments
/// * `content` - The text content of the cell
pub fn add_cell(&mut self, content: String) {
self.current_row.push(TableCell::new(content));
}
/// Adds a cell with styled spans.
///
/// # Arguments
/// * `content` - The raw text content (for width calculation)
/// * `spans` - Pre-styled spans for rendering
pub fn add_cell_with_spans(&mut self, content: String, spans: Vec<Span<'static>>) {
self.current_row.push(TableCell::with_spans(content, spans));
}
/// Sets the column alignments.
///
/// # Arguments
/// * `alignments` - Vector of alignments, one per column
pub fn set_alignments(&mut self, alignments: Vec<Alignment>) {
self.alignments = alignments;
}
/// Builds the final table.
///
/// Note: Call `calculate_column_widths` on the result before rendering.
pub fn build(self) -> Table {
Table::new(self.headers, self.rows, self.alignments)
}
}
// ============================================================
// RENDER FUNCTIONS
// ============================================================
/// Renders a table to Lines with full ASCII borders.
///
/// # Arguments
/// * `table` - The table to render
/// * `border_color` - Color for border characters
/// * `header_style` - Style for header cell content
/// * `cell_style` - Style for data cell content
/// * `max_width` - Maximum total width for the table
///
/// # Returns
/// A vector of `Line`s ready for display in ratatui.
pub fn render_table(
table: &Table,
border_color: Color,
header_style: Style,
cell_style: Style,
max_width: u16,
) -> Vec<Line<'static>> {
// Handle empty table
if table.is_empty() {
return Vec::new();
}
// Clone and calculate widths if not already done
let mut table = table.clone();
if table.column_widths.iter().all(|&w| w == 0) {
table.calculate_column_widths(max_width);
}
// Handle case where we still have no columns
if table.num_columns() == 0 {
return Vec::new();
}
let border_style = Style::default().fg(border_color);
let widths = &table.column_widths;
let alignments = &table.alignments;
let mut lines = Vec::new();
// Top border: ┌──────┬──────┐
lines.push(render_horizontal_line(
widths,
border::TOP_LEFT,
border::T_DOWN,
border::TOP_RIGHT,
border_style,
));
// Header row
if !table.headers.is_empty() {
lines.push(render_row(
&table.headers,
widths,
alignments,
header_style,
border_style,
));
// Header separator: ├──────┼──────┤
lines.push(render_horizontal_line(
widths,
border::T_RIGHT,
border::CROSS,
border::T_LEFT,
border_style,
));
}
// Data rows
for row in &table.rows {
lines.push(render_row(
row,
widths,
alignments,
cell_style,
border_style,
));
}
// Bottom border: └──────┴──────┘
lines.push(render_horizontal_line(
widths,
border::BOTTOM_LEFT,
border::T_UP,
border::BOTTOM_RIGHT,
border_style,
));
lines
}
/// Renders a table as a simple ASCII code block without outer borders.
///
/// This produces a cleaner, minimal table format suitable for code blocks:
/// ```text
/// Header 1 | Header 2 | Header 3
/// ---------+-----------+---------
/// Cell 1 | Cell 2 | Cell 3
/// Cell 4 | Cell 5 | Cell 6
/// ```
///
/// # Arguments
/// * `table` - The table to render
/// * `header_style` - Style for header text (colored/bold headers)
/// * `cell_style` - Style for data cell text
/// * `max_width` - Maximum total width for the table
///
/// # Returns
/// A vector of `Line`s ready for display in ratatui.
pub fn render_table_simple(
table: &Table,
header_style: Style,
cell_style: Style,
max_width: u16,
) -> Vec<Line<'static>> {
// Handle empty table
if table.is_empty() {
return Vec::new();
}
// Clone and calculate widths if not already done
let mut table = table.clone();
if table.column_widths.iter().all(|&w| w == 0) {
table.calculate_column_widths(max_width);
}
// Handle case where we still have no columns
if table.num_columns() == 0 {
return Vec::new();
}
let widths = &table.column_widths;
let alignments = &table.alignments;
let mut lines = Vec::new();
// Header row (if present) - use header_style for colored headers
if !table.headers.is_empty() {
lines.push(render_simple_row(
&table.headers,
widths,
alignments,
header_style,
));
// Header separator line: ---+---+---
lines.push(render_simple_separator(widths, cell_style));
}
// Data rows - use cell_style
for row in &table.rows {
lines.push(render_simple_row(row, widths, alignments, cell_style));
}
lines
}
/// Renders a simple row without outer borders.
///
/// Format: `content | content | content`
fn render_simple_row(
cells: &[TableCell],
widths: &[usize],
alignments: &[Alignment],
style: Style,
) -> Line<'static> {
let mut spans = Vec::new();
for (i, width) in widths.iter().enumerate() {
// Get cell content or empty string if missing
let cell = cells.get(i);
let content = cell.map(|c| c.content.as_str()).unwrap_or("");
let alignment = alignments.get(i).copied().unwrap_or_default();
// Truncate and align
let truncated = truncate_with_ellipsis(content, *width);
let aligned = align_text(&truncated, *width, alignment);
// Add cell content with padding
spans.push(Span::styled(format!(" {} ", aligned), style));
// Add separator between columns (not after last)
if i < widths.len() - 1 {
spans.push(Span::styled("|", style));
}
}
Line::from(spans)
}
/// Renders a simple separator line for the header.
///
/// Format: `---+---+---`
fn render_simple_separator(widths: &[usize], style: Style) -> Line<'static> {
let mut spans = Vec::new();
for (i, &width) in widths.iter().enumerate() {
// Each column segment: padding + content + padding (same as cell)
let segment_width = width + 2; // +2 for the spaces on each side
let segment: String = std::iter::repeat('-').take(segment_width).collect();
spans.push(Span::styled(segment, style));
// Add separator between columns (not after last)
if i < widths.len() - 1 {
spans.push(Span::styled("+", style));
}
}
Line::from(spans)
}
/// Renders a horizontal border line.
///
/// # Arguments
/// * `widths` - Column widths (content only, excluding padding)
/// * `left` - Left corner/tee character
/// * `mid` - Middle intersection character
/// * `right` - Right corner/tee character
/// * `border_style` - Style for border characters
fn render_horizontal_line(
widths: &[usize],
left: char,
mid: char,
right: char,
border_style: Style,
) -> Line<'static> {
let mut spans = Vec::new();
spans.push(Span::styled(left.to_string(), border_style));
for (i, &width) in widths.iter().enumerate() {
// Each column segment: padding + content + padding
let segment_width = width + 2 * CELL_PADDING;
let segment: String = std::iter::repeat(border::HORIZONTAL)
.take(segment_width)
.collect();
spans.push(Span::styled(segment, border_style));
if i < widths.len() - 1 {
spans.push(Span::styled(mid.to_string(), border_style));
}
}
spans.push(Span::styled(right.to_string(), border_style));
Line::from(spans)
}
/// Renders a single row of cells.
///
/// # Arguments
/// * `cells` - The cells in this row
/// * `widths` - Column widths
/// * `alignments` - Column alignments
/// * `style` - Style for cell content
/// * `border_style` - Style for border characters
fn render_row(
cells: &[TableCell],
widths: &[usize],
alignments: &[Alignment],
style: Style,
border_style: Style,
) -> Line<'static> {
let mut spans = Vec::new();
// Left border
spans.push(Span::styled(border::VERTICAL.to_string(), border_style));
for (i, width) in widths.iter().enumerate() {
// Get cell content or empty string if missing
let cell = cells.get(i);
let content = cell.map(|c| c.content.as_str()).unwrap_or("");
let alignment = alignments.get(i).copied().unwrap_or_default();
// Truncate and align
let truncated = truncate_with_ellipsis(content, *width);
let aligned = align_text(&truncated, *width, alignment);
// Left padding
spans.push(Span::styled(" ".repeat(CELL_PADDING), style));
// Cell content - use spans if available, otherwise plain text
if let Some(cell) = cell {
if cell.spans.len() == 1 && cell.spans[0].content == cell.content {
// Simple case: just style the aligned text
spans.push(Span::styled(aligned, style));
} else {
// Complex case: we have styled spans, need to handle alignment
// For now, just use the aligned plain text with the base style
spans.push(Span::styled(aligned, style));
}
} else {
spans.push(Span::styled(aligned, style));
}
// Right padding
spans.push(Span::styled(" ".repeat(CELL_PADDING), style));
// Column separator or right border
spans.push(Span::styled(border::VERTICAL.to_string(), border_style));
}
Line::from(spans)
}
/// Aligns text within a given width.
///
/// # Arguments
/// * `text` - The text to align
/// * `width` - The target width
/// * `alignment` - The alignment type
fn align_text(text: &str, width: usize, alignment: Alignment) -> String {
let text_width = UnicodeWidthStr::width(text);
if text_width >= width {
return text.to_string();
}
let padding = width - text_width;
match alignment {
Alignment::Left => {
format!("{}{}", text, " ".repeat(padding))
}
Alignment::Right => {
format!("{}{}", " ".repeat(padding), text)
}
Alignment::Center => {
let left_pad = padding / 2;
let right_pad = padding - left_pad;
format!("{}{}{}", " ".repeat(left_pad), text, " ".repeat(right_pad))
}
}
}
/// Truncates text with ellipsis if it exceeds max_width.
///
/// # Arguments
/// * `text` - The text to potentially truncate
/// * `max_width` - Maximum allowed display width
///
/// # Returns
/// The original text if it fits, or truncated text with "..." appended.
fn truncate_with_ellipsis(text: &str, max_width: usize) -> String {
let text_width = UnicodeWidthStr::width(text);
if text_width <= max_width {
return text.to_string();
}
if max_width <= 3 {
// Not enough space for ellipsis, just return dots
return ".".repeat(max_width);
}
// We need to fit text + "..." into max_width
let target_width = max_width - 3; // Reserve 3 chars for "..."
let mut result = String::new();
let mut current_width = 0;
for ch in text.chars() {
let ch_width = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
if current_width + ch_width > target_width {
break;
}
result.push(ch);
current_width += ch_width;
}
result.push_str("...");
result
}
/// Calculates the width of the longest word in a string.
///
/// Words are split by whitespace. This is used for minimum column width calculation.
fn longest_word_width(text: &str) -> usize {
text.split_whitespace()
.map(|word| UnicodeWidthStr::width(word))
.max()
.unwrap_or(MIN_COLUMN_WIDTH)
.max(MIN_COLUMN_WIDTH)
}
// ============================================================
// TESTS
// ============================================================
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_empty_table() {
let table = Table::default();
assert!(table.is_empty());
let lines = render_table(&table, Color::Gray, Style::default(), Style::default(), 80);
assert!(lines.is_empty());
}
#[test]
fn test_single_cell() {
let mut builder = TableBuilder::new();
builder.start_header();
builder.add_cell("Header".to_string());
builder.end_header();
builder.start_row();
builder.add_cell("Value".to_string());
builder.end_row();
let table = builder.build();
assert!(!table.is_empty());
assert_eq!(table.num_columns(), 1);
let lines = render_table(&table, Color::Gray, Style::default(), Style::default(), 80);
// Should have: top border, header, separator, data row, bottom border = 5 lines
assert_eq!(lines.len(), 5);
}
#[test]
fn test_multiple_columns_and_alignments() {
let mut builder = TableBuilder::new();
builder.start_header();
builder.add_cell("Left".to_string());
builder.add_cell("Center".to_string());
builder.add_cell("Right".to_string());
builder.end_header();
builder.start_row();
builder.add_cell("A".to_string());
builder.add_cell("B".to_string());
builder.add_cell("C".to_string());
builder.end_row();
builder.set_alignments(vec![Alignment::Left, Alignment::Center, Alignment::Right]);
let table = builder.build();
assert_eq!(table.num_columns(), 3);
assert_eq!(table.alignments[0], Alignment::Left);
assert_eq!(table.alignments[1], Alignment::Center);
assert_eq!(table.alignments[2], Alignment::Right);
}
#[test]
fn test_unicode_content() {
let mut builder = TableBuilder::new();
builder.start_header();
builder.add_cell("Language".to_string());
builder.add_cell("Greeting".to_string());
builder.end_header();
builder.start_row();
builder.add_cell("Japanese".to_string());
builder.add_cell("こんにちは".to_string());
builder.end_row();
builder.start_row();
builder.add_cell("Chinese".to_string());
builder.add_cell("你好".to_string());
builder.end_row();
builder.start_row();
builder.add_cell("Emoji".to_string());
builder.add_cell("Hello! \u{1F44B}".to_string());
builder.end_row();
let table = builder.build();
let lines = render_table(&table, Color::Gray, Style::default(), Style::default(), 80);
// Should have: top border, header, separator, 3 data rows, bottom border = 7 lines
assert_eq!(lines.len(), 7);
}
#[test]
fn test_truncation() {
let result = truncate_with_ellipsis("Hello, World!", 8);
assert_eq!(result, "Hello...");
let result = truncate_with_ellipsis("Hi", 10);
assert_eq!(result, "Hi");
let result = truncate_with_ellipsis("Hello", 3);
assert_eq!(result, "...");
let result = truncate_with_ellipsis("Hello", 2);
assert_eq!(result, "..");
}
#[test]
fn test_alignment() {
assert_eq!(align_text("Hi", 6, Alignment::Left), "Hi ");
assert_eq!(align_text("Hi", 6, Alignment::Right), " Hi");
assert_eq!(align_text("Hi", 6, Alignment::Center), " Hi ");
assert_eq!(align_text("Hi", 7, Alignment::Center), " Hi ");
}
#[test]
fn test_cell_width() {
let cell = TableCell::new("Hello");
assert_eq!(cell.width(), 5);
let cell = TableCell::new("こんにちは"); // 5 wide chars = 10 width
assert_eq!(cell.width(), 10);
let cell = TableCell::new("");
assert_eq!(cell.width(), 0);
}
#[test]
fn test_column_width_calculation() {
let mut builder = TableBuilder::new();
builder.start_header();
builder.add_cell("Short".to_string());
builder.add_cell("A much longer header".to_string());
builder.end_header();
builder.start_row();
builder.add_cell("A".to_string());
builder.add_cell("B".to_string());
builder.end_row();
let mut table = builder.build();
table.calculate_column_widths(80);
// First column should be at least 5 (length of "Short")
assert!(table.column_widths[0] >= 5);
// Second column should be at least 20 (length of "A much longer header")
assert!(table.column_widths[1] >= 20);
}
#[test]
fn test_missing_cells_in_rows() {
let mut builder = TableBuilder::new();
builder.start_header();
builder.add_cell("A".to_string());
builder.add_cell("B".to_string());
builder.add_cell("C".to_string());
builder.end_header();
builder.start_row();
builder.add_cell("1".to_string());
// Missing cells B and C
builder.end_row();
builder.start_row();
builder.add_cell("2".to_string());
builder.add_cell("3".to_string());
// Missing cell C
builder.end_row();
let table = builder.build();
let lines = render_table(&table, Color::Gray, Style::default(), Style::default(), 80);
// Should render without panicking
assert!(!lines.is_empty());
}
#[test]
fn test_narrow_max_width() {
let mut builder = TableBuilder::new();
builder.start_header();
builder.add_cell("Very Long Header Name".to_string());
builder.end_header();
builder.start_row();
builder.add_cell("Some long cell content".to_string());
builder.end_row();
let table = builder.build();
let lines = render_table(
&table,
Color::Gray,
Style::default(),
Style::default(),
20, // Very narrow
);
// Should still render, content will be truncated
assert!(!lines.is_empty());
}
#[test]
fn test_builder_workflow() {
let mut builder = TableBuilder::new();
// Header phase
builder.start_header();
builder.add_cell("Col1".to_string());
builder.add_cell("Col2".to_string());
builder.end_header();
// Multiple rows