use super::*;
use crate::model::*;
use regex::Regex;
use std::sync::LazyLock;
static SECTION_NUMBER: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^(?:\d+(?:\.\d+)*\.?|[A-Z](?:\.\d+)+\.?|[A-Z]\.|[IVXL]+\.)\s+").unwrap());
const LEGIBLE_MIN_SCALE: f32 = 0.7;
const HTML_NEST_EM: f32 = 1.5;
const COVER_MIN_AREA_RATIO: f32 = 0.8;
pub(crate) enum WidthUnit {
Em {
pt_per_em: f32,
},
EmFit {
pt_per_em: f32,
},
Cqw {
page_width: f32,
},
}
impl WidthUnit {
fn css(&self, width_pt: f32, legible: bool) -> String {
match self {
WidthUnit::Em { pt_per_em } if legible => {
let width = width_pt / pt_per_em;
format!(
"width:{width:.2}em;max-width:max(100%,{:.2}em)",
width * LEGIBLE_MIN_SCALE
)
}
WidthUnit::Em { pt_per_em } | WidthUnit::EmFit { pt_per_em } => {
format!("width:{:.2}em;max-width:100%", width_pt / pt_per_em)
}
WidthUnit::Cqw { page_width } => format!("width:{:.2}cqw;max-width:100%", width_pt / page_width * 100.0),
}
}
}
pub(crate) struct FlowCtx {
pub unit: WidthUnit,
pub offprint: bool,
pub covers: (Option<usize>, Option<usize>),
pub sides: std::collections::HashMap<usize, &'static str>,
pub math: bool,
pub note_asides: bool,
}
const SIDE_MAX_WIDTH_RATIO: f32 = 0.4;
const SIDE_MIN_OVERLAP_RATIO: f32 = 0.5;
const SIDE_EDGE_TOLERANCE_PT: f32 = 2.0;
pub(crate) fn side_figures(doc: &Document, blocks: &[&Block]) -> std::collections::HashMap<usize, &'static str> {
let mut sides = std::collections::HashMap::new();
for pair in blocks.windows(2) {
let (fig, text) = (pair[0], pair[1]);
let BlockKind::Figure {
image: Some(image),
label: None,
..
} = &fig.kind
else {
continue;
};
let textual = matches!(
text.kind,
BlockKind::Paragraph { .. } | BlockKind::Note | BlockKind::Heading { .. }
);
let Some(page) = doc.pages.get(image.page) else {
continue;
};
if !textual
|| fig.table.is_some()
|| text.page != image.page
|| image.rect.width() > SIDE_MAX_WIDTH_RATIO * page.width
{
continue;
}
let (rect, other) = (image.rect, text.bbox);
let overlap = rect.y1.min(other.y1) - rect.y0.max(other.y0);
if overlap < SIDE_MIN_OVERLAP_RATIO * rect.height().min(other.height()) {
continue;
}
if other.x0 >= rect.x1 - SIDE_EDGE_TOLERANCE_PT {
sides.insert(fig.id, "side-l");
} else if other.x1 <= rect.x0 + SIDE_EDGE_TOLERANCE_PT {
sides.insert(fig.id, "side-r");
}
}
sides
}
pub(crate) fn caption_first(block: &Block, image: Option<&ImageSpec>) -> bool {
match (image, block.lines.first()) {
(Some(spec), Some(line)) => line.bbox.cy() < spec.rect.cy(),
_ => block.caption_above,
}
}
pub(crate) fn equation_math<'a>(
block: &'a Block,
image: Option<&ImageSpec>,
equations: Equations,
) -> Option<&'a MathNode> {
block
.math
.as_ref()
.filter(|_| equations == Equations::MathMl || image.is_none())
}
pub(crate) fn cover_blocks(doc: &Document) -> (Option<usize>, Option<usize>) {
let mut figures = doc
.blocks
.iter()
.filter(|block| matches!(block.kind, BlockKind::Figure { .. }));
let covering = |block: &Block, page_idx: usize| {
let BlockKind::Figure { image: Some(image), .. } = &block.kind else {
return false;
};
doc.pages.get(page_idx).is_some_and(|page| {
image.page == page_idx && image.rect.area() >= COVER_MIN_AREA_RATIO * page.width * page.height
})
};
let front = figures.next().filter(|block| covering(block, 0)).map(|block| block.id);
let last_page = doc.pages.len().saturating_sub(1);
let back = figures
.next_back()
.filter(|block| last_page > 0 && covering(block, last_page))
.map(|block| block.id);
(front, back)
}
#[derive(PartialEq, Clone, Copy)]
enum Group {
None,
List,
Refs,
Abstract,
}
pub(crate) fn heading_tag(level: u8) -> &'static str {
match level {
0 | 1 => "h2",
2 => "h3",
3 => "h4",
_ => "h5",
}
}
pub(crate) fn render_flow(blocks: &[&Block], images: &mut ImageStore<'_>, ctx: &FlowCtx) -> String {
let mut out = String::new();
let mut group = Group::None;
let mut block_idx = 0;
let mut held_notes = String::new();
while block_idx < blocks.len() {
crate::common::cancel::check();
let block = blocks[block_idx];
if ctx.offprint
&& let Some(end) = code_run(blocks, block_idx)
{
close_group(group, &mut out);
group = Group::None;
let run = &blocks[block_idx..end];
out.push_str(&code::listing_html(&code::listing_lines(run), "", &id_attr(run[0])));
block_idx = end;
continue;
}
let want = group_of(block, group);
if want != group {
close_group(group, &mut out);
open_group(want, blocks, block_idx, &mut out);
group = want;
}
if ctx.offprint
&& let BlockKind::Equation { image, number: None } = &block.kind
&& let Some(number) = blocks.get(block_idx + 1).and_then(|next| stray_equation_number(next))
{
out.push_str(&equation_html(
block,
image.as_ref(),
&Some(number),
&id_attr(block),
images,
ctx,
));
block_idx += 2;
continue;
}
if group == Group::None
&& ctx.sides.contains_key(&block.id)
&& let Some(next) = blocks.get(block_idx + 1)
&& group_of(next, group) == Group::None
{
out.push_str("<div class=\"beside\">");
block_with_notes(block, images, ctx, &mut out, &mut held_notes);
block_with_notes(next, images, ctx, &mut out, &mut held_notes);
out.push_str("</div>\n");
block_idx += 2;
continue;
}
block_with_notes(block, images, ctx, &mut out, &mut held_notes);
block_idx += 1;
}
close_group(group, &mut out);
out.push_str(&held_notes);
out
}
pub(crate) fn stray_equation_number(block: &Block) -> Option<String> {
if !matches!(block.kind, BlockKind::Paragraph { in_abstract: false }) {
return None;
}
let text = plain(&block.spans);
let text = text.trim();
let inner = text.strip_prefix('(')?.strip_suffix(')')?;
let digits = inner
.split('.')
.all(|part| !part.is_empty() && part.len() <= 3 && part.bytes().all(|b| b.is_ascii_digit()));
digits.then(|| text.to_string())
}
pub(crate) fn code_run(blocks: &[&Block], start: usize) -> Option<usize> {
let end = start
+ blocks[start..]
.iter()
.take_while(|block| code::is_code_paragraph(block))
.count();
let lines: usize = blocks[start..end].iter().map(|block| block.lines.len()).sum();
let listing = blocks[start..end]
.iter()
.any(|block| matches!(block.kind, BlockKind::Code));
(lines >= 2 || listing).then_some(end)
}
pub(crate) fn authors_html(blocks: &[&Block]) -> String {
let cards: Vec<String> = blocks
.iter()
.filter(|block| matches!(block.kind, BlockKind::Authors))
.map(|block| {
let rows: Vec<String> = block
.rows
.iter()
.enumerate()
.map(|(i, row)| {
format!(
"<div class=\"{}\">{}</div>",
if i == 0 { "au-name" } else { "au-line" },
spans_html(row)
)
})
.collect();
format!("<div class=\"author\">{}</div>", rows.join(""))
})
.collect();
if cards.is_empty() {
String::new()
} else {
format!("<div class=\"authors\">{}</div>\n", cards.join("\n"))
}
}
fn group_of(block: &Block, current: Group) -> Group {
match &block.kind {
BlockKind::ListItem { .. } | BlockKind::ListContinuation => Group::List,
BlockKind::Reference { .. } => Group::Refs,
BlockKind::Paragraph { in_abstract: true } => Group::Abstract,
BlockKind::Equation { .. } if current == Group::Abstract => current,
_ => Group::None,
}
}
fn close_group(group: Group, out: &mut String) {
match group {
Group::List => out.push_str("</ul>\n"),
Group::Refs => out.push_str("</ol>\n"),
Group::Abstract => out.push_str("</section>\n"),
Group::None => {}
}
}
fn open_group(group: Group, blocks: &[&Block], block_idx: usize, out: &mut String) {
match group {
Group::List => out.push_str("<ul class=\"list\">\n"),
Group::Refs => out.push_str("<ol class=\"refs\">\n"),
Group::Abstract => {
let had_heading = block_idx > 0
&& matches!(blocks[block_idx - 1].kind, BlockKind::Heading { .. })
&& is_abstract_text(&blocks[block_idx - 1].spans);
out.push_str("<section class=\"abstract\">\n");
if !had_heading {
out.push_str("<div class=\"abstract-label\">Abstract</div>\n");
}
}
Group::None => {}
}
}
pub(crate) fn is_abstract_text(spans: &[Span]) -> bool {
plain(spans)
.trim_end_matches(['.', ':'])
.eq_ignore_ascii_case("abstract")
}
pub(crate) fn is_scene_break(spans: &[Span]) -> bool {
let text = plain(spans);
let marks: Vec<char> = text.chars().filter(|ch| !ch.is_whitespace()).collect();
!marks.is_empty() && marks.len() <= 5 && marks.iter().all(|ch| matches!(ch, '#' | '*' | '\u{2042}'))
}
fn block_with_notes(block: &Block, images: &mut ImageStore<'_>, ctx: &FlowCtx, out: &mut String, held: &mut String) {
let start = out.len();
block_html(block, images, ctx, out);
if !ctx.note_asides {
return;
}
held.push_str(&super::notes::aside_html(&[block], ctx.math));
if matches!(block.kind, BlockKind::Heading { .. }) || held.is_empty() {
return;
}
let aside = std::mem::take(held);
match out[start..].strip_suffix("</li>\n") {
Some(item) => {
let end = start + item.len();
out.insert_str(end, aside.trim_end());
}
None => out.push_str(&aside),
}
}
fn block_html(block: &Block, images: &mut ImageStore<'_>, ctx: &FlowCtx, out: &mut String) {
let id = id_attr(block);
match &block.kind {
BlockKind::Title | BlockKind::Authors => {}
BlockKind::Note => out.push_str(&format!(
"<p class=\"note\">{}</p>\n",
text_html(&block.spans, ctx.math)
)),
BlockKind::Heading { level } => {
let tag = heading_tag(*level);
let cls = if is_abstract_text(&block.spans) {
" class=\"abstract-heading\""
} else {
""
};
if let Some((label, rest)) = chapter_label(&block.spans).filter(|_| cls.is_empty()) {
out.push_str(&format!(
"<{tag}{id} class=\"chapter\"><span class=\"chapno\">{}</span> {}</{tag}>\n",
esc(&label),
text_html(&rest, ctx.math)
));
return;
}
match section_number(&block.spans).filter(|_| ctx.offprint && cls.is_empty()) {
Some((number, rest)) => out.push_str(&format!(
"<{tag}{id} class=\"hang\"><span class=\"secno\">{}</span>{}</{tag}>\n",
esc(&number),
text_html(&rest, ctx.math)
)),
None => out.push_str(&format!(
"<{tag}{id}{cls}>{}</{tag}>\n",
text_html(&block.spans, ctx.math)
)),
}
}
BlockKind::Paragraph { .. } if is_scene_break(&block.spans) => {
out.push_str(&format!(
"<p{id} class=\"scene-break\">{}</p>\n",
spans_html(&block.spans)
));
}
BlockKind::Paragraph { .. } => out.push_str(&format!("<p{id}>{}</p>\n", text_html(&block.spans, ctx.math))),
BlockKind::ListItem { marker, level } => {
let cls = if marker.is_some() { " class=\"labeled\"" } else { "" };
let nest = if *level > 0 {
format!(" style=\"margin-left:{}em\"", f32::from(*level) * HTML_NEST_EM)
} else {
String::new()
};
let body = match marker.as_deref().filter(|_| ctx.offprint) {
Some(marker) => labelled_html(&block.spans, marker, "lbl", ctx.math),
None => text_html(&block.spans, ctx.math),
};
out.push_str(&format!("<li{id}{cls}{nest}>{body}</li>\n"));
}
BlockKind::ListContinuation => out.push_str(&format!(
"<li{id} class=\"more\">{}</li>\n",
text_html(&block.spans, ctx.math)
)),
BlockKind::Reference { label } => {
let body = match label.as_deref().filter(|_| ctx.offprint) {
Some(label) => reference_html(&block.spans, label, ctx.math),
None => text_html(&block.spans, ctx.math),
};
out.push_str(&format!("<li{id}>{body}</li>\n"));
}
BlockKind::Footnote { marker } => out.push_str(&footnote_html(block, marker, &id, ctx)),
BlockKind::Equation { image, number } => {
out.push_str(&equation_html(block, image.as_ref(), number, &id, images, ctx))
}
BlockKind::Figure { kind, image, label } => {
out.push_str(&figure_html(block, *kind, image, label, &id, images, ctx));
}
BlockKind::Code => out.push_str(&code_html(block, &id)),
BlockKind::ContentsEntry { level, page } => out.push_str(&format!(
"<p{id} class=\"toc toc{level}\"><span class=\"toc-t\">{}</span><span class=\"toc-p\">{}</span></p>\n",
spans_html(&block.spans),
esc(page)
)),
}
}
fn code_html(block: &Block, id: &str) -> String {
let rows: Vec<String> = block
.rows
.iter()
.map(|row| {
let spans: Vec<Span> = row
.iter()
.map(|span| Span {
style: span.style & !style::MONO,
..span.clone()
})
.collect();
spans_html(&spans)
})
.collect();
format!("<pre class=\"code\"{id}><code>{}</code></pre>\n", rows.join("\n"))
}
fn footnote_html(block: &Block, marker: &str, id: &str, ctx: &FlowCtx) -> String {
let mark = if marker.is_empty() {
String::new()
} else if ctx.offprint {
format!("<span class=\"fn-mark\">{}</span>", esc(marker))
} else {
format!("<sup class=\"fn-mark\">{}</sup> ", esc(marker))
};
format!(
"<aside class=\"footnote\"{id} role=\"note\">{mark}{}</aside>\n",
text_html(&block.spans, ctx.math)
)
}
fn equation_html(
block: &Block,
image: Option<&ImageSpec>,
number: &Option<String>,
id: &str,
images: &mut ImageStore<'_>,
ctx: &FlowCtx,
) -> String {
let num = number
.as_ref()
.map(|number| format!("<span class=\"eqno\">{}</span>", esc(number)))
.unwrap_or_default();
if let Some(math) = equation_math(block, image, images.opts.equations) {
let body = math_html(math, &plain(&block.spans));
return format!("<div class=\"eq\"{id}><span class=\"eq-body\">{body}</span>{num}</div>\n");
}
let alt = esc(&plain(&block.spans));
let Some(image) = image else {
return format!("<div class=\"eq\"{id}><span class=\"eq-body\">{alt}</span>{num}</div>\n");
};
let img = format!(
"<img src=\"{}\" alt=\"{alt}\"{} style=\"{}\" loading=\"lazy\">",
images.region(image, "eq"),
images.region_size_attrs(image),
ctx.unit.css(image.rect.width(), true)
);
format!("<div class=\"eq\"{id}><span class=\"eq-body\">{img}</span>{num}</div>\n")
}
fn figure_html(
block: &Block,
kind: FloatKind,
image: &Option<ImageSpec>,
label: &Option<String>,
id: &str,
images: &mut ImageStore<'_>,
ctx: &FlowCtx,
) -> String {
let cls = float_class(kind);
let cover = if ctx.covers.0 == Some(block.id) {
" cover"
} else if ctx.covers.1 == Some(block.id) {
" back-cover"
} else {
match ctx.sides.get(&block.id) {
Some(&"side-l") => " side-l",
Some(_) => " side-r",
None => "",
}
};
if ctx.offprint
&& kind == FloatKind::Algorithm
&& block.table.is_none()
&& let Some(lines) = code::float_listing_lines(block)
{
return code::listing_html(&lines, &caption_html_bare(&block.spans, ctx.math), id);
}
let alt = esc(&figure_alt(block, label));
let algo = (ctx.offprint && kind == FloatKind::Algorithm && block.table.is_none())
.then(|| code::algorithm_html(block))
.flatten();
let img = image
.as_ref()
.filter(|_| block.table.is_none() && algo.is_none())
.map(|spec| (images.region(spec, cls), images.region_size_attrs(spec), spec))
.map(|(src, size, spec)| {
let own = if ctx.offprint {
String::new()
} else {
format!(";--w:{}px", images.region_size(spec).0)
};
let legible = matches!(kind, FloatKind::Table | FloatKind::Algorithm);
format!(
"<img src=\"{src}\" alt=\"{alt}\"{size} style=\"{}{own}\" loading=\"lazy\">",
ctx.unit.css(spec.rect.width(), legible)
)
})
.map(|img| match kind {
FloatKind::Figure | FloatKind::Graphic if ctx.offprint => format!("<div class=\"plate\">{img}</div>"),
FloatKind::Table | FloatKind::Algorithm if ctx.offprint => format!("<div class=\"tbl-wrap\">{img}</div>"),
_ => img,
})
.unwrap_or_default();
let img = match (&block.table, algo) {
(_, Some(algo)) => algo,
(Some(table), _) if ctx.offprint => {
format!("<div class=\"tbl-wrap\">{}</div>", table_html_numeric(table, ctx.math))
}
(Some(table), _) => format!("<div class=\"tbl-wrap\">{}</div>", table_html(table, ctx.math)),
(None, None) => img,
};
let cap = if block.spans.is_empty() {
String::new()
} else if ctx.offprint {
format!("<figcaption>{}</figcaption>", caption_html_bare(&block.spans, ctx.math))
} else {
format!("<figcaption>{}</figcaption>", caption_html(&block.spans, ctx.math))
};
let caption_first = img.starts_with("<div class=\"algo\"") || caption_first(block, image.as_ref());
let inner = if caption_first {
format!("{cap}{img}")
} else {
format!("{img}{cap}")
};
format!("<figure class=\"float {cls}{cover}\"{id}>{inner}</figure>\n")
}
fn section_number(spans: &[Span]) -> Option<(String, Vec<Span>)> {
let first = spans.first()?;
let found = SECTION_NUMBER.find(&first.text)?;
if found.end() == first.text.len() && spans.len() == 1 {
return None;
}
let mut rest = spans.to_vec();
rest[0].text = first.text[found.end()..].to_string();
Some((found.as_str().trim_end().to_string(), rest))
}
fn chapter_label(spans: &[Span]) -> Option<(String, Vec<Span>)> {
let first = spans.first()?;
let found = crate::analysis::semantics::patterns::CHAPTER_LABEL.find(&first.text)?;
let mut rest = spans.to_vec();
rest[0].text = first.text[found.end()..].trim_start().to_string();
let has_rest = rest.iter().any(|span| !span.text.trim().is_empty());
has_rest.then(|| (found.as_str().trim_end().to_string(), rest))
}
fn labelled_html(spans: &[Span], marker: &str, class: &str, math: bool) -> String {
match spans.first() {
Some(first) if !marker.is_empty() && first.text.starts_with(marker) => {
let mut rest = spans.to_vec();
rest[0].text = first.text[marker.len()..].trim_start().to_string();
format!(
"<span class=\"{class}\">{}</span>{}",
esc(marker),
text_html(&rest, math)
)
}
_ => text_html(spans, math),
}
}
fn reference_html(spans: &[Span], label: &str, math: bool) -> String {
let Some(first) = spans.first() else {
return String::new();
};
let text = first.text.as_str();
for printed in [format!("[{label}]"), format!("{label}."), label.to_string()] {
if let Some(rest) = text.strip_prefix(printed.as_str()) {
let mut rest_spans = spans.to_vec();
rest_spans[0].text = rest.trim_start().to_string();
return format!(
"<span class=\"rn\">{}</span>{}",
esc(&printed),
text_html(&rest_spans, math)
);
}
}
text_html(spans, math)
}