plates-render 0.7.3

The document-to-HTML half of plates: what a published page looks like.
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
//! Full HTML document assembly: wraps rendered page bodies in the site shell
//! (head, nav, breadcrumbs, footer, interactivity script) and produces the
//! static CSS/favicon assets.
//!
//! Appearance is a *caller-supplied* input ([`SiteStyle`]) with built-in
//! defaults. A publishing client can pass a color theme, fully-custom CSS, or a
//! custom favicon; when it passes nothing, the server-side default styling
//! (the bundled stylesheet, no favicon) is used. The same renderer runs
//! client-side (publish plugin) and server-side (ARK Layer 3 render-on-write).
//!
//! The *document* around the body is caller-supplied on the same terms: a
//! [`ShellTemplate`] replaces the built-in shell below, filling the same
//! [`ShellSlots`] it does. Both shells are assembled from one set of slots
//! precisely so a template cannot see a different page than the default does.

use crate::appearance::{FaviconAsset, ThemeAppearance};

use crate::headings::render_toc;
use crate::links::root_prefix;
use crate::nav::reading_order;
use crate::page::{
    html_escape, render_breadcrumb, render_full_breadcrumbs, render_pager, render_site_nav,
    title_to_anchor,
};
use crate::shell::{ShellSlots, ShellTemplate};
use crate::types::{PageLayout, PublishedPage, SiteNavigation};

/// Caller-supplied appearance for the rendered site.
///
/// All fields are optional; an empty `SiteStyle` yields the built-in default
/// styling. Precedence:
/// - CSS: [`custom_css`](Self::custom_css) replaces the stylesheet entirely;
///   otherwise the bundled base CSS is used, with [`theme`](Self::theme) color
///   overrides appended when present.
/// - Favicon: [`custom_favicon`](Self::custom_favicon) wins; otherwise the
///   theme's favicon (or its accent-derived default) is used; otherwise none.
/// - Footer: [`generator`](Self::generator) names the tool that built the site,
///   or `None` for no attribution line at all.
#[derive(Debug, Clone, Default)]
pub struct SiteStyle {
    /// Color theme (palette + optional favicon). `None` → default palette.
    pub theme: Option<ThemeAppearance>,
    /// Fully custom stylesheet, replacing the built-in CSS entirely.
    pub custom_css: Option<String>,
    /// Custom favicon, overriding the theme/default favicon.
    pub custom_favicon: Option<FaviconAsset>,
    /// Who to credit in the site footer. `None` → no footer.
    pub generator: Option<Generator>,
}

/// The tool that built the site, credited in the footer of every shell that
/// carries one.
///
/// The engine does not name itself. A renderer with no generator writes an
/// empty `footer` slot and no `<footer>` element, so a caller that wants a
/// "Generated by …" line is the one that asks for it — and a caller embedding
/// this crate in something else credits *that*, rather than shipping a footer
/// pointing at a program its readers never ran.
#[derive(Debug, Clone)]
pub struct Generator {
    /// Display name, e.g. `"Diaryx"`. HTML-escaped when rendered.
    pub name: String,
    /// Where the name links, if anywhere. HTML-escaped when rendered.
    pub url: Option<String>,
}

impl Generator {
    /// A generator credited by name alone, with no link.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            url: None,
        }
    }

    /// A generator whose name links to `url`.
    pub fn linked(name: impl Into<String>, url: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            url: Some(url.into()),
        }
    }
}

/// The well-known filename [`HtmlRenderer::static_assets`] writes
/// [`ISLAND_CHILD_SCRIPT`] to.
pub const ISLAND_CHILD_SCRIPT_FILENAME: &str = "diaryx-island.js";

/// The child half of the island resize protocol, for an embedded HTML document
/// to load with `<script src="…/diaryx-island.js"></script>`.
///
/// An island (`![alt](page.html)`) is an `<iframe>` whose height the parent page
/// cannot read: the frame is sandboxed without `allow-same-origin`, so its
/// document is cross-origin by construction. The two sides therefore agree by
/// `postMessage`, and this is the half that lives inside the frame — see
/// [`HtmlRenderer::interactivity_script`] for the parent half and the protocol.
///
/// Written to the site root by [`HtmlRenderer::static_assets`] so an island
/// document can reference it without the site having to ship its own copy.
pub const ISLAND_CHILD_SCRIPT: &str = r#"(function () {
    function measure() {
        var doc = document.documentElement;
        var body = document.body;
        var height = Math.max(
            doc ? doc.scrollHeight : 0,
            doc ? doc.offsetHeight : 0,
            body ? body.scrollHeight : 0,
            body ? body.offsetHeight : 0
        );
        if (!height) return;
        try {
            parent.postMessage({ type: 'diaryx-html-attachment-size', height: height }, '*');
        } catch (_error) {}
    }

    window.addEventListener('message', function (event) {
        var data = event.data;
        if (data && data.type === 'diaryx-html-attachment-measure') measure();
    });
    window.addEventListener('resize', measure);
    window.addEventListener('load', measure);
    if (document.readyState === 'complete') measure();
})();
"#;

/// Everything about the *site* that wrapping one page in its shell needs.
///
/// A struct rather than seven positional arguments because the shell grew slots
/// — a template, a language, per-page assets — and a call site that reads
/// `(page, title, false, &nav, &seo, &feeds)` is one whose next argument goes in
/// the wrong place.
pub struct PageContext<'a> {
    /// The site's name, for `<title>` and the `{{site_title}}` slot.
    pub site_title: &'a str,
    /// This page's nav tree and breadcrumb trail.
    pub nav: &'a SiteNavigation,
    /// Pre-rendered SEO `<meta>` tags, or empty.
    pub seo_meta: &'a str,
    /// Pre-rendered feed `<link>` tags, or empty.
    pub feed_links: &'a str,
    /// BCP 47 language tag for `<html lang="…">`.
    pub lang: &'a str,
    /// The caller's shell, or `None` for the built-in one. Ignored by a page
    /// whose layout is [`PageLayout::Bare`].
    pub template: Option<&'a ShellTemplate>,
    /// The site's header document, already rendered for this page — the
    /// `site_header` slot. Empty when the site declares none.
    pub site_header: &'a str,
    /// The site's footer document, on the same terms — the `site_footer`
    /// slot.
    pub site_footer: &'a str,
}

/// Assembles complete HTML documents from rendered page bodies.
pub struct HtmlRenderer {
    style: SiteStyle,
}

/// The `<title>` for a page: `"Entry - Site"`, or just the site's name on the
/// page that *is* the site.
///
/// A front page named after its site — which a synthesized index is, and an
/// authored root usually is too — would otherwise be published as
/// `"Blog - Blog"`.
///
/// Returns the text unescaped: it is a text slot, and escaping it here as well
/// as where it is filled is how a site called `Ben & Co` comes out `&amp;amp;`.
fn document_title(page_title: &str, site_title: &str) -> String {
    if page_title == site_title {
        site_title.to_string()
    } else {
        format!("{page_title} - {site_title}")
    }
}

/// `<link rel="stylesheet">` tags for a page's own `styles:`, rebased to the
/// page's depth exactly as the attachments in its body are.
fn style_link_tags(styles: &[String], prefix: &str) -> Vec<String> {
    styles
        .iter()
        .map(|path| {
            format!(
                r#"<link rel="stylesheet" href="{}{}">"#,
                prefix,
                html_escape(path)
            )
        })
        .collect()
}

/// `<script defer src>` tags for a page's own `scripts:`.
///
/// `defer` rather than bare or `async`: a page script is written against the
/// rendered body, and the built-in interactivity script it follows has already
/// installed its listeners by then.
fn script_tags(scripts: &[String], prefix: &str) -> Vec<String> {
    scripts
        .iter()
        .map(|path| {
            format!(
                r#"<script defer src="{}{}"></script>"#,
                prefix,
                html_escape(path)
            )
        })
        .collect()
}

/// Join a run of head/script tags the way both shells indent them.
fn join_tags(tags: Vec<String>) -> String {
    tags.join("\n    ")
}

/// The drawer's script: what the checkbox-and-label markup
/// (`render_site_nav`) cannot do on its own. Opening and closing are the
/// checkbox's, styled by `:checked`, so a page that runs no script — a
/// reader with scripting off, or a sandboxed frame that grants none — still
/// has a working menu; this adds closing on a click outside or Escape, and
/// opens the sidebar on the reader's place in the tree rather than its top.
const NAV_DRAWER_SCRIPT: &str = r#"        var toggle = document.querySelector('.nav-toggle-state');
        var nav = document.querySelector('.site-nav');
        if (toggle && nav) {
            document.addEventListener('click', function(e) {
                var t = e.target;
                var onToggle = t === toggle || (t.closest && t.closest('.nav-toggle'));
                if (toggle.checked && !onToggle && !nav.contains(t)) toggle.checked = false;
            });
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape' && toggle.checked) {
                    toggle.checked = false;
                    toggle.focus();
                }
            });
            var current = nav.querySelector('[aria-current]');
            if (current && current.scrollIntoView) current.scrollIntoView({ block: 'center' });
        }"#;

impl HtmlRenderer {
    /// Renderer with built-in default styling (no theme, bundled CSS).
    pub fn new() -> Self {
        Self {
            style: SiteStyle::default(),
        }
    }

    /// Renderer with a color theme overriding the default palette.
    pub fn with_theme(theme: ThemeAppearance) -> Self {
        Self {
            style: SiteStyle {
                theme: Some(theme),
                ..SiteStyle::default()
            },
        }
    }

    /// Renderer with a fully caller-specified [`SiteStyle`].
    pub fn with_style(style: SiteStyle) -> Self {
        Self { style }
    }

    /// Get the CSS stylesheet: custom CSS if provided, otherwise the bundled
    /// base stylesheet with theme color overrides appended.
    fn css(&self) -> String {
        if let Some(custom) = &self.style.custom_css {
            return custom.clone();
        }
        let base = get_base_css();
        match &self.style.theme {
            Some(theme) => {
                let overrides = theme.to_css_overrides();
                if overrides.is_empty() {
                    base.to_string()
                } else {
                    format!("{}\n/* ── Theme overrides ── */\n{}", base, overrides)
                }
            }
            None => base.to_string(),
        }
    }

    /// Resolve the favicon: custom favicon if provided, else the theme's
    /// favicon (or its accent-derived default). `None` when no styling at all.
    fn favicon(&self) -> Option<FaviconAsset> {
        if let Some(fav) = &self.style.custom_favicon {
            return Some(fav.clone());
        }
        self.style.theme.as_ref().map(|t| t.favicon_or_default())
    }

    /// Generate the `<link rel="icon">` tag for the favicon, if available.
    fn favicon_link_tag(&self, prefix: &str) -> String {
        match self.favicon() {
            Some(fav) => format!(
                r#"<link rel="icon" type="{}" href="{}{}">"#,
                fav.mime_type, prefix, fav.filename
            ),
            None => String::new(),
        }
    }

    /// The built-in interactivity: spoiler toggles, and the parent half of the
    /// island resize bridge.
    ///
    /// ## The island resize protocol
    ///
    /// An island is a sandboxed `<iframe>` with no `allow-same-origin`, so the
    /// page holding it cannot read the embedded document's height. Instead:
    ///
    /// 1. On each frame's `load`, the parent posts
    ///    `{type: 'diaryx-html-attachment-measure'}` into it (twice, 80ms apart,
    ///    to catch a document whose own layout settles after load).
    /// 2. The child answers with
    ///    `{type: 'diaryx-html-attachment-size', height}` — see
    ///    [`ISLAND_CHILD_SCRIPT`], which is written to the site as
    ///    [`ISLAND_CHILD_SCRIPT_FILENAME`] for island documents to load.
    /// 3. The parent matches the reply to a frame by `event.source` and sets
    ///    that frame's height, clamped to 200–4000px — the same range
    ///    `![alt](x.html){height=…}` is clamped to, so an island cannot make
    ///    itself a pixel tall or taller than any screen.
    ///
    /// An island whose document loads no child script simply keeps the
    /// `min-height` its embed asked for; the protocol is an improvement on that
    /// default, not a requirement of it.
    pub fn interactivity_script(&self) -> &'static str {
        r#"function clampIslandHeight(value) {
        if (!Number.isFinite(value) || value <= 0) return null;
        return Math.max(200, Math.min(Math.round(value), 4000));
    }

    function requestIslandMeasurement(frame) {
        if (!frame || !frame.contentWindow) return;
        try {
            frame.contentWindow.postMessage({ type: 'diaryx-html-attachment-measure' }, '*');
        } catch (_error) {}
    }

    function installSpoilers() {
        document.querySelectorAll('.spoiler-mark').forEach(function(el) {
            el.addEventListener('click', function() {
                el.classList.toggle('spoiler-hidden');
                el.classList.toggle('spoiler-revealed');
            });
        });
    }

    function installIslandResizeBridge() {
        document.querySelectorAll('iframe.diaryx-island').forEach(function(frame) {
            frame.addEventListener('load', function() {
                requestIslandMeasurement(frame);
                setTimeout(function() { requestIslandMeasurement(frame); }, 80);
            });
        });

        window.addEventListener('message', function(event) {
            var data = event.data;
            if (!data || data.type !== 'diaryx-html-attachment-size') return;

            var nextHeight = clampIslandHeight(Number(data.height));
            if (nextHeight === null) return;

            var frames = document.querySelectorAll('iframe.diaryx-island');
            for (var i = 0; i < frames.length; i += 1) {
                var frame = frames[i];
                if (frame.contentWindow === event.source) {
                    frame.style.height = String(nextHeight) + 'px';
                    break;
                }
            }
        });
    }

    installSpoilers();
    installIslandResizeBridge();"#
    }

    /// Wrap a rendered page into a complete HTML document.
    pub fn render_page(&self, page: &PublishedPage, site_title: &str, single_file: bool) -> String {
        let prefix = root_prefix(&page.dest_filename);
        let css_link = if single_file {
            format!("<style>{}</style>", self.css())
        } else {
            format!(r#"<link rel="stylesheet" href="{}style.css">"#, prefix)
        };
        let favicon_link = self.favicon_link_tag(&prefix);
        let interactivity_script = self.interactivity_script();

        let breadcrumb_html = render_breadcrumb(page, single_file);

        format!(
            r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{document_title}</title>
    {css_link}
    {favicon_link}
</head>
<body>
    <main>
        <article>
            {breadcrumb}
            <div class="content">
                {content}
            </div>
        </article>
    </main>
    {footer}
    <script>{interactivity_script}</script>
</body>
</html>"#,
            document_title = html_escape(&document_title(&page.title, site_title)),
            footer = footer_element(self.style.generator.as_ref()),
            css_link = css_link,
            favicon_link = favicon_link,
            breadcrumb = breadcrumb_html,
            content = page.rendered_body,
            interactivity_script = interactivity_script,
        )
    }

    /// Render all pages into a single combined document.
    pub fn render_single_document(&self, pages: &[PublishedPage], site_title: &str) -> String {
        let mut sections = Vec::new();

        for page in pages {
            let anchor = title_to_anchor(&page.title);
            let breadcrumb = render_breadcrumb(page, true);

            sections.push(format!(
                r#"<section id="{anchor}">
    {breadcrumb}
    <div class="content">
        {content}
    </div>
</section>"#,
                anchor = html_escape(&anchor),
                breadcrumb = breadcrumb,
                content = page.rendered_body,
            ));
        }

        // Build table of contents
        let mut toc = String::from(r#"<nav class="toc"><h2>Table of Contents</h2><ul>"#);
        for page in pages {
            let anchor = title_to_anchor(&page.title);
            toc.push_str(&format!(
                r##"<li><a href="#{}">{}</a></li>"##,
                html_escape(&anchor),
                html_escape(&page.title)
            ));
        }
        toc.push_str("</ul></nav>");

        // For single-file output, inline the favicon as a data URI
        let favicon_link = match self.favicon() {
            Some(fav) => {
                use base64::Engine;
                let b64 = base64::engine::general_purpose::STANDARD.encode(&fav.data);
                format!(
                    r#"<link rel="icon" type="{}" href="data:{};base64,{}">"#,
                    fav.mime_type, fav.mime_type, b64
                )
            }
            None => String::new(),
        };

        let interactivity_script = self.interactivity_script();

        format!(
            r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{site_title}</title>
    <style>{css}</style>
    {favicon_link}
</head>
<body>
    <main>
        {toc}
        {sections}
    </main>
    {footer}
    <script>{interactivity_script}</script>
</body>
</html>"#,
            site_title = html_escape(site_title),
            footer = footer_element(self.style.generator.as_ref()),
            css = self.css(),
            favicon_link = favicon_link,
            toc = toc,
            sections = sections.join("\n<hr>\n"),
            interactivity_script = interactivity_script,
        )
    }

    /// Render a page with full site context (nav, breadcrumbs, SEO, feeds),
    /// into the caller's shell template or the built-in one.
    ///
    /// A page whose layout is [`PageLayout::Bare`] takes neither: it carries its
    /// own frame, and gets only the head this crate must write for it. A
    /// [`PageLayout::Verbatim`] page takes not even that — its body is already
    /// the file, and the rendered document is those bytes and nothing else.
    pub fn render_page_in_site(&self, page: &PublishedPage, ctx: &PageContext<'_>) -> String {
        match page.layout {
            PageLayout::Verbatim => page.rendered_body.clone(),
            PageLayout::Bare => self.render_bare_page(page, ctx),
            PageLayout::Site => {
                let slots = self.site_slots(page, ctx);
                match ctx.template {
                    Some(template) => template.render(&slots),
                    None => builtin_shell(&slots),
                }
            }
        }
    }

    /// The slot values both site shells — built-in and caller-supplied — are
    /// filled from.
    fn site_slots(&self, page: &PublishedPage, ctx: &PageContext<'_>) -> ShellSlots {
        let prefix = root_prefix(&page.dest_filename);

        let mut head = vec![
            format!(r#"<link rel="stylesheet" href="{}style.css">"#, prefix),
            self.favicon_link_tag(&prefix),
            ctx.seo_meta.to_string(),
            ctx.feed_links.to_string(),
        ];
        head.extend(style_link_tags(&page.styles, &prefix));

        let mut scripts = vec![format!(
            r#"<script>
    (function() {{
{NAV_DRAWER_SCRIPT}
        // The outline is written open, for a reader with scripting off; on a
        // narrow screen it would push the content down, so it starts closed.
        var toc = document.querySelector('.toc details');
        if (toc && !window.matchMedia('(min-width: 88rem)').matches) toc.open = false;
        {interactivity_script}
    }})();
    </script>"#,
            interactivity_script = self.interactivity_script(),
        )];
        scripts.extend(script_tags(&page.scripts, &prefix));

        let order = reading_order(&ctx.nav.tree);

        ShellSlots {
            lang: ctx.lang.to_string(),
            document_title: document_title(&page.title, ctx.site_title),
            site_title: ctx.site_title.to_string(),
            body_class: if ctx.nav.tree.is_empty() {
                String::new()
            } else {
                "has-site-nav".to_string()
            },
            head: join_tags(head),
            site_nav: render_site_nav(ctx.nav, ctx.site_title, &prefix),
            breadcrumbs: render_full_breadcrumbs(&ctx.nav.breadcrumbs, &prefix),
            toc: if page.toc {
                render_toc(&page.headings)
            } else {
                String::new()
            },
            site_header: ctx.site_header.to_string(),
            content: page.rendered_body.clone(),
            pager: render_pager(&order, &page.dest_filename, &prefix),
            site_footer: ctx.site_footer.to_string(),
            footer: footer_html(self.style.generator.as_ref()),
            scripts: join_tags(scripts),
            root_prefix: prefix,
        }
    }

    /// A `layout: bare` page: the document this crate is obliged to write —
    /// doctype, charset, viewport, title, favicon, SEO, feeds — plus the page's
    /// own styles, its body, and its own scripts. Nothing else.
    fn render_bare_page(&self, page: &PublishedPage, ctx: &PageContext<'_>) -> String {
        let prefix = root_prefix(&page.dest_filename);

        let mut head = vec![
            self.favicon_link_tag(&prefix),
            ctx.seo_meta.to_string(),
            ctx.feed_links.to_string(),
        ];
        head.extend(style_link_tags(&page.styles, &prefix));

        format!(
            r#"<!DOCTYPE html>
<html lang="{lang}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{document_title}</title>
    {head}
</head>
<body>
{content}
    {scripts}
</body>
</html>"#,
            lang = html_escape(ctx.lang),
            document_title = html_escape(&document_title(&page.title, ctx.site_title)),
            head = join_tags(head),
            content = page.rendered_body,
            scripts = join_tags(script_tags(&page.scripts, &prefix)),
        )
    }

    /// Static assets to write alongside output files: the stylesheet, the
    /// favicon when there is one, and the island child script.
    ///
    /// The island script is written unconditionally because an island document
    /// referencing it is written by hand, and a site that publishes one has no
    /// way to ask for the file to appear. Returns `(filename, content)` pairs.
    pub fn static_assets(&self) -> Vec<(String, Vec<u8>)> {
        let mut assets = vec![("style.css".to_string(), self.css().into_bytes())];
        if let Some(fav) = self.favicon() {
            assets.push((fav.filename, fav.data));
        }
        assets.push((
            ISLAND_CHILD_SCRIPT_FILENAME.to_string(),
            ISLAND_CHILD_SCRIPT.as_bytes().to_vec(),
        ));
        assets
    }
}

/// The attribution line both site shells carry: a paragraph, for the shell to
/// place inside whatever `<footer>` it writes.
///
/// Empty when no [`Generator`] is named, which is what an unbranded render is.
/// It used to carry its own `<footer>` element; the built-in shell now writes
/// one for the site footer and this together, so a caller's stylesheet that
/// selected `footer` still reaches it.
fn footer_html(generator: Option<&Generator>) -> String {
    let Some(generator) = generator else {
        return String::new();
    };
    let name = html_escape(&generator.name);
    let credit = match &generator.url {
        Some(url) => format!(r#"<a href="{}">{}</a>"#, html_escape(url), name),
        None => name,
    };
    format!(r#"<p class="generator">Generated by {credit}</p>"#)
}

/// [`footer_html`] in a `<footer>` of its own, for the two shells that write
/// no site footer around it — or nothing at all, rather than an empty element.
fn footer_element(generator: Option<&Generator>) -> String {
    let credit = footer_html(generator);
    if credit.is_empty() {
        return credit;
    }
    format!("<footer>\n        {credit}\n    </footer>")
}

/// The built-in site shell.
///
/// Kept as a `format!` rather than expressed as a [`ShellTemplate`] because its
/// inline script is full of braces that a slot syntax would have to be taught to
/// ignore, and because the output of *this* function is what "byte-identical to
/// what we published yesterday" means. It reads the same slots a template does,
/// so the two shells cannot come to disagree about what a page contains.
fn builtin_shell(slots: &ShellSlots) -> String {
    let body_class = if slots.body_class.is_empty() {
        String::new()
    } else {
        format!(r#" class="{}""#, html_escape(&slots.body_class))
    };

    format!(
        r##"<!DOCTYPE html>
<html lang="{lang}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{document_title}</title>
    {head}
</head>
<body{body_class}>
    <a class="skip-link" href="#content">Skip to content</a>
    {site_nav}
    <div class="site-content">
    <header class="site-header">{site_header}</header>
    <main id="content">
        <article>
            {breadcrumbs}
            {toc}
            <div class="content">
                {content}
            </div>
        </article>
        {pager}
    </main>
    <footer class="site-footer">{site_footer}{footer}</footer>
    </div>
    {scripts}
</body>
</html>"##,
        lang = html_escape(&slots.lang),
        document_title = html_escape(&slots.document_title),
        head = slots.head,
        body_class = body_class,
        site_nav = slots.site_nav,
        site_header = slots.site_header,
        breadcrumbs = slots.breadcrumbs,
        toc = slots.toc,
        content = slots.content,
        pager = slots.pager,
        site_footer = slots.site_footer,
        footer = slots.footer,
        scripts = slots.scripts,
    )
}

impl Default for HtmlRenderer {
    fn default() -> Self {
        Self::new()
    }
}

/// Get the built-in base CSS stylesheet (without theme overrides).
fn get_base_css() -> &'static str {
    include_str!("html_format_css.css")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::appearance::{ColorPalette, ThemeAppearance};
    use std::path::PathBuf;

    /// A renderer that credits a generator, so a test asserting a shell has
    /// *no* footer is asserting something. Deliberately not this project's own
    /// name: the engine ships no attribution, and a fixture that hardcoded one
    /// would be the branding coming back in through the tests.
    fn credited() -> HtmlRenderer {
        HtmlRenderer::with_style(SiteStyle {
            generator: Some(Generator::linked("Example", "https://example.com")),
            ..SiteStyle::default()
        })
    }

    fn make_page(dest: &str, title: &str, is_root: bool) -> PublishedPage {
        PublishedPage {
            source_path: PathBuf::from(format!("/workspace/{}", dest.replace(".html", ".md"))),
            dest_filename: dest.to_string(),
            title: title.to_string(),
            rendered_body: "<p>Hello world</p>".to_string(),
            markdown_body: "Hello world".to_string(),
            contents_links: vec![],
            parent_link: None,
            is_root,
            description: None,
            author: None,
            created: None,
            updated: None,
            date_of_document: None,
            group_keys: vec![],
            attachments: vec![],
            styles: vec![],
            scripts: vec![],
            layout: PageLayout::default(),
            shell: None,
            lang: None,
            nav_title: None,
            nav_order: None,
            hide_from_nav: false,
            hide_from_feed: false,
            id: None,
            source_markdown: String::new(),
            headings: vec![],
            toc: true,
        }
    }

    #[test]
    fn render_page_installs_html_attachment_resize_listener() {
        let page = make_page("index.html", "Home", true);
        let rendered = HtmlRenderer::new().render_page(&page, "My Site", false);

        assert!(rendered.contains("diaryx-html-attachment-measure"));
        assert!(rendered.contains("diaryx-html-attachment-size"));
        assert!(rendered.contains("iframe.diaryx-island"));
    }

    #[test]
    fn default_css_has_no_overrides() {
        let css = HtmlRenderer::new().css();
        assert!(css.contains("body {"));
        assert!(!css.contains("Theme overrides"));
    }

    #[test]
    fn theme_css_includes_overrides() {
        let theme = ThemeAppearance {
            id: Some("custom".into()),
            light: ColorPalette {
                bg: Some("#ff0000".into()),
                ..Default::default()
            },
            dark: Default::default(),
            ..Default::default()
        };

        let css = HtmlRenderer::with_theme(theme).css();
        assert!(css.contains("body {"));
        assert!(css.contains("Theme overrides"));
        assert!(css.contains("--bg: #ff0000"));
    }

    #[test]
    fn custom_css_replaces_base() {
        let style = SiteStyle {
            custom_css: Some("/* mine */ body { color: red }".to_string()),
            ..SiteStyle::default()
        };
        let css = HtmlRenderer::with_style(style).css();
        assert_eq!(css, "/* mine */ body { color: red }");
        assert!(!css.contains("Theme overrides"));
    }

    #[test]
    fn custom_favicon_overrides_theme() {
        let style = SiteStyle {
            custom_favicon: Some(FaviconAsset {
                filename: "fav.png".into(),
                mime_type: "image/png".into(),
                data: vec![1, 2, 3],
            }),
            ..SiteStyle::default()
        };
        let assets = HtmlRenderer::with_style(style).static_assets();
        assert!(assets.iter().any(|(n, _)| n == "fav.png"));
    }

    #[test]
    fn themed_page_inlines_overrides_in_single_file() {
        let theme = ThemeAppearance {
            id: None,
            light: ColorPalette {
                bg: Some("oklch(0.98 0 0)".into()),
                ..Default::default()
            },
            dark: Default::default(),
            ..Default::default()
        };

        let page = make_page("index.html", "Home", true);
        let html = HtmlRenderer::with_theme(theme).render_page(&page, "Test Site", true);
        assert!(html.contains("--bg: oklch(0.98 0 0)"));
    }

    #[test]
    fn themed_static_assets_include_overrides() {
        let theme = ThemeAppearance {
            id: None,
            light: ColorPalette {
                accent: Some("hotpink".into()),
                ..Default::default()
            },
            dark: Default::default(),
            ..Default::default()
        };

        let assets = HtmlRenderer::with_theme(theme).static_assets();
        let read = |name: &str| {
            assets
                .iter()
                .find(|(n, _)| n == name)
                .map(|(_, b)| String::from_utf8(b.clone()).unwrap())
                .unwrap_or_else(|| panic!("no {name} in the static assets"))
        };
        // CSS + auto-generated favicon + the island child script
        assert_eq!(assets.len(), 3);
        assert!(read("style.css").contains("--accent: hotpink"));
        // Favicon is auto-generated from accent color
        assert!(read("favicon.svg").contains("hotpink"));
    }

    /// An island document has to be able to answer the parent's measurement
    /// request, and nothing in a vault can ask for the file that lets it.
    #[test]
    fn static_assets_carry_the_island_child_script() {
        let assets = HtmlRenderer::new().static_assets();
        let (_, bytes) = assets
            .iter()
            .find(|(n, _)| n == ISLAND_CHILD_SCRIPT_FILENAME)
            .expect("the island child script is always written");
        let js = String::from_utf8(bytes.clone()).unwrap();
        assert!(js.contains("diaryx-html-attachment-measure"), "listens");
        assert!(js.contains("diaryx-html-attachment-size"), "answers");
        assert!(js.contains("scrollHeight"), "measures the document");
        assert!(js.contains("'resize'"), "and answers again when it changes");
    }

    // ── The shell ───────────────────────────────────────────────────────────

    fn site_ctx<'a>(
        nav: &'a SiteNavigation,
        template: Option<&'a ShellTemplate>,
    ) -> PageContext<'a> {
        PageContext {
            site_title: "My Site",
            nav,
            seo_meta: "",
            feed_links: "",
            lang: "en",
            template,
            site_header: "",
            site_footer: "",
        }
    }

    fn empty_nav() -> SiteNavigation {
        SiteNavigation {
            tree: vec![],
            breadcrumbs: vec![],
        }
    }

    /// The exact document the built-in shell produces. Pinned byte for byte,
    /// because "the default is unchanged" is the promise every site published
    /// without a template is published under, and a promise about bytes cannot
    /// be kept by an assertion about substrings. When the shell changes on
    /// purpose — a slot added, a landmark moved — this is updated, not
    /// weakened: it is the record of what a page contains.
    #[test]
    fn the_built_in_shell_is_unchanged() {
        let page = make_page("index.html", "Home", true);
        let nav = empty_nav();
        let html = credited().render_page_in_site(&page, &site_ctx(&nav, None));

        // The shell's format string, reproduced verbatim with its slots filled
        // by hand. Written this way rather than as the finished document
        // because the empty slots leave lines of trailing whitespace, which a
        // literal in this file would be one editor away from losing.
        let expected = format!(
            r##"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{document_title}</title>
    {css_link}
    {favicon_link}
    {seo_meta}
    {feed_links}
</head>
<body{body_class}>
    <a class="skip-link" href="#content">Skip to content</a>
    {site_nav}
    <div class="site-content">
    <header class="site-header">{site_header}</header>
    <main id="content">
        <article>
            {breadcrumb}
            {toc}
            <div class="content">
                {content}
            </div>
        </article>
        {pager}
    </main>
    <footer class="site-footer">{site_footer}<p class="generator">Generated by <a href="https://example.com">Example</a></p></footer>
    </div>
    <script>
    (function() {{
{nav_drawer}
        // The outline is written open, for a reader with scripting off; on a
        // narrow screen it would push the content down, so it starts closed.
        var toc = document.querySelector('.toc details');
        if (toc && !window.matchMedia('(min-width: 88rem)').matches) toc.open = false;
        {interactivity_script}
    }})();
    </script>
</body>
</html>"##,
            nav_drawer = NAV_DRAWER_SCRIPT,
            document_title = "Home - My Site",
            css_link = r#"<link rel="stylesheet" href="style.css">"#,
            favicon_link = "",
            seo_meta = "",
            feed_links = "",
            body_class = "",
            site_nav = "",
            site_header = "",
            breadcrumb = "",
            toc = "",
            content = "<p>Hello world</p>",
            pager = "",
            site_footer = "",
            interactivity_script = HtmlRenderer::new().interactivity_script(),
        );
        assert_eq!(html, expected);
    }

    #[test]
    fn a_template_replaces_the_shell_and_escapes_its_text_slots() {
        let page = make_page("index.html", "Ben & Co", true);
        let nav = empty_nav();
        let template = ShellTemplate::parse(
            "<html lang=\"{{lang}}\"><head>{{{head}}}</head><body>{{{content}}}{{{scripts}}}</body></html>",
        )
        .unwrap();
        let html = credited().render_page_in_site(&page, &site_ctx(&nav, Some(&template)));

        assert!(html.starts_with(r#"<html lang="en">"#));
        assert!(html.contains(r#"<link rel="stylesheet" href="style.css">"#));
        assert!(html.contains("<p>Hello world</p>"));
        assert!(html.contains("installSpoilers();"), "got {html}");
        assert!(
            !html.contains("Generated by"),
            "a template that omits the footer slot has no footer"
        );
    }

    #[test]
    fn a_template_escapes_the_document_title_once() {
        let page = make_page("index.html", "Ben & Co", true);
        let nav = empty_nav();
        let template = ShellTemplate::parse("<title>{{document_title}}</title>").unwrap();
        let html = HtmlRenderer::new().render_page_in_site(&page, &site_ctx(&nav, Some(&template)));
        assert_eq!(html, "<title>Ben &amp; Co - My Site</title>");
    }

    /// `bare` is a page that carries its own frame: no nav, no breadcrumbs, no
    /// footer, no site stylesheet and no built-in script — and a supplied
    /// template does not get to put one back.
    #[test]
    fn a_bare_page_takes_neither_shell() {
        let mut page = make_page("notes/poster.html", "Poster", false);
        page.layout = PageLayout::Bare;
        page.styles = vec!["assets/poster.css".to_string()];
        page.scripts = vec!["assets/poster.js".to_string()];
        let nav = empty_nav();
        let template = ShellTemplate::parse("<p>{{{content}}}</p>").unwrap();
        let html = credited().render_page_in_site(&page, &site_ctx(&nav, Some(&template)));

        assert!(html.starts_with("<!DOCTYPE html>"));
        assert!(html.contains("<title>Poster - My Site</title>"));
        assert!(html.contains("<p>Hello world</p>"));
        // Its own assets, rebased to its own depth.
        assert!(html.contains(r#"<link rel="stylesheet" href="../assets/poster.css">"#));
        assert!(html.contains(r#"<script defer src="../assets/poster.js"></script>"#));
        // And nothing of the site's.
        assert!(!html.contains("style.css"), "no site stylesheet");
        assert!(!html.contains("site-content"), "no site frame");
        assert!(!html.contains("Generated by"), "no footer");
        assert!(!html.contains("installSpoilers"), "no built-in script");
    }

    /// A verbatim page is its body and nothing else — not even the head a bare
    /// page gets, and not a supplied template either.
    #[test]
    fn a_verbatim_page_is_only_its_body() {
        let mut page = make_page("landing.html", "Landing", false);
        page.layout = PageLayout::Verbatim;
        page.styles = vec!["assets/landing.css".to_string()];
        let nav = empty_nav();
        let template = ShellTemplate::parse("<main>{{{content}}}</main>").unwrap();
        let html = HtmlRenderer::new().render_page_in_site(&page, &site_ctx(&nav, Some(&template)));

        assert_eq!(html, "<p>Hello world</p>");
    }

    /// A page's own styles follow the site stylesheet, so they can override it,
    /// and its scripts follow the built-in one, so it has already run.
    #[test]
    fn page_assets_are_emitted_after_the_sites_own() {
        let mut page = make_page("notes/entry.html", "Entry", false);
        page.styles = vec!["assets/entry.css".to_string()];
        page.scripts = vec!["assets/entry.js".to_string()];
        let nav = empty_nav();
        let html = HtmlRenderer::new().render_page_in_site(&page, &site_ctx(&nav, None));

        let site_css = html
            .find(r#"href="../style.css""#)
            .expect("site stylesheet");
        let page_css = html
            .find(r#"href="../assets/entry.css""#)
            .expect("the page's own");
        assert!(site_css < page_css, "the page's stylesheet can override");

        let builtin = html.find("installSpoilers();").expect("built-in script");
        let page_js = html
            .find(r#"<script defer src="../assets/entry.js"></script>"#)
            .expect("the page's own");
        assert!(builtin < page_js);
    }
}