mbterm 0.1.4

ANSI terminal renderer for MBDown documents
Documentation
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

use crate::{bbcode, table, Color, Theme};
use mbdown::Padding;

const MIN_FRAME_WIDTH: usize = 4;

#[derive(Clone, Copy)]
pub(crate) enum FrameStyle<'a> {
    Semantic(&'a str),
    Color(&'a str),
}

pub(crate) fn render(
    title: &str,
    content: &str,
    width: usize,
    theme: &Theme,
    style: FrameStyle<'_>,
) -> String {
    render_with_background(
        title,
        content,
        width,
        theme,
        style,
        None,
        Padding { x: 1, y: 0 },
    )
}

pub(crate) fn render_with_background(
    title: &str,
    content: &str,
    width: usize,
    theme: &Theme,
    style: FrameStyle<'_>,
    background: Option<Color>,
    padding: Padding,
) -> String {
    let title = bbcode::sanitize_terminal_controls(title.trim());
    let width = width.max(MIN_FRAME_WIDTH);
    let padding_x = padding.x.min(width.saturating_sub(3) / 2);
    let inner_width = width.saturating_sub(2 + padding_x.saturating_mul(2)).max(1);
    let corners = theme.corner_style();
    let mut output = styled(
        theme,
        style,
        &top_border(&title, width, corners),
        background,
    );

    let lines = content_lines(content, inner_width);
    for _ in 0..padding.y {
        append_content_line(
            &mut output,
            "",
            inner_width,
            padding_x,
            theme,
            style,
            background,
        );
    }
    for line in lines {
        append_content_line(
            &mut output,
            &line,
            inner_width,
            padding_x,
            theme,
            style,
            background,
        );
    }
    for _ in 0..padding.y {
        append_content_line(
            &mut output,
            "",
            inner_width,
            padding_x,
            theme,
            style,
            background,
        );
    }
    output.push('\n');
    output.push_str(&styled(
        theme,
        style,
        &format!(
            "{}{}{}",
            corners.bottom_left(),
            "─".repeat(width.saturating_sub(2)),
            corners.bottom_right()
        ),
        background,
    ));
    output
}

#[allow(clippy::too_many_arguments)]
fn append_content_line(
    output: &mut String,
    line: &str,
    inner_width: usize,
    padding_x: usize,
    theme: &Theme,
    style: FrameStyle<'_>,
    background: Option<Color>,
) {
    output.push('\n');
    output.push_str(&styled(theme, style, "│", background));
    output.extend(std::iter::repeat_n(' ', padding_x));
    output.push_str(line);
    output.extend(std::iter::repeat_n(
        ' ',
        inner_width.saturating_sub(table::visible_width(line)) + padding_x,
    ));
    output.push_str(&styled(theme, style, "│", background));
}

fn top_border(title: &str, width: usize, corners: crate::CornerStyle) -> String {
    let available = width.saturating_sub(2);
    if title.is_empty() || available < 4 {
        return format!(
            "{}{}{}",
            corners.top_left(),
            "─".repeat(available),
            corners.top_right()
        );
    }
    let title_width = available.saturating_sub(3);
    let title = truncate(title, title_width);
    let used = 3 + UnicodeWidthStr::width(title.as_str());
    format!(
        "{}─ {title} {}{}",
        corners.top_left(),
        "─".repeat(available.saturating_sub(used)),
        corners.top_right()
    )
}

fn truncate(value: &str, maximum: usize) -> String {
    if UnicodeWidthStr::width(value) <= maximum {
        return value.to_string();
    }
    if maximum == 0 {
        return String::new();
    }
    let ellipsis_width = UnicodeWidthChar::width('…').unwrap_or(1);
    let target = maximum.saturating_sub(ellipsis_width);
    let mut result = String::new();
    let mut width = 0;
    for ch in value.chars() {
        let char_width = UnicodeWidthChar::width(ch).unwrap_or(0);
        if width + char_width > target {
            break;
        }
        result.push(ch);
        width += char_width;
    }
    result.push('…');
    result
}

fn content_lines(content: &str, width: usize) -> Vec<String> {
    let mut lines = Vec::new();
    for line in content.split('\n') {
        lines.extend(table::wrap_ansi(line, width));
    }
    if lines.is_empty() {
        lines.push(String::new());
    }
    lines
}

fn styled(theme: &Theme, style: FrameStyle<'_>, value: &str, background: Option<Color>) -> String {
    let escaped = escape_bbcode(value);
    let escaped = match background {
        Some(color) => format!("[bg={}]{}[/bg]", bbcode::color_value(color), escaped),
        None => escaped,
    };
    let markup = match style {
        FrameStyle::Semantic(style) => format!("[{style}]{escaped}[/{style}]"),
        FrameStyle::Color(color) => format!("[color={color}]{escaped}[/color]"),
    };
    bbcode::render(&markup, true, theme)
}

fn escape_bbcode(value: &str) -> String {
    let mut output = String::with_capacity(value.len());
    for ch in value.chars() {
        if matches!(ch, '[' | ']' | '\\') {
            output.push('\\');
        }
        output.push(ch);
    }
    output
}