Files
zesdex/src/view/markdown.rs
T
asepharyana 683715cd7a feat(view): Tambah parameter dim dan pewarnaan baris diff di markdown renderer
Tambahkan helper apply_dim dan diff_line_style, ubah signature
render_markdown untuk menerima flag dim, serta deteksi fence bahasa
diff sehingga baris +/-/@@ tetap berwarna meskipun pesan sedang
dirender dim (tampilan tool-output).
2026-07-15 06:32:57 +07:00

478 lines
21 KiB
Rust

//! Markdown-to-styled-spans rendering for the chat transcript.
//!
//! Flow: `render_markdown` walks a `pulldown_cmark` event stream and
//! translates each markdown construct into styled `ratatui::text::Span`s,
//! then re-wraps the flat span list to a target column width.
//!
//! Design: code blocks get a dark background with a labeled top bar,
//! headings are bold with distinct colors, blockquotes get a vertical
//! accent bar prefix, and inline code is highlighted with a background.
//! Deliberately adds no leading indentation of its own for paragraphs,
//! headings, or list bullets — the caller (`chat.rs`) owns column
//! alignment via its `PREFIX_WIDTH` scheme, so any indent added here
//! would only apply to a construct's first rendered line and throw
//! wrapped continuation lines out of alignment with it. Code-block lines
//! are the exception: every line gets its `" "` prefix independently
//! and consistently, so there's no first-line-only misalignment there.
use ratatui::style::{Modifier, Style};
use ratatui::text::Span;
use super::theme::Theme;
/// Apply the "tool output" dim/italic style, or pass `style` through
/// unchanged, depending on `dim`.
fn apply_dim(style: Style, dim: bool) -> Style {
if dim {
Style::default().fg(Theme::TEXT_DIM).add_modifier(Modifier::ITALIC)
} else {
style
}
}
/// Classify a single line inside a ` ```diff ` fenced block by its unified-diff
/// prefix, returning the color it should always render with (even when the
/// surrounding tool output is dimmed) — or `None` for context lines and the
/// `+++`/`---` file-header lines, which use the normal code-block color.
fn diff_line_style(line: &str) -> Option<Style> {
if line.starts_with("@@") {
Some(Style::default().fg(Theme::INFO).bg(Theme::CODE_BG))
} else if line.starts_with('+') && !line.starts_with("+++") {
Some(Style::default().fg(Theme::SUCCESS).bg(Theme::CODE_BG))
} else if line.starts_with('-') && !line.starts_with("---") {
Some(Style::default().fg(Theme::ERROR).bg(Theme::CODE_BG))
} else {
None
}
}
/// Render a markdown string into styled terminal spans, word-wrapped to `width`.
///
/// Flow: `pulldown_cmark` parses `text` into an event stream → each
/// Start/End/Text/Code/Break event is translated into styled `Span`s →
/// if `width > 0`, a second pass wraps long lines.
///
/// `dim`: when `true`, every span falls back to `Theme::TEXT_DIM` + italic
/// (the "tool output" look) *except* lines inside a ` ```diff ` fenced
/// block, which always keep their +/-/@@ diff color regardless of `dim` —
/// this is what lets diff output stay colored inside otherwise-dimmed
/// `Role::Tool` chat messages.
///
/// Return: a flat vec of styled spans; `chat::split_spans_into_lines`
/// turns it back into `Line`s for the Paragraph widget.
#[allow(clippy::too_many_lines)]
pub fn render_markdown(text: &str, width: u16, dim: bool) -> Vec<Span<'static>> {
let mut spans = Vec::new();
let mut options = pulldown_cmark::Options::empty();
options.insert(pulldown_cmark::Options::ENABLE_TABLES);
let parser = pulldown_cmark::Parser::new_ext(text, options);
let mut in_code_block = false;
let mut in_diff_block = false;
let mut in_heading = false;
let mut heading_level = 0;
let mut in_table_cell = false;
let mut table_rows: Vec<Vec<Vec<Span<'static>>>> = Vec::new();
let mut current_row: Vec<Vec<Span<'static>>> = Vec::new();
let mut current_cell: Vec<Span<'static>> = Vec::new();
for event in parser {
match event {
pulldown_cmark::Event::Start(tag) => {
match tag {
pulldown_cmark::Tag::CodeBlock(kind) => {
in_code_block = true;
in_diff_block = matches!(
&kind,
pulldown_cmark::CodeBlockKind::Fenced(lang) if lang.as_ref() == "diff"
);
// Code block top bar
spans.push(Span::styled(
"\n",
Style::default(),
));
spans.push(Span::styled(
" ┌─ code ",
apply_dim(Style::default().fg(Theme::TEXT_MUTED).bg(Theme::CODE_BG), dim),
));
spans.push(Span::styled(
"\n",
Style::default(),
));
}
pulldown_cmark::Tag::Heading { level, .. } => {
in_heading = true;
heading_level = match level {
pulldown_cmark::HeadingLevel::H1 => 1,
pulldown_cmark::HeadingLevel::H2 => 2,
pulldown_cmark::HeadingLevel::H3 => 3,
_ => 4,
};
// No prefix, we'll handle in the text events
}
pulldown_cmark::Tag::Item => {
// List item bullet
spans.push(Span::styled(
"• ",
apply_dim(Style::default().fg(Theme::PRIMARY), dim),
));
}
pulldown_cmark::Tag::Link { dest_url, .. } => {
spans.push(Span::styled(
"[",
apply_dim(Style::default().fg(Theme::INFO), dim),
));
// We push the URL as a tooltip-like suffix
// After the link text ends, we'll add the URL
spans.push(Span::styled(
format!("]({dest_url})"),
apply_dim(Style::default().fg(Theme::TEXT_MUTED).add_modifier(Modifier::ITALIC), dim),
));
}
pulldown_cmark::Tag::BlockQuote(_) => {
spans.push(Span::styled(
"▎",
apply_dim(Style::default().fg(Theme::BLOCKQUOTE_BAR), dim),
));
}
pulldown_cmark::Tag::Table(_) => {
table_rows.clear();
}
pulldown_cmark::Tag::TableHead | pulldown_cmark::Tag::TableRow => {
current_row.clear();
}
pulldown_cmark::Tag::TableCell => {
in_table_cell = true;
current_cell.clear();
}
_ => {}
}
}
pulldown_cmark::Event::End(tag) => {
match tag {
pulldown_cmark::TagEnd::CodeBlock => {
in_code_block = false;
in_diff_block = false;
// Code block bottom bar
spans.push(Span::styled(
"\n └─\n",
apply_dim(Style::default().fg(Theme::TEXT_MUTED).bg(Theme::CODE_BG), dim),
));
}
pulldown_cmark::TagEnd::Heading(_) => {
in_heading = false;
heading_level = 0;
spans.push(Span::raw("\n"));
}
pulldown_cmark::TagEnd::Paragraph => {
spans.push(Span::raw("\n\n"));
}
pulldown_cmark::TagEnd::Item | pulldown_cmark::TagEnd::BlockQuote(_) => {
spans.push(Span::raw("\n"));
}
pulldown_cmark::TagEnd::TableCell => {
in_table_cell = false;
current_row.push(std::mem::take(&mut current_cell));
}
pulldown_cmark::TagEnd::TableHead | pulldown_cmark::TagEnd::TableRow => {
table_rows.push(std::mem::take(&mut current_row));
}
pulldown_cmark::TagEnd::Table => {
let cols_count = table_rows.first().map(|r| r.len()).unwrap_or(0);
if cols_count == 0 {
continue;
}
let mut col_widths = vec![0; cols_count];
for row in &table_rows {
for (i, cell) in row.iter().enumerate() {
if i < cols_count {
let cell_width: usize = cell.iter().map(|s| s.content.chars().count()).sum();
if cell_width > col_widths[i] {
col_widths[i] = cell_width;
}
}
}
}
let effective_width = if width > 0 { (width as usize).saturating_sub(2) } else { 0 };
let border_overhead = cols_count * 3 + 4;
let available_width = effective_width.saturating_sub(border_overhead);
let mut total_width: usize = col_widths.iter().sum();
if width > 0 && total_width > available_width && available_width > 0 {
while total_width > available_width {
let max_idx = col_widths.iter().enumerate().max_by_key(|&(_, &w)| w).map(|(i, _)| i).unwrap();
if col_widths[max_idx] <= 3 { break; }
col_widths[max_idx] -= 1;
total_width -= 1;
}
}
spans.push(Span::raw("\n"));
for (r, row) in table_rows.iter().enumerate() {
let mut cell_lines = Vec::new();
for (i, cell) in row.iter().enumerate() {
if i < cols_count {
cell_lines.push(wrap_spans_to_lines(cell, col_widths[i]));
}
}
let max_height = cell_lines.iter().map(|cl| cl.len()).max().unwrap_or(1);
for y in 0..max_height {
spans.push(Span::styled(" | ", apply_dim(Style::default().fg(Theme::BORDER), dim)));
for (i, cl) in cell_lines.iter().enumerate() {
let line_spans = if y < cl.len() { &cl[y] } else { [].as_slice() };
let mut line_width = 0;
for span in line_spans {
line_width += span.content.chars().count();
spans.push(span.clone());
}
let pad = col_widths[i].saturating_sub(line_width);
spans.push(Span::raw(" ".repeat(pad)));
spans.push(Span::styled(" | ", apply_dim(Style::default().fg(Theme::BORDER), dim)));
}
spans.push(Span::raw("\n"));
}
if r == 0 {
spans.push(Span::styled(" |", apply_dim(Style::default().fg(Theme::BORDER), dim)));
for w in &col_widths {
spans.push(Span::styled(format!("{}-|", "-".repeat(*w + 2)), apply_dim(Style::default().fg(Theme::BORDER), dim)));
}
spans.push(Span::raw("\n"));
}
}
spans.push(Span::raw("\n"));
}
_ => {}
}
}
pulldown_cmark::Event::Text(text) => {
let s = text.to_string();
if in_code_block {
if in_diff_block {
for (i, line) in s.split('\n').enumerate() {
if i > 0 {
spans.push(Span::raw("\n"));
}
if line.is_empty() {
continue;
}
let style = diff_line_style(line)
.unwrap_or_else(|| Style::default().fg(Theme::ACCENT_TEAL).bg(Theme::CODE_BG));
spans.push(Span::styled(format!(" {line}"), style));
}
} else {
let indented = format!(" {}", s.replace('\n', "\n "));
spans.push(Span::styled(
indented,
apply_dim(Style::default().fg(Theme::ACCENT_TEAL).bg(Theme::CODE_BG), dim),
));
}
} else if in_heading {
let color = match heading_level {
1 => Theme::PRIMARY,
2 => Theme::INFO,
3 => Theme::ACCENT_PURPLE,
_ => Theme::TEXT,
};
spans.push(Span::styled(
s,
apply_dim(Style::default().fg(color).add_modifier(Modifier::BOLD), dim),
));
} else if in_table_cell {
current_cell.push(Span::styled(s, apply_dim(Style::default(), dim)));
} else {
spans.push(Span::styled(s, apply_dim(Style::default(), dim)));
}
}
pulldown_cmark::Event::Code(text) => {
let span = Span::styled(
format!(" {text} "),
apply_dim(
Style::default()
.fg(Theme::ACCENT_TEAL)
.bg(Theme::CODE_BAR)
.add_modifier(Modifier::BOLD),
dim,
),
);
if in_table_cell {
current_cell.push(span);
} else {
spans.push(span);
}
}
pulldown_cmark::Event::SoftBreak => {
spans.push(Span::raw(" "));
}
pulldown_cmark::Event::HardBreak => {
spans.push(Span::raw("\n"));
}
_ => {}
}
}
if width > 0 {
let mut spans_out = Vec::new();
let mut line_len = 0;
let effective_width = (width as usize).saturating_sub(2); // leave margin
for span in spans {
let style = span.style;
let text = span.content.as_ref();
let mut current = String::new();
let mut tokens = Vec::new();
for c in text.chars() {
if c == ' ' {
if !current.is_empty() { tokens.push(current.clone()); current.clear(); }
tokens.push(" ".to_string());
} else if c == '\n' {
if !current.is_empty() { tokens.push(current.clone()); current.clear(); }
tokens.push("\n".to_string());
} else {
current.push(c);
}
}
if !current.is_empty() { tokens.push(current); }
for token in tokens {
if token == "\n" {
spans_out.push(Span::styled("\n", style));
line_len = 0;
} else if token == " " {
if line_len > 0 && line_len < effective_width {
spans_out.push(Span::styled(" ", style));
line_len += 1;
}
} else {
let token_len = token.chars().count();
if line_len + token_len > effective_width && line_len > 0 {
spans_out.push(Span::raw("\n"));
line_len = 0;
}
if token_len > effective_width {
for c in token.chars() {
if line_len >= effective_width {
spans_out.push(Span::raw("\n"));
line_len = 0;
}
spans_out.push(Span::styled(c.to_string(), style));
line_len += 1;
}
} else {
spans_out.push(Span::styled(token, style));
line_len += token_len;
}
}
}
}
spans = spans_out;
}
spans
}
fn wrap_spans_to_lines(spans: &[Span<'static>], target_width: usize) -> Vec<Vec<Span<'static>>> {
let mut lines = Vec::new();
let mut current_line = Vec::new();
let mut line_len = 0;
for span in spans {
let style = span.style;
let text = span.content.as_ref();
let mut current_word = String::new();
let mut tokens = Vec::new();
for c in text.chars() {
if c == ' ' {
if !current_word.is_empty() { tokens.push(current_word.clone()); current_word.clear(); }
tokens.push(" ".to_string());
} else {
current_word.push(c);
}
}
if !current_word.is_empty() { tokens.push(current_word); }
for token in tokens {
if token == " " {
if line_len > 0 && line_len < target_width {
current_line.push(Span::styled(" ", style));
line_len += 1;
}
} else {
let token_len = token.chars().count();
if line_len + token_len > target_width && line_len > 0 {
lines.push(std::mem::take(&mut current_line));
line_len = 0;
}
if token_len > target_width {
for c in token.chars() {
if target_width > 0 && line_len >= target_width {
lines.push(std::mem::take(&mut current_line));
line_len = 0;
}
current_line.push(Span::styled(c.to_string(), style));
line_len += 1;
}
} else {
current_line.push(Span::styled(token, style));
line_len += token_len;
}
}
}
}
if !current_line.is_empty() {
lines.push(current_line);
}
if lines.is_empty() {
lines.push(vec![]);
}
lines
}
#[cfg(test)]
mod tests {
use super::*;
fn span_text(spans: &[Span<'static>]) -> String {
spans.iter().map(|s| s.content.as_ref()).collect()
}
#[test]
fn dim_false_plain_text_has_no_color() {
let spans = render_markdown("hello world", 0, false);
assert_eq!(span_text(&spans), "hello world");
assert_eq!(spans[0].style, Style::default());
}
#[test]
fn dim_true_plain_text_is_dim_italic() {
let spans = render_markdown("hello", 0, true);
let expected = Style::default().fg(Theme::TEXT_DIM).add_modifier(Modifier::ITALIC);
assert_eq!(spans[0].style, expected);
}
#[test]
fn dim_true_diff_lines_keep_their_own_color() {
let md = "```diff\n@@ -1,2 +1,2 @@\n-old line\n+new line\n context line\n```";
let spans = render_markdown(md, 0, true);
let plus_span = spans.iter().find(|s| s.content.contains("+new line")).expect("plus span present");
assert_eq!(plus_span.style.fg, Some(Theme::SUCCESS));
let minus_span = spans.iter().find(|s| s.content.contains("-old line")).expect("minus span present");
assert_eq!(minus_span.style.fg, Some(Theme::ERROR));
let hunk_span = spans.iter().find(|s| s.content.contains("@@")).expect("hunk header span present");
assert_eq!(hunk_span.style.fg, Some(Theme::INFO));
}
#[test]
fn dim_true_non_diff_code_block_is_dimmed() {
let md = "```rust\nfn main() {}\n```";
let spans = render_markdown(md, 0, true);
let code_span = spans.iter().find(|s| s.content.contains("fn main")).expect("code span present");
assert_eq!(code_span.style, Style::default().fg(Theme::TEXT_DIM).add_modifier(Modifier::ITALIC));
}
}