Skip to main content

trusty_code_tui/render/
markdown.rs

1//! Markdown-aware rendering helpers for the chat scrollback: fenced
2//! code-block detection and box-drawing table rendering.
3//!
4//! Why: DOC-50 §5 Slice 4 migrates tagent's `repl/tui/markdown.rs` (297
5//! lines) into this shared crate verbatim — every function here is already
6//! engine-agnostic (pure `&str`/`Vec<String>` in, `Line`/`Span` out; no
7//! `ReplApp` dependency), so the migration is a straight move rather than a
8//! generalization. [`crate::widgets::scrollback::build_chat_lines`] is the
9//! sole caller, walking a message body line-by-line and dispatching to
10//! [`code_fence_lang`]/[`is_executable_shell_lang`] (fence detection) or
11//! [`is_md_table_row`]/[`is_md_table_separator`]/[`parse_md_table_cells`]/
12//! [`render_markdown_table`] (table detection) as it goes.
13//!
14//! What: no state, no I/O — every function is a pure transform, which is why
15//! this module lives under [`crate::render`] rather than [`crate::widgets`]
16//! (see that module's doc comment for the distinction).
17//!
18//! # Spec References
19//! - [`SPEC-TTUI-05~draft`](docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-05~draft) — Slice 4 deliverable (§5, Slice 4): migrate `markdown.rs`.
20
21use ratatui::style::{Color, Modifier, Style};
22use ratatui::text::{Line, Span};
23
24/// Parse a fenced code-block opener line and return the language tag.
25///
26/// Why: We need to distinguish opening fences (` ```bash `) from closing
27/// fences (` ``` `) and from non-fence content. Returning `Some(lang)` for
28/// openers (including `Some("")` for bare ``` ``` openers) and `None` for
29/// anything that isn't a fence line at all lets the renderer drive its state
30/// machine cleanly.
31/// What: Trims the line; if it starts with three backticks, returns the
32/// trailing tag (lowercased) — empty string for bare openers, `None` for
33/// anything that isn't a fence line at all.
34/// Test: `tests::code_fence_lang_recognizes_openers_and_closers`.
35pub fn code_fence_lang(line: &str) -> Option<String> {
36    let t = line.trim();
37    t.strip_prefix("```")
38        .map(|rest| rest.trim().to_ascii_lowercase())
39}
40
41/// Whether a fenced-code-block language tag denotes an executable shell.
42///
43/// Why: Shell blocks get a distinct visual treatment from other languages so
44/// a reader can spot "this is something you could paste into a terminal" at
45/// a glance.
46/// What: Matches `bash`, `sh`, `zsh`, `fish` (case-insensitive — caller
47/// passes a lowercased tag).
48/// Test: `tests::is_executable_shell_lang_matches_shells`.
49pub fn is_executable_shell_lang(lang: &str) -> bool {
50    matches!(lang, "bash" | "sh" | "zsh" | "fish")
51}
52
53/// Extract the last executable-shell fenced code block body from a message.
54///
55/// Why: When a message contains multiple shell blocks, "grab the most
56/// recently shown command" needs the *last* one, not the first.
57/// What: Walks the lines, tracks fence state, and returns `Some(body)` of the
58/// last completed bash/sh/zsh/fish block. Body lines are joined with `\n`.
59/// Returns `None` if no executable shell block is found, or the block was
60/// opened but never closed (an unclosed fence is discarded, not inferred to
61/// end at EOF — a truncated response should not be pasted as a partial
62/// command).
63/// Test: `tests::extract_last_shell_block_finds_bash`,
64/// `tests::extract_last_shell_block_returns_last_when_multiple`,
65/// `tests::extract_last_shell_block_ignores_non_shell`,
66/// `tests::extract_last_shell_block_none_without_block`,
67/// `tests::extract_last_shell_block_unclosed_fence_returns_none`,
68/// `tests::extract_last_shell_block_closed_then_unclosed_returns_closed`.
69pub fn extract_last_shell_block(text: &str) -> Option<String> {
70    let mut last: Option<String> = None;
71    let mut current_body: Option<Vec<String>> = None;
72    let mut in_shell = false;
73    for line in text.lines() {
74        if let Some(lang) = code_fence_lang(line) {
75            if let Some(body) = current_body.take() {
76                if in_shell {
77                    last = Some(body.join("\n"));
78                }
79                in_shell = false;
80            } else {
81                in_shell = is_executable_shell_lang(&lang);
82                current_body = Some(Vec::new());
83            }
84        } else if let Some(body) = current_body.as_mut() {
85            body.push(line.to_string());
86        }
87    }
88    last
89}
90
91/// Detect a markdown table row: trimmed line starts with `|`.
92///
93/// Why: Table detection is the gate for box-drawing rendering — non-table
94/// lines fall through to plain rendering.
95/// What: Returns true if the trimmed line starts with `|`.
96/// Test: `tests::is_md_table_row_basic`.
97pub fn is_md_table_row(line: &str) -> bool {
98    line.trim_start().starts_with('|')
99}
100
101/// Detect a markdown table separator row: cells contain only `-`, `:`, spaces.
102///
103/// Why: The separator row distinguishes header from body and confirms a
104/// block is actually a markdown table (not just a line that happens to start
105/// with `|`).
106/// What: Returns true if every non-empty cell after split-on-`|` is composed
107/// solely of `-`, `:`, or whitespace, AND at least one `-` appears.
108/// Test: `tests::is_md_table_separator_basic`.
109pub fn is_md_table_separator(line: &str) -> bool {
110    if !is_md_table_row(line) {
111        return false;
112    }
113    let cells = parse_md_table_cells(line);
114    if cells.is_empty() {
115        return false;
116    }
117    let mut saw_dash = false;
118    for c in &cells {
119        for ch in c.chars() {
120            match ch {
121                '-' => saw_dash = true,
122                ':' | ' ' | '\t' => {}
123                _ => return false,
124            }
125        }
126    }
127    saw_dash
128}
129
130/// Split a markdown table row on `|` and trim each cell.
131///
132/// Why: Markdown table rows have leading and trailing pipes that produce
133/// empty cells when split naïvely; consumers want only the real cell content.
134/// What: Returns the trimmed cell strings, dropping leading/trailing empties
135/// produced by the bordering pipes.
136/// Test: `tests::parse_md_table_cells_basic`.
137pub fn parse_md_table_cells(line: &str) -> Vec<String> {
138    let trimmed = line.trim();
139    let mut parts: Vec<String> = trimmed.split('|').map(|s| s.trim().to_string()).collect();
140    if parts.first().map(|s| s.is_empty()).unwrap_or(false) {
141        parts.remove(0);
142    }
143    if parts.last().map(|s| s.is_empty()).unwrap_or(false) {
144        parts.pop();
145    }
146    parts
147}
148
149/// Truncate a string to `max` display chars, appending `…` if shortened.
150///
151/// Why: Table cells must fit within a column width budget; oversized content
152/// gets a visual ellipsis so the reader knows truncation happened.
153/// What: Returns the input unchanged if it fits, otherwise the first `max-1`
154/// chars + `…`. If `max == 0`, returns an empty string.
155/// Test: `tests::truncate_cell_basic`.
156pub fn truncate_cell(s: &str, max: usize) -> String {
157    if max == 0 {
158        return String::new();
159    }
160    let count = s.chars().count();
161    if count <= max {
162        return s.to_string();
163    }
164    let mut out: String = s.chars().take(max.saturating_sub(1)).collect();
165    out.push('…');
166    out
167}
168
169/// Render a parsed markdown table as box-drawing styled `Line`s.
170///
171/// Why: Inline rendering keeps the table flush with surrounding chat text,
172/// avoiding a layout split for a ratatui `Table` widget. Box characters give
173/// a clean visual frame that scans well in monospaced fonts.
174/// What: Given header + body rows, computes per-column widths (max of header
175/// and any body cell), clamps total table width to `available_width`, and
176/// emits top border, header row, separator, body rows, bottom border. Border
177/// glyphs use `Color::DarkGray`; cell content uses `body_color` if provided.
178/// Test: `tests::render_markdown_table_emits_expected_lines`,
179/// `tests::render_markdown_table_truncates_when_too_wide`.
180pub fn render_markdown_table(
181    header: &[String],
182    body: &[Vec<String>],
183    available_width: usize,
184    indent: &str,
185    body_color: Option<Color>,
186) -> Vec<Line<'static>> {
187    let ncols = header
188        .len()
189        .max(body.iter().map(|r| r.len()).max().unwrap_or(0));
190    if ncols == 0 {
191        return Vec::new();
192    }
193
194    let header_n: Vec<String> = (0..ncols)
195        .map(|i| header.get(i).cloned().unwrap_or_default())
196        .collect();
197    let body_n: Vec<Vec<String>> = body
198        .iter()
199        .map(|r| {
200            (0..ncols)
201                .map(|i| r.get(i).cloned().unwrap_or_default())
202                .collect()
203        })
204        .collect();
205
206    let mut widths: Vec<usize> = (0..ncols)
207        .map(|i| {
208            let mut w = header_n[i].chars().count();
209            for r in &body_n {
210                w = w.max(r[i].chars().count());
211            }
212            w
213        })
214        .collect();
215
216    let indent_w = indent.chars().count();
217    let frame_overhead = 1 + ncols;
218    let padding_per_col = 2;
219    let mut total: usize =
220        indent_w + frame_overhead + widths.iter().map(|w| w + padding_per_col).sum::<usize>();
221
222    let limit = available_width.max(indent_w + frame_overhead + ncols * (padding_per_col + 1));
223    while total > available_width && available_width > 0 {
224        let widest = widths
225            .iter()
226            .enumerate()
227            .filter(|(_, w)| **w > 1)
228            .max_by_key(|(_, w)| **w)
229            .map(|(i, _)| i);
230        match widest {
231            Some(i) => {
232                widths[i] -= 1;
233                total -= 1;
234            }
235            None => break,
236        }
237    }
238    let _ = limit;
239
240    let border_style = Style::default()
241        .fg(Color::DarkGray)
242        .add_modifier(Modifier::DIM);
243    let cell_style = match body_color {
244        Some(c) => Style::default().fg(c),
245        None => Style::default(),
246    };
247
248    let make_border = |left: char, mid: char, right: char| -> String {
249        let mut s = String::new();
250        s.push_str(indent);
251        s.push(left);
252        for (i, w) in widths.iter().enumerate() {
253            for _ in 0..(w + padding_per_col) {
254                s.push('─');
255            }
256            if i + 1 < widths.len() {
257                s.push(mid);
258            }
259        }
260        s.push(right);
261        s
262    };
263
264    let make_data_row = |cells: &[String]| -> Line<'static> {
265        let mut spans: Vec<Span<'static>> = Vec::with_capacity(ncols * 2 + 2);
266        spans.push(Span::raw(indent.to_string()));
267        spans.push(Span::styled("│".to_string(), border_style));
268        for (i, w) in widths.iter().enumerate() {
269            let cell = truncate_cell(&cells[i], *w);
270            let pad_right = w.saturating_sub(cell.chars().count());
271            let mut content = String::with_capacity(2 + w);
272            content.push(' ');
273            content.push_str(&cell);
274            for _ in 0..pad_right {
275                content.push(' ');
276            }
277            content.push(' ');
278            spans.push(Span::styled(content, cell_style));
279            let _ = i;
280            spans.push(Span::styled("│".to_string(), border_style));
281        }
282        Line::from(spans)
283    };
284
285    let mut out: Vec<Line<'static>> = Vec::with_capacity(body_n.len() + 4);
286    out.push(Line::from(Span::styled(
287        make_border('┌', '┬', '┐'),
288        border_style,
289    )));
290    out.push(make_data_row(&header_n));
291    out.push(Line::from(Span::styled(
292        make_border('├', '┼', '┤'),
293        border_style,
294    )));
295    for row in &body_n {
296        out.push(make_data_row(row));
297    }
298    out.push(Line::from(Span::styled(
299        make_border('└', '┴', '┘'),
300        border_style,
301    )));
302    out
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308
309    #[test]
310    fn code_fence_lang_recognizes_openers_and_closers() {
311        assert_eq!(code_fence_lang("```bash"), Some("bash".into()));
312        assert_eq!(code_fence_lang("```sh"), Some("sh".into()));
313        assert_eq!(code_fence_lang("```Rust"), Some("rust".into()));
314        assert_eq!(code_fence_lang("```"), Some("".into()));
315        assert_eq!(code_fence_lang("  ```bash  "), Some("bash".into()));
316        assert_eq!(code_fence_lang("hello"), None);
317        assert_eq!(code_fence_lang("``"), None);
318    }
319
320    #[test]
321    fn is_executable_shell_lang_matches_shells() {
322        assert!(is_executable_shell_lang("bash"));
323        assert!(is_executable_shell_lang("sh"));
324        assert!(is_executable_shell_lang("zsh"));
325        assert!(is_executable_shell_lang("fish"));
326        assert!(!is_executable_shell_lang("rust"));
327        assert!(!is_executable_shell_lang("python"));
328        assert!(!is_executable_shell_lang(""));
329    }
330
331    #[test]
332    fn extract_last_shell_block_finds_bash() {
333        let text = "Run this:\n```bash\necho hello\nls -la\n```\nDone.";
334        assert_eq!(
335            extract_last_shell_block(text),
336            Some("echo hello\nls -la".into())
337        );
338    }
339
340    #[test]
341    fn extract_last_shell_block_returns_last_when_multiple() {
342        let text = "```bash\nfirst\n```\nstuff\n```sh\nsecond\nthird\n```\n";
343        assert_eq!(extract_last_shell_block(text), Some("second\nthird".into()));
344    }
345
346    #[test]
347    fn extract_last_shell_block_ignores_non_shell() {
348        let text = "```rust\nfn main() {}\n```";
349        assert_eq!(extract_last_shell_block(text), None);
350    }
351
352    #[test]
353    fn extract_last_shell_block_none_without_block() {
354        assert_eq!(extract_last_shell_block("plain prose only"), None);
355    }
356
357    #[test]
358    fn extract_last_shell_block_unclosed_fence_returns_none() {
359        let text = "Here's a script:\n```bash\necho hello\nls -la";
360        assert_eq!(extract_last_shell_block(text), None);
361    }
362
363    #[test]
364    fn extract_last_shell_block_closed_then_unclosed_returns_closed() {
365        let text = "```bash\necho first\n```\n```sh\nunclosed";
366        assert_eq!(
367            extract_last_shell_block(text),
368            Some("echo first".to_string())
369        );
370    }
371
372    #[test]
373    fn is_md_table_row_basic() {
374        assert!(is_md_table_row("| a | b |"));
375        assert!(is_md_table_row("  |x|"));
376        assert!(!is_md_table_row("hello"));
377        assert!(!is_md_table_row(""));
378    }
379
380    #[test]
381    fn is_md_table_separator_basic() {
382        assert!(is_md_table_separator("|---|---|"));
383        assert!(is_md_table_separator("| :--- | ---: |"));
384        assert!(is_md_table_separator("|:-:|:-:|"));
385        assert!(!is_md_table_separator("| a | b |"));
386        assert!(!is_md_table_separator("hello"));
387        assert!(!is_md_table_separator("|   |   |"));
388    }
389
390    #[test]
391    fn parse_md_table_cells_basic() {
392        assert_eq!(
393            parse_md_table_cells("| a | b |"),
394            vec!["a".to_string(), "b".to_string()]
395        );
396        assert_eq!(
397            parse_md_table_cells("|x|y|z|"),
398            vec!["x".to_string(), "y".to_string(), "z".to_string()]
399        );
400        assert_eq!(
401            parse_md_table_cells("| Technique | Impact | Effort |"),
402            vec![
403                "Technique".to_string(),
404                "Impact".to_string(),
405                "Effort".to_string()
406            ]
407        );
408    }
409
410    #[test]
411    fn truncate_cell_basic() {
412        assert_eq!(truncate_cell("abc", 5), "abc");
413        assert_eq!(truncate_cell("abcdef", 4), "abc…");
414        assert_eq!(truncate_cell("hello", 0), "");
415        assert_eq!(truncate_cell("hello", 5), "hello");
416    }
417
418    #[test]
419    fn render_markdown_table_emits_expected_lines() {
420        let header = vec![
421            "Technique".to_string(),
422            "Impact".to_string(),
423            "Effort".to_string(),
424        ];
425        let body = vec![
426            vec![
427                "Prompt constraints".to_string(),
428                "10–20%".to_string(),
429                "Low".to_string(),
430            ],
431            vec![
432                "max_tokens caps".to_string(),
433                "Prevents runaway".to_string(),
434                "Low".to_string(),
435            ],
436        ];
437        let out = render_markdown_table(&header, &body, 200, "   ", None);
438        assert_eq!(out.len(), 6);
439        let first: String = out[0]
440            .spans
441            .iter()
442            .map(|s| s.content.as_ref())
443            .collect::<Vec<_>>()
444            .join("");
445        assert!(
446            first.contains('┌'),
447            "expected ┌ in top border, got: {first}"
448        );
449        assert!(first.contains('┬'));
450        assert!(first.contains('┐'));
451        let header_line: String = out[1]
452            .spans
453            .iter()
454            .map(|s| s.content.as_ref())
455            .collect::<Vec<_>>()
456            .join("");
457        assert!(header_line.contains("Technique"));
458        assert!(header_line.contains("Impact"));
459        assert!(header_line.contains("Effort"));
460        let sep_line: String = out[2]
461            .spans
462            .iter()
463            .map(|s| s.content.as_ref())
464            .collect::<Vec<_>>()
465            .join("");
466        assert!(sep_line.contains('├'));
467        assert!(sep_line.contains('┼'));
468        assert!(sep_line.contains('┤'));
469        let last: String = out[5]
470            .spans
471            .iter()
472            .map(|s| s.content.as_ref())
473            .collect::<Vec<_>>()
474            .join("");
475        assert!(last.contains('└'));
476        assert!(last.contains('┴'));
477        assert!(last.contains('┘'));
478        for l in &out {
479            let s: String = l
480                .spans
481                .iter()
482                .map(|sp| sp.content.as_ref())
483                .collect::<Vec<_>>()
484                .join("");
485            assert!(s.starts_with("   "), "line missing indent: {s:?}");
486        }
487    }
488
489    #[test]
490    fn render_markdown_table_truncates_when_too_wide() {
491        let header = vec!["AVeryLongHeaderName".to_string(), "B".to_string()];
492        let body = vec![vec!["X".to_string(), "Y".to_string()]];
493        let out = render_markdown_table(&header, &body, 18, "", None);
494        assert_eq!(out.len(), 5);
495        let header_line: String = out[1]
496            .spans
497            .iter()
498            .map(|s| s.content.as_ref())
499            .collect::<Vec<_>>()
500            .join("");
501        assert!(
502            header_line.chars().count() <= 18,
503            "row too wide: {header_line:?}"
504        );
505    }
506}