Skip to main content

shape_runtime/renderers/
terminal.rs

1//! Terminal renderer — renders ContentNode to ANSI-escaped terminal output.
2//!
3//! Supports:
4//! - Styled text with fg/bg colors, bold, italic, underline, dim
5//! - Tables with unicode box-drawing characters (6 border styles)
6//! - Code blocks with indentation and language label
7//! - Charts as placeholder text
8//! - Key-value pairs with aligned output
9//! - Fragments via concatenation
10
11use crate::content_renderer::{ContentRenderer, RenderContext, RendererCapabilities};
12use shape_value::content::{
13    BorderStyle, ChartSpec, Color, ContentNode, ContentTable, NamedColor, Style, StyledText,
14};
15use std::fmt::Write;
16
17/// Renders ContentNode trees to ANSI terminal output.
18///
19/// Carries a [`RenderContext`] to control terminal width, max rows, etc.
20pub struct TerminalRenderer {
21    pub ctx: RenderContext,
22}
23
24impl TerminalRenderer {
25    /// Create a renderer with default terminal context.
26    pub fn new() -> Self {
27        Self {
28            ctx: RenderContext::terminal(),
29        }
30    }
31
32    /// Create a renderer with a specific context.
33    pub fn with_context(ctx: RenderContext) -> Self {
34        Self { ctx }
35    }
36}
37
38impl Default for TerminalRenderer {
39    fn default() -> Self {
40        Self::new()
41    }
42}
43
44impl ContentRenderer for TerminalRenderer {
45    fn capabilities(&self) -> RendererCapabilities {
46        RendererCapabilities::terminal()
47    }
48
49    fn render(&self, content: &ContentNode) -> String {
50        render_node(content, &self.ctx)
51    }
52}
53
54fn render_node(node: &ContentNode, ctx: &RenderContext) -> String {
55    match node {
56        ContentNode::Text(st) => render_styled_text(st),
57        ContentNode::Table(table) => render_table(table, ctx),
58        ContentNode::Code { language, source } => render_code(language.as_deref(), source),
59        ContentNode::Chart(spec) => render_chart(spec),
60        ContentNode::KeyValue(pairs) => render_key_value(pairs, ctx),
61        ContentNode::Fragment(parts) => parts.iter().map(|n| render_node(n, ctx)).collect(),
62    }
63}
64
65fn render_styled_text(st: &StyledText) -> String {
66    let mut out = String::new();
67    for span in &st.spans {
68        let codes = style_to_ansi_codes(&span.style);
69        if codes.is_empty() {
70            out.push_str(&span.text);
71        } else {
72            let _ = write!(out, "\x1b[{}m{}\x1b[0m", codes, span.text);
73        }
74    }
75    out
76}
77
78fn style_to_ansi_codes(style: &Style) -> String {
79    let mut codes = Vec::new();
80    if style.bold {
81        codes.push("1".to_string());
82    }
83    if style.dim {
84        codes.push("2".to_string());
85    }
86    if style.italic {
87        codes.push("3".to_string());
88    }
89    if style.underline {
90        codes.push("4".to_string());
91    }
92    if let Some(ref color) = style.fg {
93        codes.push(color_to_fg_code(color));
94    }
95    if let Some(ref color) = style.bg {
96        codes.push(color_to_bg_code(color));
97    }
98    codes.join(";")
99}
100
101fn color_to_fg_code(color: &Color) -> String {
102    match color {
103        Color::Named(named) => named_color_fg(*named).to_string(),
104        Color::Rgb(r, g, b) => format!("38;2;{};{};{}", r, g, b),
105    }
106}
107
108fn color_to_bg_code(color: &Color) -> String {
109    match color {
110        Color::Named(named) => named_color_bg(*named).to_string(),
111        Color::Rgb(r, g, b) => format!("48;2;{};{};{}", r, g, b),
112    }
113}
114
115fn named_color_fg(color: NamedColor) -> u8 {
116    match color {
117        NamedColor::Red => 31,
118        NamedColor::Green => 32,
119        NamedColor::Yellow => 33,
120        NamedColor::Blue => 34,
121        NamedColor::Magenta => 35,
122        NamedColor::Cyan => 36,
123        NamedColor::White => 37,
124        NamedColor::Default => 39,
125    }
126}
127
128fn named_color_bg(color: NamedColor) -> u8 {
129    match color {
130        NamedColor::Red => 41,
131        NamedColor::Green => 42,
132        NamedColor::Yellow => 43,
133        NamedColor::Blue => 44,
134        NamedColor::Magenta => 45,
135        NamedColor::Cyan => 46,
136        NamedColor::White => 47,
137        NamedColor::Default => 49,
138    }
139}
140
141// ========== Table rendering ==========
142
143/// Box-drawing character set for a given border style.
144struct BoxChars {
145    top_left: &'static str,
146    top_mid: &'static str,
147    top_right: &'static str,
148    mid_left: &'static str,
149    mid_mid: &'static str,
150    mid_right: &'static str,
151    bot_left: &'static str,
152    bot_mid: &'static str,
153    bot_right: &'static str,
154    horizontal: &'static str,
155    vertical: &'static str,
156}
157
158fn box_chars(style: BorderStyle) -> BoxChars {
159    match style {
160        BorderStyle::Rounded => BoxChars {
161            top_left: "\u{256d}",   // ╭
162            top_mid: "\u{252c}",    // ┬
163            top_right: "\u{256e}",  // ╮
164            mid_left: "\u{251c}",   // ├
165            mid_mid: "\u{253c}",    // ┼
166            mid_right: "\u{2524}",  // ┤
167            bot_left: "\u{2570}",   // ╰
168            bot_mid: "\u{2534}",    // ┴
169            bot_right: "\u{256f}",  // ╯
170            horizontal: "\u{2500}", // ─
171            vertical: "\u{2502}",   // │
172        },
173        BorderStyle::Sharp => BoxChars {
174            top_left: "\u{250c}",   // ┌
175            top_mid: "\u{252c}",    // ┬
176            top_right: "\u{2510}",  // ┐
177            mid_left: "\u{251c}",   // ├
178            mid_mid: "\u{253c}",    // ┼
179            mid_right: "\u{2524}",  // ┤
180            bot_left: "\u{2514}",   // └
181            bot_mid: "\u{2534}",    // ┴
182            bot_right: "\u{2518}",  // ┘
183            horizontal: "\u{2500}", // ─
184            vertical: "\u{2502}",   // │
185        },
186        BorderStyle::Heavy => BoxChars {
187            top_left: "\u{250f}",   // ┏
188            top_mid: "\u{2533}",    // ┳
189            top_right: "\u{2513}",  // ┓
190            mid_left: "\u{2523}",   // ┣
191            mid_mid: "\u{254b}",    // ╋
192            mid_right: "\u{252b}",  // ┫
193            bot_left: "\u{2517}",   // ┗
194            bot_mid: "\u{253b}",    // ┻
195            bot_right: "\u{251b}",  // ┛
196            horizontal: "\u{2501}", // ━
197            vertical: "\u{2503}",   // ┃
198        },
199        BorderStyle::Double => BoxChars {
200            top_left: "\u{2554}",   // ╔
201            top_mid: "\u{2566}",    // ╦
202            top_right: "\u{2557}",  // ╗
203            mid_left: "\u{2560}",   // ╠
204            mid_mid: "\u{256c}",    // ╬
205            mid_right: "\u{2563}",  // ╣
206            bot_left: "\u{255a}",   // ╚
207            bot_mid: "\u{2569}",    // ╩
208            bot_right: "\u{255d}",  // ╝
209            horizontal: "\u{2550}", // ═
210            vertical: "\u{2551}",   // ║
211        },
212        BorderStyle::Minimal => BoxChars {
213            top_left: " ",
214            top_mid: " ",
215            top_right: " ",
216            mid_left: " ",
217            mid_mid: " ",
218            mid_right: " ",
219            bot_left: " ",
220            bot_mid: " ",
221            bot_right: " ",
222            horizontal: "-",
223            vertical: " ",
224        },
225        BorderStyle::None => BoxChars {
226            top_left: "",
227            top_mid: "",
228            top_right: "",
229            mid_left: "",
230            mid_mid: "",
231            mid_right: "",
232            bot_left: "",
233            bot_mid: "",
234            bot_right: "",
235            horizontal: "",
236            vertical: " ",
237        },
238    }
239}
240
241fn render_table(table: &ContentTable, ctx: &RenderContext) -> String {
242    if table.border == BorderStyle::None {
243        return render_table_no_border(table);
244    }
245
246    let bc = box_chars(table.border);
247
248    // Compute column widths
249    let col_count = table.headers.len();
250    let mut widths: Vec<usize> = table.headers.iter().map(|h| h.len()).collect();
251
252    let limit = table.max_rows.or(ctx.max_rows).unwrap_or(table.rows.len());
253    let display_rows = &table.rows[..limit.min(table.rows.len())];
254    let truncated = table.rows.len().saturating_sub(limit);
255
256    for row in display_rows {
257        for (i, cell) in row.iter().enumerate() {
258            if i < col_count {
259                let cell_text = cell.to_string();
260                if cell_text.len() > widths[i] {
261                    widths[i] = cell_text.len();
262                }
263            }
264        }
265    }
266
267    // Constrain column widths to ctx.max_width (proportional shrink)
268    if let Some(max_w) = ctx.max_width {
269        let overhead = col_count + 1 + col_count * 2; // borders + padding
270        if overhead < max_w {
271            let available = max_w - overhead;
272            let total_natural: usize = widths.iter().sum();
273            if total_natural > available && total_natural > 0 {
274                for w in &mut widths {
275                    *w = (*w * available / total_natural).max(3);
276                }
277            }
278        }
279    }
280
281    let mut out = String::new();
282
283    // Top border
284    let _ = write!(out, "{}", bc.top_left);
285    for (i, w) in widths.iter().enumerate() {
286        for _ in 0..(w + 2) {
287            out.push_str(bc.horizontal);
288        }
289        if i < col_count - 1 {
290            out.push_str(bc.top_mid);
291        }
292    }
293    let _ = writeln!(out, "{}", bc.top_right);
294
295    // Header row
296    let _ = write!(out, "{}", bc.vertical);
297    for (i, header) in table.headers.iter().enumerate() {
298        let _ = write!(out, " {:width$} ", header, width = widths[i]);
299        out.push_str(bc.vertical);
300    }
301    let _ = writeln!(out);
302
303    // Separator
304    let _ = write!(out, "{}", bc.mid_left);
305    for (i, w) in widths.iter().enumerate() {
306        for _ in 0..(w + 2) {
307            out.push_str(bc.horizontal);
308        }
309        if i < col_count - 1 {
310            out.push_str(bc.mid_mid);
311        }
312    }
313    let _ = writeln!(out, "{}", bc.mid_right);
314
315    // Data rows
316    for row in display_rows {
317        let _ = write!(out, "{}", bc.vertical);
318        for i in 0..col_count {
319            let cell_text = row.get(i).map(|c| c.to_string()).unwrap_or_default();
320            let _ = write!(out, " {:width$} ", cell_text, width = widths[i]);
321            out.push_str(bc.vertical);
322        }
323        let _ = writeln!(out);
324    }
325
326    // Truncation indicator
327    if truncated > 0 {
328        let _ = write!(out, "{}", bc.vertical);
329        let msg = format!("... {} more rows", truncated);
330        let total_width: usize = widths.iter().sum::<usize>() + (col_count - 1) * 3 + 2;
331        let _ = write!(out, " {:width$} ", msg, width = total_width);
332        out.push_str(bc.vertical);
333        let _ = writeln!(out);
334    }
335
336    // Bottom border
337    let _ = write!(out, "{}", bc.bot_left);
338    for (i, w) in widths.iter().enumerate() {
339        for _ in 0..(w + 2) {
340            out.push_str(bc.horizontal);
341        }
342        if i < col_count - 1 {
343            out.push_str(bc.bot_mid);
344        }
345    }
346    let _ = writeln!(out, "{}", bc.bot_right);
347
348    out
349}
350
351fn render_table_no_border(table: &ContentTable) -> String {
352    let col_count = table.headers.len();
353    let mut widths: Vec<usize> = table.headers.iter().map(|h| h.len()).collect();
354
355    let limit = table.max_rows.unwrap_or(table.rows.len());
356    let display_rows = &table.rows[..limit.min(table.rows.len())];
357    let truncated = table.rows.len().saturating_sub(limit);
358
359    for row in display_rows {
360        for (i, cell) in row.iter().enumerate() {
361            if i < col_count {
362                let cell_text = cell.to_string();
363                if cell_text.len() > widths[i] {
364                    widths[i] = cell_text.len();
365                }
366            }
367        }
368    }
369
370    let mut out = String::new();
371
372    // Header row
373    for (i, header) in table.headers.iter().enumerate() {
374        if i > 0 {
375            out.push_str("  ");
376        }
377        let _ = write!(out, "{:width$}", header, width = widths[i]);
378    }
379    let _ = writeln!(out);
380
381    // Data rows
382    for row in display_rows {
383        for i in 0..col_count {
384            if i > 0 {
385                out.push_str("  ");
386            }
387            let cell_text = row.get(i).map(|c| c.to_string()).unwrap_or_default();
388            let _ = write!(out, "{:width$}", cell_text, width = widths[i]);
389        }
390        let _ = writeln!(out);
391    }
392
393    if truncated > 0 {
394        let _ = writeln!(out, "... {} more rows", truncated);
395    }
396
397    out
398}
399
400fn render_code(language: Option<&str>, source: &str) -> String {
401    let mut out = String::new();
402    if let Some(lang) = language {
403        let _ = writeln!(out, "\x1b[2m[{}]\x1b[0m", lang);
404    }
405    for line in source.lines() {
406        let _ = writeln!(out, "    {}", line);
407    }
408    out
409}
410
411fn render_chart(spec: &ChartSpec) -> String {
412    let title = spec.title.as_deref().unwrap_or("untitled");
413    let type_name = match spec.chart_type {
414        shape_value::content::ChartType::Line => "Line",
415        shape_value::content::ChartType::Bar => "Bar",
416        shape_value::content::ChartType::Scatter => "Scatter",
417        shape_value::content::ChartType::Area => "Area",
418        shape_value::content::ChartType::Candlestick => "Candlestick",
419        shape_value::content::ChartType::Histogram => "Histogram",
420    };
421    format!(
422        "[{} Chart: {} ({} series)]\n",
423        type_name,
424        title,
425        spec.series.len()
426    )
427}
428
429fn render_key_value(pairs: &[(String, ContentNode)], ctx: &RenderContext) -> String {
430    if pairs.is_empty() {
431        return String::new();
432    }
433    let max_key_len = pairs.iter().map(|(k, _)| k.len()).max().unwrap_or(0);
434    let mut out = String::new();
435    for (key, value) in pairs {
436        let value_str = render_node(value, ctx);
437        let _ = writeln!(out, "{:width$}  {}", key, value_str, width = max_key_len);
438    }
439    out
440}
441
442#[cfg(test)]
443mod tests {
444    use super::*;
445    use shape_value::content::ContentTable;
446
447    fn renderer() -> TerminalRenderer {
448        TerminalRenderer::new()
449    }
450
451    #[test]
452    fn test_plain_text_no_ansi() {
453        let node = ContentNode::plain("hello world");
454        let output = renderer().render(&node);
455        assert_eq!(output, "hello world");
456    }
457
458    #[test]
459    fn test_bold_text_ansi() {
460        let node = ContentNode::plain("bold").with_bold();
461        let output = renderer().render(&node);
462        assert!(output.contains("\x1b[1m"));
463        assert!(output.contains("bold"));
464        assert!(output.contains("\x1b[0m"));
465    }
466
467    #[test]
468    fn test_fg_color_ansi() {
469        let node = ContentNode::plain("red").with_fg(Color::Named(NamedColor::Red));
470        let output = renderer().render(&node);
471        assert!(output.contains("\x1b[31m"));
472        assert!(output.contains("red"));
473        assert!(output.contains("\x1b[0m"));
474    }
475
476    #[test]
477    fn test_bg_color_ansi() {
478        let node = ContentNode::plain("bg").with_bg(Color::Named(NamedColor::Blue));
479        let output = renderer().render(&node);
480        assert!(output.contains("\x1b[44m"));
481    }
482
483    #[test]
484    fn test_rgb_fg_color() {
485        let node = ContentNode::plain("rgb").with_fg(Color::Rgb(255, 128, 0));
486        let output = renderer().render(&node);
487        assert!(output.contains("\x1b[38;2;255;128;0m"));
488    }
489
490    #[test]
491    fn test_rgb_bg_color() {
492        let node = ContentNode::plain("rgb").with_bg(Color::Rgb(0, 255, 128));
493        let output = renderer().render(&node);
494        assert!(output.contains("\x1b[48;2;0;255;128m"));
495    }
496
497    #[test]
498    fn test_italic_ansi() {
499        let node = ContentNode::plain("italic").with_italic();
500        let output = renderer().render(&node);
501        assert!(output.contains("\x1b[3m"));
502    }
503
504    #[test]
505    fn test_underline_ansi() {
506        let node = ContentNode::plain("underline").with_underline();
507        let output = renderer().render(&node);
508        assert!(output.contains("\x1b[4m"));
509    }
510
511    #[test]
512    fn test_dim_ansi() {
513        let node = ContentNode::plain("dim").with_dim();
514        let output = renderer().render(&node);
515        assert!(output.contains("\x1b[2m"));
516    }
517
518    #[test]
519    fn test_combined_styles() {
520        let node = ContentNode::plain("styled")
521            .with_bold()
522            .with_fg(Color::Named(NamedColor::Green));
523        let output = renderer().render(&node);
524        // Should contain both bold (1) and green fg (32)
525        assert!(output.contains("1;32") || output.contains("32;1"));
526        assert!(output.contains("styled"));
527    }
528
529    #[test]
530    fn test_rounded_table() {
531        let table = ContentNode::Table(ContentTable {
532            headers: vec!["Name".into(), "Age".into()],
533            rows: vec![
534                vec![ContentNode::plain("Alice"), ContentNode::plain("30")],
535                vec![ContentNode::plain("Bob"), ContentNode::plain("25")],
536            ],
537            border: BorderStyle::Rounded,
538            max_rows: None,
539            column_types: None,
540            total_rows: None,
541            sortable: false,
542        });
543        let output = renderer().render(&table);
544        assert!(output.contains("\u{256d}")); // ╭
545        assert!(output.contains("\u{256f}")); // ╯
546        assert!(output.contains("Alice"));
547        assert!(output.contains("Bob"));
548    }
549
550    #[test]
551    fn test_heavy_table() {
552        let table = ContentNode::Table(ContentTable {
553            headers: vec!["X".into()],
554            rows: vec![vec![ContentNode::plain("1")]],
555            border: BorderStyle::Heavy,
556            max_rows: None,
557            column_types: None,
558            total_rows: None,
559            sortable: false,
560        });
561        let output = renderer().render(&table);
562        assert!(output.contains("\u{250f}")); // ┏
563        assert!(output.contains("\u{251b}")); // ┛
564    }
565
566    #[test]
567    fn test_double_table() {
568        let table = ContentNode::Table(ContentTable {
569            headers: vec!["X".into()],
570            rows: vec![vec![ContentNode::plain("1")]],
571            border: BorderStyle::Double,
572            max_rows: None,
573            column_types: None,
574            total_rows: None,
575            sortable: false,
576        });
577        let output = renderer().render(&table);
578        assert!(output.contains("\u{2554}")); // ╔
579        assert!(output.contains("\u{255d}")); // ╝
580    }
581
582    #[test]
583    fn test_table_max_rows_truncation() {
584        let table = ContentNode::Table(ContentTable {
585            headers: vec!["X".into()],
586            rows: vec![
587                vec![ContentNode::plain("1")],
588                vec![ContentNode::plain("2")],
589                vec![ContentNode::plain("3")],
590                vec![ContentNode::plain("4")],
591            ],
592            border: BorderStyle::Rounded,
593            max_rows: Some(2),
594            column_types: None,
595            total_rows: None,
596            sortable: false,
597        });
598        let output = renderer().render(&table);
599        assert!(output.contains("1"));
600        assert!(output.contains("2"));
601        assert!(!output.contains(" 3 "));
602        assert!(output.contains("... 2 more rows"));
603    }
604
605    #[test]
606    fn test_no_border_table() {
607        let table = ContentNode::Table(ContentTable {
608            headers: vec!["A".into(), "B".into()],
609            rows: vec![vec![ContentNode::plain("x"), ContentNode::plain("y")]],
610            border: BorderStyle::None,
611            max_rows: None,
612            column_types: None,
613            total_rows: None,
614            sortable: false,
615        });
616        let output = renderer().render(&table);
617        assert!(output.contains("A"));
618        assert!(output.contains("B"));
619        assert!(output.contains("x"));
620        assert!(output.contains("y"));
621        // Should not contain box-drawing characters
622        assert!(!output.contains("\u{256d}"));
623        assert!(!output.contains("\u{2500}"));
624    }
625
626    #[test]
627    fn test_code_block_with_language() {
628        let code = ContentNode::Code {
629            language: Some("rust".into()),
630            source: "fn main() {\n    println!(\"hi\");\n}".into(),
631        };
632        let output = renderer().render(&code);
633        assert!(output.contains("[rust]"));
634        assert!(output.contains("    fn main() {"));
635    }
636
637    #[test]
638    fn test_code_block_no_language() {
639        let code = ContentNode::Code {
640            language: None,
641            source: "hello".into(),
642        };
643        let output = renderer().render(&code);
644        assert!(!output.contains("["));
645        assert!(output.contains("    hello"));
646    }
647
648    #[test]
649    fn test_chart_placeholder() {
650        let chart = ContentNode::Chart(shape_value::content::ChartSpec {
651            chart_type: shape_value::content::ChartType::Line,
652            series: vec![],
653            title: Some("Revenue".into()),
654            x_label: None,
655            y_label: None,
656            width: None,
657            height: None,
658            echarts_options: None,
659            interactive: true,
660        });
661        let output = renderer().render(&chart);
662        assert!(output.contains("Line Chart: Revenue (0 series)"));
663    }
664
665    #[test]
666    fn test_key_value_aligned() {
667        let kv = ContentNode::KeyValue(vec![
668            ("name".into(), ContentNode::plain("Alice")),
669            ("age".into(), ContentNode::plain("30")),
670            ("location".into(), ContentNode::plain("NYC")),
671        ]);
672        let output = renderer().render(&kv);
673        assert!(output.contains("name"));
674        assert!(output.contains("Alice"));
675        assert!(output.contains("location"));
676        assert!(output.contains("NYC"));
677    }
678
679    #[test]
680    fn test_fragment_concatenation() {
681        let frag = ContentNode::Fragment(vec![
682            ContentNode::plain("hello "),
683            ContentNode::plain("world"),
684        ]);
685        let output = renderer().render(&frag);
686        assert_eq!(output, "hello world");
687    }
688
689    #[test]
690    fn test_sharp_table_borders() {
691        let table = ContentNode::Table(ContentTable {
692            headers: vec!["X".into()],
693            rows: vec![vec![ContentNode::plain("1")]],
694            border: BorderStyle::Sharp,
695            max_rows: None,
696            column_types: None,
697            total_rows: None,
698            sortable: false,
699        });
700        let output = renderer().render(&table);
701        assert!(output.contains("\u{250c}")); // ┌
702        assert!(output.contains("\u{2518}")); // ┘
703    }
704}