use std::path::{Path, PathBuf};
use crate::addresses::{Owned, address};
use crate::document::{Document, Paper, Pdf};
use crate::folder::{ServedFolder, lexical};
use crate::html::{Link, escape};
use crate::markup::title;
use crate::nav;
use crate::problem::Problem;
use crate::widgets::Widgets;
use super::content::Rendered;
use super::navbar;
use super::sidebar::sidebar;
pub(super) fn tab_title(page: &str, site: &str) -> String {
let (page, site) = (page.trim(), site.trim());
if page.to_lowercase() == site.to_lowercase() {
site.to_string()
} else {
format!("{page} · {site}")
}
}
pub(super) fn html_open(served: &ServedFolder) -> String {
match served.mount() {
"" => r#"<html lang="en">"#.to_string(),
mount => format!(r#"<html lang="en" data-mount="{}">"#, escape(mount)),
}
}
fn page_script(print: bool, comments: bool) -> String {
let setting = if print {
" data-print"
} else if !comments {
" data-no-comments"
} else {
""
};
format!(
"<script defer fetchpriority=\"high\" src=\"{}\"{setting}></script>",
address(Owned::Asset("devpage.js"))
)
}
pub fn page(
document: &Document,
widgets: &Widgets,
rendered: &Rendered,
comments: bool,
found: &[Problem],
) -> Option<String> {
let page = title(rendered.source(), rendered.file());
framed(
document,
widgets,
rendered.file(),
&page,
rendered.html(),
comments,
found,
)
}
pub fn missing(document: &Document, widgets: &Widgets, rendered: &Rendered) -> Option<String> {
let page = title(rendered.source(), rendered.file());
let content = rebase(rendered.html(), rendered.file(), document);
framed(
document,
widgets,
rendered.file(),
&page,
&content,
false,
&[],
)
}
pub fn generated(
document: &Document,
widgets: &Widgets,
rendered: &Rendered,
current: &Path,
found: &[Problem],
) -> Option<String> {
let page = title(rendered.source(), rendered.file());
let html = framed(
document,
widgets,
current,
&page,
rendered.html(),
false,
found,
)?;
let shown = document.url(current)?;
let own = document.url(rendered.file())?;
Some(html.replacen(
&format!("<article data-source=\"{}\">", escape(&shown)),
&format!("<article data-source=\"{}\">", escape(&own)),
1,
))
}
pub fn nothing_at(
document: &Document,
widgets: &Widgets,
address: &str,
meant: Option<&str>,
) -> Option<String> {
let content = nothing_at_content(document, address, meant);
framed(
document,
widgets,
&document.base.join("404.md"),
NOT_FOUND,
&content,
false,
&[],
)
}
pub fn nothing_at_alone(entry: &Document, asked: &str, meant: Option<&str>) -> String {
format!(
r#"<!doctype html>
{html}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{NOT_FOUND} · {document}</title>
{theme}
<link rel="stylesheet" href="{stylesheet}">
</head>
<body class="missing" data-build="{build}">
<main id="devpage-page"><article>{content}</article></main>
</body>
</html>"#,
html = html_open(&entry.served),
stylesheet = address(Owned::Asset("style.css")),
build = crate::addresses::BUILD,
document = escape(&entry.title),
theme = navbar::head(entry),
content = nothing_at_content(entry, asked, meant),
)
}
const NOT_FOUND: &str = "Page not found";
fn nothing_at_content(document: &Document, address: &str, meant: Option<&str>) -> String {
let meant = meant.map_or_else(String::new, |meant| {
format!(
r#"<p>Did you mean <a href="{0}">{0}</a>?</p>"#,
escape(meant)
)
});
format!(
r#"<h1>{NOT_FOUND}</h1><p>There is nothing at <code>{address}</code>.</p>{meant}<p><a href="{home}">Go to {title}</a></p>"#,
address = escape(address),
home = escape(&document.entry()),
title = escape(&document.title),
)
}
fn framed(
document: &Document,
widgets: &Widgets,
file: &Path,
page: &str,
content: &str,
comments: bool,
found: &[Problem],
) -> Option<String> {
let _render = tracing::info_span!("render").entered();
let current = document.url(file)?;
let tree = if document.sidebar || !document.navbar.is_empty() {
nav::tree(document)
} else {
Vec::new()
};
Some(format!(
r#"<!doctype html>
{html}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{tab}</title>
{theme}
<link rel="stylesheet" href="{stylesheet}">
{script}
{widgets}
</head>
<body class="{body_class}" data-build="{build}">
{navbar}{sidebar}{corner}
<main id="devpage-page">{problems}<article data-source="{current}">{content}</article></main>
</body>
</html>"#,
html = html_open(&document.served),
stylesheet = address(Owned::Asset("style.css")),
build = crate::addresses::BUILD,
tab = escape(&tab_title(page, &document.title)),
theme = navbar::head(document),
body_class = site_class(document),
navbar = navbar::render(document, &tree, ¤t, comments),
sidebar = sidebar(document, &tree, ¤t),
script = page_script(false, comments),
corner = if document.navbar.is_empty() {
navbar::corner(document, comments)
} else {
String::new()
},
problems = problems(found),
widgets = widgets.head(
content,
if document.sidebar {
&[crate::widgets::SIDEBAR]
} else {
&[]
}
),
))
}
pub fn workspace(
document: &Document,
widgets: &Widgets,
_file: &Path,
title: &str,
content: &str,
comments: bool,
) -> String {
format!(
r#"<!doctype html>
{html}<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{title}</title>{theme}<link rel="stylesheet" href="{style}">{script}{widgets}</head>
<body class="site no-sidebar devpage-workspace" data-build="{build}">
<main id="devpage-page">{content}</main></body></html>"#,
html = html_open(&document.served),
title = escape(&tab_title(title, &document.title)),
theme = navbar::head(document),
style = address(Owned::Asset("style.css")),
script = page_script(false, comments),
widgets = widgets.head(content, &[]),
build = crate::addresses::BUILD,
)
}
pub fn doc(
document: &Document,
widgets: &Widgets,
chapters: &[Rendered],
pdf: &Pdf,
print: bool,
comments: bool,
found: &[Problem],
) -> String {
let _render = tracing::info_span!("render").entered();
let mut content = String::new();
let mut outline = String::new();
let files: Vec<PathBuf> = chapters.iter().map(|c| c.file().to_path_buf()).collect();
let names = chapter_names(&files, &document.served);
for rendered in chapters {
let chapter = rendered.file();
let mut html = rendered.html().to_string();
if chapters.len() > 1 {
html = scope_ids(&html, chapter, &names, &document.served);
}
let html = rebase(&html, chapter, document);
for (level, id, text) in headings(&html) {
outline.push_str(&format!(
"<li class=\"h{level}\"><a href=\"#{id}\">{text}</a></li>"
));
}
let id = if chapters.len() > 1 {
format!(
" id=\"{}\"",
chapter_name(chapter, &names, &document.served)
)
} else {
String::new()
};
content.push_str(&format!(
"<section class=\"chapter\"{id} data-source=\"{}\">{html}</section>",
document.part_url(chapter)
));
}
let paper = match pdf.paper {
Paper::A4 => "A4",
Paper::Letter => "letter",
};
let outline = if print {
String::new()
} else {
format!(
"<nav id=\"devpage-nav\" class=\"outline\"><a class=\"document-title current\" href=\"#\">{}{}</a><ul>{outline}</ul></nav>",
navbar::logo(document),
escape(&document.title)
)
};
format!(
r#"<!doctype html>
{html}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title}</title>
{theme}
<link rel="stylesheet" href="{stylesheet}">
{script}
{widgets}
<style>@page {{ size: {paper}; margin: 22mm 18mm; }}</style>
</head>
<body class="doc{print_class}" data-build="{build}">
{corner}{outline}
<main id="devpage-page">{problems}<article>{heading}{content}</article></main>
</body>
</html>"#,
html = html_open(&document.served),
stylesheet = address(Owned::Asset("style.css")),
build = crate::addresses::BUILD,
title = escape(&document.title),
theme = navbar::head(document),
corner = if print {
String::new()
} else {
navbar::corner(document, comments)
},
widgets = widgets.head(&content, &[]),
heading = if document.file_name.ends_with(".md") {
String::new()
} else {
format!("<p class=\"doc-title\">{}</p>", escape(&document.title))
},
print_class = if print { " print" } else { "" },
script = page_script(print, comments),
problems = if print {
String::new()
} else {
problems(found)
},
)
}
pub(super) fn chapter_names(chapters: &[PathBuf], served: &ServedFolder) -> Vec<(PathBuf, String)> {
chapters
.iter()
.map(|chapter| {
let canonical = served.inside(chapter).unwrap_or_else(|| chapter.clone());
let name = chapter
.file_stem()
.unwrap_or_default()
.to_string_lossy()
.into_owned();
(canonical, name)
})
.collect()
}
fn chapter_name(chapter: &Path, names: &[(PathBuf, String)], served: &ServedFolder) -> String {
let canonical = served
.inside(chapter)
.unwrap_or_else(|| chapter.to_path_buf());
names
.iter()
.find(|(path, _)| *path == canonical)
.map(|(_, name)| name.clone())
.unwrap_or_default()
}
fn scope_ids(
html: &str,
chapter: &Path,
names: &[(PathBuf, String)],
served: &ServedFolder,
) -> String {
let own = chapter_name(chapter, names, served);
let html = html.replace(" id=\"", &format!(" id=\"{own}--"));
let mut out = String::new();
let mut rest = html.as_str();
while let Some(at) = rest.find(" href=\"") {
out.push_str(&rest[..at + 7]);
rest = &rest[at + 7..];
let end = rest.find('"').unwrap_or(rest.len());
let href = &rest[..end];
let target = match Link::classify(href) {
Link::File { path: "", fragment } => Some((own.clone(), fragment)),
Link::File { path, fragment } => {
let resolved =
served.inside(&chapter.parent().unwrap_or(Path::new(".")).join(path));
names
.iter()
.find(|(file, _)| Some(file) == resolved.as_ref())
.map(|(_, name)| (name.clone(), fragment))
}
Link::Web(_) | Link::Elsewhere => None,
};
match target {
Some((name, "")) => out.push_str(&format!("#{name}")),
Some((name, fragment)) => out.push_str(&format!("#{name}--{fragment}")),
None => out.push_str(href),
}
rest = &rest[end..];
}
out.push_str(rest);
out
}
fn rebase(html: &str, file: &Path, document: &Document) -> String {
let folder = file.parent().unwrap_or(Path::new("."));
let mut out = String::new();
let mut rest = html;
const STARTS: [(&str, &str); 2] = [(" href=\"", "\""), (" src=\"", "\"")];
loop {
let next = STARTS
.iter()
.filter_map(|(start, end)| rest.find(start).map(|at| (at + start.len(), *end)))
.min();
let Some((start, close)) = next else { break };
out.push_str(&rest[..start]);
rest = &rest[start..];
let end = rest.find(close).unwrap_or(rest.len());
let value = &rest[..end];
match Link::classify(value) {
Link::File { path, fragment } if !path.is_empty() && !path.starts_with('/') => {
match document.url(&lexical(&folder.join(path))) {
Some(address) => {
out.push_str(&address);
if value.contains('#') {
out.push('#');
out.push_str(fragment);
}
}
None => out.push_str(value),
}
}
_ => out.push_str(value),
}
rest = &rest[end..];
}
out.push_str(rest);
out
}
pub fn invalid(entry: &Document, file: &Path, error: &str) -> Option<String> {
let address = entry.url(file)?;
Some(format!(
r#"<!doctype html>
{html}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{address} · {document}</title>
{theme}
<link rel="stylesheet" href="{stylesheet}">
{page_script}
</head>
<body class="invalid" data-build="{build}">
<main id="devpage-page"><div class="problems"><b>{address} is not a valid document</b><ul><li>{error}</li></ul></div></main>
</body>
</html>"#,
html = html_open(&entry.served),
stylesheet = crate::addresses::address(Owned::Asset("style.css")),
build = crate::addresses::BUILD,
page_script = page_script(false, true),
address = escape(&address),
document = escape(&entry.title),
theme = navbar::head(entry),
error = escape(error),
))
}
fn problems(found: &[Problem]) -> String {
if found.is_empty() {
return String::new();
}
let items: String = found
.iter()
.map(|problem| format!("<li>{}</li>", escape(&problem.to_string())))
.collect();
let broken: Vec<&str> = found.iter().filter_map(|p| p.target.as_deref()).collect();
format!(
"<div class=\"problems\" data-broken=\"{}\"><b>{} problem{}</b><ul>{items}</ul></div>",
escape(&serde_json::to_string(&broken).unwrap_or_default()),
found.len(),
if found.len() == 1 { "" } else { "s" }
)
}
pub fn slides(
document: &Document,
widgets: &Widgets,
slides: &[Rendered],
print: bool,
comments: bool,
found: &[Problem],
) -> String {
let _render = tracing::info_span!("render").entered();
let mut content = String::new();
for (index, slide) in slides.iter().enumerate() {
content.push_str(&format!(
"<section class=\"slide\" data-slide=\"{}\" data-source=\"{}\"><div class=\"slide-body\">{}</div></section>",
index + 1,
document.part_url(slide.file()),
rebase(slide.html(), slide.file(), document)
));
}
format!(
r#"<!doctype html>
{html}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title}</title>
{theme}
<link rel="stylesheet" href="{stylesheet}">
{script}
{widgets}
<style>@page {{ size: 1920px 1080px; margin: 0; }}</style>
</head>
<body class="slides{print_class}" data-build="{build}">
{corner}<main id="devpage-page" class="deck">{problems}{content}</main>
</body>
</html>"#,
html = html_open(&document.served),
stylesheet = address(Owned::Asset("style.css")),
build = crate::addresses::BUILD,
title = escape(&document.title),
theme = navbar::head(document),
corner = if print {
String::new()
} else {
navbar::corner(document, comments)
},
widgets = widgets.head(&content, &[]),
print_class = if print { " print" } else { "" },
script = page_script(print, comments),
problems = if print {
String::new()
} else {
problems(found)
},
)
}
fn headings(html: &str) -> Vec<(u8, String, String)> {
let mut found = Vec::new();
let mut rest = html;
while let Some(start) = rest.find("<h") {
rest = &rest[start + 2..];
let level = rest.as_bytes().first().copied().unwrap_or(0);
if level != b'1' && level != b'2' {
continue;
}
let close = format!("</h{}>", level as char);
let Some(end) = rest.find(&close) else { break };
let inner = &rest[..end];
let id = inner
.split("id=\"")
.nth(1)
.and_then(|tail| tail.split('"').next())
.unwrap_or_default()
.to_string();
let text = strip_tags(inner.split_once('>').map_or(inner, |(_, body)| body));
found.push((level - b'0', id, text));
rest = &rest[end..];
}
found
}
fn strip_tags(html: &str) -> String {
let mut text = String::new();
let mut in_tag = false;
for c in html.chars() {
match c {
'<' => in_tag = true,
'>' => in_tag = false,
c if !in_tag => text.push(c),
_ => {}
}
}
text.trim().to_string()
}
fn site_class(document: &Document) -> String {
let mut class = String::from("site");
if !document.navbar.is_empty() {
class.push_str(" with-navbar");
}
if !document.sidebar {
class.push_str(" no-sidebar");
}
class
}