docgen-render 0.1.1

HTML rendering 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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
use docgen_core::headings::Heading;
use docgen_core::model::{Backlink, TreeNode};
use minijinja::{context, Environment};
use serde::Serialize;

/// The built-in page template, embedded at compile time.
pub const DEFAULT_PAGE_TEMPLATE: &str = include_str!("../templates/page.html");

/// The vendored search client script, emitted to `dist/search.js`.
///
/// Deprecated: assets now flow through the `docgen-assets` crate. Kept for one
/// phase so dependents migrate without breakage. The bytes are byte-identical to
/// `docgen-assets`' embedded copy.
#[deprecated(note = "use docgen-assets::core_assets() / emit()")]
pub const SEARCH_JS: &str = include_str!("../assets/search.js");

// The canonical, fully-themed stylesheet now lives in the `docgen-assets` crate
// (`assets/docgen/docgen.css`, embedded via include_dir and emitted as
// `dist/docgen.css`). The previous stale 37-line copy under
// `crates/docgen-render/assets/docgen.css` was deleted to avoid divergence; use
// `docgen-assets::core_assets()` / `emit()` for the shipped theme.

/// The built-in per-doc history-timeline template, embedded at compile time.
pub const DEFAULT_HISTORY_TEMPLATE: &str = include_str!("../templates/history.html");

/// The built-in `/graph/` doc-link-graph template, embedded at compile time.
pub const DEFAULT_GRAPH_TEMPLATE: &str = include_str!("../templates/graph.html");

/// The built-in `/diff/` workspace shell template, embedded at compile time.
/// The page is a mount point (`#docgen-diff-root`) hydrated by `islands/diff.js`
/// from the build-time `timeline.json` + `revisions/<id>.json` payloads.
pub const DEFAULT_DIFF_TEMPLATE: &str = include_str!("../templates/diff.html");

/// The dev editor's live-preview document template, embedded at compile time.
/// Content-only (no app chrome): the rendered article wrapped in the SAME asset
/// and island stack a published page uses, so a doc previewed in the editor
/// renders identically to its built page (mermaid, components, tooltips, math).
pub const DEFAULT_PREVIEW_TEMPLATE: &str = include_str!("../templates/preview.html");

/// One diff line, render-friendly. `kind`/line numbers are pre-stringified by
/// the caller so `docgen-render` stays free of the `docgen-diff` domain types.
#[derive(Serialize)]
pub struct LineView {
    pub kind: String,
    pub text: String,
    pub old_line: Option<u32>,
    pub new_line: Option<u32>,
}

/// A contiguous diff hunk (run of lines).
#[derive(Serialize)]
pub struct HunkView {
    pub lines: Vec<LineView>,
}

/// One changed file within a timeline point.
#[derive(Serialize)]
pub struct FileView {
    pub path: String,
    pub status: String,
    pub hunks: Vec<HunkView>,
}

/// One commit in the timeline (render-friendly projection of a `DocDiffTimelinePoint`).
#[derive(Serialize)]
pub struct TimelinePointView {
    pub short_hash: String,
    pub subject: String,
    pub author: Option<String>,
    pub date: Option<String>,
    pub added_lines: u32,
    pub removed_lines: u32,
    pub files: Vec<FileView>,
}

/// A labelled bucket of timeline points (e.g. "Today").
#[derive(Serialize)]
pub struct TimelineBucketView {
    pub label: String,
    pub points: Vec<TimelinePointView>,
}

/// Everything the history page render needs.
#[derive(Serialize)]
pub struct HistoryContext<'a> {
    pub title: &'a str,
    pub slug: &'a str,
    pub tree: &'a [TreeNode],
    pub buckets: &'a [TimelineBucketView],
    /// Deployed base path (e.g. `/docs`); `""` → no `<base>` tag (default).
    pub base: &'a str,
    /// Site title; `""` → no `"page — site"` suffix (default).
    pub site_title: &'a str,
    /// Whether the search UI ships (gates the trigger + `search.js`).
    pub search_enabled: bool,
}

/// Everything the `/graph/` page render needs. `graph_json` is the serialized
/// `GraphData` embedded verbatim into a `<script type="application/json">` tag.
#[derive(Serialize)]
pub struct GraphContext<'a> {
    pub tree: &'a [TreeNode],
    pub graph_json: &'a str,
    pub node_count: usize,
    pub edge_count: usize,
    /// Deployed base path (e.g. `/docs`); `""` → no `<base>` tag (default).
    pub base: &'a str,
    /// Site title; `""` → no `"page — site"` suffix (default).
    pub site_title: &'a str,
    /// Whether the search UI ships (gates the trigger + `search.js`).
    pub search_enabled: bool,
    /// Whether the `/diff/` workspace page exists (drives the topbar diff icon).
    pub has_diff: bool,
}

/// Everything the `/diff/` workspace shell render needs. The diff data itself
/// is not templated — it ships as `timeline.json` + `revisions/<id>.json` and
/// is hydrated client-side by `islands/diff.js` into `#docgen-diff-root`.
#[derive(Serialize)]
pub struct DiffContext<'a> {
    pub tree: &'a [TreeNode],
    /// Deployed base path (e.g. `/docs`); `""` → no `<base>` tag (default).
    pub base: &'a str,
    /// Site title; `""` → no `"page — site"` suffix (default).
    pub site_title: &'a str,
    /// Whether the search UI ships (gates the trigger + `search.js`).
    pub search_enabled: bool,
}

/// Everything the editor's live-preview document render needs. The body is the
/// already-rendered inner HTML (run through the same per-doc pipeline as a build);
/// the flags gate the same conditional asset links a published page uses.
#[derive(Serialize)]
pub struct PreviewContext<'a> {
    pub title: &'a str,
    pub body_html: &'a str,
    /// Deployed base path (e.g. `/docs`); `""` for the dev server root (default).
    pub base: &'a str,
    /// Whether this doc contains a mermaid diagram (gates the mermaid island).
    pub has_mermaid: bool,
    /// Whether this doc contains math (gates the KaTeX stylesheet link).
    pub has_math: bool,
    /// Whether any component shipped a `style.css` (links `/components.css`).
    pub has_components_css: bool,
    /// Whether this doc used a component with an `island.js` (links `/components.js`).
    pub has_component_island: bool,
}

/// One section card on the home dashboard: a top-level folder ("section"), the
/// number of docs in it, and a link to its first page. Mirrors the original
/// home's `sectionCards`.
#[derive(Serialize)]
pub struct HomeSection<'a> {
    pub label: &'a str,
    /// Slug of the section's first doc (template prefixes `base`). Folders have no
    /// index doc, so this points at a real page.
    pub slug: &'a str,
    pub count: usize,
}

/// One row in the home dashboard's "Recent" list.
#[derive(Serialize)]
pub struct HomeRecent<'a> {
    pub title: &'a str,
    pub slug: &'a str,
    /// The doc's top-level section label (or `""` for a root-level doc).
    pub section: &'a str,
}

/// The home dashboard payload. `PageContext.home` is `Some` only for the index
/// doc; every other page passes `None` (and the template skips the dashboard).
#[derive(Serialize)]
pub struct HomeData<'a> {
    /// Hero subtitle (the index doc's frontmatter `description`). `""` → omitted.
    pub description: &'a str,
    /// Total published doc count — the "pages" stat tile.
    pub pages: usize,
    /// Total resolved wikilink count — the "links" stat tile.
    pub links: usize,
    /// Section cards (top-level folders). Empty → the Sections column is omitted.
    pub sections: &'a [HomeSection<'a>],
    /// The most-recent docs (build order, home excluded), capped for the panel.
    pub recent: &'a [HomeRecent<'a>],
}

/// Everything a single page render needs.
#[derive(Serialize)]
pub struct PageContext<'a> {
    pub title: &'a str,
    /// Optional frontmatter `description:`, rendered as the page header "lede"
    /// under the title on doc pages. `""` → no lede paragraph.
    pub description: &'a str,
    pub slug: &'a str,
    pub body_html: &'a str,
    pub tree: &'a [TreeNode],
    /// Inbound references, rendered as cards in the right rail's "Referenced by"
    /// section (this supersedes the old in-content backlinks block).
    pub backlinks: &'a [Backlink],
    /// The `h2`/`h3` outline of this page, for the right-rail "On this page" TOC.
    pub headings: &'a [Heading],
    /// Short commit hash for the rail's "Additional info" → Commit row. `""` →
    /// the Commit row is omitted (no git repo / detached build).
    pub commit: &'a str,
    /// Build timestamp (`YYYY-MM-DD HH:MM`) for the "Built" row. `""` → omitted.
    pub built: &'a str,
    /// Whether this doc has an emitted `/<slug>/history/` page (drives the nav link).
    pub has_history: bool,
    /// Whether this page contains a mermaid diagram (gates the mermaid island script).
    pub has_mermaid: bool,
    /// Whether this page contains math (gates the KaTeX stylesheet `<head>` link).
    pub has_math: bool,
    /// Deployed base path (e.g. `/docs`); `""` → no `<base>` tag (default).
    pub base: &'a str,
    /// Site title; `""` → no `"page — site"` suffix (default).
    pub site_title: &'a str,
    /// Whether the search UI ships (gates the trigger + `search.js`).
    pub search_enabled: bool,
    /// Whether the `/diff/` workspace page exists (drives the topbar diff icon).
    pub has_diff: bool,
    /// Whether any component shipped a `style.css` (links `/components.css`). The
    /// component stylesheet is small + cacheable, so it links on every page when
    /// present rather than per-page.
    pub has_components_css: bool,
    /// Whether this page used ≥1 component with an `island.js` (links
    /// `/components.js`, gated per-page like the mermaid island).
    pub has_component_island: bool,
    /// Whether this page is the site home. Drives the home-only graph embed
    /// (the original surfaces the doc graph on the home page, not the sidebar).
    pub is_home: bool,
    /// Force-layout graph JSON for the home embed (raw — `render_page` applies
    /// the `</` → `<\/` escaping for the inline `<script>`). `""` → no graph
    /// block (not home, or the graph feature is off).
    pub graph_json: &'a str,
    /// Node/edge counts for the home graph caption (ignored when `graph_json` is empty).
    pub graph_node_count: usize,
    pub graph_edge_count: usize,
    /// Home dashboard payload (hero/stats/sections/recent). `Some` only for the
    /// index doc; `None` everywhere else.
    pub home: Option<HomeData<'a>>,
}

/// Owns a configured minijinja environment with the `page` template registered.
pub struct Renderer {
    env: Environment<'static>,
}

impl Renderer {
    /// Build a renderer from a page-template source string.
    pub fn new(page_template: &str) -> Result<Self, minijinja::Error> {
        let mut env = Environment::new();
        // Register under a `.html` name so minijinja's default auto-escape callback
        // enables HTML escaping for `{{ title }}`, `{{ node.name }}`, `{{ node.title }}`.
        // `{{ body | safe }}` remains raw, as intended for already-rendered markdown.
        env.add_template_owned("page.html", page_template.to_string())?;
        env.add_template_owned("history.html", DEFAULT_HISTORY_TEMPLATE.to_string())?;
        env.add_template_owned("graph.html", DEFAULT_GRAPH_TEMPLATE.to_string())?;
        env.add_template_owned("diff.html", DEFAULT_DIFF_TEMPLATE.to_string())?;
        env.add_template_owned("preview.html", DEFAULT_PREVIEW_TEMPLATE.to_string())?;
        Ok(Self { env })
    }

    /// Render one page to a full HTML document.
    pub fn render_page(&self, ctx: &PageContext) -> Result<String, minijinja::Error> {
        let tmpl = self.env.get_template("page.html")?;
        // Escape `</` so a literal `</script>` inside a doc title can't break out
        // of the inline `<script type="application/json">` graph payload (same
        // guard as `render_graph`). Empty → still empty, so the block is skipped.
        let safe_graph_json = ctx.graph_json.replace("</", "<\\/");
        tmpl.render(context! {
            title => ctx.title,
            description => ctx.description,
            body => ctx.body_html,
            slug => ctx.slug,
            tree => ctx.tree,
            backlinks => ctx.backlinks,
            headings => ctx.headings,
            commit => ctx.commit,
            built => ctx.built,
            has_history => ctx.has_history,
            has_mermaid => ctx.has_mermaid,
            has_math => ctx.has_math,
            base => ctx.base,
            site_title => ctx.site_title,
            search_enabled => ctx.search_enabled,
            has_components_css => ctx.has_components_css,
            has_component_island => ctx.has_component_island,
            is_home => ctx.is_home,
            has_diff => ctx.has_diff,
            graph_json => safe_graph_json,
            graph_node_count => ctx.graph_node_count,
            graph_edge_count => ctx.graph_edge_count,
            home => ctx.home,
        })
    }

    /// Render the `/graph/` doc-link-graph page to a full HTML document.
    ///
    /// `graph_json` is injected raw (the island's `JSON.parse` needs valid JSON,
    /// not HTML-escaped text). To stop a literal `</script>` inside a doc title
    /// from breaking out of the embedding `<script type="application/json">` tag,
    /// `</` is rewritten to `<\/` first — still valid JSON, inert as markup.
    pub fn render_graph(&self, ctx: &GraphContext) -> Result<String, minijinja::Error> {
        let tmpl = self.env.get_template("graph.html")?;
        let safe_json = ctx.graph_json.replace("</", "<\\/");
        tmpl.render(context! {
            tree => ctx.tree,
            slug => "",
            graph_json => safe_json,
            node_count => ctx.node_count,
            edge_count => ctx.edge_count,
            base => ctx.base,
            site_title => ctx.site_title,
            search_enabled => ctx.search_enabled,
            has_diff => ctx.has_diff,
        })
    }

    /// Render one doc's history timeline to a full HTML document.
    pub fn render_history(&self, ctx: &HistoryContext) -> Result<String, minijinja::Error> {
        let tmpl = self.env.get_template("history.html")?;
        tmpl.render(context! {
            title => ctx.title,
            slug => ctx.slug,
            tree => ctx.tree,
            buckets => ctx.buckets,
            base => ctx.base,
            site_title => ctx.site_title,
            search_enabled => ctx.search_enabled,
        })
    }

    /// Render the editor's live-preview document (content-only, real asset stack).
    pub fn render_preview(&self, ctx: &PreviewContext) -> Result<String, minijinja::Error> {
        let tmpl = self.env.get_template("preview.html")?;
        tmpl.render(context! {
            title => ctx.title,
            body => ctx.body_html,
            base => ctx.base,
            has_mermaid => ctx.has_mermaid,
            has_math => ctx.has_math,
            has_components_css => ctx.has_components_css,
            has_component_island => ctx.has_component_island,
        })
    }

    /// Render the `/diff/` workspace shell to a full HTML document.
    pub fn render_diff(&self, ctx: &DiffContext) -> Result<String, minijinja::Error> {
        let tmpl = self.env.get_template("diff.html")?;
        tmpl.render(context! {
            tree => ctx.tree,
            slug => "",
            base => ctx.base,
            site_title => ctx.site_title,
            search_enabled => ctx.search_enabled,
        })
    }
}

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

    fn renderer() -> Renderer {
        Renderer::new(DEFAULT_PAGE_TEMPLATE).unwrap()
    }

    #[test]
    fn renders_title_and_body() {
        let html = renderer()
            .render_page(&PageContext {
                title: "My Page",
                slug: "my-page",
                body_html: "<p>hello</p>",
                tree: &[],
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: false,
                base: "",
                site_title: "",
                search_enabled: true,
                has_components_css: false,
                has_component_island: false,
                is_home: false,
                has_diff: false,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
            })
            .unwrap();
        assert!(html.contains("<title>My Page</title>"));
        assert!(html.contains("<p>hello</p>"));
    }

    #[test]
    fn page_has_accessibility_landmarks() {
        let html = renderer()
            .render_page(&PageContext {
                title: "P",
                slug: "p",
                body_html: "",
                tree: &[],
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: false,
                base: "",
                site_title: "",
                search_enabled: true,
                has_components_css: false,
                has_component_island: false,
                is_home: false,
                has_diff: false,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
            })
            .unwrap();
        // Skip link targets a labelled, focusable <main>.
        assert!(html.contains(r##"class="docgen-skip-link" href="#docgen-main""##));
        assert!(html.contains(r#"id="docgen-main""#));
        assert!(html.contains(r#"tabindex="-1""#));
        // Hamburger links to the drawer it controls; Escape closes it.
        assert!(html.contains(r#"aria-controls="docgen-sidebar""#));
        assert!(html.contains("@keydown.escape.window=\"navOpen=false\""));
        // Theme toggle exposes pressed state to AT.
        assert!(html.contains(":aria-pressed=\"theme==='light'\""));
        assert!(html.contains(":aria-pressed=\"theme==='dark'\""));
    }

    #[test]
    fn component_asset_links_are_gated() {
        let off = renderer()
            .render_page(&PageContext {
                title: "P",
                slug: "p",
                body_html: "",
                tree: &[],
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: false,
                base: "",
                site_title: "",
                search_enabled: true,
                has_components_css: false,
                has_component_island: false,
                is_home: false,
                has_diff: false,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
            })
            .unwrap();
        assert!(!off.contains("/components.css"));
        assert!(!off.contains("/components.js"));

        let on = renderer()
            .render_page(&PageContext {
                title: "P",
                slug: "p",
                body_html: "",
                tree: &[],
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: false,
                base: "",
                site_title: "",
                search_enabled: true,
                has_components_css: true,
                has_component_island: true,
                is_home: false,
                has_diff: false,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
            })
            .unwrap();
        assert!(on.contains(r#"<link rel="stylesheet" href="/components.css" />"#));
        assert!(on.contains(r#"<script src="/components.js"></script>"#));
    }

    #[test]
    fn page_title_gets_site_suffix_when_configured() {
        let html = renderer()
            .render_page(&PageContext {
                title: "Intro",
                site_title: "My Docs",
                search_enabled: true,
                has_components_css: false,
                has_component_island: false,
                is_home: false,
                has_diff: false,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
                base: "",
                slug: "x",
                body_html: "",
                tree: &[],
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: false,
            })
            .unwrap();
        assert!(html.contains("<title>Intro — My Docs</title>"));
    }

    #[test]
    fn no_site_title_leaves_plain_title_and_no_base() {
        let html = renderer()
            .render_page(&PageContext {
                title: "Intro",
                site_title: "",
                search_enabled: true,
                has_components_css: false,
                has_component_island: false,
                is_home: false,
                has_diff: false,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
                base: "",
                slug: "x",
                body_html: "",
                tree: &[],
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: false,
            })
            .unwrap();
        assert!(html.contains("<title>Intro</title>"));
        assert!(!html.contains("<base"));
    }

    #[test]
    fn search_disabled_hides_search_ui() {
        let on = renderer()
            .render_page(&PageContext {
                title: "X",
                site_title: "",
                search_enabled: true,
                has_components_css: false,
                has_component_island: false,
                is_home: false,
                has_diff: false,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
                base: "",
                slug: "x",
                body_html: "",
                tree: &[],
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: false,
            })
            .unwrap();
        assert!(on.contains("data-docgen-search"));

        let off = renderer()
            .render_page(&PageContext {
                title: "X",
                site_title: "",
                search_enabled: false,
                has_components_css: false,
                has_component_island: false,
                is_home: false,
                has_diff: false,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
                base: "",
                slug: "x",
                body_html: "",
                tree: &[],
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: false,
            })
            .unwrap();
        assert!(!off.contains("data-docgen-search"));
        assert!(!off.contains("/search.js"));
    }

    #[test]
    fn base_prefixes_every_asset_and_nav_link_and_emits_no_base_tag() {
        // A sub-path deployment must rewrite every root-absolute URL to live under
        // `base`; <base> alone cannot do this (it only affects relative URLs).
        let tree = vec![TreeNode::Doc {
            name: "guide".into(),
            slug: "guide".into(),
            title: "Guide".into(),
        }];
        let html = renderer()
            .render_page(&PageContext {
                title: "X",
                site_title: "",
                search_enabled: true,
                has_components_css: true,
                has_component_island: false,
                is_home: false,
                has_diff: true,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
                base: "/docs",
                slug: "x",
                body_html: "",
                tree: &tree,
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: false,
            })
            .unwrap();
        // No <base> tag — links are prefixed directly so they actually resolve.
        assert!(!html.contains("<base"));
        // Assets under base.
        assert!(html.contains(r#"href="/docs/docgen.css""#));
        assert!(html.contains(r#"href="/docs/components.css""#));
        assert!(html.contains(r#"src="/docs/bootstrap.js""#));
        assert!(html.contains(r#"src="/docs/search.js""#));
        // Nav + diff links under base. (The sidebar graph link was removed;
        // the graph now lives on the home page, covered by its own test.)
        assert!(html.contains(r#"href="/docs/guide""#));
        assert!(html.contains(r#"href="/docs/diff""#));
        // Nothing left at the bare root.
        assert!(!html.contains(r#"href="/docgen.css""#));
        assert!(!html.contains(r#"src="/bootstrap.js""#));
    }

    #[test]
    fn renders_sidebar_links() {
        let tree = vec![TreeNode::Doc {
            name: "intro".into(),
            slug: "guide/intro".into(),
            title: "Intro".into(),
        }];
        let html = renderer()
            .render_page(&PageContext {
                title: "X",
                slug: "x",
                body_html: "",
                tree: &tree,
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: false,
                base: "",
                site_title: "",
                search_enabled: true,
                has_components_css: false,
                has_component_island: false,
                is_home: false,
                has_diff: false,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
            })
            .unwrap();
        assert!(html.contains(r#"href="/guide/intro""#));
        assert!(html.contains(">Intro</a>"));
    }

    #[test]
    fn escapes_title_and_sidebar_text_but_not_body() {
        let tree = vec![TreeNode::Doc {
            name: "intro".into(),
            slug: "guide/intro".into(),
            title: "A & B <x>".into(),
        }];
        let html = renderer()
            .render_page(&PageContext {
                title: "Tom & Jerry <script>",
                slug: "tj",
                body_html: "<p>raw & ok</p>",
                tree: &tree,
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: false,
                base: "",
                site_title: "",
                search_enabled: true,
                has_components_css: false,
                has_component_island: false,
                is_home: false,
                has_diff: false,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
            })
            .unwrap();
        // Title is HTML-escaped.
        assert!(html.contains("<title>Tom &amp; Jerry &lt;script&gt;</title>"));
        assert!(!html.contains("<title>Tom & Jerry <script>"));
        // Sidebar link text is escaped.
        assert!(html.contains("A &amp; B &lt;x&gt;"));
        // Body marked `| safe` is emitted raw.
        assert!(html.contains("<p>raw & ok</p>"));
    }

    #[test]
    fn renders_backlinks_section() {
        use docgen_core::model::Backlink;
        let backlinks = vec![Backlink {
            slug: "a".into(),
            title: "Page A".into(),
            description: Some("All about A".into()),
        }];
        let html = renderer()
            .render_page(&PageContext {
                title: "X",
                slug: "x",
                body_html: "",
                tree: &[],
                backlinks: &backlinks,
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: false,
                base: "",
                site_title: "",
                search_enabled: true,
                has_components_css: false,
                has_component_island: false,
                is_home: false,
                has_diff: false,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
            })
            .unwrap();
        // Backlinks now live in the right rail's "Referenced by" section as cards.
        assert!(html.contains("Referenced by"));
        assert!(html.contains(r#"class="docgen-rail__backlink" href="/a""#));
        assert!(html.contains("<span>Page A</span>"));
        assert!(html.contains("<small>All about A</small>"));
        // The old in-content backlinks block is gone.
        assert!(!html.contains("docgen-backlinks"));
    }

    #[test]
    fn omits_backlinks_section_when_empty() {
        let html = renderer()
            .render_page(&PageContext {
                title: "X",
                slug: "x",
                body_html: "",
                tree: &[],
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: false,
                base: "",
                site_title: "",
                search_enabled: true,
                has_components_css: false,
                has_component_island: false,
                is_home: false,
                has_diff: false,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
            })
            .unwrap();
        // No backlinks → the "Referenced by" rail section is omitted entirely.
        assert!(!html.contains("Referenced by"));
        assert!(!html.contains("docgen-rail__backlink"));
    }

    #[test]
    fn renders_diff_link_only_when_has_diff() {
        let with = renderer()
            .render_page(&PageContext {
                title: "X",
                slug: "guide/intro",
                body_html: "",
                tree: &[],
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: false,
                base: "",
                site_title: "",
                search_enabled: true,
                has_components_css: false,
                has_component_island: false,
                is_home: false,
                has_diff: true,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
            })
            .unwrap();
        assert!(with.contains(r#"href="/diff""#));

        let without = renderer()
            .render_page(&PageContext {
                title: "X",
                slug: "guide/intro",
                body_html: "",
                tree: &[],
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: false,
                base: "",
                site_title: "",
                search_enabled: true,
                has_components_css: false,
                has_component_island: false,
                is_home: false,
                has_diff: false,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
            })
            .unwrap();
        assert!(!without.contains(r#"href="/diff""#));
    }

    #[test]
    fn page_loads_bootstrap_and_alpine_and_gates_mermaid_island() {
        let html = renderer()
            .render_page(&PageContext {
                title: "X",
                slug: "x",
                body_html: "",
                tree: &[],
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: false,
                base: "",
                site_title: "",
                search_enabled: true,
                has_components_css: false,
                has_component_island: false,
                is_home: false,
                has_diff: false,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
            })
            .unwrap();
        assert!(html.contains(r#"src="/bootstrap.js""#));
        assert!(html.contains(r#"src="/vendor/alpine/alpine.min.js""#));
        assert!(!html.contains("islands/mermaid.js")); // gated off

        let withm = renderer()
            .render_page(&PageContext {
                title: "X",
                slug: "x",
                body_html: "",
                tree: &[],
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: true,
                has_math: false,
                base: "",
                site_title: "",
                search_enabled: true,
                has_components_css: false,
                has_component_island: false,
                is_home: false,
                has_diff: false,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
            })
            .unwrap();
        assert!(withm.contains(r#"src="/islands/mermaid.js""#));
    }

    #[test]
    fn page_links_katex_css_only_when_has_math() {
        let no_math = renderer()
            .render_page(&PageContext {
                title: "X",
                slug: "x",
                body_html: "",
                tree: &[],
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: false,
                base: "",
                site_title: "",
                search_enabled: true,
                has_components_css: false,
                has_component_island: false,
                is_home: false,
                has_diff: false,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
            })
            .unwrap();
        assert!(!no_math.contains("katex.min.css"));

        let with_math = renderer()
            .render_page(&PageContext {
                title: "X",
                slug: "x",
                body_html: "",
                tree: &[],
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: true,
                base: "",
                site_title: "",
                search_enabled: true,
                has_components_css: false,
                has_component_island: false,
                is_home: false,
                has_diff: false,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
            })
            .unwrap();
        assert!(with_math.contains(r#"href="/vendor/katex/katex.min.css""#));
    }

    #[test]
    #[allow(deprecated)] // SEARCH_JS kept one phase as a byte-identical re-export
    fn ships_self_contained_search_assets() {
        assert!(SEARCH_JS.contains("search-index.json"));
        assert!(SEARCH_JS.contains("metaKey"));
        assert!(!SEARCH_JS.contains("import ")); // no module imports / npm
    }

    // ---- editor live-preview document ----

    #[test]
    fn preview_is_content_only_with_real_asset_stack() {
        let r = renderer();
        let html = r
            .render_preview(&PreviewContext {
                title: "Intro",
                body_html: r#"<h1>Intro</h1><p>See <a class="docgen-wikilink" href="/guide">g</a></p>"#,
                base: "",
                has_mermaid: false,
                has_math: false,
                has_components_css: false,
                has_component_island: false,
            })
            .unwrap();
        // The article content is emitted raw inside the published prose wrapper.
        assert!(html.contains(r#"<article class="docgen-doc-content">"#));
        assert!(html.contains(r#"href="/guide""#));
        // Same content + island stack a built page uses — so islands hydrate.
        assert!(html.contains(r#"href="/docgen.css""#));
        assert!(html.contains(r#"href="/code.css""#));
        assert!(html.contains(r#"src="/bootstrap.js""#));
        assert!(html.contains(r#"src="/islands/wikilink.js""#));
        assert!(html.contains(r#"src="/vendor/alpine/alpine.min.js""#));
        // No app chrome: this is a preview pane, not a full page.
        assert!(!html.contains("docgen-topbar"));
        assert!(!html.contains("docgen-sidebar"));
        assert!(!html.contains("docgen-rail"));
        // Conditional assets gated off.
        assert!(!html.contains("islands/mermaid.js"));
        assert!(!html.contains("components.css"));
        assert!(!html.contains("katex.min.css"));
    }

    #[test]
    fn preview_gates_mermaid_math_and_component_assets() {
        let r = renderer();
        let html = r
            .render_preview(&PreviewContext {
                title: "D",
                body_html: r#"<div class="docgen-mermaid"></div>"#,
                base: "",
                has_mermaid: true,
                has_math: true,
                has_components_css: true,
                has_component_island: true,
            })
            .unwrap();
        assert!(html.contains(r#"src="/islands/mermaid.js""#));
        assert!(html.contains(r#"href="/vendor/katex/katex.min.css""#));
        assert!(html.contains(r#"href="/components.css""#));
        assert!(html.contains(r#"src="/components.js""#));
    }

    #[test]
    fn preview_prefixes_base() {
        let r = renderer();
        let html = r
            .render_preview(&PreviewContext {
                title: "X",
                body_html: "<p>x</p>",
                base: "/docs",
                has_mermaid: true,
                has_math: false,
                has_components_css: false,
                has_component_island: false,
            })
            .unwrap();
        assert!(html.contains(r#"href="/docs/docgen.css""#));
        assert!(html.contains(r#"src="/docs/bootstrap.js""#));
        assert!(html.contains(r#"src="/docs/islands/mermaid.js""#));
        assert!(!html.contains(r#"href="/docgen.css""#));
    }

    fn sample_buckets() -> Vec<TimelineBucketView> {
        vec![TimelineBucketView {
            label: "Today".into(),
            points: vec![TimelinePointView {
                short_hash: "abc1234".into(),
                subject: "edit a".into(),
                author: Some("docgen test".into()),
                date: Some("2026-05-15".into()),
                added_lines: 1,
                removed_lines: 1,
                files: vec![FileView {
                    path: "docs/a.md".into(),
                    status: "modified".into(),
                    hunks: vec![HunkView {
                        lines: vec![
                            LineView {
                                kind: "context".into(),
                                text: "# A".into(),
                                old_line: Some(1),
                                new_line: Some(1),
                            },
                            LineView {
                                kind: "removed".into(),
                                text: "first".into(),
                                old_line: Some(2),
                                new_line: None,
                            },
                            LineView {
                                kind: "added".into(),
                                text: "second".into(),
                                old_line: None,
                                new_line: Some(2),
                            },
                        ],
                    }],
                }],
            }],
        }]
    }

    // ---- P4 B-4: /graph/ page ----

    #[test]
    fn renders_graph_page_with_embedded_json_and_island() {
        let r = Renderer::new(DEFAULT_PAGE_TEMPLATE).unwrap();
        let json = r#"{"nodes":[{"slug":"a","title":"A","x":1.0,"y":2.0,"degree":0}],"edges":[]}"#;
        let html = r
            .render_graph(&GraphContext {
                tree: &[],
                graph_json: json,
                node_count: 1,
                has_diff: false,
                edge_count: 0,
                base: "",
                site_title: "",
                search_enabled: true,
            })
            .unwrap();
        assert!(html.contains("<title>Graph</title>"));
        assert!(html.contains(r#"id="docgen-graph-data""#));
        assert!(html.contains(r#"type="application/json""#));
        assert!(html.contains(json)); // JSON embedded verbatim, NOT escaped
        assert!(html.contains(r#"x-data="docgenGraph""#));
        assert!(html.contains(r#"src="/islands/graph.js""#));
        assert!(html.contains(r#"src="/bootstrap.js""#));
        assert!(html.contains(r#"src="/vendor/alpine/alpine.min.js""#));
        assert!(html.contains("1 nodes")); // meta caption
    }

    #[test]
    fn graph_page_renders_sidebar_tree() {
        let r = Renderer::new(DEFAULT_PAGE_TEMPLATE).unwrap();
        let tree = vec![docgen_core::model::TreeNode::Doc {
            name: "intro".into(),
            slug: "guide/intro".into(),
            title: "Intro".into(),
        }];
        let html = r
            .render_graph(&GraphContext {
                tree: &tree,
                graph_json: r#"{"nodes":[],"edges":[]}"#,
                node_count: 0,
                has_diff: false,
                edge_count: 0,
                base: "",
                site_title: "",
                search_enabled: true,
            })
            .unwrap();
        assert!(html.contains(r#"href="/guide/intro""#));
    }

    #[test]
    fn embedded_json_neutralizes_script_close() {
        let r = Renderer::new(DEFAULT_PAGE_TEMPLATE).unwrap();
        let json = r#"{"nodes":[{"slug":"x","title":"a</script>b","x":0.0,"y":0.0,"degree":0}],"edges":[]}"#;
        let html = r
            .render_graph(&GraphContext {
                tree: &[],
                graph_json: json,
                node_count: 1,
                has_diff: false,
                edge_count: 0,
                base: "",
                site_title: "",
                search_enabled: true,
            })
            .unwrap();
        assert!(!html.contains("a</script>b")); // raw close-tag must not survive
        assert!(html.contains(r#"a<\/script>b"#)); // escaped form present
    }

    #[test]
    fn graph_page_renders_graph_canvas_without_sidebar_link() {
        let r = Renderer::new(DEFAULT_PAGE_TEMPLATE).unwrap();
        let html = r
            .render_graph(&GraphContext {
                tree: &[],
                graph_json: r#"{"nodes":[],"edges":[]}"#,
                node_count: 0,
                has_diff: false,
                edge_count: 0,
                base: "",
                site_title: "",
                search_enabled: true,
            })
            .unwrap();
        // The standalone /graph page still renders its graph canvas + island.
        assert!(html.contains(r#"x-data="docgenGraph""#));
        assert!(html.contains("docgen-graph__svg"));
        // The sidebar graph link was removed (the graph lives on the home page).
        assert!(!html.contains("docgen-sidebar__graph"));
    }

    #[test]
    fn home_page_embeds_graph_and_non_home_does_not() {
        let r = renderer();
        let ctx = |is_home: bool, graph_json: &'static str| PageContext {
            title: "X",
            slug: if is_home { "index" } else { "x" },
            body_html: "",
            tree: &[],
            backlinks: &[],
            headings: &[],
            commit: "",
            built: "",
            has_history: false,
            has_mermaid: false,
            has_math: false,
            base: "",
            site_title: "",
            search_enabled: true,
            has_diff: false,
            has_components_css: false,
            has_component_island: false,
            is_home,
            graph_json,
            graph_node_count: 2,
            graph_edge_count: 1,
            description: "",
            home: None,
        };
        // Home page with graph data: embeds the graph block + data + island script.
        let home = r
            .render_page(&ctx(true, r#"{"nodes":[],"edges":[]}"#))
            .unwrap();
        assert!(home.contains("docgen-home-graph"));
        assert!(home.contains(r#"id="docgen-graph-data""#));
        assert!(home.contains(r#"x-data="docgenGraph""#));
        assert!(home.contains("islands/graph.js"));
        // The sidebar graph link is gone.
        assert!(!home.contains("docgen-sidebar__graph"));
        // A non-home page (even if a graph_json were passed) embeds nothing.
        let other = r.render_page(&ctx(false, "")).unwrap();
        assert!(!other.contains("docgen-home-graph"));
        assert!(!other.contains("islands/graph.js"));
    }

    #[test]
    fn renders_history_timeline_with_buckets_and_diff_lines() {
        let buckets = sample_buckets();
        let html = renderer()
            .render_history(&HistoryContext {
                title: "A",
                slug: "a",
                tree: &[],
                buckets: &buckets,
                base: "",
                site_title: "",
                search_enabled: true,
            })
            .unwrap();
        assert!(html.contains("<title>History: A</title>"));
        assert!(html.contains("Today"));
        assert!(html.contains("edit a"));
        assert!(html.contains("abc1234"));
        assert!(html.contains("docgen-diff-line--removed"));
        assert!(html.contains("docgen-diff-line--added"));
        assert!(html.contains("first"));
        assert!(html.contains(r#"href="/a""#));
    }

    #[test]
    fn history_escapes_diff_text() {
        let buckets = vec![TimelineBucketView {
            label: "Today".into(),
            points: vec![TimelinePointView {
                short_hash: "abc1234".into(),
                subject: "edit".into(),
                author: None,
                date: None,
                added_lines: 1,
                removed_lines: 0,
                files: vec![FileView {
                    path: "docs/a.md".into(),
                    status: "modified".into(),
                    hunks: vec![HunkView {
                        lines: vec![LineView {
                            kind: "added".into(),
                            text: "<script>alert(1)</script>".into(),
                            old_line: None,
                            new_line: Some(1),
                        }],
                    }],
                }],
            }],
        }];
        let html = renderer()
            .render_history(&HistoryContext {
                title: "A",
                slug: "a",
                tree: &[],
                buckets: &buckets,
                base: "",
                site_title: "",
                search_enabled: true,
            })
            .unwrap();
        assert!(html.contains("&lt;script&gt;alert(1)&lt;&#x2f;script&gt;"));
        assert!(!html.contains("<script>alert(1)</script>"));
    }

    // ---- P7 Cluster A: app shell, themes, theme-toggle, sidebar tree ----

    fn page(slug: &str, tree: &[TreeNode]) -> String {
        renderer()
            .render_page(&PageContext {
                title: "X",
                slug,
                body_html: "<p>hi</p>",
                tree,
                backlinks: &[],
                headings: &[],
                commit: "",
                built: "",
                has_history: false,
                has_mermaid: false,
                has_math: false,
                base: "",
                site_title: "Docs",
                search_enabled: true,
                has_components_css: false,
                has_component_island: false,
                is_home: false,
                has_diff: false,
                graph_json: "",
                graph_node_count: 0,
                graph_edge_count: 0,
                description: "",
                home: None,
            })
            .unwrap()
    }

    #[test]
    fn page_has_app_shell() {
        let html = page("x", &[]);
        for cls in [
            "docgen-app",
            "docgen-topbar",
            "docgen-layout",
            "docgen-sidebar",
            "docgen-content",
            "docgen-doc-content",
        ] {
            assert!(html.contains(cls), "app shell missing {cls}");
        }
    }

    #[test]
    fn page_has_no_flash_script_in_head() {
        let html = page("x", &[]);
        let script_at = html
            .find("localStorage.getItem('doc-theme')")
            .expect("no-flash script present");
        let css_at = html.find("/docgen.css").expect("docgen.css link present");
        assert!(
            script_at < css_at,
            "no-flash script must precede docgen.css link"
        );
        assert!(html.contains("prefers-color-scheme"));
        // Dark is the bare default: pre-paint falls back to dark, not light.
        assert!(html.contains("'light':'dark'"));
    }

    #[test]
    fn page_has_theme_toggle_island() {
        let html = page("x", &[]);
        assert!(html.contains(r#"x-data="docgenThemeToggle""#));
        assert!(html.contains("/islands/theme-toggle.js"));
        // Dark is the bare default: <html> carries NO data-theme attr server-side;
        // the pre-paint script sets it (dark when nothing stored / no light pref).
        assert!(!html.contains(r#"<html lang="en" data-theme="#));
    }

    #[test]
    fn sidebar_marks_active_doc() {
        let tree = vec![TreeNode::Doc {
            name: "a".into(),
            slug: "a".into(),
            title: "A".into(),
        }];
        let active = page("a", &tree);
        assert!(active.contains(r#"docgen-tree__item is-active"#));
        assert!(active.contains(r#"aria-current="page""#));

        let inactive = page("b", &tree);
        assert!(!inactive.contains(r#"docgen-tree__item is-active"#));
        assert!(!inactive.contains(r#"aria-current="page""#));
    }

    #[test]
    fn sidebar_renders_nested_dir_as_details() {
        let tree = vec![TreeNode::Dir {
            name: "guide".into(),
            slug: None,
            children: vec![TreeNode::Doc {
                name: "intro".into(),
                slug: "guide/intro".into(),
                title: "Intro".into(),
            }],
        }];
        let html = page("x", &tree);
        assert!(html.contains("<details"));
        assert!(html.contains("<summary"));
        assert!(html.contains("docgen-tree"));
        // Each folder carries a stable path key so its collapse state persists.
        assert!(html.contains(r#"data-tree-path="/guide""#));
    }

    #[test]
    fn graph_and_history_share_shell() {
        let r = Renderer::new(DEFAULT_PAGE_TEMPLATE).unwrap();
        let graph = r
            .render_graph(&GraphContext {
                tree: &[],
                graph_json: r#"{"nodes":[],"edges":[]}"#,
                node_count: 0,
                has_diff: false,
                edge_count: 0,
                base: "",
                site_title: "",
                search_enabled: true,
            })
            .unwrap();
        let hist = r
            .render_history(&HistoryContext {
                title: "A",
                slug: "a",
                tree: &[],
                buckets: &[],
                base: "",
                site_title: "",
                search_enabled: true,
            })
            .unwrap();
        for html in [&graph, &hist] {
            assert!(html.contains("docgen-topbar"));
            assert!(html.contains("data-theme"));
            assert!(html.contains("/islands/theme-toggle.js"));
            assert!(html.contains("localStorage.getItem('doc-theme')"));
        }
    }
}