1#![warn(missing_docs)]
37
38use ndarray::Array2;
39use unicode_width::UnicodeWidthChar;
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum AmbiguousWidth {
51 Narrow,
53 Wide,
55 Auto,
57}
58
59impl AmbiguousWidth {
60 fn resolve(self) -> usize {
62 match self {
63 AmbiguousWidth::Narrow => 1,
64 AmbiguousWidth::Wide => 2,
65 AmbiguousWidth::Auto => {
66 if is_cjk_locale() {
67 2
68 } else {
69 1
70 }
71 }
72 }
73 }
74}
75
76impl Default for AmbiguousWidth {
77 fn default() -> Self {
84 AmbiguousWidth::Wide
85 }
86}
87
88fn is_cjk_locale() -> bool {
93 for key in ["LC_ALL", "LC_CTYPE", "LANG"] {
94 if let Ok(v) = std::env::var(key) {
95 let v = v.to_ascii_lowercase();
96 if v.starts_with("zh")
97 || v.starts_with("ja")
98 || v.starts_with("ko")
99 || v.contains("utf-8.zh")
100 || v.contains("utf-8.ja")
101 || v.contains("utf-8.ko")
102 {
103 return true;
104 }
105 }
106 }
107 false
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub enum Style {
117 Simple,
119 Boxed,
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum Align {
126 Left,
128 Right,
130 Auto,
133}
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub enum Color {
138 Black,
140 Red,
142 Green,
144 Yellow,
146 Blue,
148 Magenta,
150 Cyan,
152 White,
154 BrightBlack,
156 BrightRed,
158 BrightGreen,
160 BrightYellow,
162 BrightBlue,
164 BrightMagenta,
166 BrightCyan,
168 BrightWhite,
170}
171
172impl Color {
173 fn fg_code(self) -> u8 {
174 match self {
175 Color::Black => 30,
176 Color::Red => 31,
177 Color::Green => 32,
178 Color::Yellow => 33,
179 Color::Blue => 34,
180 Color::Magenta => 35,
181 Color::Cyan => 36,
182 Color::White => 37,
183 Color::BrightBlack => 90,
184 Color::BrightRed => 91,
185 Color::BrightGreen => 92,
186 Color::BrightYellow => 93,
187 Color::BrightBlue => 94,
188 Color::BrightMagenta => 95,
189 Color::BrightCyan => 96,
190 Color::BrightWhite => 97,
191 }
192 }
193}
194
195#[derive(Debug, Clone)]
197pub struct Table {
198 rows: Vec<Vec<String>>,
199 style: Style,
200 aligns: Vec<Align>,
201 max_cell_width: Option<usize>,
202 header_color: Option<Color>,
203 body_color: Option<Color>,
204 ambiguous_width: AmbiguousWidth,
205}
206
207impl Table {
208 pub fn new(rows: Vec<Vec<String>>) -> Self {
214 Self {
215 rows,
216 style: Style::Simple,
217 aligns: Vec::new(),
218 max_cell_width: None,
219 header_color: None,
220 body_color: None,
221 ambiguous_width: AmbiguousWidth::default(),
222 }
223 }
224
225 pub fn from_array2(array: Array2<String>) -> Self {
227 let rows = array
228 .outer_iter()
229 .map(|row| row.iter().cloned().collect())
230 .collect();
231 Self::new(rows)
232 }
233
234 pub fn style(mut self, style: Style) -> Self {
236 self.style = style;
237 self
238 }
239
240 pub fn aligns(mut self, aligns: Vec<Align>) -> Self {
242 self.aligns = aligns;
243 self
244 }
245
246 pub fn max_cell_width(mut self, width: usize) -> Self {
248 self.max_cell_width = Some(width);
249 self
250 }
251
252 pub fn header_color(mut self, color: Color) -> Self {
254 self.header_color = Some(color);
255 self
256 }
257
258 pub fn body_color(mut self, color: Color) -> Self {
260 self.body_color = Some(color);
261 self
262 }
263
264 pub fn ambiguous_width(mut self, mode: AmbiguousWidth) -> Self {
270 self.ambiguous_width = mode;
271 self
272 }
273
274 pub fn cjk_context(self, cjk: bool) -> Self {
276 let mode = if cjk {
277 AmbiguousWidth::Wide
278 } else {
279 AmbiguousWidth::Narrow
280 };
281 self.ambiguous_width(mode)
282 }
283
284 pub fn render(&self) -> String {
286 if self.rows.is_empty() {
287 return String::new();
288 }
289 let aw = self.ambiguous_width.resolve();
290 let widths = self.column_widths(aw);
291 let mut out = String::new();
292
293 match self.style {
294 Style::Simple => {
295 out.push('│');
296 out.push_str(&self.render_row(&self.rows[0], &widths, true, aw));
297 out.push_str("│\n");
298 out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
299 out.push('\n');
300 for row in &self.rows[1..] {
301 out.push('│');
302 out.push_str(&self.render_row(row, &widths, false, aw));
303 out.push_str("│\n");
304 }
305 }
306 Style::Boxed => {
307 out.push_str(&Self::horizontal(&widths, "┌", "┬", "┐", "─"));
308 out.push('\n');
309 out.push('│');
310 out.push_str(&self.render_row(&self.rows[0], &widths, true, aw));
311 out.push_str("│\n");
312 out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
313 out.push('\n');
314 for (i, row) in self.rows[1..].iter().enumerate() {
315 out.push('│');
316 out.push_str(&self.render_row(row, &widths, false, aw));
317 out.push_str("│\n");
318 if i + 1 < self.rows.len() - 1 {
319 out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
320 out.push('\n');
321 }
322 }
323 out.push_str(&Self::horizontal(&widths, "└", "┴", "┘", "─"));
324 out.push('\n');
325 }
326 }
327 out
328 }
329}
330
331impl Table {
332 fn align_of(&self, col: usize) -> Align {
333 self.aligns.get(col).copied().unwrap_or(Align::Left)
334 }
335
336 fn column_count(&self) -> usize {
337 self.rows.iter().map(|r| r.len()).max().unwrap_or(0)
338 }
339
340 fn prepare_cell(&self, content: &str, aw: usize) -> (String, usize) {
341 let stripped = strip_ansi(content);
342 let trimmed = stripped.trim();
343 let truncated = match self.max_cell_width {
344 Some(max) => truncate_visible_with(trimmed, max, aw),
345 None => trimmed.to_string(),
346 };
347 let w = display_width_with(&truncated, aw);
348 (truncated, w)
349 }
350
351 fn column_widths(&self, aw: usize) -> Vec<usize> {
352 let cols = self.column_count();
353 let mut widths = vec![0usize; cols];
354 for (r, row) in self.rows.iter().enumerate() {
355 for (i, cell) in row.iter().enumerate() {
356 let w = if r == 0 {
357 display_width_with(cell, aw)
358 } else {
359 let (_, w) = self.prepare_cell(cell, aw);
360 w
361 };
362 if w > widths[i] {
363 widths[i] = w;
364 }
365 }
366 }
367 widths.into_iter().map(|w| w + 2).collect()
368 }
369
370 fn render_cell(&self, content: &str, width: usize, align: Align, aw: usize) -> String {
371 let (text, vis) = self.prepare_cell(content, aw);
372 let inner = width.saturating_sub(2);
373 let pad = inner.saturating_sub(vis);
374
375 let aligned = match align {
376 Align::Left => format!("{}{}", text, " ".repeat(pad)),
377 Align::Right => format!("{}{}", " ".repeat(pad), text),
378 Align::Auto => {
379 if is_numeric_like(&strip_ansi(content)) {
380 format!("{}{}", " ".repeat(pad), text)
381 } else {
382 format!("{}{}", text, " ".repeat(pad))
383 }
384 }
385 };
386
387 let padded = format!(" {} ", aligned);
388 colorize(&padded, self.body_color)
389 }
390
391 fn render_header_cell(&self, content: &str, width: usize, aw: usize) -> String {
392 let stripped = strip_ansi(content);
393 let vis = display_width_with(&stripped, aw);
394 let inner = width.saturating_sub(2);
395 let pad = inner.saturating_sub(vis);
396 let padded = format!(" {}{} ", stripped, " ".repeat(pad));
397 colorize(&padded, self.header_color)
398 }
399
400 fn render_row(
401 &self,
402 row: &[String],
403 widths: &[usize],
404 is_header: bool,
405 aw: usize,
406 ) -> String {
407 let mut cells = Vec::with_capacity(widths.len());
408 for (i, w) in widths.iter().enumerate() {
409 let content = row.get(i).map(String::as_str).unwrap_or("");
410 if is_header {
411 cells.push(self.render_header_cell(content, *w, aw));
412 } else {
413 let align = self.align_of(i);
414 cells.push(self.render_cell(content, *w, align, aw));
415 }
416 }
417 cells.join("│")
418 }
419
420 fn horizontal(widths: &[usize], left: &str, mid: &str, right: &str, fill: &str) -> String {
421 let segments: Vec<String> = widths.iter().map(|w| fill.repeat(*w)).collect();
422 format!("{}{}{}", left, segments.join(mid), right)
423 }
424}
425
426pub fn render_table(rows: Vec<Vec<String>>, style: Style) -> String {
428 Table::new(rows).style(style).render()
429}
430
431fn colorize(s: &str, color: Option<Color>) -> String {
436 match color {
437 Some(c) => format!("\x1b[{}m{}\x1b[0m", c.fg_code(), s),
438 None => s.to_string(),
439 }
440}
441
442fn is_ambiguous(c: char) -> bool {
448 matches!(
449 c,
450 '\u{0391}'..='\u{03A9}'
451 | '\u{03B1}'..='\u{03C9}'
452 | '±' | '×' | '÷' | '≤' | '≥' | '≠' | '≈' | '∞' | '√'
453 | '→' | '←' | '↑' | '↓' | '↔'
454 | 'Ⅰ' | 'Ⅱ' | 'Ⅲ' | 'Ⅳ' | 'Ⅴ' | 'Ⅵ' | 'Ⅶ' | 'Ⅷ' | 'Ⅸ' | 'Ⅹ'
455 | 'ⅰ' | 'ⅱ' | 'ⅲ' | 'ⅳ' | 'ⅴ' | 'ⅵ' | 'ⅶ' | 'ⅷ' | 'ⅸ' | 'ⅹ'
456 | '①'..='⑳'
457 )
458}
459
460fn char_width(c: char, aw: usize) -> usize {
462 if is_ambiguous(c) {
463 aw
464 } else {
465 UnicodeWidthChar::width(c).unwrap_or(0)
466 }
467}
468
469fn display_width_with(s: &str, aw: usize) -> usize {
471 let stripped = strip_ansi(s);
472 stripped.chars().map(|c| char_width(c, aw)).sum()
473}
474
475pub fn display_width(s: &str) -> usize {
479 display_width_with(s, AmbiguousWidth::default().resolve())
480}
481
482pub fn pad_right_with_spaces(s: &str, width: usize) -> String {
484 let w = display_width(s);
485 if w >= width {
486 return s.to_string();
487 }
488 let mut out = String::with_capacity(s.len() + (width - w));
489 out.push_str(s);
490 out.push_str(&" ".repeat(width - w));
491 out
492}
493
494pub fn pad_left_with_spaces(s: &str, width: usize) -> String {
496 let w = display_width(s);
497 if w >= width {
498 return s.to_string();
499 }
500 let mut out = String::with_capacity(s.len() + (width - w));
501 out.push_str(&" ".repeat(width - w));
502 out.push_str(s);
503 out
504}
505
506pub fn strip_ansi(s: &str) -> String {
512 let mut out = String::with_capacity(s.len());
513 let mut chars = s.chars().peekable();
514 while let Some(c) = chars.next() {
515 if c == '\x1b' {
516 if chars.peek() == Some(&'[') {
517 chars.next();
518 for c2 in chars.by_ref() {
519 if c2.is_ascii_alphabetic() {
520 break;
521 }
522 }
523 }
524 } else {
525 out.push(c);
526 }
527 }
528 out
529}
530
531pub fn truncate_visible(s: &str, max_width: usize) -> String {
540 truncate_visible_with(s, max_width, AmbiguousWidth::default().resolve())
541}
542
543pub fn truncate_visible_with(s: &str, max_width: usize, aw: usize) -> String {
546 if max_width == 0 {
547 return String::new();
548 }
549 let vis = display_width_with(s, aw);
550 if vis <= max_width {
551 return s.to_string();
552 }
553 let suffix = "...";
554 let suffix_w = 3usize;
555 if max_width <= suffix_w {
556 return suffix.to_string();
557 }
558 let target = max_width - suffix_w;
559 let mut out = String::new();
560 let mut used = 0usize;
561 let mut chars = s.chars().peekable();
562 while let Some(c) = chars.next() {
563 if c == '\x1b' {
564 out.push(c);
565 if chars.peek() == Some(&'[') {
566 out.push(chars.next().unwrap());
567 for c2 in chars.by_ref() {
568 out.push(c2);
569 if c2.is_ascii_alphabetic() {
570 break;
571 }
572 }
573 }
574 continue;
575 }
576 let cw = char_width(c, aw);
577 if used + cw > target {
578 break;
579 }
580 out.push(c);
581 used += cw;
582 }
583 out.push_str(suffix);
584 out
585}
586
587pub fn is_numeric_like(s: &str) -> bool {
593 let s = s.trim();
594 if s.is_empty() {
595 return false;
596 }
597 let head = s.split_whitespace().next().unwrap_or("");
598 head.parse::<f64>().is_ok()
599}
600
601#[cfg(test)]
606mod tests {
607 use super::*;
608 use unicode_width::UnicodeWidthStr;
609
610 #[test]
611 fn phi_is_ambiguous_width() {
612 let s = "Φ170";
613 assert_eq!(UnicodeWidthStr::width(s), 4);
614 assert_eq!(UnicodeWidthStr::width_cjk(s), 4);
615 assert_eq!(display_width_with(s, 2), 5);
616 assert_eq!(display_width_with(s, 1), 4);
617 }
618
619 #[test]
620 fn ambiguous_width_respects_context() {
621 assert_eq!(display_width_with("Φ", 2), 2);
622 assert_eq!(display_width_with("Φ", 1), 1);
623 assert_eq!(display_width_with("Φ170", 2), 5);
624 assert_eq!(display_width_with("Φ170", 1), 4);
625 assert_eq!(display_width_with("Φ8", 2), 3);
626 assert_eq!(display_width_with("Φ16 III", 2), 9);
627 assert_eq!(display_width_with("Φ16 III", 1), 8);
628 }
629
630 #[test]
631 fn default_ambiguous_width_is_wide() {
632 assert_eq!(AmbiguousWidth::default(), AmbiguousWidth::Wide);
634 assert_eq!(display_width("Φ"), 2);
635 assert_eq!(display_width("Φ170"), 5);
636 }
637
638 #[test]
639 fn display_width_ascii_unchanged() {
640 assert_eq!(display_width("abc"), 3);
641 assert_eq!(display_width("170CD1"), 6);
642 assert_eq!(display_width("NUT-1"), 5);
643 }
644
645 #[test]
646 fn display_width_cjk_unchanged() {
647 assert_eq!(display_width("电杆"), 4);
648 assert_eq!(display_width("名称"), 4);
649 assert_eq!(display_width("电阻值设计定"), 12);
650 }
651
652 #[test]
653 fn display_width_strips_ansi() {
654 let colored = "\x1b[93m电杆\x1b[0m";
655 assert_eq!(display_width(colored), 4);
656 }
657
658 #[test]
659 fn phi_rows_align_default_wide() {
660 let rows = vec![
662 vec!["名称".into(), "规格".into(), "材料".into()],
663 vec!["电杆".into(), "Φ170".into(), "".into()],
664 vec!["横担".into(), "03D103-133".into(), "2II2".into()],
665 vec!["接地线".into(), "Φ8".into(), "".into()],
666 vec!["拉线棒".into(), "03D103-187".into(), "Φ16 III".into()],
667 ];
668 let out = Table::new(rows).style(Style::Boxed).render();
669 for line in out.lines() {
670 if line.starts_with('│') {
671 assert_eq!(line.matches('│').count(), 4, "行: {:?}", line);
672 }
673 }
674 }
675
676 #[test]
677 fn phi_rows_align_narrow() {
678 let rows = vec![
679 vec!["名称".into(), "规格".into(), "材料".into()],
680 vec!["电杆".into(), "Φ170".into(), "".into()],
681 vec!["横担".into(), "03D103-133".into(), "2II2".into()],
682 vec!["接地线".into(), "Φ8".into(), "".into()],
683 vec!["拉线棒".into(), "03D103-187".into(), "Φ16 III".into()],
684 ];
685 let out = Table::new(rows)
686 .style(Style::Boxed)
687 .ambiguous_width(AmbiguousWidth::Narrow)
688 .render();
689 for line in out.lines() {
690 if line.starts_with('│') {
691 assert_eq!(line.matches('│').count(), 4, "行: {:?}", line);
692 }
693 }
694 }
695
696 #[test]
697 fn truncate_phi_consistent_wide() {
698 let s = "Φ170CD1XYZ";
699 let t = truncate_visible_with(s, 6, 2);
700 assert_eq!(t, "Φ1...");
701 assert_eq!(display_width_with(&t, 2), 6);
702 }
703
704 #[test]
705 fn truncate_phi_consistent_narrow() {
706 let s = "Φ170CD1XYZ";
707 let t = truncate_visible_with(s, 6, 1);
708 assert_eq!(t, "Φ17...");
709 assert_eq!(display_width_with(&t, 1), 6);
710 }
711
712 #[test]
713 fn truncate_visible_two_arg_uses_default_wide() {
714 let t = truncate_visible("Φ170CD1XYZ", 6);
716 assert_eq!(t, "Φ1...");
717 }
718
719 #[test]
720 fn truncate_ascii_unchanged() {
721 let s = "abcdefghij";
722 let t = truncate_visible_with(s, 7, 2);
723 assert_eq!(t, "abcd...");
724 assert_eq!(display_width_with(&t, 2), 7);
725 }
726
727 #[test]
728 fn truncate_no_overflow_returns_original() {
729 let s = "Φ8";
730 let t = truncate_visible_with(s, 10, 2);
731 assert_eq!(t, "Φ8");
732 }
733
734 #[test]
735 fn cjk_context_builder_sets_mode() {
736 let t = Table::new(vec![vec!["a".into()]]).cjk_context(true);
737 assert_eq!(t.ambiguous_width, AmbiguousWidth::Wide);
738 let t = Table::new(vec![vec!["a".into()]]).cjk_context(false);
739 assert_eq!(t.ambiguous_width, AmbiguousWidth::Narrow);
740 }
741}