Skip to main content

markdoc_pdf/render/
external_tagrefs.rs

1//! Turn `{% tagref %}` targets that are not in this PDF into website links.
2//!
3//! Scope is the rendered tree (conditionals already resolved), so a tag
4//! that was dropped from the PDF is not an internal destination. The
5//! caller supplies `tag id → { url, title }` from the site catalog.
6
7use std::collections::{HashMap, HashSet};
8
9use markdoc::types::{RenderableTreeNode, Scalar, Tag};
10
11use super::inline::anchor_id_attr;
12
13/// Website destination for a `{% tag %}` that is not in the PDF.
14#[derive(Debug, Clone, Default)]
15pub struct ExternalTagref {
16    pub url: String,
17    pub title: String,
18}
19
20/// Replace out-of-scope `{% tagref %}` nodes with `<a href>` links.
21///
22/// Tagrefs whose target `{% tag %}` is in `root` are left alone so they
23/// stay internal PDF destinations. Tagrefs with no catalog entry are
24/// left alone as well.
25pub fn externalize_out_of_scope_tagrefs(
26    root: &RenderableTreeNode,
27    external: &HashMap<String, ExternalTagref>,
28) -> RenderableTreeNode {
29    if external.is_empty() {
30        return root.clone();
31    }
32
33    let mut scope = HashSet::new();
34    collect_tag_ids(root, &mut scope);
35    let mut missing = HashSet::new();
36    let rewritten = rewrite(root, &scope, external, &mut missing);
37    for id in missing {
38        eprintln!("warning: tagref {id:?} is not in this PDF and has no page on the website");
39    }
40    rewritten
41}
42
43fn collect_tag_ids(node: &RenderableTreeNode, scope: &mut HashSet<String>) {
44    let RenderableTreeNode::Tag(tag) = node else {
45        return;
46    };
47    if tag.name == "tag"
48        && let Some(id) = anchor_id_attr(tag)
49    {
50        scope.insert(id);
51    }
52    for child in &tag.children {
53        collect_tag_ids(child, scope);
54    }
55}
56
57fn rewrite(
58    node: &RenderableTreeNode,
59    scope: &HashSet<String>,
60    external: &HashMap<String, ExternalTagref>,
61    missing: &mut HashSet<String>,
62) -> RenderableTreeNode {
63    let RenderableTreeNode::Tag(tag) = node else {
64        return node.clone();
65    };
66
67    if tag.name == "tagref"
68        && let Some(id) = anchor_id_attr(tag)
69        && !scope.contains(&id)
70    {
71        if let Some(dest) = external.get(&id).filter(|dest| !dest.url.is_empty()) {
72            // Print the full URL. A heading title disappears on paper.
73            return link_node(&dest.url);
74        }
75        missing.insert(id);
76    }
77
78    let children = tag
79        .children
80        .iter()
81        .map(|child| rewrite(child, scope, external, missing))
82        .collect();
83    RenderableTreeNode::Tag(Box::new(Tag {
84        name: tag.name.clone(),
85        attributes: tag.attributes.clone(),
86        children,
87    }))
88}
89
90fn link_node(url: &str) -> RenderableTreeNode {
91    let mut attributes = markdoc::IndexMap::new();
92    attributes.insert("href".to_string(), Scalar::String(url.to_string()));
93    attributes.insert("title".to_string(), Scalar::String(url.to_string()));
94    RenderableTreeNode::Tag(Box::new(Tag {
95        name: "a".to_string(),
96        attributes,
97        children: vec![RenderableTreeNode::Scalar(Scalar::String(url.to_string()))],
98    }))
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    fn string_attr(key: &str, value: &str) -> (String, Scalar) {
106        (key.to_string(), Scalar::String(value.to_string()))
107    }
108
109    fn tag(
110        name: &str,
111        attrs: Vec<(String, Scalar)>,
112        children: Vec<RenderableTreeNode>,
113    ) -> RenderableTreeNode {
114        RenderableTreeNode::Tag(Box::new(Tag {
115            name: name.to_string(),
116            attributes: attrs.into_iter().collect(),
117            children,
118        }))
119    }
120
121    fn href_of(node: &RenderableTreeNode) -> Option<String> {
122        let RenderableTreeNode::Tag(tag) = node else {
123            return None;
124        };
125        match tag.attributes.get("href") {
126            Some(Scalar::String(href)) => Some(href.clone()),
127            _ => None,
128        }
129    }
130
131    fn text_of(node: &RenderableTreeNode) -> String {
132        let RenderableTreeNode::Tag(tag) = node else {
133            return String::new();
134        };
135        tag.children
136            .iter()
137            .filter_map(|child| match child {
138                RenderableTreeNode::Scalar(Scalar::String(text)) => Some(text.clone()),
139                _ => None,
140            })
141            .collect()
142    }
143
144    #[test]
145    fn in_scope_tagref_stays_internal() {
146        let root = tag(
147            "p",
148            vec![],
149            vec![
150                tag("tag", vec![string_attr("id", "brake")], vec![]),
151                tag("tagref", vec![string_attr("id", "brake")], vec![]),
152            ],
153        );
154        let mut external = HashMap::new();
155        external.insert(
156            "brake".to_string(),
157            ExternalTagref {
158                url: "https://docs.example/brake".into(),
159                title: "Brake".into(),
160            },
161        );
162        let rewritten = externalize_out_of_scope_tagrefs(&root, &external);
163        let RenderableTreeNode::Tag(paragraph) = &rewritten else {
164            panic!("expected paragraph");
165        };
166        assert_eq!(paragraph.children[1].tag_name(), Some("tagref"));
167    }
168
169    #[test]
170    fn out_of_scope_tagref_becomes_website_link() {
171        let root = tag(
172            "p",
173            vec![],
174            vec![tag(
175                "tagref",
176                vec![string_attr("primary", "modbus")],
177                vec![],
178            )],
179        );
180        let mut external = HashMap::new();
181        external.insert(
182            "modbus".to_string(),
183            ExternalTagref {
184                url: "https://docs.example/modbus#modbus".into(),
185                title: "Modbus".into(),
186            },
187        );
188        let rewritten = externalize_out_of_scope_tagrefs(&root, &external);
189        let RenderableTreeNode::Tag(paragraph) = &rewritten else {
190            panic!("expected paragraph");
191        };
192        let link = &paragraph.children[0];
193        assert_eq!(link.tag_name(), Some("a"));
194        assert_eq!(
195            href_of(link).as_deref(),
196            Some("https://docs.example/modbus#modbus")
197        );
198        assert_eq!(text_of(link), "https://docs.example/modbus#modbus");
199    }
200
201    #[test]
202    fn printed_text_is_the_full_url_even_with_text_attribute() {
203        let root = tag(
204            "p",
205            vec![],
206            vec![tag(
207                "tagref",
208                vec![
209                    string_attr("id", "modbus"),
210                    string_attr("text", "the Modbus page"),
211                ],
212                vec![],
213            )],
214        );
215        let mut external = HashMap::new();
216        external.insert(
217            "modbus".to_string(),
218            ExternalTagref {
219                url: "https://docs.example/modbus#modbus".into(),
220                title: "Modbus".into(),
221            },
222        );
223        let rewritten = externalize_out_of_scope_tagrefs(&root, &external);
224        let RenderableTreeNode::Tag(paragraph) = &rewritten else {
225            panic!("expected paragraph");
226        };
227        assert_eq!(
228            text_of(&paragraph.children[0]),
229            "https://docs.example/modbus#modbus"
230        );
231    }
232
233    trait TagName {
234        fn tag_name(&self) -> Option<&str>;
235    }
236
237    impl TagName for RenderableTreeNode {
238        fn tag_name(&self) -> Option<&str> {
239            match self {
240                RenderableTreeNode::Tag(tag) => Some(tag.name.as_str()),
241                RenderableTreeNode::Scalar(_) => None,
242            }
243        }
244    }
245}