docgen-core 0.1.1

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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
use std::collections::BTreeMap;

use comrak::{parse_document, Arena};

use crate::frontmatter::parse_frontmatter;
use crate::graph::{build_link_graph, LinkGraph};
use crate::markdown::{comrak_options, format_ast};
use crate::model::{Doc, RawDoc, SearchEntry};
use crate::search::plaintext;
use crate::wikilink::{transform_wikilinks, SlugSet};

/// Docs-relative path → frontmatter-stripped body, for `:include` targets.
pub type Partials = std::collections::BTreeMap<String, String>;

/// A doc is an include-only *partial* (never its own page) when its filename
/// starts with `_`. Only the basename matters — a `_dir/` directory does not
/// hide the pages inside it.
pub fn is_partial_rel(rel_path: &str) -> bool {
    rel_path
        .rsplit('/')
        .next()
        .map(|name| name.starts_with('_'))
        .unwrap_or(false)
}

/// Split discovered raw docs into rendered pages and the include-only partial
/// map (keyed by docs-relative path, frontmatter stripped).
pub fn partition_partials(raws: Vec<RawDoc>) -> (Vec<RawDoc>, Partials) {
    let mut pages = Vec::new();
    let mut partials = Partials::new();
    for raw in raws {
        if is_partial_rel(&raw.rel_path) {
            let body = parse_frontmatter(&raw.raw).body;
            partials.insert(raw.rel_path, body);
        } else {
            pages.push(raw);
        }
    }
    (pages, partials)
}

/// Resolve a relative include `src` against the docs-relative directory
/// `base_dir` into a normalized docs-relative key (no `./`, `..` collapsed). A
/// leading `/` is treated as docs-root-absolute. Returns `None` if the path
/// escapes above the docs root.
pub fn resolve_include_key(base_dir: &str, src: &str) -> Option<String> {
    let src = src.trim();
    let combined = if let Some(rest) = src.strip_prefix('/') {
        rest.to_string()
    } else if base_dir.is_empty() {
        src.to_string()
    } else {
        format!("{base_dir}/{src}")
    };
    let mut parts: Vec<&str> = Vec::new();
    for seg in combined.split('/') {
        match seg {
            "" | "." => continue,
            ".." => {
                parts.pop()?;
            }
            s => parts.push(s),
        }
    }
    Some(parts.join("/"))
}

/// A document after pass 1: frontmatter parsed, slug/title derived, raw body kept.
#[derive(Debug, Clone, PartialEq)]
pub struct PreparedDoc {
    pub rel_path: String,
    pub slug: String,
    pub title: String,
    /// Optional `description:` from frontmatter, surfaced in backlink cards.
    pub description: Option<String>,
    pub body_md: String,
}

/// The fully assembled site after pass 2.
pub struct SiteBuild {
    pub docs: Vec<Doc>,
    pub graph: LinkGraph,
    pub search: Vec<SearchEntry>,
    /// True if any doc contains a mermaid diagram. Lets the build subcommand flip
    /// `EmitOptions.include_mermaid` once for the whole site.
    pub any_mermaid: bool,
    /// True if any doc used ≥1 custom component (gates the components asset slice).
    pub any_components: bool,
}

impl SiteBuild {
    /// Build the deterministic `GraphData` for the `/graph/` page from this
    /// site's docs (node order = doc order) and its already-built `LinkGraph`.
    /// Never recomputes links.
    pub fn graph_data(
        &self,
        params: crate::graphlayout::LayoutParams,
    ) -> crate::graphlayout::GraphData {
        let meta: Vec<(String, String)> = self
            .docs
            .iter()
            .map(|d| (d.slug.clone(), d.title.clone()))
            .collect();
        crate::graphlayout::layout_graph(&meta, &self.graph, params)
    }
}

fn first_h1(body: &str) -> Option<String> {
    body.lines()
        .find_map(|line| line.strip_prefix("# ").map(|h| h.trim().to_string()))
}

/// Pass 1: pure per-doc preparation, no cross-doc knowledge.
pub fn prepare(raw: RawDoc) -> PreparedDoc {
    let parsed = parse_frontmatter(&raw.raw);
    let slug = raw
        .rel_path
        .strip_suffix(".md")
        .unwrap_or(&raw.rel_path)
        .to_string();

    let fm_title = parsed
        .frontmatter
        .get("title")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());
    let title = fm_title
        .or_else(|| first_h1(&parsed.body))
        .unwrap_or_else(|| slug.rsplit('/').next().unwrap_or("").to_string());

    let description = parsed
        .frontmatter
        .get("description")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    PreparedDoc {
        rel_path: raw.rel_path,
        slug,
        title,
        description,
        body_md: parsed.body,
    }
}

/// Render a markdown fragment (a block directive's inner content) to inner HTML,
/// running the full directive + AST pipeline but emitting no page chrome.
///
/// Wikilinks inside a directive body are resolved against the same site `slugs`
/// and `base` as top-level body content, so `[[target|label]]` becomes a resolved
/// `<a>` (or a broken span) exactly as it would outside a directive. The
/// nested-directive case works because `substitute` recurses through this fn.
///
/// Note: resolved targets discovered inside directive bodies are NOT folded into
/// the link graph / backlinks (the graph is built from the top-level pass only);
/// the rendered HTML is correct, but a wikilink that *only* appears inside a
/// directive body does not yet create a graph edge.
pub fn render_block_markdown(
    md: &str,
    config: &docgen_config::SiteConfig,
    registry: &docgen_components::Registry,
    slugs: &SlugSet,
    partials: &Partials,
    base_dir: &str,
    stack: &[String],
) -> String {
    let (rewritten, instances) = crate::directivepass::extract(md);
    let options = comrak_options();
    let arena = Arena::new();
    let root = parse_document(&arena, &rewritten, &options);
    // Resolve wikilinks in the directive body the same way top-level body content
    // does, before math/mermaid rewrite their nodes.
    let _pass = transform_wikilinks(root, &arena, slugs, &config.base);
    if config.features.math {
        crate::mathpass::transform_math(root);
    }
    if config.features.mermaid {
        crate::mermaidpass::transform_mermaid(root);
    }
    let inner_html = format_ast(root, &options);
    let render_inner =
        |m: &str| render_block_markdown(m, config, registry, slugs, partials, base_dir, stack);
    let resolve_include =
        |src: &str| resolve_include_src(src, base_dir, partials, stack, config, registry, slugs);
    let (out, _used) = crate::directivepass::substitute(
        &inner_html,
        &instances,
        registry,
        &render_inner,
        &resolve_include,
    );
    out
}

/// Resolve `:include{src}` against `base_dir`, render the partial's body through
/// the recursive pipeline. Missing target or an include cycle degrades to an
/// inert error span (never panics). `stack` holds the include keys currently on
/// the rendering path, for cycle detection.
fn resolve_include_src(
    src: &str,
    base_dir: &str,
    partials: &Partials,
    stack: &[String],
    config: &docgen_config::SiteConfig,
    registry: &docgen_components::Registry,
    slugs: &SlugSet,
) -> String {
    let key = match resolve_include_key(base_dir, src) {
        Some(k) => k,
        None => return crate::directivepass::error_span("include", "src escapes docs root"),
    };
    if stack.iter().any(|s| s == &key) {
        return crate::directivepass::error_span("include", "include cycle");
    }
    let Some(body) = partials.get(&key) else {
        return crate::directivepass::error_span("include", "missing `src`");
    };
    let mut next = stack.to_vec();
    next.push(key.clone());
    let child_dir = key.rsplit_once('/').map(|(d, _)| d).unwrap_or("");
    render_block_markdown(body, config, registry, slugs, partials, child_dir, &next)
}

/// A single rendered doc plus the by-products the site assembly needs: its
/// search plaintext and the slugs it links out to (for the link graph). Returned
/// by [`render_doc`] so both the whole-site build and the editor live-preview run
/// the *same* per-doc pipeline rather than two drifting copies.
pub struct RenderedDoc {
    pub doc: Doc,
    /// Plaintext extracted from the pristine AST (no markup), for the search index.
    pub search_text: String,
    /// Resolved outbound wikilink target slugs, in document order (for the graph).
    pub resolved_links: Vec<String>,
}

/// Render ONE prepared doc to its final inner HTML, running the full per-doc
/// pipeline: directive pre-pass → parse → search plaintext → headings → wikilink
/// resolve → math → mermaid → format → heading-id stamp → directive substitute.
///
/// `slugs` is the *whole site's* slug set so `[[wikilinks]]` resolve against every
/// doc, not just this one — the caller must build it from all docs. This is the
/// single source of truth the static build ([`render_docs`]) and the dev server's
/// editor preview both call, so a doc previewed in the editor renders byte-for-byte
/// like its published page.
pub fn render_doc(
    p: &PreparedDoc,
    config: &docgen_config::SiteConfig,
    registry: &docgen_components::Registry,
    slugs: &SlugSet,
    partials: &Partials,
) -> RenderedDoc {
    let options = comrak_options();

    // Directive pre-pass: rewrite the raw body, replacing each `:::`/`:leaf`
    // directive with an HTML-comment sentinel that survives comrak verbatim.
    let (rewritten, instances) = crate::directivepass::extract(&p.body_md);

    // Parse the (directive-free) body once. Extract search plaintext from the
    // pristine AST *before* the wikilink pass rewrites `[[...]]` Text nodes.
    let arena = Arena::new();
    let root = parse_document(&arena, &rewritten, &options);

    let search_text = plaintext(root);

    // Heading outline for the right-rail TOC. Collected from the pristine
    // AST (after parse, before formatting) so the anchorized ids match what
    // `stamp_heading_ids` writes onto the rendered tags below.
    let headings = crate::headings::collect_headings(root);

    // Wikilink AST pass (mutates `root`) + highlighted HTML.
    let pass = transform_wikilinks(root, &arena, slugs, &config.base);
    let resolved_links = pass.resolved;
    // Build-time math: replace math nodes with KaTeX HTML before formatting.
    let math_count = if config.features.math {
        crate::mathpass::transform_math(root)
    } else {
        0
    };
    // Mermaid: replace ```mermaid fences with island containers before formatting.
    let mermaid_count = if config.features.mermaid {
        crate::mermaidpass::transform_mermaid(root)
    } else {
        0
    };
    let formatted = format_ast(root, &options);
    // Stamp the anchorized ids onto the `<h2>`/`<h3>` tags so the rail TOC +
    // scroll-spy can target them via `h2[id]` / `h3[id]`.
    let formatted = crate::headings::stamp_heading_ids(&formatted, &headings);

    // Directive post-pass: substitute each sentinel with the component's
    // rendered HTML; block inner content + `:include` partials are rendered by
    // the full recursive pipeline. `used` drives per-page island/style gating.
    let base_dir = p.rel_path.rsplit_once('/').map(|(d, _)| d).unwrap_or("");
    let stack: Vec<String> = Vec::new();
    let render_inner =
        |m: &str| render_block_markdown(m, config, registry, slugs, partials, base_dir, &stack);
    let resolve_include =
        |src: &str| resolve_include_src(src, base_dir, partials, &stack, config, registry, slugs);
    let (body_html, used) = crate::directivepass::substitute(
        &formatted,
        &instances,
        registry,
        &render_inner,
        &resolve_include,
    );

    RenderedDoc {
        doc: Doc {
            rel_path: p.rel_path.clone(),
            slug: p.slug.clone(),
            title: p.title.clone(),
            description: p.description.clone(),
            body_html,
            has_math: math_count > 0,
            has_mermaid: mermaid_count > 0,
            components_used: used,
            headings,
        },
        search_text,
        resolved_links,
    }
}

/// Pass 2: build the slug set, run the wikilink pass + syntect highlight per doc,
/// assemble the link graph + search index. Input order preserved.
pub fn render_docs(
    prepared: Vec<PreparedDoc>,
    partials: &Partials,
    config: &docgen_config::SiteConfig,
    registry: &docgen_components::Registry,
) -> SiteBuild {
    let slugs: SlugSet = prepared.iter().map(|p| p.slug.clone()).collect();
    let doc_meta: Vec<(String, String, Option<String>)> = prepared
        .iter()
        .map(|p| (p.slug.clone(), p.title.clone(), p.description.clone()))
        .collect();

    let mut docs = Vec::with_capacity(prepared.len());
    let mut outbound: BTreeMap<String, Vec<String>> = BTreeMap::new();
    let mut search = Vec::with_capacity(prepared.len());

    for p in &prepared {
        // Same per-doc pipeline the editor preview runs (single source of truth).
        let rendered = render_doc(p, config, registry, &slugs, partials);
        search.push(SearchEntry {
            slug: p.slug.clone(),
            title: p.title.clone(),
            text: rendered.search_text,
        });
        outbound.insert(p.slug.clone(), rendered.resolved_links);
        docs.push(rendered.doc);
    }

    let graph = build_link_graph(&doc_meta, &outbound);
    let any_mermaid = docs.iter().any(|d| d.has_mermaid);
    let any_components = docs.iter().any(|d| !d.components_used.is_empty());
    SiteBuild {
        docs,
        graph,
        search,
        any_mermaid,
        any_components,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::RawDoc;

    fn raw(path: &str, body: &str) -> RawDoc {
        RawDoc {
            rel_path: path.into(),
            raw: body.into(),
        }
    }

    #[test]
    fn is_partial_rel_detects_underscore_basename() {
        assert!(is_partial_rel("dev/server/_systems.gen.md"));
        assert!(is_partial_rel("_root.md"));
        assert!(!is_partial_rel("dev/server/index.md"));
        assert!(!is_partial_rel("dev/_dir/page.md")); // only the *basename* counts
    }

    #[test]
    fn partition_partials_splits_pages_and_strips_frontmatter() {
        let raws = vec![
            raw("a/index.md", "# Page\n"),
            raw("a/_inc.md", "---\ntitle: x\n---\n## Inc\n"),
        ];
        let (pages, partials) = partition_partials(raws);
        assert_eq!(pages.len(), 1);
        assert_eq!(pages[0].rel_path, "a/index.md");
        assert_eq!(
            partials.get("a/_inc.md").map(String::as_str),
            Some("## Inc\n")
        );
    }

    #[test]
    fn resolve_include_key_normalizes_relative_and_absolute() {
        assert_eq!(
            resolve_include_key("dev/server", "./_s.gen.md").as_deref(),
            Some("dev/server/_s.gen.md")
        );
        assert_eq!(
            resolve_include_key("dev/server", "../_top.md").as_deref(),
            Some("dev/_top.md")
        );
        assert_eq!(
            resolve_include_key("dev/server", "/root/_x.md").as_deref(),
            Some("root/_x.md")
        );
        assert_eq!(resolve_include_key("", "_x.md").as_deref(), Some("_x.md"));
        assert_eq!(resolve_include_key("dev", "../../escape.md"), None); // escapes docs root
    }

    #[test]
    fn prepare_keeps_raw_body_and_derives_meta() {
        let p = prepare(raw(
            "guide/intro.md",
            "---\ntitle: Intro\n---\n# H\nbody [[index]]\n",
        ));
        assert_eq!(p.slug, "guide/intro");
        assert_eq!(p.title, "Intro");
        assert!(p.body_md.contains("[[index]]"));
        assert!(!p.body_md.contains("title:")); // frontmatter stripped
    }

    #[test]
    fn render_doc_matches_render_docs_for_one_doc() {
        // The preview path (render_doc) and the build path (render_docs) must run
        // the identical per-doc pipeline: same body_html, search text, and links.
        let prepared = vec![
            prepare(raw("index.md", "# Home\nGo to [[guide/intro]].\n")),
            prepare(raw(
                "guide/intro.md",
                "# Intro\n```rust\nfn x(){}\n```\nBack to [[index]] and [[ghost]].\n",
            )),
        ];
        let slugs: SlugSet = prepared.iter().map(|p| p.slug.clone()).collect();
        let cfg = docgen_config::SiteConfig::default();
        let reg = docgen_components::Registry::empty();

        let site = render_docs(prepared.clone(), &Partials::new(), &cfg, &reg);
        let single = render_doc(&prepared[1], &cfg, &reg, &slugs, &Partials::new());

        assert_eq!(single.doc.body_html, site.docs[1].body_html);
        assert_eq!(single.doc.has_mermaid, site.docs[1].has_mermaid);
        assert_eq!(single.doc.has_math, site.docs[1].has_math);
        assert_eq!(single.doc.headings, site.docs[1].headings);
        assert_eq!(single.search_text, site.search[1].text);
        // Resolved outbound links match what the graph was built from (ghost dropped).
        assert!(single.resolved_links.contains(&"index".to_string()));
        assert!(!single.resolved_links.contains(&"ghost".to_string()));
    }

    #[test]
    fn render_docs_resolves_links_highlights_and_indexes() {
        let prepared = vec![
            prepare(raw("index.md", "# Home\nGo to [[guide/intro]].\n")),
            prepare(raw(
                "guide/intro.md",
                "# Intro\n```rust\nfn x(){}\n```\nBack to [[index]] and [[ghost]].\n",
            )),
        ];
        let site = render_docs(
            prepared,
            &Partials::new(),
            &docgen_config::SiteConfig::default(),
            &docgen_components::Registry::empty(),
        );

        // Doc order preserved.
        assert_eq!(site.docs[0].slug, "index");
        assert_eq!(site.docs[1].slug, "guide/intro");

        // index links to guide/intro (resolved anchor).
        assert!(site.docs[0].body_html.contains(r#"href="/guide/intro""#));
        // intro has highlighted code (class-based) + a resolved link + a broken span.
        assert!(site.docs[1]
            .body_html
            .contains(r#"<pre class="docgen-code">"#));
        assert!(site.docs[1].body_html.contains(r#"href="/index""#));
        assert!(site.docs[1].body_html.contains("docgen-wikilink--broken"));

        // Graph: index->guide/intro and guide/intro->index (ghost dropped).
        assert!(site
            .graph
            .edges
            .iter()
            .any(|e| e.from == "index" && e.to == "guide/intro"));
        assert!(site
            .graph
            .edges
            .iter()
            .any(|e| e.from == "guide/intro" && e.to == "index"));
        assert!(!site.graph.edges.iter().any(|e| e.to == "ghost"));

        // Backlinks: index is linked from guide/intro.
        assert_eq!(
            site.graph.backlinks.get("index").unwrap()[0].slug,
            "guide/intro"
        );

        // Search index: one entry per doc, plaintext, no markup.
        assert_eq!(site.search.len(), 2);
        let home = site.search.iter().find(|e| e.slug == "index").unwrap();
        assert_eq!(home.title, "Home");
        assert!(home.text.contains("Go to"));
        assert!(!home.text.contains("[["));
    }

    #[test]
    fn render_docs_renders_math_at_build_time() {
        let prepared = vec![prepare(raw("m.md", "# M\nmass: $E=mc^2$\n"))];
        let site = render_docs(
            prepared,
            &Partials::new(),
            &docgen_config::SiteConfig::default(),
            &docgen_components::Registry::empty(),
        );
        assert!(site.docs[0].body_html.contains("katex"));
        assert!(site.docs[0].has_math);
        assert!(!site.docs[0].body_html.contains("$E=mc^2$"));
    }

    #[test]
    fn math_feature_off_skips_build_time_katex() {
        let prepared = vec![prepare(raw("m.md", "# M\n$E=mc^2$\n"))];
        let mut cfg = docgen_config::SiteConfig::default();
        cfg.features.math = false;
        let site = render_docs(
            prepared,
            &Partials::new(),
            &cfg,
            &docgen_components::Registry::empty(),
        );
        assert!(!site.docs[0].has_math);
        assert!(!site.docs[0].body_html.contains("katex"));
    }

    #[test]
    fn mermaid_feature_off_leaves_code_block() {
        let prepared = vec![prepare(raw(
            "d.md",
            "# D\n```mermaid\ngraph TD;A-->B;\n```\n",
        ))];
        let mut cfg = docgen_config::SiteConfig::default();
        cfg.features.mermaid = false;
        let site = render_docs(
            prepared,
            &Partials::new(),
            &cfg,
            &docgen_components::Registry::empty(),
        );
        assert!(!site.docs[0].has_mermaid);
        assert!(!site.any_mermaid);
    }

    #[test]
    fn render_docs_marks_mermaid_pages_and_site() {
        let prepared = vec![
            prepare(raw("d.md", "# D\n```mermaid\ngraph TD;A-->B;\n```\n")),
            prepare(raw("p.md", "# P\nplain\n")),
        ];
        let site = render_docs(
            prepared,
            &Partials::new(),
            &docgen_config::SiteConfig::default(),
            &docgen_components::Registry::empty(),
        );
        assert!(site.docs[0].has_mermaid && site.docs[0].body_html.contains("docgen-mermaid"));
        assert!(!site.docs[1].has_mermaid);
        assert!(site.any_mermaid);
    }

    #[test]
    fn site_graph_data_matches_docs_and_links() {
        let prepared = vec![
            prepare(raw("index.md", "# Home\nGo to [[guide/intro]].\n")),
            prepare(raw("guide/intro.md", "# Intro\nBack to [[index]].\n")),
        ];
        let site = render_docs(
            prepared,
            &Partials::new(),
            &docgen_config::SiteConfig::default(),
            &docgen_components::Registry::empty(),
        );
        let gd = site.graph_data(crate::graphlayout::LayoutParams::default());
        assert_eq!(gd.nodes.len(), 2);
        assert!(gd
            .nodes
            .iter()
            .any(|n| n.slug == "index" && n.title == "Home"));
        assert!(gd
            .nodes
            .iter()
            .any(|n| n.slug == "guide/intro" && n.title == "Intro"));
        // Reciprocal [[..]] pair collapses to a single undirected edge.
        let is_pair = |e: &crate::graphlayout::GraphDataEdge| {
            (e.from == "index" && e.to == "guide/intro")
                || (e.from == "guide/intro" && e.to == "index")
        };
        assert_eq!(gd.edges.iter().filter(|e| is_pair(e)).count(), 1);
        assert_eq!(gd.edges.len(), 1);
    }

    #[test]
    fn render_docs_without_mermaid_clears_site_flag() {
        let prepared = vec![prepare(raw("p.md", "# P\nplain\n"))];
        let site = render_docs(
            prepared,
            &Partials::new(),
            &docgen_config::SiteConfig::default(),
            &docgen_components::Registry::empty(),
        );
        assert!(!site.any_mermaid);
    }

    #[test]
    fn render_docs_renders_callout_directive_with_inner_markdown() {
        let mut reg = docgen_components::Registry::empty();
        reg.insert(docgen_components::Component::from_parts(
            "callout",
            "<aside class=\"docgen-callout--{{ attrs.type | default('note') }}\">{{ content | safe }}</aside>",
            None,
            None,
        ));
        let prepared = vec![prepare(raw(
            "d.md",
            "# D\n\n:::callout{type=warning}\nBe **careful**.\n:::\n",
        ))];
        let site = render_docs(
            prepared,
            &Partials::new(),
            &docgen_config::SiteConfig::default(),
            &reg,
        );
        let h = &site.docs[0].body_html;
        assert!(h.contains("docgen-callout--warning"));
        assert!(h.contains("<strong>careful</strong>")); // inner markdown rendered
        assert!(site.docs[0].components_used.contains("callout"));
        assert!(site.any_components);
    }

    #[test]
    fn unknown_directive_in_doc_yields_error_span_not_crash() {
        let prepared = vec![prepare(raw("d.md", "# D\n\n:nope[x]{}\n"))];
        let site = render_docs(
            prepared,
            &Partials::new(),
            &docgen_config::SiteConfig::default(),
            &docgen_components::Registry::empty(),
        );
        assert!(site.docs[0].body_html.contains("docgen-directive-error"));
        assert!(!site.any_components);
    }

    #[test]
    fn wikilink_outside_directive_still_resolves() {
        let mut reg = docgen_components::Registry::empty();
        reg.insert(docgen_components::Component::from_parts(
            "callout",
            "<aside>{{ content | safe }}</aside>",
            None,
            None,
        ));
        let prepared = vec![
            prepare(raw(
                "index.md",
                "# Home\nSee [[guide]].\n\n:::callout{}\nx\n:::\n",
            )),
            prepare(raw("guide.md", "# Guide\n")),
        ];
        let site = render_docs(
            prepared,
            &Partials::new(),
            &docgen_config::SiteConfig::default(),
            &reg,
        );
        assert!(site.docs[0].body_html.contains(r#"href="/guide""#));
    }

    #[test]
    fn wikilink_inside_directive_body_resolves_to_anchor() {
        let mut reg = docgen_components::Registry::empty();
        reg.insert(docgen_components::Component::from_parts(
            "callout",
            "<aside>{{ content | safe }}</aside>",
            None,
            None,
        ));
        let prepared = vec![
            prepare(raw(
                "index.md",
                "# Home\n\n:::callout{}\nSee [[guide/intro|wikilink]] and [[ghost]].\n:::\n",
            )),
            prepare(raw("guide/intro.md", "# Intro\n")),
        ];
        let site = render_docs(
            prepared,
            &Partials::new(),
            &docgen_config::SiteConfig::default(),
            &reg,
        );
        let h = &site.docs[0].body_html;
        // The resolved wikilink inside the directive body is a real anchor with the
        // label text, not literal `[[...]]`.
        assert!(h.contains(r#"href="/guide/intro""#));
        assert!(h.contains(r#">wikilink</a>"#));
        assert!(!h.contains("[[guide/intro|wikilink]]"));
        // An unresolved target inside a directive body still gets the broken span.
        assert!(h.contains("docgen-wikilink--broken"));
        assert!(!h.contains("[[ghost]]"));
    }

    #[test]
    fn self_link_renders_anchor_but_no_self_backlink() {
        // A doc that links to its own slug renders a resolved anchor, but the
        // self-edge is dropped from the graph (no self-backlink).
        let prepared = vec![prepare(raw("index.md", "# Home\nBack to [[index]].\n"))];
        let site = render_docs(
            prepared,
            &Partials::new(),
            &docgen_config::SiteConfig::default(),
            &docgen_components::Registry::empty(),
        );

        assert!(site.docs[0].body_html.contains(r#"href="/index""#));
        assert!(!site
            .graph
            .edges
            .iter()
            .any(|e| e.from == "index" && e.to == "index"));
        assert!(!site.graph.backlinks.contains_key("index"));
    }
}