mod columns;
use unicode_width::UnicodeWidthStr;
use crate::ansi::{self, Token};
use crate::frame::{self, FrameStyle};
use crate::{bbcode, table, Color, Theme};
use mbdown::{BorderMode, BoxSpec, ColumnsSpec, Node, WidthMode};
const MIN_FRAME_WIDTH: usize = 4;
const BOX_STYLE: &str = "markdown-box";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BlockKind {
Text,
Structural,
}
struct RenderedBlock {
text: String,
width: usize,
kind: BlockKind,
}
pub(crate) fn render<F>(
nodes: &[Node<'_>],
width: usize,
theme: &Theme,
render_markup: F,
) -> Result<String, String>
where
F: Fn(&mbdown::Markdown<'_>, usize, usize) -> String,
{
let blocks = render_nodes(nodes, width.max(1), 0, theme, &render_markup)?;
Ok(join_blocks(&blocks))
}
fn render_nodes<F>(
nodes: &[Node<'_>],
available: usize,
paragraph_indent: usize,
theme: &Theme,
render_markup: &F,
) -> Result<Vec<RenderedBlock>, String>
where
F: Fn(&mbdown::Markdown<'_>, usize, usize) -> String,
{
let mut blocks = Vec::new();
for node in nodes {
match node {
Node::Markdown(markdown) => {
let text = render_markup(markdown, available, paragraph_indent);
if !text.is_empty() {
blocks.push(RenderedBlock {
width: visible_block_width(&text),
text,
kind: BlockKind::Text,
});
}
}
Node::Box { spec, children } => {
blocks.push(render_box(spec, children, available, theme, render_markup)?);
}
Node::Center { children } => {
let children =
render_nodes(children, available, paragraph_indent, theme, render_markup)?;
blocks.extend(
children
.into_iter()
.map(|child| center_block(child, available)),
);
}
Node::Right { children } => {
let children =
render_nodes(children, available, paragraph_indent, theme, render_markup)?;
blocks.extend(
children
.into_iter()
.map(|child| right_align_block(child, available)),
);
}
Node::Indent { spec, children } => {
blocks.extend(render_nodes(
children,
available,
paragraph_indent.saturating_add(spec.first),
theme,
render_markup,
)?);
}
Node::Columns { spec, children } => {
blocks.push(render_columns(
children,
available,
paragraph_indent,
spec,
theme,
render_markup,
)?);
}
Node::Column { .. } => {
return Err("structural BBCode [column] must be inside [columns]".to_string());
}
}
}
Ok(blocks)
}
fn render_box<F>(
spec: &BoxSpec,
children: &[Node<'_>],
available: usize,
theme: &Theme,
render_markup: &F,
) -> Result<RenderedBlock, String>
where
F: Fn(&mbdown::Markdown<'_>, usize, usize) -> String,
{
let width = box_width(spec, children, available, theme, render_markup)?;
let inner_width = box_inner_width(spec, width);
let content = join_blocks(&render_nodes(
children,
inner_width,
0,
theme,
render_markup,
)?);
let background = resolve_background("box", spec.bg.as_deref(), theme)?;
let text = match spec.border {
BorderMode::Single => {
let style = box_border_style(spec, theme)?;
frame::render_with_background(
&spec.title,
&content,
width,
theme,
style,
background,
spec.padding,
)
}
BorderMode::None => pad_ansi_block(&content, width, spec.padding, None),
};
let text = match background {
Some(bg) => fill_rectangle(&text, width, bg),
None => text,
};
Ok(RenderedBlock {
text,
width,
kind: BlockKind::Structural,
})
}
fn box_border_style<'a>(spec: &'a BoxSpec, theme: &'a Theme) -> Result<FrameStyle<'a>, String> {
match spec.border_color.as_deref() {
Some(color) => {
if !bbcode::is_foreground_value(color, theme) {
return Err(format!(
"box border-color {color:?} is not a registered color"
));
}
Ok(FrameStyle::Color(color))
}
None => Ok(FrameStyle::Semantic(if theme.get(BOX_STYLE).is_some() {
BOX_STYLE
} else {
"gray"
})),
}
}
fn box_width<F>(
spec: &BoxSpec,
children: &[Node<'_>],
available: usize,
theme: &Theme,
render_markup: &F,
) -> Result<usize, String>
where
F: Fn(&mbdown::Markdown<'_>, usize, usize) -> String,
{
let minimum = match spec.border {
BorderMode::Single => MIN_FRAME_WIDTH,
BorderMode::None => 1,
};
let available = available.max(minimum);
match spec.width {
WidthMode::Full => Ok(available),
WidthMode::Exact(width) => Ok(width.clamp(minimum, available)),
WidthMode::Fit => {
let inner_limit = box_inner_width(spec, available);
let content_width = measure_nodes(children, inner_limit, 0, theme, render_markup)?;
let overhead = box_horizontal_overhead(spec);
let title_width = match spec.border {
BorderMode::Single => UnicodeWidthStr::width(
bbcode::sanitize_terminal_controls(spec.title.trim()).as_str(),
)
.saturating_add(6),
BorderMode::None => 0,
};
Ok(title_width
.max(content_width.saturating_add(overhead))
.max(minimum)
.min(available))
}
}
}
fn box_horizontal_overhead(spec: &BoxSpec) -> usize {
usize::from(spec.border == BorderMode::Single) * 2 + spec.padding.x.saturating_mul(2)
}
fn box_inner_width(spec: &BoxSpec, width: usize) -> usize {
width.saturating_sub(box_horizontal_overhead(spec)).max(1)
}
fn render_columns<F>(
children: &[Node<'_>],
available: usize,
paragraph_indent: usize,
spec: &ColumnsSpec,
theme: &Theme,
render_markup: &F,
) -> Result<RenderedBlock, String>
where
F: Fn(&mbdown::Markdown<'_>, usize, usize) -> String,
{
let column_nodes = collect_columns(children)?;
if column_nodes.len() < 2 {
return Err("structural BBCode [columns] requires at least two [column] children".into());
}
let specs: Vec<_> = column_nodes
.iter()
.map(|(column, _)| (*column).clone())
.collect();
let parent_bg = resolve_background("columns", spec.bg.as_deref(), theme)?;
let column_bgs = specs
.iter()
.map(|column| resolve_background("column", column.bg.as_deref(), theme))
.collect::<Result<Vec<_>, _>>()?;
let padding = constrained_padding(available, spec.padding);
let inner_available = available.saturating_sub(padding.x.saturating_mul(2)).max(1);
let Some(widths) = columns::allocate_widths(&specs, inner_available, spec.gap) else {
return render_stacked_columns(
&column_nodes,
available,
paragraph_indent,
padding,
parent_bg,
&column_bgs,
theme,
render_markup,
);
};
if specs
.iter()
.zip(&widths)
.any(|(column, width)| *width <= column.padding.x.saturating_mul(2))
{
return render_stacked_columns(
&column_nodes,
available,
paragraph_indent,
padding,
parent_bg,
&column_bgs,
theme,
render_markup,
);
}
let mut contents = Vec::with_capacity(column_nodes.len());
for (((column, children), width), background) in
column_nodes.iter().zip(&widths).zip(&column_bgs)
{
let column_padding = constrained_padding(*width, column.padding);
let content_width = width
.saturating_sub(column_padding.x.saturating_mul(2))
.max(1);
let content = join_blocks(&render_nodes(
children,
content_width,
paragraph_indent,
theme,
render_markup,
)?);
contents.push(pad_ansi_block(
&content,
*width,
column_padding,
(column_padding != mbdown::Padding::default())
.then_some((*background).or(parent_bg))
.flatten(),
));
}
if contents
.iter()
.zip(&widths)
.any(|(content, width)| visible_block_width(content) > *width)
{
return render_stacked_columns(
&column_nodes,
available,
paragraph_indent,
padding,
parent_bg,
&column_bgs,
theme,
render_markup,
);
}
let width = widths.iter().sum::<usize>() + spec.gap * widths.len().saturating_sub(1);
let has_bg = parent_bg.is_some() || column_bgs.iter().any(Option::is_some);
let text = if has_bg {
columns::compose_filled(&contents, &widths, spec.gap, parent_bg, &column_bgs)
} else {
columns::compose(&contents, &widths, spec.gap)
};
let width = width.saturating_add(padding.x.saturating_mul(2));
let text = pad_ansi_block(
&text,
width,
padding,
(padding != mbdown::Padding::default())
.then_some(parent_bg)
.flatten(),
);
Ok(RenderedBlock {
text,
width,
kind: BlockKind::Structural,
})
}
type ColumnNode<'a, 'node> = (&'node mbdown::ColumnSpec, &'node [Node<'a>]);
#[allow(clippy::too_many_arguments)]
fn render_stacked_columns<F>(
columns: &[ColumnNode<'_, '_>],
available: usize,
paragraph_indent: usize,
padding: mbdown::Padding,
parent_bg: Option<Color>,
column_bgs: &[Option<Color>],
theme: &Theme,
render_markup: &F,
) -> Result<RenderedBlock, String>
where
F: Fn(&mbdown::Markdown<'_>, usize, usize) -> String,
{
let has_bg = parent_bg.is_some() || column_bgs.iter().any(Option::is_some);
let mut contents = Vec::with_capacity(columns.len());
let inner_width = available.saturating_sub(padding.x.saturating_mul(2)).max(1);
for ((column, children), column_bg) in columns.iter().zip(column_bgs) {
let column_padding = constrained_padding(inner_width, column.padding);
let content_width = inner_width
.saturating_sub(column_padding.x.saturating_mul(2))
.max(1);
let content = join_blocks(&render_nodes(
children,
content_width,
paragraph_indent,
theme,
render_markup,
)?);
contents.push(pad_ansi_block(
&content,
inner_width,
column_padding,
(*column_bg).or(parent_bg),
));
}
let text = if has_bg {
let separator = parent_bg.map_or_else(
|| "\n\n".to_string(),
|bg| format!("\n{}\n", fill_line("", inner_width, bg)),
);
contents.join(&separator)
} else {
contents.join("\n\n")
};
let text = pad_ansi_block(
&text,
available,
padding,
(padding != mbdown::Padding::default())
.then_some(parent_bg)
.flatten(),
);
Ok(RenderedBlock {
text,
width: available,
kind: BlockKind::Structural,
})
}
fn collect_columns<'a, 'node>(
children: &'node [Node<'a>],
) -> Result<Vec<ColumnNode<'a, 'node>>, String> {
let mut columns = Vec::new();
for child in children {
match child {
Node::Column { spec, children } => columns.push((spec, children.as_slice())),
Node::Markdown(markdown) if markdown.source().trim().is_empty() => {}
_ => {
return Err(
"structural BBCode [columns] may contain only [column] children".to_string(),
)
}
}
}
Ok(columns)
}
fn measure_nodes<F>(
nodes: &[Node<'_>],
available: usize,
paragraph_indent: usize,
theme: &Theme,
render_markup: &F,
) -> Result<usize, String>
where
F: Fn(&mbdown::Markdown<'_>, usize, usize) -> String,
{
let mut width = 0;
for node in nodes {
let measured = match node {
Node::Markdown(markdown) => {
visible_block_width(&render_markup(markdown, available, paragraph_indent))
}
Node::Box { spec, children } => {
box_width(spec, children, available, theme, render_markup)?
}
Node::Center { children } => {
measure_nodes(children, available, paragraph_indent, theme, render_markup)?
}
Node::Right { children } => {
measure_nodes(children, available, paragraph_indent, theme, render_markup)?
}
Node::Indent { spec, children } => measure_nodes(
children,
available,
paragraph_indent.saturating_add(spec.first),
theme,
render_markup,
)?,
Node::Columns { spec, children } => {
render_columns(
children,
available,
paragraph_indent,
spec,
theme,
render_markup,
)?
.width
}
Node::Column { .. } => {
return Err("structural BBCode [column] must be inside [columns]".to_string());
}
};
width = width.max(measured);
}
Ok(width.min(available))
}
fn center_block(block: RenderedBlock, available: usize) -> RenderedBlock {
let text = match block.kind {
BlockKind::Text => block
.text
.split('\n')
.map(|line| {
let padding = available.saturating_sub(table::visible_width(line)) / 2;
format!("{}{line}", " ".repeat(padding))
})
.collect::<Vec<_>>()
.join("\n"),
BlockKind::Structural => {
let padding = available.saturating_sub(block.width) / 2;
let prefix = " ".repeat(padding);
block
.text
.split('\n')
.map(|line| format!("{prefix}{line}"))
.collect::<Vec<_>>()
.join("\n")
}
};
RenderedBlock {
text,
width: available,
kind: BlockKind::Structural,
}
}
fn right_align_block(block: RenderedBlock, available: usize) -> RenderedBlock {
let text = match block.kind {
BlockKind::Text => block
.text
.split('\n')
.map(|line| {
let padding = available.saturating_sub(table::visible_width(line));
format!("{}{line}", " ".repeat(padding))
})
.collect::<Vec<_>>()
.join("\n"),
BlockKind::Structural => {
let prefix = " ".repeat(available.saturating_sub(block.width));
block
.text
.split('\n')
.map(|line| format!("{prefix}{line}"))
.collect::<Vec<_>>()
.join("\n")
}
};
RenderedBlock {
text,
width: available,
kind: BlockKind::Structural,
}
}
fn join_blocks(blocks: &[RenderedBlock]) -> String {
let mut output = String::new();
for block in blocks {
if block.text.is_empty() {
continue;
}
if !output.is_empty() {
output.truncate(output.trim_end_matches('\n').len());
output.push_str("\n\n");
}
output.push_str(&block.text);
}
output
}
fn resolve_background(
context: &str,
value: Option<&str>,
theme: &Theme,
) -> Result<Option<Color>, String> {
let Some(value) = value else {
return Ok(None);
};
bbcode::background_color(value, theme)
.map(Some)
.ok_or_else(|| format!("{context} bg {value:?} is not a registered background color"))
}
fn fill_rectangle(content: &str, width: usize, bg: Color) -> String {
let lines: Vec<_> = if content.is_empty() {
vec![""]
} else {
content.split('\n').collect()
};
lines
.into_iter()
.map(|line| fill_line(line, width, bg))
.collect::<Vec<_>>()
.join("\n")
}
fn constrained_padding(width: usize, padding: mbdown::Padding) -> mbdown::Padding {
mbdown::Padding {
x: padding.x.min(width.saturating_sub(1) / 2),
y: padding.y,
}
}
fn pad_ansi_block(
content: &str,
width: usize,
padding: mbdown::Padding,
background: Option<Color>,
) -> String {
if padding == mbdown::Padding::default() {
return match background {
Some(bg) => fill_rectangle(content, width, bg),
None => content.to_string(),
};
}
let padding_x = padding.x.min(width.saturating_sub(1) / 2);
let content_width = width.saturating_sub(padding_x.saturating_mul(2)).max(1);
let mut lines = Vec::new();
for _ in 0..padding.y {
lines.push(String::new());
}
for line in content.split('\n') {
let mut padded = " ".repeat(padding_x);
padded.push_str(line);
padded.extend(std::iter::repeat_n(
' ',
content_width.saturating_sub(table::visible_width(line)) + padding_x,
));
lines.push(padded);
}
for _ in 0..padding.y {
lines.push(String::new());
}
lines
.into_iter()
.map(|line| match background {
Some(bg) => fill_line(&line, width, bg),
None => {
let mut line = line;
line.extend(std::iter::repeat_n(
' ',
width.saturating_sub(table::visible_width(&line)),
));
line
}
})
.collect::<Vec<_>>()
.join("\n")
}
fn fill_line(line: &str, width: usize, bg: Color) -> String {
let background = bbcode::background_sequence(bg);
let mut output = String::with_capacity(line.len() + width + background.len() * 2);
output.push_str(&background);
for token in ansi::tokens(line) {
match token {
Token::Sequence(sequence) => {
output.push_str(sequence.as_str());
if sequence.is_sgr_reset() {
output.push_str(&background);
}
}
Token::Char(character) => output.push(character),
}
}
output.extend(std::iter::repeat_n(
' ',
width.saturating_sub(table::visible_width(line)),
));
output.push_str(bbcode::RESET);
output
}
fn visible_block_width(value: &str) -> usize {
value.lines().map(table::visible_width).max().unwrap_or(0)
}