1#![warn(missing_docs)]
23
24use ndarray::Array2;
25use unicode_width::UnicodeWidthChar;
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum Style {
34 Simple,
36 Boxed,
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum Align {
43 Left,
45 Right,
47 Auto,
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum Color {
59 Black,
61 Red,
63 Green,
65 Yellow,
67 Blue,
69 Magenta,
71 Cyan,
73 White,
75 BrightBlack,
77 BrightRed,
79 BrightGreen,
81 BrightYellow,
83 BrightBlue,
85 BrightMagenta,
87 BrightCyan,
89 BrightWhite,
91}
92
93impl Color {
94 fn fg_code(self) -> u8 {
96 match self {
97 Color::Black => 30,
98 Color::Red => 31,
99 Color::Green => 32,
100 Color::Yellow => 33,
101 Color::Blue => 34,
102 Color::Magenta => 35,
103 Color::Cyan => 36,
104 Color::White => 37,
105 Color::BrightBlack => 90,
106 Color::BrightRed => 91,
107 Color::BrightGreen => 92,
108 Color::BrightYellow => 93,
109 Color::BrightBlue => 94,
110 Color::BrightMagenta => 95,
111 Color::BrightCyan => 96,
112 Color::BrightWhite => 97,
113 }
114 }
115}
116
117#[derive(Debug, Clone)]
119pub struct Table {
120 rows: Vec<Vec<String>>,
121 style: Style,
122 aligns: Vec<Align>,
123 max_cell_width: Option<usize>,
126 header_color: Option<Color>,
128 body_color: Option<Color>,
130}
131
132impl Table {
133 pub fn new(rows: Vec<Vec<String>>) -> Self {
137 Self {
138 rows,
139 style: Style::Simple,
140 aligns: Vec::new(),
141 max_cell_width: None,
142 header_color: None,
143 body_color: None,
144 }
145 }
146
147 pub fn from_array2(array: Array2<String>) -> Self {
151 let rows = array
152 .outer_iter()
153 .map(|row| row.iter().cloned().collect())
154 .collect();
155 Self::new(rows)
156 }
157
158 pub fn style(mut self, style: Style) -> Self {
160 self.style = style;
161 self
162 }
163
164 pub fn aligns(mut self, aligns: Vec<Align>) -> Self {
166 self.aligns = aligns;
167 self
168 }
169
170 pub fn max_cell_width(mut self, width: usize) -> Self {
173 self.max_cell_width = Some(width);
174 self
175 }
176
177 pub fn header_color(mut self, color: Color) -> Self {
179 self.header_color = Some(color);
180 self
181 }
182
183 pub fn body_color(mut self, color: Color) -> Self {
185 self.body_color = Some(color);
186 self
187 }
188
189 pub fn render(&self) -> String {
191 if self.rows.is_empty() {
192 return String::new();
193 }
194 let widths = self.column_widths();
195 let mut out = String::new();
196
197 match self.style {
198 Style::Simple => {
199 out.push('│');
200 out.push_str(&self.render_row(&self.rows[0], &widths, true));
201 out.push_str("│\n");
202 out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
203 out.push('\n');
204 for row in &self.rows[1..] {
205 out.push('│');
206 out.push_str(&self.render_row(row, &widths, false));
207 out.push_str("│\n");
208 }
209 }
210 Style::Boxed => {
211 out.push_str(&Self::horizontal(&widths, "┌", "┬", "┐", "─"));
212 out.push('\n');
213 out.push('│');
214 out.push_str(&self.render_row(&self.rows[0], &widths, true));
215 out.push_str("│\n");
216 out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
217 out.push('\n');
218 for (i, row) in self.rows[1..].iter().enumerate() {
219 out.push('│');
220 out.push_str(&self.render_row(row, &widths, false));
221 out.push_str("│\n");
222 if i + 1 < self.rows.len() - 1 {
223 out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
224 out.push('\n');
225 }
226 }
227 out.push_str(&Self::horizontal(&widths, "└", "┴", "┘", "─"));
228 out.push('\n');
229 }
230 }
231 out
232 }
233}
234
235impl Table {
236 fn align_of(&self, col: usize) -> Align {
237 self.aligns.get(col).copied().unwrap_or(Align::Left)
238 }
239
240 fn column_count(&self) -> usize {
242 self.rows.iter().map(|r| r.len()).max().unwrap_or(0)
243 }
244
245 fn prepare_cell(&self, content: &str) -> (String, usize) {
253 let stripped = strip_ansi(content);
254 let trimmed = stripped.trim();
255 let truncated = match self.max_cell_width {
256 Some(max) => truncate_visible(trimmed, max),
257 None => trimmed.to_string(),
258 };
259 let w = display_width(&truncated);
260 (truncated, w)
261 }
262
263 fn column_widths(&self) -> Vec<usize> {
269 let cols = self.column_count();
270 let mut widths = vec![0usize; cols];
271 for (r, row) in self.rows.iter().enumerate() {
272 for (i, cell) in row.iter().enumerate() {
273 let w = if r == 0 {
274 display_width(cell)
277 } else {
278 let (_, w) = self.prepare_cell(cell);
280 w
281 };
282 if w > widths[i] {
283 widths[i] = w;
284 }
285 }
286 }
287 widths.into_iter().map(|w| w + 2).collect()
289 }
290
291 fn render_cell(&self, content: &str, width: usize, align: Align) -> String {
294 let (text, vis) = self.prepare_cell(content);
295
296 let inner = width.saturating_sub(2);
298 let pad = inner.saturating_sub(vis);
299
300 let aligned = match align {
301 Align::Left => format!("{}{}", text, " ".repeat(pad)),
302 Align::Right => format!("{}{}", " ".repeat(pad), text),
303 Align::Auto => {
304 if is_numeric_like(&strip_ansi(content)) {
306 format!("{}{}", " ".repeat(pad), text)
307 } else {
308 format!("{}{}", text, " ".repeat(pad))
309 }
310 }
311 };
312
313 let padded = format!(" {} ", aligned);
314 colorize(&padded, self.body_color)
315 }
316
317 fn render_header_cell(&self, content: &str, width: usize) -> String {
320 let stripped = strip_ansi(content);
321 let vis = display_width(&stripped);
322 let inner = width.saturating_sub(2);
323 let pad = inner.saturating_sub(vis);
324 let padded = format!(" {}{} ", stripped, " ".repeat(pad));
325 colorize(&padded, self.header_color)
326 }
327
328 fn render_row(&self, row: &[String], widths: &[usize], is_header: bool) -> String {
330 let mut cells = Vec::with_capacity(widths.len());
331 for (i, w) in widths.iter().enumerate() {
332 let content = row.get(i).map(String::as_str).unwrap_or("");
333 if is_header {
334 cells.push(self.render_header_cell(content, *w));
335 } else {
336 let align = self.align_of(i);
337 cells.push(self.render_cell(content, *w, align));
338 }
339 }
340 cells.join("│")
341 }
342
343 fn horizontal(widths: &[usize], left: &str, mid: &str, right: &str, fill: &str) -> String {
345 let segments: Vec<String> = widths.iter().map(|w| fill.repeat(*w)).collect();
346 format!("{}{}{}", left, segments.join(mid), right)
347 }
348}
349
350pub fn render_table(rows: Vec<Vec<String>>, style: Style) -> String {
352 Table::new(rows).style(style).render()
353}
354
355fn colorize(s: &str, color: Option<Color>) -> String {
361 match color {
362 Some(c) => format!("\x1b[{}m{}\x1b[0m", c.fg_code(), s),
363 None => s.to_string(),
364 }
365}
366
367fn extra_wide(c: char) -> bool {
378 matches!(
379 c,
380 'Φ' | 'φ' | 'Ⅱ' | 'Ⅲ' | 'Ⅰ' | '±' | '×' | '÷' | '≤' | '≥' | '≠'
384 | '→' | '←' | '↑' | '↓'
385 | '①'..='⑳' )
387}
388
389fn char_width(c: char) -> usize {
391 if extra_wide(c) {
392 2
393 } else {
394 UnicodeWidthChar::width(c).unwrap_or(0)
395 }
396}
397
398pub fn display_width(s: &str) -> usize {
403 let stripped = strip_ansi(s);
404 stripped.chars().map(char_width).sum()
405}
406
407pub fn pad_right_with_spaces(s: &str, width: usize) -> String {
409 let w = display_width(s);
410 if w >= width {
411 return s.to_string();
412 }
413 let mut out = String::with_capacity(s.len() + (width - w));
414 out.push_str(s);
415 out.push_str(&" ".repeat(width - w));
416 out
417}
418
419pub fn pad_left_with_spaces(s: &str, width: usize) -> String {
421 let w = display_width(s);
422 if w >= width {
423 return s.to_string();
424 }
425 let mut out = String::with_capacity(s.len() + (width - w));
426 out.push_str(&" ".repeat(width - w));
427 out.push_str(s);
428 out
429}
430
431pub fn strip_ansi(s: &str) -> String {
437 let mut out = String::with_capacity(s.len());
438 let mut chars = s.chars().peekable();
439 while let Some(c) = chars.next() {
440 if c == '\x1b' {
441 if chars.peek() == Some(&'[') {
442 chars.next(); for c2 in chars.by_ref() {
444 if c2.is_ascii_alphabetic() {
445 break;
446 }
447 }
448 }
449 } else {
450 out.push(c);
451 }
452 }
453 out
454}
455
456pub fn truncate_visible(s: &str, max_width: usize) -> String {
471 if max_width == 0 {
472 return String::new();
473 }
474 let vis = display_width(s);
475 if vis <= max_width {
476 return s.to_string();
477 }
478 let suffix = "...";
479 let suffix_w = 3usize;
480 if max_width <= suffix_w {
481 return suffix.to_string();
483 }
484 let target = max_width - suffix_w;
485 let mut out = String::new();
486 let mut used = 0usize;
487 let mut chars = s.chars().peekable();
488 while let Some(c) = chars.next() {
489 if c == '\x1b' {
490 out.push(c);
491 if chars.peek() == Some(&'[') {
492 out.push(chars.next().unwrap());
493 for c2 in chars.by_ref() {
494 out.push(c2);
495 if c2.is_ascii_alphabetic() {
496 break;
497 }
498 }
499 }
500 continue;
501 }
502 let cw = char_width(c);
504 if used + cw > target {
505 break;
506 }
507 out.push(c);
508 used += cw;
509 }
510 out.push_str(suffix);
511 out
512}
513
514pub fn is_numeric_like(s: &str) -> bool {
524 let s = s.trim();
525 if s.is_empty() {
526 return false;
527 }
528 let head = s.split_whitespace().next().unwrap_or("");
529 head.parse::<f64>().is_ok()
530}
531
532#[cfg(test)]
537mod tests {
538 use super::*;
539 use unicode_width::UnicodeWidthStr;
540
541 #[test]
542 fn phi_is_ambiguous_width() {
543 let s = "Φ170";
546 assert_eq!(UnicodeWidthStr::width(s), 4, "crate 默认宽度:Φ(1)+170(3)=4");
547 assert_eq!(
548 UnicodeWidthStr::width_cjk(s),
549 4,
550 "crate cjk 宽度同样是 4"
551 );
552 assert_eq!(
553 display_width(s),
554 5,
555 "display_width 补偿后:Φ(2)+170(3)=5"
556 );
557 }
558
559 #[test]
560 fn display_width_uses_cjk_for_phi() {
561 assert_eq!(display_width("Φ"), 2);
562 assert_eq!(display_width("Φ170"), 5);
563 assert_eq!(display_width("Φ8"), 3);
564 assert_eq!(display_width("Φ16 III"), 9);
566 }
567
568 #[test]
569 fn display_width_ascii_unchanged() {
570 assert_eq!(display_width("abc"), 3);
572 assert_eq!(display_width("170CD1"), 6);
573 assert_eq!(display_width("NUT-1"), 5);
574 }
575
576 #[test]
577 fn display_width_cjk_unchanged() {
578 assert_eq!(display_width("电杆"), 4);
580 assert_eq!(display_width("名称"), 4);
581 assert_eq!(display_width("电阻值设计定"), 12);
582 }
583
584 #[test]
585 fn display_width_strips_ansi() {
586 let colored = "\x1b[93m电杆\x1b[0m";
588 assert_eq!(display_width(colored), 4);
589 }
590
591 #[test]
592 fn phi_rows_align() {
593 let rows = vec![
595 vec!["名称".into(), "规格".into(), "材料".into()],
596 vec!["电杆".into(), "Φ170".into(), "".into()],
597 vec!["横担".into(), "03D103-133".into(), "2II2".into()],
598 vec!["接地线".into(), "Φ8".into(), "".into()],
599 vec!["拉线棒".into(), "03D103-187".into(), "Φ16 III".into()],
600 ];
601 let out = Table::new(rows).style(Style::Boxed).render();
602
603 for line in out.lines() {
605 if line.starts_with('│') {
606 let n = line.matches('│').count();
607 assert_eq!(n, 4, "行竖线数量异常: {:?}", line);
608 }
609 }
610 }
611
612 #[test]
613 fn phi_align_matches_ascii_row() {
614 let rows = vec![
616 vec!["规格".into()],
617 vec!["Φ170".into()],
618 vec!["170C".into()], ];
620 let out = Table::new(rows).style(Style::Boxed).render();
621
622 let data_lines: Vec<&str> = out
623 .lines()
624 .filter(|l| l.starts_with('│') && !l.contains("规格"))
625 .collect();
626
627 let widths: Vec<usize> = data_lines
628 .iter()
629 .map(|l| {
630 let inner = l.trim_matches('│');
631 display_width(inner)
632 })
633 .collect();
634
635 assert!(
636 widths.windows(2).all(|w| w[0] == w[1]),
637 "含 Φ 的行与 ASCII 行宽度不一致: {:?}",
638 widths
639 );
640 }
641
642 #[test]
643 fn truncate_phi_consistent() {
644 let s = "Φ170CD1XYZ";
647 let t = truncate_visible(s, 6);
648 assert_eq!(t, "Φ1...");
649 assert_eq!(display_width(&t), 6);
650 }
651
652 #[test]
653 fn truncate_ascii_unchanged() {
654 let s = "abcdefghij";
655 let t = truncate_visible(s, 7);
656 assert_eq!(t, "abcd...");
657 assert_eq!(display_width(&t), 7);
658 }
659
660 #[test]
661 fn truncate_no_overflow_returns_original() {
662 let s = "Φ8";
663 let t = truncate_visible(s, 10);
664 assert_eq!(t, "Φ8");
665 }
666}