docgen-core 0.8.0

Core Markdown processing and page model for docgen, the Cargo-only static documentation-site generator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
use std::collections::BTreeSet;

use comrak::nodes::{AstNode, NodeValue};
use comrak::Arena;

/// The set of all known slugs, used to resolve wikilink targets.
pub type SlugSet = BTreeSet<String>;

/// Split a `[[...]]` inner string into `(target, Some(label))` or `(target, None)`.
/// Splits on the FIRST `|` only; the remainder is the label.
pub fn parse_wikilink(inner: &str) -> (String, Option<String>) {
    match inner.split_once('|') {
        Some((t, label)) => (t.trim().to_string(), Some(label.trim().to_string())),
        None => (inner.trim().to_string(), None),
    }
}

/// Resolve a wikilink target to a slug.
/// Order: trimmed-exact slug match, then case-insensitive basename match
/// (basename = last `/`-segment of a slug). First basename match wins by
/// `SlugSet` (BTreeSet) order, making resolution deterministic.
pub fn resolve_target(target: &str, slugs: &SlugSet) -> Option<String> {
    let t = target.trim();
    if t.is_empty() {
        return None;
    }
    if slugs.contains(t) {
        return Some(t.to_string());
    }
    let needle = t.to_ascii_lowercase();
    slugs
        .iter()
        .find(|slug| {
            slug.rsplit('/')
                .next()
                .unwrap_or(slug)
                .eq_ignore_ascii_case(&needle)
        })
        .cloned()
}

/// Outcome of transforming one document's AST.
pub struct WikilinkPass {
    /// Target slugs this doc links to, deduped, in first-seen document order.
    pub resolved: Vec<String>,
}

/// Minimal HTML-attribute / text escaper for the small strings we inject.
/// Single-pass into one allocation (avoids the 4-string `replace` chain).
fn esc(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            _ => out.push(c),
        }
    }
    out
}

/// The display text for a wikilink: the label if present and non-blank, else the
/// target. An empty/whitespace-only label is treated as absent so we never emit an
/// anchor with invisible text. Mirrors `search::push_unwrapping_wikilinks`.
fn display_text(target: &str, label: Option<String>) -> String {
    label
        .filter(|l| !l.trim().is_empty())
        .unwrap_or_else(|| target.to_string())
}

/// Anchorize a single heading text into the base id the rendered page carries.
/// Uses comrak's [`Anchorizer`] — the same scheme `headings::collect_headings`
/// / `stamp_heading_ids` use — so `[[page#Heading]]` fragments match the ids
/// stamped onto `<h2>`/`<h3>` tags. A fresh anchorizer per string means no
/// `-1`/`-2` dedup context: an anchor always targets the FIRST heading with
/// that text (write `[[page#heading-1]]` to hit a duplicate explicitly).
fn anchorize(text: &str) -> String {
    comrak::Anchorizer::new().anchorize(text)
}

/// Build the inline HTML for one wikilink occurrence and, if resolved, push its
/// target slug into `resolved` (deduped, first-seen order).
///
/// `[[page#anchor]]` resolves the page part and links to `{base}/{slug}#{id}`;
/// `[[#anchor]]` (empty page part) is a same-page fragment link. The display
/// text stays the ORIGINAL target string, anchor included (Obsidian-style
/// `page#anchor`), unless a label overrides it.
fn render_link(
    inner: &str,
    slugs: &SlugSet,
    base: &str,
    resolved: &mut Vec<String>,
    seen: &mut BTreeSet<String>,
) -> String {
    let (target, label) = parse_wikilink(inner);
    // Split the optional `#anchor` off the page part. A blank anchor (`[[x#]]`)
    // is treated as absent.
    let (page, anchor) = match target.split_once('#') {
        Some((p, a)) => (
            p.trim().to_string(),
            Some(a.trim()).filter(|a| !a.is_empty()),
        ),
        None => (target.clone(), None),
    };
    let text = display_text(&target, label);

    // `[[#heading]]`: same-page anchor link — no page to resolve.
    if page.is_empty() {
        if let Some(a) = anchor {
            return format!(
                r##"<a class="docgen-wikilink" href="#{}">{}</a>"##,
                esc(&anchorize(a)),
                esc(&text)
            );
        }
        // Empty target with no anchor falls through to the broken span.
    }

    match resolve_target(&page, slugs) {
        Some(slug) => {
            if seen.insert(slug.clone()) {
                resolved.push(slug.clone());
            }
            let fragment = anchor
                .map(|a| format!("#{}", esc(&anchorize(a))))
                .unwrap_or_default();
            format!(
                r#"<a class="docgen-wikilink" href="{0}/{1}{2}" data-wikilink-title="{3}" data-wikilink-path="/{1}">{3}</a>"#,
                base,
                esc(&slug),
                fragment,
                esc(&text)
            )
        }
        None => format!(
            r#"<span class="docgen-wikilink docgen-wikilink--broken" data-target="{}">{}</span>"#,
            esc(&target),
            esc(&text)
        ),
    }
}

/// Walk the AST; for each Text node containing `[[...]]`, split it into
/// surrounding Text nodes + raw-HTML inline nodes for each wikilink.
/// The flat source text a child node contributes when reconstructing an inline
/// run, or `None` if the node breaks the run (it is not foldable into text).
pub(crate) fn flat_source(node: &AstNode<'_>) -> Option<String> {
    match &node.data.borrow().value {
        NodeValue::Text(t) => Some(t.to_string()),
        // Raw inline HTML inside `[[ ... ]]` is folded back into the target string
        // (e.g. `[[a<b>]]`), so the resolver/escaper sees the literal `a<b>`.
        NodeValue::HtmlInline(h) => Some(h.clone()),
        _ => None,
    }
}

/// `base` is the deployed sub-path prefix (e.g. `/docs`); `""` for root
/// deployment. Resolved-wikilink hrefs are emitted as `{base}/{slug}`.
pub fn transform_wikilinks<'a>(
    root: &'a AstNode<'a>,
    arena: &'a Arena<'a>,
    slugs: &SlugSet,
    base: &str,
) -> WikilinkPass {
    let mut resolved: Vec<String> = Vec::new();
    let mut seen: BTreeSet<String> = BTreeSet::new();

    // Collect every node that has children, so we can scan their direct child
    // runs. We snapshot the list first to avoid iterating while mutating.
    let parents: Vec<&'a AstNode<'a>> = root
        .descendants()
        .filter(|n| n.first_child().is_some())
        .collect();

    for parent in parents {
        // Snapshot direct children.
        let children: Vec<&'a AstNode<'a>> = parent.children().collect();

        // Walk maximal runs of foldable (Text/HtmlInline) children, rebuild any
        // run that contains a complete `[[...]]`.
        let mut i = 0;
        while i < children.len() {
            if flat_source(children[i]).is_none() {
                i += 1;
                continue;
            }
            // Extend the foldable run.
            let start = i;
            let mut combined = String::new();
            while i < children.len() {
                match flat_source(children[i]) {
                    Some(s) => {
                        combined.push_str(&s);
                        i += 1;
                    }
                    None => break,
                }
            }

            if !combined.contains("[[") {
                continue;
            }

            // Build replacement nodes from the combined run, inserted before the
            // first node of the run; then detach the whole run.
            let anchor = children[start];
            let mut rest = combined.as_str();
            let mut produced_any = false;
            while let Some(open) = rest.find("[[") {
                if let Some(close_rel) = rest[open + 2..].find("]]") {
                    let close = open + 2 + close_rel;
                    let before = &rest[..open];
                    let inner = &rest[open + 2..close];

                    if !before.is_empty() {
                        let n =
                            arena.alloc(AstNode::from(NodeValue::Text(before.to_string().into())));
                        anchor.insert_before(n);
                    }
                    let html = render_link(inner, slugs, base, &mut resolved, &mut seen);
                    let n = arena.alloc(AstNode::from(NodeValue::HtmlInline(html)));
                    anchor.insert_before(n);

                    rest = &rest[close + 2..];
                    produced_any = true;
                } else {
                    break; // unterminated `[[` — leave the remainder literal
                }
            }

            if produced_any {
                if !rest.is_empty() {
                    let n = arena.alloc(AstNode::from(NodeValue::Text(rest.to_string().into())));
                    anchor.insert_before(n);
                }
                for node in &children[start..i] {
                    node.detach();
                }
            }
        }
    }

    WikilinkPass { resolved }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::markdown::comrak_options;
    use comrak::{parse_document, Arena};

    fn slugs() -> SlugSet {
        ["index", "guide/intro", "guide/Advanced", "reference/api"]
            .iter()
            .map(|s| s.to_string())
            .collect()
    }

    #[test]
    fn resolves_exact_slug() {
        assert_eq!(
            resolve_target("guide/intro", &slugs()),
            Some("guide/intro".to_string())
        );
    }

    #[test]
    fn resolves_basename_case_insensitive() {
        // "advanced" matches the basename of "guide/Advanced".
        assert_eq!(
            resolve_target("advanced", &slugs()),
            Some("guide/Advanced".to_string())
        );
        assert_eq!(
            resolve_target("INTRO", &slugs()),
            Some("guide/intro".to_string())
        );
    }

    #[test]
    fn trims_surrounding_whitespace() {
        assert_eq!(
            resolve_target("  index  ", &slugs()),
            Some("index".to_string())
        );
    }

    #[test]
    fn unresolved_returns_none() {
        assert_eq!(resolve_target("does/not/exist", &slugs()), None);
        assert_eq!(resolve_target("", &slugs()), None);
    }

    #[test]
    fn parse_splits_label() {
        assert_eq!(
            parse_wikilink("target|Label"),
            ("target".to_string(), Some("Label".to_string()))
        );
        assert_eq!(parse_wikilink("target"), ("target".to_string(), None));
        // Only the first pipe splits; extra pipes belong to the label.
        assert_eq!(
            parse_wikilink("a|b|c"),
            ("a".to_string(), Some("b|c".to_string()))
        );
    }

    fn render(md: &str, slugs: &SlugSet) -> (String, Vec<String>) {
        render_with_base(md, slugs, "")
    }

    fn render_with_base(md: &str, slugs: &SlugSet, base: &str) -> (String, Vec<String>) {
        let arena = Arena::new();
        let options = comrak_options();
        let root = parse_document(&arena, md, &options);
        let pass = transform_wikilinks(root, &arena, slugs, base);
        let html = crate::markdown::format_ast(root, &options);
        (html, pass.resolved)
    }

    #[test]
    fn resolved_wikilink_href_is_prefixed_with_base() {
        let (html, _) = render_with_base("[[guide/intro]]\n", &slugs(), "/docs");
        assert!(html.contains(r#"href="/docs/guide/intro""#));
        assert!(!html.contains(r#"href="/guide/intro""#));
    }

    #[test]
    fn resolved_wikilink_becomes_anchor() {
        let (html, resolved) = render("see [[guide/intro]] now\n", &slugs());
        assert!(html.contains(
            r#"<a class="docgen-wikilink" href="/guide/intro" data-wikilink-title="guide/intro" data-wikilink-path="/guide/intro">guide/intro</a>"#
        ));
        assert_eq!(resolved, vec!["guide/intro".to_string()]);
    }

    #[test]
    fn labeled_wikilink_uses_label_text() {
        let (html, _) = render("[[guide/intro|The Intro]]\n", &slugs());
        assert!(html.contains(r#"href="/guide/intro""#));
        assert!(html.contains(r#"data-wikilink-title="The Intro""#));
        assert!(html.contains(r#">The Intro</a>"#));
    }

    #[test]
    fn broken_wikilink_becomes_marked_span() {
        let (html, resolved) = render("[[nope]] here\n", &slugs());
        assert!(html.contains(
            r#"<span class="docgen-wikilink docgen-wikilink--broken" data-target="nope">nope</span>"#
        ));
        assert!(resolved.is_empty());
    }

    #[test]
    fn resolved_targets_are_deduped_in_order() {
        let (_html, resolved) = render("[[guide/intro]] and [[index]] and [[intro]]\n", &slugs());
        // "intro" resolves to guide/intro (already present) -> deduped.
        assert_eq!(
            resolved,
            vec!["guide/intro".to_string(), "index".to_string()]
        );
    }

    #[test]
    fn empty_or_whitespace_label_falls_back_to_target() {
        // `[[index|]]` and `[[index|   ]]` must not render an empty clickable text;
        // they fall back to the target, matching the search-index unwrap path.
        let (html, _) = render("[[index|]]\n", &slugs());
        assert!(html.contains(r#"href="/index""#));
        assert!(html.contains(r#">index</a>"#));
        assert!(!html.contains(r#">      </a>"#));

        let (html, _) = render("[[index|   ]]\n", &slugs());
        assert!(html.contains(r#">index</a>"#));

        // Broken target with empty label also falls back to the target text.
        let (html, _) = render("[[nope|]] x\n", &slugs());
        assert!(html.contains(r#"data-target="nope">nope</span>"#));
    }

    #[test]
    fn ambiguous_basename_resolves_deterministically() {
        // Two slugs share the basename `dup`; resolution is first by BTreeSet order.
        let amb: SlugSet = ["a/dup", "b/dup"].iter().map(|s| s.to_string()).collect();
        assert_eq!(resolve_target("dup", &amb), Some("a/dup".to_string()));
    }

    #[test]
    fn anchored_wikilink_resolves_page_and_appends_anchor_id() {
        let (html, resolved) = render_with_base("[[guide/intro#Setup Steps]]\n", &slugs(), "/docs");
        // Page resolves; anchor is anchorized like heading ids.
        assert!(
            html.contains(r#"href="/docs/guide/intro#setup-steps""#),
            "{html}"
        );
        // Display text keeps the original target INCLUDING the anchor part.
        assert!(html.contains(">guide/intro#Setup Steps</a>"), "{html}");
        // The preview path is the page (no fragment).
        assert!(
            html.contains(r#"data-wikilink-path="/guide/intro""#),
            "{html}"
        );
        // Anchored links count as real links to the page (graph/backlinks).
        assert_eq!(resolved, vec!["guide/intro".to_string()]);
    }

    #[test]
    fn anchored_wikilink_label_overrides_display_text() {
        let (html, _) = render("[[guide/intro#setup|Setup]]\n", &slugs());
        assert!(html.contains(r#"href="/guide/intro#setup""#), "{html}");
        assert!(html.contains(">Setup</a>"), "{html}");
    }

    #[test]
    fn anchor_only_wikilink_is_a_same_page_fragment_link() {
        let (html, resolved) = render("[[#My Heading]]\n", &slugs());
        assert!(
            html.contains(r##"<a class="docgen-wikilink" href="#my-heading">#My Heading</a>"##),
            "{html}"
        );
        // A same-page link is not an outbound edge.
        assert!(resolved.is_empty());
    }

    #[test]
    fn broken_page_with_anchor_stays_a_broken_span() {
        let (html, resolved) = render("[[nope#section]]\n", &slugs());
        assert!(
            html.contains(r#"data-target="nope#section">nope#section</span>"#),
            "{html}"
        );
        assert!(resolved.is_empty());

        // A blank anchor on a real page is ignored (plain page link).
        let (html, _) = render("[[index#]]\n", &slugs());
        assert!(html.contains(r#"href="/index""#), "{html}");
        assert!(!html.contains(r##"href="/index#""##), "{html}");
    }

    #[test]
    fn html_special_chars_in_broken_target_are_escaped() {
        let (html, _) = render("[[a<b>]] x\n", &slugs());
        assert!(html.contains("data-target=\"a&lt;b&gt;\""));
        assert!(!html.contains("<b>"));
    }
}