mbterm 0.1.0

ANSI terminal renderer for MBDown documents
Documentation
use mbdown::Alignment;
use unicode_width::UnicodeWidthChar;

use crate::ansi::{self, Osc8, Token};
use crate::bbcode::RESET;
use crate::CornerStyle;

#[derive(Debug)]
pub(crate) struct Row {
    pub(crate) cells: Vec<String>,
    pub(crate) header: bool,
}

pub(crate) fn render(
    alignments: &[Alignment],
    rows: &[Row],
    max_width: usize,
    corners: CornerStyle,
) -> String {
    let columns = alignments
        .len()
        .max(rows.iter().map(|row| row.cells.len()).max().unwrap_or(0));
    if columns == 0 {
        return String::new();
    }

    let mut natural = vec![1; columns];
    for row in rows {
        for (index, cell) in row.cells.iter().enumerate() {
            natural[index] = natural[index].max(
                cell.split('\n')
                    .map(visible_width)
                    .max()
                    .unwrap_or(0)
                    .max(1),
            );
        }
    }

    let padding = usize::from(max_width == 0 || columns.saturating_mul(3) < max_width);
    let overhead = columns + 1 + 2 * padding * columns;
    let available = if max_width == 0 {
        natural.iter().sum()
    } else {
        max_width.saturating_sub(overhead).max(columns)
    };
    let widths = allocate_widths(&natural, available);
    let top_border = border(
        &widths,
        padding,
        corners.top_left(),
        '┬',
        corners.top_right(),
        '─',
    );
    let row_border = border(&widths, padding, '├', '┼', '┤', '─');
    let header_border = border(&widths, padding, '╞', '╪', '╡', '═');
    let bottom_border = border(
        &widths,
        padding,
        corners.bottom_left(),
        '┴',
        corners.bottom_right(),
        '─',
    );
    let mut output = String::new();
    output.push_str(&top_border);
    output.push('\n');

    for (row_index, row) in rows.iter().enumerate() {
        let wrapped: Vec<Vec<String>> = (0..columns)
            .map(|column| {
                row.cells.get(column).map_or_else(
                    || vec![String::new()],
                    |cell| wrap_ansi(cell, widths[column]),
                )
            })
            .collect();
        let height = wrapped.iter().map(Vec::len).max().unwrap_or(1);
        for line in 0..height {
            output.push('│');
            for column in 0..columns {
                if padding > 0 {
                    output.push(' ');
                }
                let content = wrapped[column].get(line).map_or("", String::as_str);
                push_aligned(
                    &mut output,
                    content,
                    widths[column],
                    alignments.get(column).copied().unwrap_or(Alignment::None),
                );
                if padding > 0 {
                    output.push(' ');
                }
                output.push('│');
            }
            output.push('\n');
        }
        if row_index + 1 == rows.len() {
            output.push_str(&bottom_border);
        } else if row.header {
            output.push_str(&header_border);
        } else {
            output.push_str(&row_border);
        }
        output.push('\n');
    }
    output.pop();
    output
}

fn allocate_widths(natural: &[usize], available: usize) -> Vec<usize> {
    let mut widths = vec![1; natural.len()];
    let mut remaining = available.saturating_sub(natural.len());
    while remaining > 0 {
        let Some((index, _)) = widths
            .iter()
            .enumerate()
            .filter(|(index, width)| **width < natural[*index])
            .min_by_key(|(_, width)| **width)
        else {
            break;
        };
        widths[index] += 1;
        remaining -= 1;
    }
    widths
}

fn border(
    widths: &[usize],
    padding: usize,
    left: char,
    junction: char,
    right: char,
    fill: char,
) -> String {
    let mut output = String::new();
    output.push(left);
    for (index, width) in widths.iter().enumerate() {
        output.extend(std::iter::repeat_n(fill, width + 2 * padding));
        output.push(if index + 1 == widths.len() {
            right
        } else {
            junction
        });
    }
    output
}

fn push_aligned(output: &mut String, content: &str, width: usize, alignment: Alignment) {
    let content_width = visible_width(content).min(width);
    let remaining = width.saturating_sub(content_width);
    let (left, right) = match alignment {
        Alignment::Right => (remaining, 0),
        Alignment::Center => (remaining / 2, remaining - remaining / 2),
        Alignment::None | Alignment::Left => (0, remaining),
    };
    output.extend(std::iter::repeat_n(' ', left));
    output.push_str(content);
    output.extend(std::iter::repeat_n(' ', right));
}

pub(crate) fn visible_width(input: &str) -> usize {
    ansi::tokens(input)
        .filter_map(|token| match token {
            Token::Char('\n') | Token::Sequence(_) => None,
            Token::Char(character) => UnicodeWidthChar::width(character),
        })
        .sum()
}

pub(crate) fn wrap_ansi(input: &str, max_width: usize) -> Vec<String> {
    wrap_ansi_with_widths(input, max_width, max_width)
}

pub(crate) fn wrap_ansi_with_widths(
    input: &str,
    first_width: usize,
    continuation_width: usize,
) -> Vec<String> {
    if first_width == 0 || continuation_width == 0 {
        return vec![input.to_string()];
    }
    let mut lines = Vec::new();
    let mut line = String::new();
    let mut active_sgr = Vec::new();
    let mut active_link = None;
    let mut width = 0;

    for token in ansi::tokens(input) {
        match token {
            Token::Sequence(sequence) => {
                line.push_str(sequence.as_str());
                update_active_sgr(sequence, &mut active_sgr);
                match sequence.osc8() {
                    Some(Osc8::Open(open)) => active_link = Some(open.to_string()),
                    Some(Osc8::Close) => active_link = None,
                    None => {}
                }
            }
            Token::Char('\n') => {
                finish_line(&mut lines, &mut line, &active_sgr, active_link.as_deref());
                width = 0;
            }
            Token::Char(character) => {
                let character_width = UnicodeWidthChar::width(character).unwrap_or(0);
                let limit = if lines.is_empty() {
                    first_width
                } else {
                    continuation_width
                };
                if character_width > 0 && width > 0 && width + character_width > limit {
                    finish_line(&mut lines, &mut line, &active_sgr, active_link.as_deref());
                    width = 0;
                }
                line.push(character);
                width += character_width;
            }
        }
    }
    if !line.is_empty() || lines.is_empty() {
        if active_link.is_some() {
            line.push_str(ansi::OSC8_CLOSE);
        }
        lines.push(line);
    }
    lines
}

fn finish_line(
    lines: &mut Vec<String>,
    line: &mut String,
    active_sgr: &[String],
    active_link: Option<&str>,
) {
    if active_link.is_some() {
        line.push_str(ansi::OSC8_CLOSE);
    }
    if !active_sgr.is_empty() {
        line.push_str(RESET);
    }
    lines.push(std::mem::take(line));
    for sequence in active_sgr {
        line.push_str(sequence);
    }
    if let Some(open) = active_link {
        line.push_str(open);
    }
}

fn update_active_sgr(sequence: ansi::Sequence<'_>, active: &mut Vec<String>) {
    if !sequence.is_sgr() {
        return;
    }
    if sequence.is_sgr_reset() {
        active.clear();
    } else {
        active.push(sequence.as_str().to_string());
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn wraps_cjk_and_restores_active_sgr_per_physical_line() {
        let lines = wrap_ansi("\x1b[31m天地玄黄\x1b[0m", 4);
        assert_eq!(lines.len(), 2);
        assert_eq!(visible_width(&lines[0]), 4);
        assert_eq!(visible_width(&lines[1]), 4);
        assert!(lines[0].ends_with(RESET));
        assert!(lines[1].starts_with("\x1b[31m"));
    }

    #[test]
    fn wraps_osc8_links_without_linking_padding_or_borders() {
        let open = "\x1b]8;;https://example.test\x07";
        let linked = format!("{open}天地玄黄{}", ansi::OSC8_CLOSE);
        let lines = wrap_ansi(&linked, 4);
        assert_eq!(lines.len(), 2);
        assert_eq!(crate::strip_terminal_sequences(&lines[0]), "天地");
        assert_eq!(crate::strip_terminal_sequences(&lines[1]), "玄黄");
        assert!(lines[0].ends_with(ansi::OSC8_CLOSE), "{:?}", lines[0]);
        assert!(lines[1].starts_with(open), "{:?}", lines[1]);
        assert!(lines[1].ends_with(ansi::OSC8_CLOSE), "{:?}", lines[1]);

        let rendered = render(
            &[Alignment::Left],
            &[Row {
                cells: vec![linked],
                header: false,
            }],
            8,
            CornerStyle::Square,
        );
        let content_lines: Vec<_> = rendered
            .lines()
            .filter(|line| line.starts_with('│'))
            .collect();
        assert_eq!(content_lines.len(), 2);
        for line in content_lines {
            let open_at = line.find(open).unwrap();
            let close_at = line.find(ansi::OSC8_CLOSE).unwrap();
            assert!(open_at >= "│ ".len(), "{line:?}");
            assert!(close_at < line.rfind(" │").unwrap(), "{line:?}");
        }
    }

    #[test]
    fn wraps_first_line_with_a_distinct_width() {
        let lines = wrap_ansi_with_widths("天地玄黄宇宙", 4, 8);
        assert_eq!(lines, vec!["天地", "玄黄宇宙"]);
    }

    #[test]
    fn distributes_width_without_exceeding_budget() {
        assert_eq!(allocate_widths(&[3, 20, 5], 12).iter().sum::<usize>(), 12);
        assert_eq!(allocate_widths(&[2, 2], 20), vec![2, 2]);
    }

    #[test]
    fn renders_connected_utf8_box_drawing_borders() {
        let rows = vec![
            Row {
                cells: vec!["甲".into(), "状态".into()],
                header: true,
            },
            Row {
                cells: vec!["乙".into(), "正常".into()],
                header: false,
            },
        ];
        let rendered = render(
            &[Alignment::Left, Alignment::Left],
            &rows,
            80,
            CornerStyle::Square,
        );
        assert!(rendered.starts_with("┌────┬──────┐\n│ 甲 │ 状态 │"));
        assert!(rendered.contains("╞════╪══════╡"));
        assert!(rendered.ends_with("└────┴──────┘"));

        let rounded = render(
            &[Alignment::Left, Alignment::Left],
            &rows,
            80,
            CornerStyle::Rounded,
        );
        assert!(rounded.starts_with("╭────┬──────╮"));
        assert!(rounded.ends_with("╰────┴──────╯"));
    }
}