mbterm 0.1.4

ANSI terminal renderer for MBDown documents
Documentation
use super::fill_line;
use crate::{table, Color};
use mbdown::{ColumnSpec, ColumnWidth};

const MIN_FLEX_COLUMN_WIDTH: usize = 8;

pub(super) fn allocate_widths(
    specs: &[ColumnSpec],
    available: usize,
    gap: usize,
) -> Option<Vec<usize>> {
    if specs.len() < 2 {
        return None;
    }
    let gap_total = gap.checked_mul(specs.len().saturating_sub(1))?;
    let content_available = available.checked_sub(gap_total)?;
    let fixed_total = specs
        .iter()
        .try_fold(0usize, |total, spec| match spec.width {
            ColumnWidth::Fixed(width) => total.checked_add(width),
            ColumnWidth::Flex(_) => Some(total),
        })?;
    if fixed_total > content_available {
        return None;
    }
    let mut widths = Vec::with_capacity(specs.len());
    let flex_available = content_available - fixed_total;
    let flex_weight: usize = specs
        .iter()
        .map(|spec| match spec.width {
            ColumnWidth::Fixed(_) => 0,
            ColumnWidth::Flex(weight) => weight,
        })
        .sum();
    if flex_weight == 0 {
        return Some(
            specs
                .iter()
                .map(|spec| match spec.width {
                    ColumnWidth::Fixed(width) => width,
                    ColumnWidth::Flex(_) => unreachable!(),
                })
                .collect(),
        );
    }

    let mut assigned = 0;
    for spec in specs {
        match spec.width {
            ColumnWidth::Fixed(width) => widths.push(width),
            ColumnWidth::Flex(weight) => {
                let width =
                    ((flex_available as u128) * (weight as u128) / (flex_weight as u128)) as usize;
                widths.push(width);
                assigned += width;
            }
        }
    }
    let mut remainder = flex_available - assigned;
    for (spec, width) in specs.iter().zip(&mut widths) {
        if remainder == 0 {
            break;
        }
        if matches!(spec.width, ColumnWidth::Flex(_)) {
            *width += 1;
            remainder -= 1;
        }
    }
    if specs.iter().zip(&widths).any(|(spec, width)| {
        matches!(spec.width, ColumnWidth::Flex(_)) && *width < MIN_FLEX_COLUMN_WIDTH
    }) {
        return None;
    }
    Some(widths)
}

pub(super) fn compose(contents: &[String], widths: &[usize], gap: usize) -> String {
    let lines: Vec<Vec<&str>> = contents
        .iter()
        .map(|content| {
            if content.is_empty() {
                vec![""]
            } else {
                content.split('\n').collect()
            }
        })
        .collect();
    let height = lines.iter().map(Vec::len).max().unwrap_or(0);
    let mut output = String::new();
    for row in 0..height {
        if row > 0 {
            output.push('\n');
        }
        let row_start = output.len();
        for column in 0..contents.len() {
            let line = lines[column].get(row).copied().unwrap_or("");
            output.push_str(line);
            if column + 1 < contents.len() {
                output.extend(std::iter::repeat_n(
                    ' ',
                    widths[column].saturating_sub(table::visible_width(line)) + gap,
                ));
            }
        }
        let trimmed = output[row_start..].trim_end_matches(' ').len();
        output.truncate(row_start + trimmed);
    }
    output
}

pub(super) fn compose_filled(
    contents: &[String],
    widths: &[usize],
    gap: usize,
    parent_bg: Option<Color>,
    column_bgs: &[Option<Color>],
) -> String {
    let lines: Vec<Vec<&str>> = contents
        .iter()
        .map(|content| {
            if content.is_empty() {
                vec![""]
            } else {
                content.split('\n').collect()
            }
        })
        .collect();
    let height = lines.iter().map(Vec::len).max().unwrap_or(0);
    let mut output = String::new();
    for row in 0..height {
        if row > 0 {
            output.push('\n');
        }
        let last = if parent_bg.is_some() {
            contents.len().checked_sub(1)
        } else {
            (0..contents.len()).rev().find(|column| {
                column_bgs[*column].is_some()
                    || lines[*column]
                        .get(row)
                        .is_some_and(|line| !line.trim_end_matches(' ').is_empty())
            })
        };
        let Some(last) = last else {
            continue;
        };
        for column in 0..=last {
            let line = lines[column].get(row).copied().unwrap_or("");
            match column_bgs[column].or(parent_bg) {
                Some(bg) => output.push_str(&fill_line(line, widths[column], bg)),
                None => {
                    output.push_str(line);
                    if column < last {
                        output.extend(std::iter::repeat_n(
                            ' ',
                            widths[column].saturating_sub(table::visible_width(line)),
                        ));
                    }
                }
            }
            if column < last {
                match parent_bg {
                    Some(bg) => output.push_str(&fill_line("", gap, bg)),
                    None => output.extend(std::iter::repeat_n(' ', gap)),
                }
            }
        }
    }
    output
}

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

    fn fixed(width: usize) -> ColumnSpec {
        ColumnSpec {
            width: ColumnWidth::Fixed(width),
            bg: None,
            padding: mbdown::Padding::default(),
        }
    }

    fn flex(weight: usize) -> ColumnSpec {
        ColumnSpec {
            width: ColumnWidth::Flex(weight),
            bg: None,
            padding: mbdown::Padding::default(),
        }
    }

    #[test]
    fn allocates_fixed_and_weighted_columns() {
        assert_eq!(
            allocate_widths(&[fixed(10), fixed(8)], 20, 2),
            Some(vec![10, 8])
        );
        assert_eq!(
            allocate_widths(&[flex(1), flex(2)], 32, 2),
            Some(vec![10, 20])
        );
        assert_eq!(
            allocate_widths(&[fixed(10), flex(1)], 30, 2),
            Some(vec![10, 18])
        );
    }

    #[test]
    fn requests_stacking_when_columns_do_not_fit() {
        assert_eq!(allocate_widths(&[fixed(20), fixed(20)], 32, 2), None);
        assert_eq!(allocate_widths(&[flex(1), flex(1)], 16, 2), None);
    }

    #[test]
    fn composes_rows_by_visible_width() {
        assert_eq!(
            compose(&["甲\n乙".into(), "状态".into()], &[4, 4], 2),
            "甲    状态\n乙"
        );
    }

    #[test]
    fn filled_composition_colors_cells_and_parent_gaps() {
        let output = compose_filled(
            &["A".into(), "B\nC".into()],
            &[3, 3],
            1,
            Some(Color::Rgb(1, 2, 3)),
            &[Some(Color::Basic(crate::BasicColor::Red)), None],
        );
        assert!(output.contains("\x1b[41mA  \x1b[0m"), "{output:?}");
        assert!(output.contains("\x1b[48;2;1;2;3m \x1b[0m"), "{output:?}");
        assert_eq!(
            output.lines().map(table::visible_width).collect::<Vec<_>>(),
            vec![7, 7]
        );

        let child_only = compose_filled(
            &["A".into(), "B".into()],
            &[3, 3],
            1,
            None,
            &[Some(Color::Basic(crate::BasicColor::Red)), None],
        );
        assert_eq!(table::visible_width(&child_only), 5);
        assert!(child_only.ends_with('B'), "{child_only:?}");

        let absent_later_row = compose_filled(
            &["A\n".into(), "B".into()],
            &[3, 3],
            1,
            None,
            &[Some(Color::Basic(crate::BasicColor::Red)), None],
        );
        let rows: Vec<_> = absent_later_row.lines().collect();
        assert_eq!(rows.len(), 2);
        assert_eq!(table::visible_width(rows[1]), 3);
        assert!(!rows[1].ends_with(' '), "{absent_later_row:?}");
    }
}