summaryrefslogtreecommitdiff
path: root/src/generate_html.rs
diff options
context:
space:
mode:
authorBen Bridle <bridle.benjamin@gmail.com>2025-01-07 17:41:46 +1300
committerBen Bridle <bridle.benjamin@gmail.com>2025-01-07 17:41:58 +1300
commit87436bb887c435461e371e0b8d83cfe79dd3c9b2 (patch)
treedcd2b3e7653f2ffdfb23041d2c6cc19169edde5c /src/generate_html.rs
parent8b6bb67e39b59f68dc005550dd42f031b6f415e8 (diff)
downloadtoaster-87436bb887c435461e371e0b8d83cfe79dd3c9b2.zip
A collection of fixes
Fixed a lot of issues around internal relative links and link validity checks. Added a math fragment syntax and the $$..$$ math form. Added heading link validity checks.
Diffstat (limited to 'src/generate_html.rs')
-rw-r--r--src/generate_html.rs88
1 files changed, 50 insertions, 38 deletions
diff --git a/src/generate_html.rs b/src/generate_html.rs
index 3f22d3b..1e3acc7 100644
--- a/src/generate_html.rs
+++ b/src/generate_html.rs
@@ -20,8 +20,8 @@ pub fn generate_html(document: &MarkdownDocument, page: &SourceFile, website: &W
</html> \
",
page.name, website.name,
- get_html_head(document),
- document_to_html(document, page, website)
+ get_html_head(document).trim(),
+ document_to_html(document, page, website).trim()
)
}
@@ -34,9 +34,9 @@ pub fn get_html_head(document: &MarkdownDocument) -> String {
}
}
String::from("\
-<link rel='stylesheet' type='text/css' media='screen' href='static/screen.css'>
-<link rel='stylesheet' type='text/css' media='print' href='static/print.css'>
-<script src='static/render_math.js' defer></script> \
+<link rel='stylesheet' type='text/css' media='screen' href='/static/screen.css'>
+<link rel='stylesheet' type='text/css' media='print' href='/static/print.css'>
+<script src='/static/render_math.js' defer></script> \
")
}
@@ -50,7 +50,8 @@ pub fn document_to_html(document: &MarkdownDocument, page: &SourceFile, website:
macro_rules! html {
($($arg:tt)*) => {{ html.push_str(&format!($($arg)*)); html.push('\n'); }}; }
macro_rules! tag {
- ($t:expr,$l:expr) => { html!("<{}>{}</{}>", $t, line_to_html!($l), $t) }; }
+ ($t:expr,$l:expr,$c:expr) => { html!("<{} {}>{}</{}>", $t, $c, line_to_html!($l), $t) };
+ ($t:expr,$l:expr) => { html!("<{}>{}</{}>", $t, line_to_html!($l), $t) }; }
macro_rules! wrap {
($t:expr,$f:expr) => {{ html!("<{}>", $t); $f; html!("</{}>", $t); }};
}
@@ -58,11 +59,19 @@ pub fn document_to_html(document: &MarkdownDocument, page: &SourceFile, website:
for block in &document.blocks {
match block {
Block::Heading { level, line } => match level {
- Level::Heading1 => tag!("h1", line),
- Level::Heading2 => tag!("h2", line),
- Level::Heading3 => tag!("h3", line),
+ Level::Heading1 => tag!("h1", line, format!("id='{}'", make_url_safe(&line_to_html!(line)))),
+ Level::Heading2 => tag!("h2", line, format!("id='{}'", make_url_safe(&line_to_html!(line)))),
+ Level::Heading3 => tag!("h3", line, format!("id='{}'", make_url_safe(&line_to_html!(line)))),
+ }
+ Block::Paragraph(line) => {
+ if let Some(stripped) = line.to_string().strip_prefix("$$ ") {
+ if let Some(stripped) = stripped.strip_suffix(" $$") {
+ html!("<div class='math'>{stripped}</div>");
+ continue;
+ }
+ }
+ tag!("p", line);
}
- Block::Paragraph(line) => tag!("p", line),
Block::List(lines) => wrap!("ul", for line in lines {
// Insert a <br> tag directly after the first untagged colon.
let mut depth = 0;
@@ -88,19 +97,18 @@ pub fn document_to_html(document: &MarkdownDocument, page: &SourceFile, website:
Block::Embedded { label, path } => match path.rsplit_once('.') {
Some((_, extension)) => match extension.to_lowercase().as_str() {
"jpg"|"jpeg"|"png"|"webp"|"gif"|"tiff" => html!(
- "<figure><a href='{}'><img src='{}' alt='{}' title='{}'></a></figure>",
- path, path, label, label
- ),
+ "<figure><a href='{path}'><img src='{path}' alt='{label}' title='{label}'></a></figure>"),
"mp3"|"wav"|"m4a" => html!("<audio src='{path}' controls>"),
- ext @ _ => error!("Unrecognised extension for embedded file '{path}' with extension '{ext}'"),
+ ext @ _ => warn!("Unrecognised extension for embedded file {path:?} with extension {ext:?} in page {:?}", page.name),
}
- _ => error!("Cannot embed file '{path}' with no file extension"),
+ _ => warn!("Cannot embed file {path:?} with no file extension in page {:?}", page.name),
}
Block::Fragment { language, content } => {
match language.as_str() {
- "embed-html" => html!("{}", content),
- "embed-css" => wrap!("style", html!("{}", content)),
- "embed-javascript"|"embed-js" => wrap!("script", html!("{}", content)),
+ "math" => html!("<div class='math'>{content}</div>"),
+ "embed-html" => html!("{content}"),
+ "embed-css" => wrap!("style", html!("{content}")),
+ "embed-javascript"|"embed-js" => wrap!("script", html!("{content}")),
"hidden"|"todo"|"embed-html-head" => (),
_ => {
html!("<pre class='{}'>", language);
@@ -165,37 +173,41 @@ fn line_to_html(line: &Line, page: &SourceFile, website: &Website) -> String {
let text = &sanitize_text(text); html.push_str(&format!("<span class='math'>{text}</span>")) }
Token::InternalLink(path) => {
let (label, class, path) = match path.split_once('#') {
- Some(("", section)) => (section, "heading", format!("#{}", make_url_safe(path))),
- Some((page, section)) => (section, "page", format!("{}.html#{}", make_url_safe(page), make_url_safe(section))),
- _ => (path.as_str(), "page", format!("{}.html", make_url_safe(path))),
+ Some(("", section)) => (section, "heading", format!("#{section}")),
+ Some((page, section)) => (section, "page", format!("{page}.html#{section}")),
+ _ => (path.as_str(), "page", format!("{path}.html")),
};
+ let mut path = make_url_safe(&path);
let full_label = sanitize_text(label);
- let label = match full_label.split_once('/') {
+ let label = match full_label.rsplit_once('/') {
Some((_parent, label)) => label.trim(),
None => &full_label,
};
// Check that the linked internal page exists.
if class == "page" {
- let path_no_ext = path.strip_suffix(".html").unwrap();
- if !website.has_page(&path_no_ext) {
- error!("Page {:?} contains invalid link to {:?}", page.name, path_no_ext);
+ match website.has_page(page, &path, "html") {
+ Some(resolved_path) => path = resolved_path,
+ None => warn!("Page {:?} contains link to nonexistent page {path:?}", page.name),
+ }
+ }
+ // Check that the heading exists.
+ if class == "heading" {
+ let heading = path.strip_prefix('#').unwrap().to_string();
+ if !page.headings.contains(&heading) {
+ warn!("Page {:?} contains link to nonexistent internal heading {heading:?}", page.name);
}
}
- // Return to the site root before descending into a link.
- let mut back = String::new();
- let levels = page.full_url.chars().filter(|c| *c == '/').count();
- for _ in 0..levels { back.push_str("../") }
- html.push_str(&format!("<a href='{back}{path}' class='{class}'>{label}</a>"))
+ html.push_str(&format!("<a href='{path}' class='{class}'>{label}</a>"))
}
Token::ExternalLink { label, path } => {
- let is_internal = path.find("/").is_none();
- let (new_label, class, path) = match (is_internal, path.split_once("#")) {
- (true, Some(("", frag))) => (sanitize_text(frag), "heading", format!("#{}", make_url_safe(frag)) ),
- (true, Some((page, frag))) => (sanitize_text(frag), "page", format!("{}.html#{}", make_url_safe(page), make_url_safe(frag)) ),
- (true, None) => (sanitize_text(path), "page", if path.contains(".") { path.clone() } else { format!("{}.html", make_url_safe(path)) } ),
- (false, _) => (sanitize_text(path), "external", path.clone() ) };
- let label = match label.is_empty() { true => new_label, false => sanitize_text(label) };
- html.push_str(&format!("<a href='{path}' class='{class}'>{label}</a>"));
+ let mut label = label.to_string();
+ // Strip the protocol from the path when using the path as a label.
+ if label.is_empty() {
+ for protocol in ["mailto://", "http://", "https://"] {
+ if let Some(stripped) = path.strip_prefix(protocol) {
+ label = stripped.to_string(); } } }
+ let label = sanitize_text(&label);
+ html.push_str(&format!("<a href='{path}' class='external'>{label}</a>"));
}
}
}