calepin 0.0.16

A Rust CLI for preprocessing Typst documents with executable code chunks
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
mod assets;
mod minify;
mod syntax;
mod theme;

use anyhow::{Context, Result};
use std::path::Path;
#[cfg(test)]
use std::path::PathBuf;

pub(crate) use minify::minify_html_file;
pub(crate) use syntax::HtmlSyntaxTheme;
pub(crate) use theme::{
    SiteContextInput, SiteLanguageEntry, SiteNavEntry, SiteNavSection, SitePagefindEntry,
};

/// Read `path`, transform its contents, and write the result back only when it
/// changed (so `watch` does not retrigger the child `typst watch` on a no-op).
fn rewrite_file_in_place(
    path: &Path,
    transform: impl FnOnce(&str) -> Result<String>,
) -> Result<()> {
    let original = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read {}", path.display()))?;
    let updated = transform(&original)?;
    if updated != original {
        std::fs::write(path, &updated)
            .with_context(|| format!("failed to write {}", path.display()))?;
    }
    Ok(())
}

/// Concatenate non-empty CSS/JS chunks separated by a blank line, each
/// terminated by a newline. Returns `None` when there is nothing to join.
fn join_blocks(chunks: impl IntoIterator<Item = String>) -> Option<String> {
    let mut out = String::new();
    for chunk in chunks {
        if !out.is_empty() {
            out.push_str("\n\n");
        }
        out.push_str(&chunk);
        if !chunk.ends_with('\n') {
            out.push('\n');
        }
    }
    (!out.is_empty()).then_some(out)
}

#[cfg(test)]
pub(crate) fn apply_html_theme_file(
    path: &Path,
    entry: Option<&crate::theme::HtmlEntry>,
    root: &Path,
    site_context: Option<&SiteContextInput>,
) -> Result<()> {
    apply_html_theme_file_with_site_context(
        path,
        entry,
        &HtmlSyntaxTheme::builtin(),
        root,
        site_context,
    )
}

pub(crate) fn apply_html_theme_file_with_site_context(
    path: &Path,
    entry: Option<&crate::theme::HtmlEntry>,
    syntax_theme: &HtmlSyntaxTheme,
    root: &Path,
    site_context: Option<&SiteContextInput>,
) -> Result<()> {
    rewrite_file_in_place(path, |source| {
        theme::apply_html_theme(
            source,
            entry,
            syntax_theme,
            Some(path),
            Some(root),
            site_context,
        )
    })
}

pub(crate) fn inline_html_images_file(path: &Path, root: &Path) -> Result<()> {
    let base_dir = path.parent().unwrap_or(root);
    rewrite_file_in_place(path, |source| {
        assets::inline_html_images(source, root, base_dir)
    })
}

pub(crate) fn html_theme_stylesheet(
    entry: &crate::theme::HtmlEntry,
    syntax_theme: &HtmlSyntaxTheme,
) -> Result<Option<String>> {
    theme::theme_stylesheet(entry, syntax_theme)
}

pub(crate) fn html_theme_script(entry: &crate::theme::HtmlEntry) -> Option<String> {
    join_blocks(entry.scripts.iter().map(|(_, content)| content.clone()))
}

#[cfg(test)]
pub(crate) fn write_html_theme_stylesheet(
    entry: &crate::theme::HtmlEntry,
    out_dir: &Path,
    rel_path: &Path,
) -> Result<bool> {
    let syntax_theme = HtmlSyntaxTheme::builtin();
    let Some(css) = html_theme_stylesheet(entry, &syntax_theme)? else {
        return Ok(false);
    };
    let path = out_dir.join(rel_path);
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }
    std::fs::write(&path, css).with_context(|| format!("failed to write {}", path.display()))?;
    Ok(true)
}

#[cfg(test)]
mod minify_tests {
    use super::minify::minify_html;

    #[test]
    fn minifies_html_css_and_js() {
        let html = r#"<!doctype html>
<html>
  <head>
    <style>
      body { color: red; }
    </style>
  </head>
  <body>
    <p>  Hello, world!  </p>
    <script>const value = 1 + 2;</script>
  </body>
</html>
"#;

        let minified = minify_html(html);

        assert!(minified.len() < html.len());
        assert!(minified.contains("<p>Hello, world!"));
        assert!(!minified.contains("\n  <body>"));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::theme::{resolve_html_entry, HtmlEntry, HtmlScope, ThemeSelection};

    const SAMPLE_HTML: &str = "<html><head><title>Standard Title</title></head><body><h1>Standard Title</h1></body></html>";

    fn entry_for(selection: &ThemeSelection, scope: HtmlScope) -> HtmlEntry {
        resolve_html_entry(selection, scope).unwrap().unwrap()
    }

    fn apply_html_theme(html: &str, entry: Option<&HtmlEntry>) -> Result<String> {
        theme::apply_html_theme(html, entry, &HtmlSyntaxTheme::builtin(), None, None, None)
    }

    /// Writes a minimal theme bundle directory holding one entry file.
    fn write_theme(parent: &Path, name: &str, entry_file: &str, layout: &str) -> PathBuf {
        let dir = parent.join(name);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join(entry_file);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(path, layout).unwrap();
        dir
    }

    fn dir_document_entry(dir: &Path) -> HtmlEntry {
        entry_for(&ThemeSelection::Dir(dir.to_path_buf()), HtmlScope::Document)
    }

    fn dir_site_entry(dir: &Path) -> HtmlEntry {
        entry_for(&ThemeSelection::Dir(dir.to_path_buf()), HtmlScope::Site)
    }

    #[test]
    fn default_document_theme_preserves_title_and_wraps_body() {
        let entry = entry_for(&ThemeSelection::Default, HtmlScope::Document);
        let themed = apply_html_theme(SAMPLE_HTML, Some(&entry)).unwrap();

        assert!(themed.contains("<title>Standard Title</title>"));
        assert!(themed.contains("https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css"));
        assert!(themed.contains("<main class=\"container calepin-content calepin-document-main\">"));
        assert!(themed.contains(".sourceCode,"));
        assert!(themed.contains(".cell-output,"));
        assert!(themed.contains("calepin-copy-code"));
        assert!(themed.contains(r#"<nav class="calepin-theme-switcher""#));
        assert!(themed.contains("data-calepin-theme-storage-key=\"calepin-html-theme\""));
        assert!(themed.contains("data-calepin-theme-toggle"));
        assert!(themed.contains("const order = [\"\", \"light\", \"dark\"]"));
        assert!(themed.contains(r#"<h1 id="standard-title">Standard Title</h1>"#));
    }

    #[test]
    fn document_theme_inlines_substituted_snippet_css() {
        let entry = entry_for(&ThemeSelection::Default, HtmlScope::Document);
        let themed = apply_html_theme(SAMPLE_HTML, Some(&entry)).unwrap();

        assert!(themed.contains("--calepin-syntax-foreground"));
        assert!(!themed.contains("__CALEPIN_SYNTAX_LIGHT__"));
        assert!(!themed.contains("__CALEPIN_SYNTAX_DARK__"));
    }

    #[test]
    fn user_html_theme_cannot_include_removed_template_context() {
        let dir = tempfile::tempdir().unwrap();
        let theme_dir = write_theme(
            dir.path(),
            "with-removed-context",
            "layouts/notebook.html",
            r#"{{ doc.body_open }}<style>{{ removed_template_context.css.code }}</style><main>{{ doc.body }}</main>{{ doc.body_close }}"#,
        );

        let result = apply_html_theme(SAMPLE_HTML, Some(&dir_document_entry(&theme_dir)));

        assert!(result.is_err());
    }

    #[test]
    fn user_html_theme_gets_docs_navigation_and_toc_context() {
        let dir = tempfile::tempdir().unwrap();
        let docs = dir.path().join("docs-src2");
        std::fs::create_dir_all(&docs).unwrap();
        std::fs::write(docs.join("index.typ"), "").unwrap();
        std::fs::write(docs.join("cli.typ"), "").unwrap();
        let theme_dir = write_theme(
            dir.path(),
            "zensical",
            "layouts/notebook.html",
            r#"{{ doc.body_open }}<aside>{% for item in site.sidebar %}<a href="{{ item.href }}"{% if item.active %} aria-current="page"{% endif %}>{{ item.label }}</a>{% endfor %}</aside><nav>{% for item in site.toc %}<a href="{{ item.href }}">{{ item.label }}</a>{% endfor %}</nav><main>{{ doc.body }}</main>{{ doc.body_close }}"#,
        );
        let output = dir.path().join("docs-src2-build/html/cli.html");

        let themed = theme::apply_html_theme(
            SAMPLE_HTML,
            Some(&dir_document_entry(&theme_dir)),
            &HtmlSyntaxTheme::builtin(),
            Some(&output),
            Some(dir.path()),
            None,
        )
        .unwrap();

        assert!(themed.contains("index.html"));
        assert!(themed.contains("cli.html"));
        assert!(themed.contains("cli.typ"));
        assert!(themed.contains(r#"aria-current="page""#));
        assert!(themed.contains("href=\"#standard-title\""));
        assert!(themed.contains(r#"<h1 id="standard-title">Standard Title</h1>"#));
    }

    #[test]
    fn website_toc_skips_title_heading() {
        let dir = tempfile::tempdir().unwrap();
        let theme_dir = write_theme(
            dir.path(),
            "site-toc",
            "layouts/webpage.html",
            r#"{{ doc.body_open }}<nav>{% for item in site.toc %}<a href="{{ item.href }}" class="level-{{ item.level }}">{{ item.label }}</a>{% endfor %}</nav><main>{{ doc.body }}</main>{{ doc.body_close }}"#,
        );
        let html = "<html><head><title>Standard Title</title></head><body><h1>Standard Title</h1><h2>Section</h2></body></html>";

        let themed = theme::apply_html_theme(
            html,
            Some(&dir_site_entry(&theme_dir)),
            &HtmlSyntaxTheme::builtin(),
            None,
            None,
            Some(&SiteContextInput::default()),
        )
        .unwrap();

        assert!(!themed.contains(r##"href="#standard-title""##));
        assert!(themed.contains(r##"href="#section" class="level-2">Section"##));
        assert!(themed.contains(r#"<h1 id="standard-title">Standard Title</h1>"#));
    }

    #[test]
    fn no_html_theme_returns_raw_typst_html_without_calepin_css_or_template() {
        let themed = apply_html_theme(SAMPLE_HTML, None).unwrap();

        assert_eq!(themed, SAMPLE_HTML);
        assert!(!themed.contains("calepin-copy-code"));
        assert!(!themed.contains("cdn.jsdelivr.net/npm/@picocss/pico"));
        assert!(!themed.contains("calepin-theme-switcher"));
    }

    #[test]
    fn default_document_theme_applies_to_bare_html_fragment() {
        // Typst emits a fragment (no <html>/<head>/<body>) for normal document
        // content. The theme must still apply.
        let fragment = "<h1>Hello</h1><p>World</p>";
        let entry = entry_for(&ThemeSelection::Default, HtmlScope::Document);
        let themed = apply_html_theme(fragment, Some(&entry)).unwrap();

        assert!(themed.contains("https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css"));
        assert!(themed.contains("<main class=\"container calepin-content calepin-document-main\">"));
        assert!(themed.contains(r#"<h1 id="hello">Hello</h1>"#));
    }

    #[test]
    fn html_image_inliner_embeds_root_relative_images() {
        let dir = tempfile::tempdir().unwrap();
        let image = dir.path().join(".calepin/paper/figures/fig.svg");
        std::fs::create_dir_all(image.parent().unwrap()).unwrap();
        std::fs::write(&image, "<svg></svg>").unwrap();
        let html = r#"<figure><img src="/.calepin/paper/figures/fig.svg" alt=""></figure>"#;

        let inlined = assets::inline_html_images(html, dir.path(), dir.path()).unwrap();

        assert!(inlined.contains(r#"src="data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=""#));
    }

    #[test]
    fn html_image_inliner_embeds_relative_images() {
        let dir = tempfile::tempdir().unwrap();
        let image = dir.path().join("fig.png");
        std::fs::write(&image, [0_u8, 1, 2]).unwrap();
        let html = r#"<img alt="x" src='fig.png'>"#;

        let inlined = assets::inline_html_images(html, dir.path(), dir.path()).unwrap();

        assert!(inlined.contains("src='data:image/png;base64,AAEC'"));
    }

    #[test]
    fn html_image_inliner_leaves_external_and_data_images() {
        let dir = tempfile::tempdir().unwrap();
        let html = concat!(
            r#"<img src="https://example.com/fig.png">"#,
            r#"<img src="data:image/png;base64,AA==">"#
        );

        let inlined = assets::inline_html_images(html, dir.path(), dir.path()).unwrap();

        assert_eq!(inlined, html);
    }

    #[test]
    fn user_theme_directory_can_be_referenced_directly() {
        let dir = tempfile::tempdir().unwrap();
        let theme_dir = write_theme(
            dir.path(),
            "custom",
            "layouts/notebook.html",
            "<custom-shell>{{ doc.body }}</custom-shell>",
        );

        let themed = apply_html_theme(SAMPLE_HTML, Some(&dir_document_entry(&theme_dir))).unwrap();

        assert!(themed.contains("<custom-shell>"));
    }

    #[test]
    fn user_theme_loops_styles_scripts_and_includes_partials() {
        let dir = tempfile::tempdir().unwrap();
        let theme_dir = dir.path().join("mini");
        std::fs::create_dir_all(theme_dir.join("layouts")).unwrap();
        std::fs::create_dir_all(theme_dir.join("partials")).unwrap();
        std::fs::create_dir_all(theme_dir.join("styles")).unwrap();
        std::fs::create_dir_all(theme_dir.join("scripts")).unwrap();
        std::fs::write(
            theme_dir.join("layouts/notebook.html"),
            "{{ doc.head }}{% for s in styles %}<style>{{ s.css }}</style>{% endfor %}{{ doc.body_open }}{% include \"partials/banner.html\" %}{{ doc.body }}{% for s in scripts %}<script>{{ s.content }}</script>{% endfor %}{{ doc.body_close }}",
        )
        .unwrap();
        std::fs::write(
            theme_dir.join("partials/banner.html"),
            "<header>hi</header>",
        )
        .unwrap();
        std::fs::write(theme_dir.join("styles/main.css"), "body{color:red}").unwrap();
        std::fs::write(theme_dir.join("scripts/main.js"), "console.log(1)").unwrap();

        let themed = apply_html_theme(SAMPLE_HTML, Some(&dir_document_entry(&theme_dir))).unwrap();

        assert!(themed.contains("<header>hi</header>"));
        assert!(themed.contains("<style>body{color:red}</style>"));
        assert!(themed.contains("<script>console.log(1)</script>"));
    }

    #[test]
    fn theme_template_error_names_the_theme() {
        let dir = tempfile::tempdir().unwrap();
        let theme_dir = write_theme(
            dir.path(),
            "broken",
            "layouts/notebook.html",
            "{% include \"partials/missing.html\" %}",
        );

        let err = apply_html_theme(SAMPLE_HTML, Some(&dir_document_entry(&theme_dir)))
            .unwrap_err()
            .to_string();

        assert!(err.contains("broken"));
    }

    #[test]
    fn bundled_website_theme_uses_configured_logo() {
        let site_context = SiteContextInput {
            title: Some("Example".to_string()),
            logo: Some("assets/logo.svg".to_string()),
            logo_alt: Some("Example".to_string()),
            home_url: Some("index.html".to_string()),
            ..SiteContextInput::default()
        };
        let entry = entry_for(&ThemeSelection::Default, HtmlScope::Site);

        let themed = theme::apply_html_theme(
            SAMPLE_HTML,
            Some(&entry),
            &HtmlSyntaxTheme::builtin(),
            None,
            None,
            Some(&site_context),
        )
        .unwrap();

        assert!(themed.contains(r#"<img src="assets/logo.svg" alt="Example""#));
        assert!(themed.contains(r#"aria-label="Example home""#));
        assert!(!themed.contains("logo_short.svg"));
        assert!(!themed.contains("Calepin home"));
    }

    #[test]
    fn bundled_themes_render_navbar_links_theme_toggle_and_language_picker() {
        let site_context = SiteContextInput {
            navbar_left: vec![SiteNavEntry {
                href: "about.html".to_string(),
                label: "About".to_string(),
                label_html: "About".to_string(),
                active: true,
            }],
            languages: vec![
                SiteLanguageEntry {
                    code: "en".to_string(),
                    label: "English".to_string(),
                    href: "index.html".to_string(),
                    active: true,
                },
                SiteLanguageEntry {
                    code: "fr".to_string(),
                    label: "Français".to_string(),
                    href: "fr/index.html".to_string(),
                    active: false,
                },
            ],
            language: Some("en".to_string()),
            title: Some("Example".to_string()),
            home_url: Some("index.html".to_string()),
            ..SiteContextInput::default()
        };

        for selection in [ThemeSelection::Default, ThemeSelection::Builtin("academic")] {
            let entry = entry_for(&selection, HtmlScope::Site);
            let theme_name = entry.theme_name.clone();
            let themed = theme::apply_html_theme(
                SAMPLE_HTML,
                Some(&entry),
                &HtmlSyntaxTheme::builtin(),
                None,
                None,
                Some(&site_context),
            )
            .unwrap();

            assert!(
                themed.contains(r#"href="about.html" aria-label="About""#),
                "{theme_name}: missing navbar page link"
            );
            assert!(
                themed.contains("data-calepin-theme-toggle"),
                "{theme_name}: missing theme toggle"
            );
            assert!(
                themed.contains("data-calepin-language-picker"),
                "{theme_name}: missing language picker"
            );
            assert!(
                themed.contains(r#"<option value="fr/index.html" data-calepin-language-code="fr""#),
                "{theme_name}: missing language option"
            );
        }
    }

    #[test]
    fn default_website_theme_renders_output_picker_directly() {
        let site_context = SiteContextInput {
            title: Some("Example".to_string()),
            home_url: Some("index.html".to_string()),
            ..SiteContextInput::default()
        };
        let entry = entry_for(&ThemeSelection::Default, HtmlScope::Site);
        let themed = theme::apply_html_theme(
            SAMPLE_HTML,
            Some(&entry),
            &HtmlSyntaxTheme::builtin(),
            None,
            None,
            Some(&site_context),
        )
        .unwrap();

        assert!(themed.contains(r#"id="calepin-website-view-mode""#));
        assert!(themed.contains(r#"<option value="source">Source</option>"#));
    }

    #[test]
    fn bundled_themes_hide_language_picker_for_single_language_sites() {
        let site_context = SiteContextInput {
            navbar_right: vec![SiteNavEntry {
                href: String::new(),
                label: "Language".to_string(),
                label_html: "Language".to_string(),
                active: false,
            }],
            languages: vec![SiteLanguageEntry {
                code: "en".to_string(),
                label: "English".to_string(),
                href: "index.html".to_string(),
                active: true,
            }],
            language: Some("en".to_string()),
            title: Some("Example".to_string()),
            home_url: Some("index.html".to_string()),
            ..SiteContextInput::default()
        };

        for selection in [ThemeSelection::Default, ThemeSelection::Builtin("academic")] {
            let entry = entry_for(&selection, HtmlScope::Site);
            let theme_name = entry.theme_name.clone();
            let themed = theme::apply_html_theme(
                SAMPLE_HTML,
                Some(&entry),
                &HtmlSyntaxTheme::builtin(),
                None,
                None,
                Some(&site_context),
            )
            .unwrap();

            assert!(
                !themed.contains(r#"aria-label="Language" data-calepin-language-picker"#),
                "{theme_name}: language picker should require multiple languages"
            );
        }
    }

    #[test]
    fn bundled_themes_render_borderless_language_picker_button() {
        for selection in [ThemeSelection::Default, ThemeSelection::Builtin("academic")] {
            let entry = entry_for(&selection, HtmlScope::Site);
            let theme_name = entry.theme_name.clone();
            let css = html_theme_stylesheet(&entry, &HtmlSyntaxTheme::builtin())
                .unwrap()
                .unwrap();
            let script = html_theme_script(&entry).unwrap();

            assert!(
                css.contains(
                    r#".calepin-language-picker-button {
  display: inline-flex;"#
                ),
                "{theme_name}: missing language picker button styles"
            );
            assert!(
                css.contains("border: 0;"),
                "{theme_name}: language picker button should not have a border"
            );
            assert!(
                css.contains("background: transparent;"),
                "{theme_name}: language picker button should not use the primary button color"
            );
            assert!(
                css.contains("color: inherit;"),
                "{theme_name}: language picker button should inherit text color"
            );
            assert!(
                css.contains("text-decoration: none;"),
                "{theme_name}: themed links should not be underlined"
            );
            assert!(
                script.contains(r#"summary.className = "calepin-language-picker-button";"#),
                "{theme_name}: language picker button should not use outline classes"
            );
            assert!(
                !script.contains("calepin-language-picker-button outline secondary"),
                "{theme_name}: language picker button should not use outline classes"
            );
        }
    }

    #[test]
    fn academic_site_theme_omits_toc_and_sidebar_nav_links() {
        let site_context = SiteContextInput {
            navbar_left: vec![SiteNavEntry {
                href: "about.html".to_string(),
                label: "About".to_string(),
                label_html: "About".to_string(),
                active: false,
            }],
            sidebar_sections: vec![sidebar_section("Guide", "guide.html", false)],
            title: Some("Example".to_string()),
            home_url: Some("index.html".to_string()),
            ..SiteContextInput::default()
        };
        let html = "<html><head><title>Standard Title</title></head><body><h1>Standard Title</h1><h2>Section</h2></body></html>";
        let entry = entry_for(&ThemeSelection::Builtin("academic"), HtmlScope::Site);

        let themed = theme::apply_html_theme(
            html,
            Some(&entry),
            &HtmlSyntaxTheme::builtin(),
            None,
            None,
            Some(&site_context),
        )
        .unwrap();

        assert!(themed.contains(r#"href="about.html" aria-label="About""#));
        assert!(!themed.contains(r#"href="guide.html" aria-label="Guide""#));
        assert!(!themed.contains("academic-toc"));
        assert!(!themed.contains("On this page"));
    }

    #[test]
    fn academic_site_theme_centers_text_and_inherits_shared_code_styles() {
        let entry = entry_for(&ThemeSelection::Builtin("academic"), HtmlScope::Site);
        let css = html_theme_stylesheet(&entry, &HtmlSyntaxTheme::builtin())
            .unwrap()
            .unwrap();

        assert!(css.contains(
            r#".academic-page {
  width: min(100% - 2rem, var(--academic-text-width));"#
        ));
        assert!(css.contains("justify-content: space-evenly;"));
        assert!(css.contains(
            r#".academic-menu {
  display: contents;"#
        ));
        assert!(css.contains(
            r#".academic-page-nav-link-next {
  grid-column: 2;"#
        ));
        assert!(css.contains("pre > code"));
        assert!(css.contains("calepin-copy-code"));
        assert!(!css.contains(".academic-main pre"));
        assert!(!css.contains(".academic-main code"));
        assert!(!css.contains(".academic-landing .landing-command-row code"));
        assert!(!css.contains(".academic-toc"));
    }

    #[test]
    fn academic_site_theme_enhances_footnotes_as_margin_notes() {
        let entry = entry_for(&ThemeSelection::Builtin("academic"), HtmlScope::Site);
        let css = html_theme_stylesheet(&entry, &HtmlSyntaxTheme::builtin())
            .unwrap()
            .unwrap();
        let script = html_theme_script(&entry).unwrap();

        assert!(css.contains(".academic-footnote"));
        assert!(css.contains(".academic-footnote-backref"));
        assert!(script.contains(r#"section[role="doc-endnotes"]"#));
        assert!(script.contains("sidenote academic-footnote"));
        assert!(script.contains("scrollToElement(sidenote)"));
        assert!(script.contains("scrollToElement(reference)"));
        assert!(script.contains(r#"insertAdjacentElement("afterend", sidenote)"#));
    }

    fn sidebar_section(title: &str, href: &str, active: bool) -> SiteNavSection {
        SiteNavSection {
            title: Some(title.to_string()),
            active,
            items: vec![SiteNavEntry {
                href: href.to_string(),
                label: title.to_string(),
                label_html: title.to_string(),
                active,
            }],
        }
    }

    fn details_is_open(themed: &str, title: &str) -> bool {
        let summary = themed
            .find(&format!("<summary>{title}</summary>"))
            .unwrap_or_else(|| panic!("no foldable section titled {title}"));
        let details = themed[..summary]
            .rfind("<details")
            .expect("summary outside <details>");
        themed[details..summary].contains(" open")
    }

    #[test]
    fn bundled_website_theme_folds_inactive_sidebar_sections() {
        let site_context = SiteContextInput {
            sidebar_fold: true,
            sidebar_sections: vec![
                sidebar_section("Guide", "guide.html", false),
                sidebar_section("Reference", "reference.html", true),
            ],
            ..Default::default()
        };
        let entry = entry_for(&ThemeSelection::Default, HtmlScope::Site);

        let themed = theme::apply_html_theme(
            SAMPLE_HTML,
            Some(&entry),
            &HtmlSyntaxTheme::builtin(),
            None,
            None,
            Some(&site_context),
        )
        .unwrap();

        assert!(details_is_open(&themed, "Reference"));
        assert!(!details_is_open(&themed, "Guide"));
    }

    #[test]
    fn bundled_website_theme_keeps_sections_unfolded_when_fold_disabled() {
        let site_context = SiteContextInput {
            sidebar_fold: false,
            sidebar_sections: vec![
                sidebar_section("Guide", "guide.html", false),
                sidebar_section("Reference", "reference.html", true),
            ],
            ..Default::default()
        };
        let entry = entry_for(&ThemeSelection::Default, HtmlScope::Site);

        let themed = theme::apply_html_theme(
            SAMPLE_HTML,
            Some(&entry),
            &HtmlSyntaxTheme::builtin(),
            None,
            None,
            Some(&site_context),
        )
        .unwrap();

        assert!(!themed.contains("<summary>Guide</summary>"));
        assert!(!themed.contains("<summary>Reference</summary>"));
        assert!(themed.contains("<p><strong>Guide</strong></p>"));
        assert!(themed.contains("<p><strong>Reference</strong></p>"));
    }

    #[test]
    fn bundled_website_theme_can_link_external_stylesheet() {
        let site_context = SiteContextInput {
            title: Some("Example".to_string()),
            home_url: Some("index.html".to_string()),
            stylesheet: Some("../.calepin/calepin-website.css".to_string()),
            ..SiteContextInput::default()
        };
        let entry = entry_for(&ThemeSelection::Default, HtmlScope::Site);

        let themed = theme::apply_html_theme(
            SAMPLE_HTML,
            Some(&entry),
            &HtmlSyntaxTheme::builtin(),
            None,
            None,
            Some(&site_context),
        )
        .unwrap();

        assert!(
            themed.contains(r#"<link rel="stylesheet" href="../.calepin/calepin-website.css">"#)
        );
        assert!(!themed.contains("--calepin-code-border"));
        assert!(!themed.contains("--calepin-topbar-height"));
    }

    #[test]
    fn bundled_website_theme_can_link_external_scripts() {
        let site_context = SiteContextInput {
            title: Some("Example".to_string()),
            home_url: Some("index.html".to_string()),
            scripts: vec!["../.calepin/calepin-website.0123456789abcdef.js".to_string()],
            ..SiteContextInput::default()
        };
        let entry = entry_for(&ThemeSelection::Default, HtmlScope::Site);

        let themed = theme::apply_html_theme(
            SAMPLE_HTML,
            Some(&entry),
            &HtmlSyntaxTheme::builtin(),
            None,
            None,
            Some(&site_context),
        )
        .unwrap();

        assert!(themed.contains(
            r#"<script src="../.calepin/calepin-website.0123456789abcdef.js"></script>"#
        ));
        assert!(!themed.contains("data-calepin-theme-toggle], #calepin-theme-button"));
    }

    #[test]
    fn writes_bundled_website_stylesheet() {
        let dir = tempfile::tempdir().unwrap();
        let rel = Path::new(".calepin/calepin-website.css");
        let entry = entry_for(&ThemeSelection::Default, HtmlScope::Site);

        let wrote = write_html_theme_stylesheet(&entry, dir.path(), rel).unwrap();

        assert!(wrote);
        let css = std::fs::read_to_string(dir.path().join(rel)).unwrap();
        assert!(css.contains(".cell-output,"));
        assert!(css.contains(".calepin-website-shell"));
        assert!(css.contains("--calepin-syntax-foreground"));
    }

    #[test]
    fn title_is_not_double_escaped() {
        let dir = tempfile::tempdir().unwrap();
        let theme_dir = write_theme(
            dir.path(),
            "title-only",
            "layouts/notebook.html",
            "<h1>{{ doc.title }}</h1>{{ doc.body_open }}{{ doc.body }}{{ doc.body_close }}",
        );
        let html = "<html><head><title>Foo &amp; Bar</title></head><body><p>x</p></body></html>";

        let themed = apply_html_theme(html, Some(&dir_document_entry(&theme_dir))).unwrap();

        assert!(themed.contains("<h1>Foo &amp; Bar</h1>"));
        assert!(!themed.contains("&amp;amp;"));
    }
}