use std::collections::HashMap;
use markdoc::types::{RenderableTreeNode, Scalar};
#[derive(Debug, Clone, Copy)]
pub enum InlineProp {
Bold,
Italic,
Strikethrough,
Code,
Underline {
thickness: f32,
},
Color(krilla::color::rgb::Color),
}
#[derive(Debug, Clone)]
pub struct InlineRange {
pub start: usize,
pub end: usize,
pub prop: InlineProp,
}
#[derive(Debug, Clone)]
pub struct LinkRange {
pub start: usize,
pub end: usize,
pub href: String,
pub title: Option<String>,
}
#[derive(Debug, Clone)]
pub struct MidAnchor {
pub byte_offset: usize,
pub id: String,
}
#[derive(Debug, Clone)]
pub struct FootnoteCall {
pub byte_offset: usize,
pub number: u32,
}
pub struct Inlines {
pub text: String,
pub style_ranges: Vec<InlineRange>,
pub links: Vec<LinkRange>,
pub mid_anchors: Vec<MidAnchor>,
pub footnote_calls: Vec<FootnoteCall>,
}
impl Inlines {
pub fn new() -> Self {
Self {
text: String::new(),
style_ranges: Vec::new(),
links: Vec::new(),
mid_anchors: Vec::new(),
footnote_calls: Vec::new(),
}
}
pub fn from(children: &[RenderableTreeNode], footnotes: &mut Vec<String>) -> Self {
Self::from_with_labels(children, footnotes, None)
}
pub fn from_with_labels(
children: &[RenderableTreeNode],
footnotes: &mut Vec<String>,
crossref_labels: Option<&HashMap<String, String>>,
) -> Self {
let mut i = Self::new();
collect_into(&mut i, children, footnotes, crossref_labels);
i
}
}
fn is_navigable_uri(href: &str) -> bool {
if let Some(first) = href.chars().next()
&& first == '#'
{
return true;
}
let mut chars = href.chars();
let Some(first) = chars.next() else {
return false;
};
if !first.is_ascii_alphabetic() {
return false;
}
for c in chars {
match c {
':' => return true,
c if c.is_ascii_alphanumeric() => continue,
'+' | '-' | '.' => continue,
_ => return false,
}
}
false
}
pub fn superscript_number(n: u32) -> String {
const MAP: [char; 10] = ['⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹'];
let s = n.to_string();
s.chars()
.map(|c| c.to_digit(10).map(|d| MAP[d as usize]).unwrap_or(c))
.collect()
}
pub fn anchor_id_attr(tag: &markdoc::types::Tag) -> Option<String> {
if let Some(Scalar::String(s)) = tag.attributes.get("id")
&& !s.is_empty()
{
return Some(s.clone());
}
if let Some(Scalar::String(s)) = tag.attributes.get("primary")
&& !s.is_empty()
{
return Some(s.clone());
}
None
}
pub(crate) fn scalar_text(value: &Scalar) -> Option<String> {
match value {
Scalar::String(s) => Some(s.clone()),
Scalar::Number(_) => markdoc::schema::value::scalar_to_js_string(value).ok(),
Scalar::Boolean(b) => Some(b.to_string()),
Scalar::Array(items) => Some(items.iter().filter_map(scalar_text).collect()),
_ => None,
}
}
fn non_empty_string_attr(tag: &markdoc::types::Tag, key: &str) -> Option<String> {
match tag.attributes.get(key) {
Some(Scalar::String(s)) => {
let trimmed = s.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
}
_ => None,
}
}
pub fn doc_attr(tag: &markdoc::types::Tag) -> Option<String> {
if let Some(Scalar::String(s)) = tag.attributes.get("doc")
&& !s.is_empty()
{
return Some(s.clone());
}
None
}
pub fn collect_inlines(
text: &mut String,
ranges: &mut Vec<InlineRange>,
children: &[RenderableTreeNode],
footnotes: &mut Vec<String>,
) {
let mut tmp = Inlines {
text: std::mem::take(text),
style_ranges: std::mem::take(ranges),
links: Vec::new(),
mid_anchors: Vec::new(),
footnote_calls: Vec::new(),
};
collect_into(&mut tmp, children, footnotes, None);
*text = tmp.text;
*ranges = tmp.style_ranges;
}
fn collect_into(
out: &mut Inlines,
children: &[RenderableTreeNode],
footnotes: &mut Vec<String>,
crossref_labels: Option<&HashMap<String, String>>,
) {
for child in children {
match child {
RenderableTreeNode::Scalar(Scalar::String(s)) => out.text.push_str(s),
RenderableTreeNode::Scalar(value) => {
if let Some(text) = scalar_text(value) {
out.text.push_str(&text);
}
}
RenderableTreeNode::Tag(t) => {
let prop = match t.name.as_str() {
"strong" => Some(InlineProp::Bold),
"em" => Some(InlineProp::Italic),
"s" | "strikethrough" => Some(InlineProp::Strikethrough),
"code" => Some(InlineProp::Code),
"br" | "hardbreak" => {
out.text.push('\n');
collect_into(out, &t.children, footnotes, crossref_labels);
continue;
}
"a" => {
let href = match t.attributes.get("href") {
Some(Scalar::String(s)) => Some(s.clone()),
_ => None,
};
let title = match t.attributes.get("title") {
Some(Scalar::String(s)) if !s.is_empty() => Some(s.clone()),
_ => None,
};
let start = out.text.len();
collect_into(out, &t.children, footnotes, crossref_labels);
let end = out.text.len();
if let Some(href) = href
&& end > start
{
if !is_navigable_uri(&href) {
let preview: String =
out.text[start..end].chars().take(40).collect();
eprintln!(
"warning: link href {href:?} has no URL scheme — \
PDF viewers won't follow it (link text: {preview:?})"
);
}
out.links.push(LinkRange {
start,
end,
href,
title,
});
}
continue;
}
"footnote" => {
let number = (footnotes.len() as u32) + 1;
footnotes.push(String::new());
let mut body = Inlines::new();
collect_into(&mut body, &t.children, footnotes, crossref_labels);
let body_text = body.text.trim().to_string();
if let Some(slot) = footnotes.get_mut((number - 1) as usize) {
*slot = body_text;
}
let mark = superscript_number(number);
let call_offset = out.text.len();
out.text.push_str(&mark);
out.footnote_calls.push(FootnoteCall {
byte_offset: call_offset,
number,
});
continue;
}
"tagref" => {
let doc = doc_attr(t);
let id = anchor_id_attr(t);
match (doc, id) {
(Some(doc), Some(id)) => {
let placeholder = format!("[{doc}#{id}]");
out.text.push_str(&placeholder);
}
(Some(doc), None) => {
let placeholder = format!("[{doc}#?]");
out.text.push_str(&placeholder);
}
(None, Some(id)) => {
let label = non_empty_string_attr(t, "text").unwrap_or_else(|| {
crossref_labels
.and_then(|m| m.get(&id))
.cloned()
.unwrap_or_else(|| id.clone())
});
let start = out.text.len();
out.text.push_str(&label);
let end = out.text.len();
out.links.push(LinkRange {
start,
end,
href: format!("#{id}"),
title: None,
});
}
(None, None) => {
}
}
continue;
}
"tag" => {
if let Some(id) = anchor_id_attr(t) {
out.mid_anchors.push(MidAnchor {
byte_offset: out.text.len(),
id,
});
}
continue;
}
"chip" => {
let glyph = match t.attributes.get("shape") {
Some(Scalar::String(s)) if s.trim().eq_ignore_ascii_case("square") => {
'■'
}
_ => '●',
};
let color = match t.attributes.get("color") {
Some(Scalar::String(s)) => parse_css_color(s),
_ => None,
};
let start = out.text.len();
out.text.push(glyph);
let end = out.text.len();
if let Some(c) = color {
out.style_ranges.push(InlineRange {
start,
end,
prop: InlineProp::Color(c),
});
}
continue;
}
"color" | "c" => {
match t.attributes.get("value") {
Some(Scalar::String(s)) => parse_css_color(s).map(InlineProp::Color),
_ => None,
}
}
"ref" => {
let attr = |k: &str| match t.attributes.get(k) {
Some(Scalar::String(s)) if !s.trim().is_empty() => {
Some(s.trim().to_string())
}
Some(Scalar::Number(n)) if n.fract() == 0.0 => {
Some(format!("{}", *n as i64))
}
Some(Scalar::Number(n)) => Some(n.to_string()),
_ => None,
};
let doc = attr("document");
if let Some(target) = doc.clone().or_else(|| attr("uuid")) {
let label = attr("label").unwrap_or_else(|| format!("doc {target}"));
let href = if doc.is_some() {
format!("ref:document/{target}")
} else {
format!("ref:uuid/{target}")
};
let start = out.text.len();
out.text.push_str(&label);
let end = out.text.len();
out.links.push(LinkRange {
start,
end,
href,
title: None,
});
}
continue;
}
_ => None,
};
let start = out.text.len();
collect_into(out, &t.children, footnotes, crossref_labels);
let end = out.text.len();
if let Some(p) = prop
&& end > start
{
out.style_ranges.push(InlineRange {
start,
end,
prop: p,
});
}
}
}
}
}
pub(super) fn parse_css_color(s: &str) -> Option<krilla::color::rgb::Color> {
let s = s.trim();
if let Some(hex) = s.strip_prefix('#') {
let (r, g, b) = match hex.len() {
3 => {
let d = |i: usize| u8::from_str_radix(&hex[i..i + 1], 16).ok().map(|n| n * 17);
(d(0)?, d(1)?, d(2)?)
}
6 => {
let d = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).ok();
(d(0)?, d(2)?, d(4)?)
}
_ => return None,
};
return Some(krilla::color::rgb::Color::new(r, g, b));
}
let (r, g, b) = match s.to_ascii_lowercase().as_str() {
"red" => (204, 0, 0),
"green" => (0, 128, 0),
"blue" => (0, 0, 204),
"orange" => (255, 120, 0),
"black" => (0, 0, 0),
"white" => (255, 255, 255),
_ => return None,
};
Some(krilla::color::rgb::Color::new(r, g, b))
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::*;
use markdoc::types::RenderableTreeNode;
#[test]
fn parses_hex_and_named_colors() {
use krilla::color::rgb::Color;
assert_eq!(parse_css_color("#d21e1e"), Some(Color::new(210, 30, 30)));
assert_eq!(parse_css_color("#f00"), Some(Color::new(255, 0, 0)));
assert_eq!(parse_css_color(" red "), Some(Color::new(204, 0, 0)));
assert_eq!(parse_css_color("not-a-color"), None);
assert_eq!(parse_css_color("#12"), None);
}
#[test]
fn navigable_intra_doc_anchor() {
assert!(is_navigable_uri("#section"));
assert!(is_navigable_uri("#"));
assert!(is_navigable_uri("#a-b_c.123"));
}
#[test]
fn navigable_standard_schemes() {
assert!(is_navigable_uri("http://example.com"));
assert!(is_navigable_uri("https://example.com/path?q=1"));
assert!(is_navigable_uri("file:///etc/hosts"));
assert!(is_navigable_uri("mailto:alice@example.com"));
assert!(is_navigable_uri("tel:+15551234"));
assert!(is_navigable_uri("ftp://ftp.example.com/"));
}
#[test]
fn navigable_custom_scheme() {
assert!(is_navigable_uri("asset://abc-def"));
assert!(is_navigable_uri("vscode://file/foo"));
assert!(is_navigable_uri("git+ssh://host/repo"));
assert!(is_navigable_uri("foo.bar://baz"));
}
#[test]
fn schemeless_relative_paths_are_dead() {
assert!(!is_navigable_uri("coverpage.style.toml"));
assert!(!is_navigable_uri("./foo.md"));
assert!(!is_navigable_uri("../bar"));
assert!(!is_navigable_uri("/absolute/path"));
assert!(!is_navigable_uri("just-a-word"));
}
#[test]
fn schemes_must_start_with_alpha() {
assert!(!is_navigable_uri("123:abc"));
assert!(!is_navigable_uri("-foo:bar"));
assert!(!is_navigable_uri(":colon-leader"));
assert!(!is_navigable_uri(""));
}
fn tagref_label(src: &str, section_label: Option<&str>) -> (String, Vec<LinkRange>) {
let tree = crate::pipeline::render_tree(src).unwrap();
let children = paragraph_with_tagref(&tree).expect("paragraph containing tagref");
let mut labels = HashMap::new();
if let Some(label) = section_label {
labels.insert("brake".to_string(), label.to_string());
}
let mut footnotes = Vec::new();
let inlines = Inlines::from_with_labels(children, &mut footnotes, Some(&labels));
(inlines.text, inlines.links)
}
fn paragraph_with_tagref(node: &RenderableTreeNode) -> Option<&[RenderableTreeNode]> {
let RenderableTreeNode::Tag(tag) = node else {
return None;
};
if tag
.children
.iter()
.any(|child| matches!(child, RenderableTreeNode::Tag(t) if t.name == "tagref"))
{
return Some(&tag.children);
}
for child in &tag.children {
if let Some(found) = paragraph_with_tagref(child) {
return Some(found);
}
}
None
}
#[test]
fn tagref_text_overrides_section_label() {
let (text, links) = tagref_label(
r#"See {% tagref "brake" text="the brake switch" /%}."#,
Some("6.5 Manual brake release"),
);
assert_eq!(text, "See the brake switch.");
assert_eq!(links.len(), 1);
assert_eq!(links[0].href, "#brake");
}
#[test]
fn tagref_without_text_uses_section_label() {
let (text, links) = tagref_label(
r#"See {% tagref "brake" /%}."#,
Some("6.5 Manual brake release"),
);
assert_eq!(text, "See 6.5 Manual brake release.");
assert_eq!(links[0].href, "#brake");
}
#[test]
fn tagref_blank_text_falls_back_to_section_label() {
let (text, _) = tagref_label(
r#"See {% tagref "brake" text=" " /%}."#,
Some("6.5 Manual brake release"),
);
assert_eq!(text, "See 6.5 Manual brake release.");
}
#[test]
fn scheme_must_actually_have_a_colon() {
assert!(!is_navigable_uri("http"));
assert!(!is_navigable_uri("about"));
}
}