lagrange-library 0.2.3

A WASI-rendered Markdown static site facility — multilingual out of the box
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
//! Static site builder: walks a docs tree (one directory per language),
//! renders every markdown page in every language, and writes a single HTML
//! file per page path with all language variants embedded. A small inline
//! JavaScript layer picks the active language from:
//!
//!   1. `?lang=` query parameter (shareable)
//!   2. `localStorage` key `lagrange-lang` (persistent)
//!   3. `navigator.language` (browser preference)
//!   4. the configured default (usually `"en"`)
//!
//! The output is flat — no per-language subdirectories in the URL.

use anyhow::{Context, Result};
use std::{
    collections::BTreeMap,
    fs,
    path::{Path, PathBuf},
    time::Instant,
};

use tracing::info;

use crate::{
    comments::{self, MountInput},
    config::CommentsConfig,
    frontmatter::{self, FrontMatter},
    markdown, render, theme,
};

/// Options for [`build`].
pub struct BuildOptions {
    pub src: PathBuf,
    pub out: PathBuf,
    pub site_url: Option<String>,
    pub default_lang: Option<String>,
}

/// Contents of a single page in one language.
pub struct LangPage {
    pub title: String,
    pub body: String,
    pub sidebar_html: String,
    /// Parsed frontmatter (empty when the document had none). The title above
    /// is already resolved from `frontmatter.title` if present, falling back to
    /// the first heading — so callers do not need to re-derive it.
    pub frontmatter: FrontMatter,
    /// Pre-rendered comment mount-point HTML for this page (empty when comments
    /// are inactive or opted out). Appended verbatim after the article body.
    pub comments_mount: String,
    /// Diagram runtimes this language variant needs (mermaid/KaTeX). All
    /// language variants ship in one HTML file, so page assembly unions
    /// these flags before deciding which vendor tags to inject. Build-time
    /// only — never serialized into lg-data.
    pub diagrams: crate::diagram::DiagramNeeds,
}

/// All language variants of one logical page.
pub struct MultiPage {
    pub pages: BTreeMap<String, LangPage>,
    pub page_path: String, // e.g. "index.html", "guides/quickstart.html"
}

/// Build the whole site.
pub fn build(opts: &BuildOptions) -> Result<()> {
    let t0 = Instant::now();
    let config = crate::config::Config::load(&opts.src);

    let mut available: Vec<String> = Vec::new();
    for entry in fs::read_dir(&opts.src).with_context(|| format!("read {}", opts.src.display()))? {
        let entry = entry?;
        if entry.file_type()?.is_dir() {
            if let Some(name) = entry.file_name().to_str() {
                available.push(name.to_string());
            }
        }
    }
    if available.is_empty() {
        anyhow::bail!("no language directories under {}", opts.src.display());
    }

    let langs = config.ordered_langs(&available);
    let default_lang = opts
        .default_lang
        .clone()
        .unwrap_or_else(|| config.languages.default.clone());
    info!(
        "building {} languages ({})  default={}",
        langs.len(),
        langs.join(", "),
        default_lang
    );

    // Clear output.
    if opts.out.exists() {
        fs::remove_dir_all(&opts.out).context("clean output dir")?;
    }
    fs::create_dir_all(&opts.out).context("create output dir")?;

    let mut css = theme::build_css(&config.theme);
    if let Some(ref w) = config.layout.content_width {
        css.push_str(&format!(
            ".lg-header-inner{{max-width:{w}}}.lg-hero .content{{max-width:{w}}}\
             .content{{padding-left:max(1.5rem,calc((100% - {w}) / 2));\
                     padding-right:max(1.5rem,calc((100% - {w}) / 2))}}"
        ));
    }
    if let Some(ref p) = config.layout.content_padding {
        css.push_str(&format!(
            ".content,.lg-hero .content{{padding-left:{p};padding-right:{p}}}"
        ));
    }

    // Live component blocks: scan all markdown for ```hikari blocks, compile
    // them at build time, and collect the pre-rendered HTML. The render layer
    // gracefully falls back to source-only for any blocks that fail to compile.
    let mut all_live_sources: Vec<String> = Vec::new();
    for lang in &langs {
        let lang_dir = opts.src.join(lang);
        for md_path in walk_md(&lang_dir).unwrap_or_default() {
            let source = std::fs::read_to_string(&md_path).unwrap_or_default();
            let (_, _, body_src) = frontmatter::strip(&source);
            let blocks = markdown::parse(body_src);
            all_live_sources.extend(crate::live::collect_sources(&blocks));
        }
    }
    // Deduplicate across all languages — the same snippet appears in every
    // language variant of the same page, but only needs to be compiled once.
    all_live_sources.sort();
    all_live_sources.dedup();
    let live_html = if all_live_sources.is_empty() || std::env::var("LAGRANGE_SKIP_LIVE").is_ok() {
        std::collections::HashMap::new()
    } else {
        info!(
            "compiling {} live component block(s)…",
            all_live_sources.len()
        );
        crate::live::compile_all(&all_live_sources, &opts.out)
    };

    // ── 1. For each language, parse its SUMMARY and render every markdown
    //      page into a LangPage. Collect them into per-page-path MultiPages.
    let mut multi: BTreeMap<String, MultiPage> = BTreeMap::new();
    // Site-wide union of diagram-runtime needs — one vendor asset emission
    // for the whole build when any page in any language has a diagram fence.
    let mut site_diagram_needs = crate::diagram::DiagramNeeds::default();

    for lang in &langs {
        let t_lang = Instant::now();
        // Set the i18n context for this language so hikari components
        // render with the correct UI strings (copy/cancel/etc.).
        let hi_lang =
            hikari_i18n::Language::from_code(lang).unwrap_or(hikari_i18n::Language::English);
        hikari_i18n::provide_i18n(hi_lang, Default::default());
        let lang_dir = opts.src.join(lang);
        // Parse the per-language SUMMARY.md. When it is missing (common for
        // non-English languages that haven't been fully translated yet),
        // fall back to the default language's SUMMARY so the sidebar is
        // still populated — the page URLs are language-agnostic (flat site),
        // so links work regardless of which language's nav we use.
        let summary_path = lang_dir.join("SUMMARY.md");
        let nav = parse_summary(&summary_path).unwrap_or_default();
        let nav = if nav.is_empty() && lang != &default_lang {
            let fallback = opts.src.join(&default_lang).join("SUMMARY.md");
            parse_summary(&fallback).unwrap_or_default()
        } else {
            nav
        };

        for md_path in walk_md(&lang_dir)? {
            if md_path.file_name().is_some_and(|f| f == "SUMMARY.md") {
                continue;
            }
            let rel = md_path.strip_prefix(&lang_dir).unwrap_or(&md_path);
            let source = read_md_or_follow(&md_path)
                .with_context(|| format!("read {}", md_path.display()))?;

            // Peel frontmatter off before parsing — the grammar never sees it.
            let (_fm_kind, fm, body_src) = frontmatter::strip(&source);
            let blocks = markdown::parse(body_src);
            // Render with live component HTML if any were pre-compiled.
            let body_raw = render::render_to_html_with_live(&blocks, &live_html);
            // Title: explicit frontmatter wins, else first heading, else default.
            let title = fm
                .title
                .clone()
                .or_else(|| first_heading(&blocks))
                .unwrap_or_else(|| "Lagrange".to_string());

            // Compute output page path (README/index → index.html).
            let mut out_rel = rel.with_extension("html");
            if out_rel
                .file_name()
                .is_some_and(|f| f == "README.html" || f == "index.html")
            {
                out_rel = out_rel.with_file_name("index.html");
            }
            let page_path = out_rel.to_string_lossy().replace('\\', "/");

            // Render sidebar for THIS language.
            let sidebar_html = if nav.is_empty() {
                String::new()
            } else {
                let items: String = nav
                    .iter()
                    .map(|(t, href)| {
                        let abs = absolute_href(href, lang);
                        format!("<li><a href=\"{abs}\">{t}</a></li>")
                    })
                    .collect::<Vec<_>>()
                    .join("\n");
                format!("<h2>Contents</h2><ul>\n{items}\n</ul>")
            };

            // Rewrite asset paths (logo from README `docs/logo.webp`).
            let body = rewrite_asset_paths(&body_raw, &page_path);

            // Compute the comment mount point for this page. `canonical` is the
            // frontmatter value, falling back to nothing (the component will
            // use `window.location.href`).
            let comments_mount =
                build_comments_mount(&config.comments, &fm, &page_path, fm.canonical.as_deref());

            let entry = multi.entry(page_path.clone()).or_insert_with(|| MultiPage {
                pages: BTreeMap::new(),
                page_path: page_path.clone(),
            });
            let diagrams = crate::diagram::collect_needs(&blocks);
            site_diagram_needs.merge(diagrams);
            entry.pages.insert(
                lang.clone(),
                LangPage {
                    title,
                    body,
                    sidebar_html,
                    frontmatter: fm,
                    comments_mount,
                    diagrams,
                },
            );
        }
        info!(
            "  {lang} — {} pages in {:.1}s",
            multi
                .values()
                .filter(|m| m.pages.contains_key(lang))
                .count(),
            t_lang.elapsed().as_secs_f64()
        );
    }

    // ── 2. Write one HTML file per MultiPage.
    let lang_order: Vec<&str> = langs.iter().map(|s| s.as_str()).collect();
    let mut page_count = 0;
    for mp in multi.values() {
        write_multi_page(
            &opts.out,
            mp,
            &default_lang,
            &lang_order,
            &css,
            &opts.site_url,
            &config.site.title,
            &config.site.favicon,
            &config.site.title_template,
        )?;
        page_count += 1;
    }

    // 2b. Vendored diagram runtimes (mermaid.js / KaTeX + fonts) — one
    //     emission for the whole build, only when some page in some
    //     language actually uses a ```mermaid / ```math fence.
    if site_diagram_needs.any() {
        crate::diagram::write_vendor_assets(&opts.out)?;
    }

    // ── 3. Copy assets.
    copy_root_assets(&opts.src, &opts.out)?;

    // 3b. Copy the crate-shipped comment runtime (`assets/`) into
    //     `_site/assets/` whenever the build references a custom-element mount
    //     point. Skipped for the pure-static / public-embed modes so nothing
    //     extra is shipped.
    if needs_comment_runtime(&config.comments) {
        copy_crate_assets(&opts.out)?;
    }

    // ── 4. Build the search index.
    crate::search::write_index(&opts.out, &multi)?;

    // 4b. BBS projection: when enabled, emit a boards index per language that
    //     groups pages by their frontmatter `category`. Pure static — the board
    //     listing is just another generated HTML page linking to the articles.
    if config.bbs.enabled {
        write_boards_index(&opts.out, &multi, &langs, &css, &config.bbs.boards_path)?;
    }

    // ── 5. Emit a CNAME file when a custom domain is configured, so static
    //      hosts (GitHub Pages / Cloudflare Pages / Vercel) pick it up without
    //      a separate pipeline step.
    if let Some(domain) = &config.site.cname {
        let cname_path = opts.out.join("CNAME");
        fs::write(&cname_path, format!("{domain}\n"))
            .with_context(|| format!("write {}", cname_path.display()))?;
        info!("wrote CNAME for {domain}");
    }

    info!(
        "wrote {} pages in {:.1}s total",
        page_count,
        t0.elapsed().as_secs_f64()
    );
    Ok(())
}

// ── helpers ───────────────────────────────────────────────────────────────

fn write_multi_page(
    out: &Path,
    mp: &MultiPage,
    default_lang: &str,
    lang_order: &[&str],
    css: &str,
    _site_url: &Option<String>,
    site_title: &Option<String>,
    favicon: &Option<String>,
    title_template: &str,
) -> Result<()> {
    // Pick the default language's content for the visible HTML (SEO + no-JS).
    let default = mp
        .pages
        .get(default_lang)
        .or_else(|| mp.pages.values().next())
        .ok_or_else(|| anyhow::anyhow!("no language content for {}", mp.page_path))?;

    // Serialise all language data to JSON.
    let json_data = serde_json::to_string(&mp.pages)?;

    let out_path = out.join(&mp.page_path);
    if let Some(parent) = out_path.parent() {
        fs::create_dir_all(parent)?;
    }

    let has_hero = default.frontmatter.hero.unwrap_or(false);

    let page_title = default.title.clone();
    let display_title = title_template.replace("{title}", &page_title);

    let mut html = String::new();
    html.push_str("<!doctype html>\n<html lang=\"");
    html.push_str(default_lang);
    html.push_str("\" data-langs=\"");
    html.push_str(&lang_order.join(","));
    html.push_str("\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<title>");
    html.push_str(&html_escape_text(&display_title));
    html.push_str("</title>\n");
    if let Some(f) = favicon {
        html.push_str(&format!("<link rel=\"icon\" href=\"{f}\">\n"));
    }
    html.push_str("<style>\n");
    html.push_str(css);
    let magnify = crate::icons::icon_svg("magnify", 16);
    if has_hero {
        html.push_str(
            "\n</style>\n</head>\n<body class=\"lg-hero\">\n\
             <header class=\"lg-header\"><div class=\"lg-header-inner\">\
             <a href=\"/\" class=\"lg-site-title\">",
        );
        html.push_str(&html_escape_text(
            site_title.as_deref().unwrap_or(&page_title),
        ));
        html.push_str(
            "</a><div id=\"lg-sw\"></div></div></header>\n\
             <main class=\"content\" id=\"lg-body\">\n",
        );
    } else {
        html.push_str(
            "\n</style>\n</head>\n<body>\n<div class=\"layout\">\n\
             <aside class=\"sidebar\">\n\
             <div class=\"lg-search-box\">\
             <span class=\"lg-search-icon\">",
        );
        html.push_str(&magnify);
        html.push_str(
            "</span>\
             <input type=\"text\" placeholder=\"Search…\" id=\"lg-search-input\" autocomplete=\"off\" spellcheck=\"false\">\
             <button type=\"button\" id=\"lg-search-clear\" aria-label=\"Clear search\" title=\"Clear search\">",
        );
        html.push_str(&crate::icons::icon_svg("close", 12));
        html.push_str(
            "</button>\
             <div id=\"lg-search-results\" class=\"hi-scroll-container\"></div>\
             </div>\n\
             <nav id=\"lg-sidebar\" class=\"hi-scroll-container\">\n",
        );
        html.push_str(&default.sidebar_html);
        html.push_str(
            "\n</nav>\n\
             <div class=\"lg-lang-footer\"><div id=\"lg-sw\"></div></div>\n\
             </aside>\n\
             <main class=\"content hi-scroll-container\" id=\"lg-body\">\n",
        );
    }
    html.push_str(&default.body);
    html.push_str("\n</main>\n");

    html.push_str(&default.comments_mount);

    if !has_hero {
        html.push_str("</div>\n");
    }

    // Embedded language data.
    html.push_str("<script type=\"application/json\" id=\"lg-data\">");
    html.push_str(&json_data);
    html.push_str("</script>\n");

    // Client-side language logic + live block tab toggling.
    // Diagram vendor tags go FIRST: the deferred mermaid/KaTeX scripts and
    // the diagram.js bootstrap must exist before any init pass runs, and the
    // flags are the union across every language variant of this page (all
    // variants ship in this one HTML file).
    let mut diagram_needs = crate::diagram::DiagramNeeds::default();
    for p in mp.pages.values() {
        diagram_needs.merge(p.diagrams);
    }
    html.push_str(&crate::diagram::vendor_tags(diagram_needs));
    html.push_str(&lagrange_js());
    html.push_str(&live_block_js());
    html.push_str("</body>\n</html>\n");

    fs::write(&out_path, html).with_context(|| format!("write {}", out_path.display()))?;
    Ok(())
}

// ── inline JavaScript ─────────────────────────────────────────────────────

/// Minimal JS for live block tab toggling + code copy buttons.
fn live_block_js() -> String {
    // Embed shared JS modules (vanilla, no framework):
    // - scrollbar.js: hikari overlay scrollbar port
    // - modal.js: stack-based popup manager
    // - clipboard.js: tairitsu ClipboardOps::copy_to_clipboard binding
    let scrollbar_js = include_str!("comments/scrollbar.js");
    let modal_js = include_str!("comments/modal.js");
    let clipboard_js = include_str!("comments/clipboard.js");

    // Icons for JS-generated DOM come from the lgUI icon registry injected
    // by lagrange_js() — fed from the same mdi_path table as the build-time
    // rendered icons, so nothing here hard-codes SVG path data.
    let prefix = format!(
        "<script>{scrollbar_js}</script>\n<script>{modal_js}</script>\n<script>{clipboard_js}</script>\n"
    );
    let suffix = r##"<script>
(function(){
 /* ── live block tab toggling (preview ↔ source) — delegated so tabs keep
    working after the language switcher replaces #lg-body ── */
 document.addEventListener('click',function(e){
  var tab=e.target&&e.target.closest?e.target.closest('.lg-live-tab'):null;
  if(!tab)return;
  var block=tab.closest('.lg-live-block');if(!block)return;
  var tabs=block.querySelectorAll('.lg-live-tab');
  for(var i=0;i<tabs.length;i++)tabs[i].classList.remove('active');
  tab.classList.add('active');
  var isSource=tab.getAttribute('data-tab')==='source';
  var preview=block.querySelector('.lg-live-preview');
  var source=block.querySelector('[data-lg-source]');
  if(preview)preview.style.display=isSource?'none':'';
  if(source)source.style.display=isSource?'block':'none';
 });
})();
</script>"##;
    prefix + suffix
}

fn lagrange_js() -> String {
    let ui_js = include_str!("comments/ui.js");
    // Feed the lgUI icon registry from the same mdi_path table that
    // build-time icon_svg() renders from — one source of truth for icons
    // on both the Rust and the JS side.
    let icons = crate::icons::icons_js_object(crate::icons::ALL_ICONS);
    let translate = crate::icons::icon_svg("translate", 16);
    let chevron = format!("<path d=\"{}\"/>", crate::icons::mdi_path("chevron-down"));
    let boot = LAGRANGE_JS_TEMPLATE
        .replace("@TRANSLATE_ICON@", &translate)
        .replace("@CHEVRON_ICON_PATH@", &chevron);
    format!("<script>window.lgUI=window.lgUI||{{}};lgUI.icons={icons};</script>\n<script>{ui_js}</script>\n{boot}")
}

const LAGRANGE_JS_TEMPLATE: &str = r##"<script>
(function(){
 var D=JSON.parse(document.getElementById('lg-data').textContent);
 var N={"ar":"العربية","en":"English","es":"Español","fr":"Français","ja":"日本語","ko":"한국어","ru":"Русский","zhs":"简体中文","zht":"繁體中文"};
 var DL='en',CUR='en';
 var BL={'zh':'zhs','zh-CN':'zhs','zh-Hans':'zhs','zh-TW':'zht','zh-Hant':'zht','zh-HK':'zht'};
 function gL(){var q=new URLSearchParams(location.search).get('lang');if(q&&D[q])return q;var s=localStorage['lagrange-lang'];if(s&&D[s])return s;var bl=navigator.language||'';if(BL[bl])return BL[bl];var sh=bl.split('-')[0];if(BL[sh])return BL[sh];return D[sh]?sh:DL}
 function sL(l){if(!D[l])l=DL;CUR=l;localStorage['lagrange-lang']=l;var u=new URL(location);u.searchParams.set('lang',l);history.replaceState(null,'',u);rL(l)}
 function rL(l){
  var p=D[l]||D[DL];if(!p)return;
  document.documentElement.lang=l;document.title=p.title;
  document.getElementById('lg-body').innerHTML=p.body;
  var sb=document.getElementById('lg-sidebar');if(sb){sb.innerHTML=p.sidebar_html;var cp=location.pathname.replace(/\/+$/,'')||'/index.html';var links=sb.querySelectorAll('a');for(var i=0;i<links.length;i++){var h=links[i].getAttribute('href');if(h===cp||h+'/index.html'===cp||cp+'/index.html'===h)links[i].classList.add('active')}}
  var cl=document.getElementById('lg-lang-cur');if(cl)cl.textContent=N[l]||l;
  var os=document.querySelectorAll('.lg-lang-opt');for(var i=0;i<os.length;i++)os[i].classList.toggle('selected',os[i].dataset.lang===l);
  /* chrome i18n — re-apply UI strings after every render (body is swapped) */
  var si=document.getElementById('lg-search-input');if(si)si.placeholder=lgUI.t('search');
  var sc=document.getElementById('lg-search-clear');if(sc){sc.title=lgUI.t('clearSearch');sc.setAttribute('aria-label',lgUI.t('clearSearch'))}
  var cp=document.querySelectorAll('.hi-code-highlight-copy');for(var i=0;i<cp.length;i++){cp[i].title=lgUI.t('copyCode');cp[i].setAttribute('aria-label',lgUI.t('copyCode'))}
  /* diagrams — render mermaid/KaTeX previews in the freshly swapped body */
  if(window.lgDiagram)window.lgDiagram.init();
 }
 lgUI.i18n={cur:function(){return CUR},set:sL,detect:gL};
 /* ── language dropdown ── */
 var sw=document.getElementById('lg-sw');sw.className='lg-lang-select';
 sw.innerHTML='<button type="button" class="lg-lang-trigger">@TRANSLATE_ICON@<span id="lg-lang-cur"></span><svg class="lg-lang-arrow" width="14" height="14" viewBox="0 0 24 24" fill="currentColor">@CHEVRON_ICON_PATH@</svg></button><div class="lg-lang-panel hi-scroll-container"></div>';
 var trigger=sw.querySelector('.lg-lang-trigger');
 var panel=sw.querySelector('.lg-lang-panel');
 var ls=document.documentElement.dataset.langs?document.documentElement.dataset.langs.split(','):Object.keys(D).sort();
 for(var i=0;i<ls.length;i++){var l=ls[i];var o=document.createElement('a');o.href='?lang='+l;o.className='lg-lang-opt';o.dataset.lang=l;o.textContent=N[l]||l;o.onclick=function(e){e.preventDefault();sL(this.dataset.lang);pv.close()};panel.appendChild(o)}
 var pv=lgUI.popover(sw,panel,{title:'language'});
 trigger.onclick=function(){pv.toggle()};

 /* ── search (sharded inverted index) — on lgUI timers/network/popover ── */
 var si=document.getElementById('lg-search-input'),sr=document.getElementById('lg-search-results'),sc=document.getElementById('lg-search-clear');
 var sp=si?lgUI.popover(si.closest('.lg-search-box'),sr,{title:'search'}):null;
 function he(s){return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;')}
 function isCJK(c){return(c>='\u4e00'&&c<='\u9fff')||(c>='\u3400'&&c<='\u4dbf')||(c>='\u3040'&&c<='\u30ff')||(c>='\uac00'&&c<='\ud7af')||(c>='\uf900'&&c<='\ufaff')}
 function tokenize(q){var t=[];var cs=q.split('');var i=0;while(i<cs.length){var c=cs[i];if(c.charCodeAt(0)<128&&c.match(/[a-z0-9]/i)){var w='';while(i<cs.length&&cs[i].match(/[a-z0-9]/i))w+=cs[i++].toLowerCase();if(w.length>=2)t.push(w)}else if(isCJK(c)){if(i+1<cs.length&&isCJK(cs[i+1]))t.push(c+cs[i+1]);i++}else{i++}}return t}
 function doSearch(q){
  if(!q||q.length<2){sr.innerHTML='';sp.close();return}
  lgUI.loadJSON('search_meta.json',function(meta){
   if(!meta||!meta.shards)meta={docs:[],shards:[]};
   var tokens=tokenize(q);if(!tokens.length){sr.innerHTML='';sp.close();return}
   var L=CUR;var needed={};for(var i=0;i<tokens.length;i++){var c=tokens[i].charCodeAt(0)%16;needed[meta.shards[c]]=true}
   var names=Object.keys(needed);if(!names.length){sr.innerHTML='';sp.close();return}
   var loaded=0;var all={};
   function check(){
    loaded++;if(loaded<names.length)return;
    var sets=[];
    for(var i=0;i<tokens.length;i++){
     var s={};for(var j=0;j<names.length;j++){var idx=all[names[j]]||{};if(idx[tokens[i]])for(var k=0;k<idx[tokens[i]].length;k++)s[idx[tokens[i]][k]]=true}
     sets.push(s)
    }
    var ids=sets[0];for(var i=1;i<sets.length;i++){var n={};for(var k in ids)if(sets[i][k])n[k]=true;ids=n}
    var result=[];
    for(var k in ids){var d=meta.docs[k];if(d&&d.lang===L)result.push(d)}
    result=result.slice(0,10);
    if(!result.length){sr.innerHTML='<div class="lg-no">'+he(lgUI.t('noResults'))+'</div>';sp.open();return}
    var h='';
    for(var i=0;i<result.length;i++){var r=result[i];h+='<a href="'+he(r.url)+'?lang='+L+'" class="lg-hit"><b>'+he(r.title)+'</b>';if(r.snippet)h+='<span>'+r.snippet.replace(/</g,'&lt;')+'</span>';h+='</a>'}
    sr.innerHTML=h;sp.open()
   }
   for(var i=0;i<names.length;i++){(function(n){lgUI.loadJSON(n,function(idx){all[n]=idx;check()})})(names[i])}
  })
 }
 if(si){
  si.oninput=lgUI.debounce(function(){if(sc)sc.classList.toggle('show',!!si.value);doSearch(si.value)},200);
  if(sc)sc.onclick=function(){si.value='';sc.classList.remove('show');sp.close();si.focus()};
 }

 /* ── code copy — delegated so buttons keep working after rL body swaps ── */
 document.addEventListener('click',function(e){
  var btn=e.target&&e.target.closest?e.target.closest('.hi-code-highlight-copy[data-copy]'):null;
  if(!btn)return;
  if(window.lagrangeCopy)window.lagrangeCopy(btn.getAttribute('data-copy')||'');
  btn.classList.add('copied');
  setTimeout(function(){btn.classList.remove('copied')},1500);
 });

 /* ── init ── */
 sL(gL());
})();
</script>"##;

// ── JSON serialisation for LangPage ───────────────────────────────────────

impl serde::Serialize for LangPage {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        // Three "live" fields (consumed by the client language switcher) plus a
        // `meta` bag carrying frontmatter-derived fields the front-end may want
        // (title is duplicated here intentionally so a language switch does not
        // lose the explicit frontmatter title). The comment mount is NOT
        // serialised — it is static HTML, identical across languages.
        let mut st = s.serialize_struct("LangPage", 4)?;
        st.serialize_field("title", &self.title)?;
        st.serialize_field("body", &self.body)?;
        st.serialize_field("sidebar_html", &self.sidebar_html)?;
        st.serialize_field("meta", &PageMeta::from(&self.frontmatter))?;
        st.end()
    }
}

/// The subset of frontmatter surfaced to the client (for the language switcher
/// and any future progressive enhancement). Kept small and optional.
#[derive(serde::Serialize)]
struct PageMeta {
    #[serde(skip_serializing_if = "Option::is_none")]
    date: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    category: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    tags: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    hero: Option<bool>,
}

impl From<&FrontMatter> for PageMeta {
    fn from(fm: &FrontMatter) -> Self {
        Self {
            date: fm.date.clone(),
            category: fm.category.clone(),
            tags: fm.tags.clone(),
            description: fm.description.clone(),
            hero: fm.hero,
        }
    }
}

// ── single page (legacy, kept for potential direct use) ───────────────────

/// Turn a SUMMARY href into a flat site path (no language prefix).
/// Language switching is handled via `?lang=xx` query params.
fn absolute_href(href: &str, _lang: &str) -> String {
    if href.starts_with("http://")
        || href.starts_with("https://")
        || href.starts_with("mailto:")
        || href.starts_with('/')
        || href.starts_with('#')
    {
        return href.to_string();
    }
    let p = href.trim_start_matches("./");
    let p = if let Some(stripped) = p.strip_suffix(".md") {
        format!("{stripped}.html")
    } else {
        p.to_string()
    };
    let p = if p == "README.html" {
        "index.html".to_string()
    } else {
        p
    };
    format!("/{p}")
}

fn rewrite_asset_paths(html: &str, page_path: &str) -> String {
    let depth = page_path.matches('/').count();
    let up = "../".repeat(depth);
    if up.is_empty() {
        return html.to_string();
    }
    html.replace("src=\"docs/", &format!("src=\"{up}"))
        .replace("href=\"docs/", &format!("href=\"{up}"))
}

// ── markdown helpers ──────────────────────────────────────────────────────

/// Build the per-page comment mount-point HTML. Thin wrapper around
/// [`comments::mount_html`] that assembles the [`MountInput`] from the site
/// config and the page's frontmatter.
fn build_comments_mount(
    config: &CommentsConfig,
    fm: &FrontMatter,
    page_path: &str,
    canonical: Option<&str>,
) -> String {
    let input = MountInput {
        config,
        frontmatter: fm,
        page_path,
        canonical,
    };
    comments::mount_html(&input)
}

fn first_heading(blocks: &[markdown::Block]) -> Option<String> {
    for b in blocks {
        if let markdown::Block::Heading { text, .. } = b {
            return Some(collect_text(text));
        }
    }
    None
}

fn collect_text(inlines: &[markdown::Inline]) -> String {
    use markdown::Inline;
    inlines
        .iter()
        .map(|i| match i {
            Inline::Text(s) => s.clone(),
            Inline::Code(s) => s.clone(),
            Inline::Strong(inner) | Inline::Emphasis(inner) => collect_text(inner),
            Inline::Link { text, .. } => collect_text(text),
            Inline::Image { alt, .. } => alt.clone(),
            Inline::InlineHtml(_) => String::new(),
        })
        .collect()
}

// ── file-system walkers ───────────────────────────────────────────────────

fn parse_summary(path: &Path) -> Result<Vec<(String, String)>> {
    let source = match fs::read_to_string(path) {
        Ok(s) => s,
        Err(_) => return Ok(Vec::new()),
    };
    let mut entries = Vec::new();
    for line in source.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') || trimmed == "---" {
            continue;
        }
        let body = trimmed.trim_start_matches('-').trim_start();
        let Some(open) = body.find('[') else { continue };
        let Some(rel_close) = body[open..].find(']') else {
            continue;
        };
        let close = open + rel_close;
        let title = &body[open + 1..close];
        let rest = &body[close + 1..];
        let Some(lp) = rest.find('(') else { continue };
        let Some(rp_rel) = rest[lp..].find(')') else {
            continue;
        };
        let rp = lp + rp_rel;
        let url = &rest[lp + 1..rp];
        entries.push((title.to_string(), rewrite_nav_link(url)));
    }
    Ok(entries)
}

fn rewrite_nav_link(url: &str) -> String {
    if url.starts_with("http") || url.starts_with('#') {
        return url.to_string();
    }
    // Split off fragment.
    let (path, fragment) = match url.split_once('#') {
        Some((p, f)) => (p, Some(f)),
        None => (url, None),
    };
    if path.is_empty() {
        return url.to_string();
    }
    let stripped = path.strip_prefix("./").unwrap_or(path);
    let p = std::path::Path::new(stripped);
    let is_readme = p
        .file_name()
        .is_some_and(|f| f == "README.md" || f == "readme.md");
    let rewritten = if is_readme {
        match p.parent() {
            Some(d) if !d.as_os_str().is_empty() => format!("{}/index.html", d.display()),
            _ => "index.html".to_string(),
        }
    } else {
        stripped
            .strip_suffix(".md")
            .map(|x| format!("{x}.html"))
            .unwrap_or_else(|| stripped.to_string())
    };
    match fragment {
        Some(f) => format!("{rewritten}#{f}"),
        None => rewritten,
    }
}

fn walk_md(dir: &Path) -> Result<Vec<PathBuf>> {
    let mut out = Vec::new();
    walk_md_inner(dir, &mut out)?;
    out.sort();
    Ok(out)
}

/// Read a markdown file, following relative-path symlinks.
///
/// On Windows with `core.symlinks = false`, git stores a symlink as a
/// regular file whose content is the symlink target path (e.g.
/// `../../README.md`). This function detects that pattern — a file whose
/// entire content looks like a relative path pointing to another `.md`
/// file — and transparently follows it, reading the real target instead.
///
/// Real symlink targets (on Unix or Windows with symlinks enabled) are
/// resolved by the OS and work without this logic; this is a fallback
/// for the broken-symlink-as-text-file case.
fn read_md_or_follow(path: &Path) -> Result<String> {
    let raw = fs::read_to_string(path)?;

    // Heuristic: the file is a broken symlink if its trimmed content is a
    // single line that looks like a relative path to a .md file.
    let trimmed = raw.trim();
    if trimmed.lines().count() <= 1
        && (trimmed.starts_with("../") || trimmed.starts_with("./"))
        && trimmed.ends_with(".md")
    {
        // Resolve relative to the symlink file's directory.
        let dir = path.parent().unwrap_or(Path::new("."));
        let target = dir.join(trimmed);
        if target.is_file() {
            tracing::debug!(
                "following path-symlink: {} → {}",
                path.display(),
                target.display()
            );
            return fs::read_to_string(&target)
                .with_context(|| format!("read symlink target {}", target.display()));
        }
    }

    Ok(raw)
}

fn walk_md_inner(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
    for entry in fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            walk_md_inner(&path, out)?;
        } else if path.extension().and_then(|e| e.to_str()) == Some("md") {
            out.push(path);
        }
    }
    Ok(())
}

// ── assets ────────────────────────────────────────────────────────────────

fn copy_root_assets(src: &Path, out: &Path) -> Result<()> {
    for entry in fs::read_dir(src)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_file() && path.extension().and_then(|e| e.to_str()) != Some("md") {
            fs::copy(&path, out.join(entry.file_name()))?;
        }
    }
    let license_src = src.parent().map(|root| root.join("LICENSE"));
    if let Some(ref license) = license_src {
        if license.is_file() && !out.join("LICENSE").exists() {
            fs::copy(license, out.join("LICENSE"))?;
        }
    }
    Ok(())
}

/// True when the configured comment mode needs the lagrange comment runtime
/// (the `<lagrange-comments>` custom element + its JS/CSS). The third-party
/// embeds (`disqus`/`giscus`/`github-issue`) ship their own scripts, so they
/// do not need our runtime; `none` obviously needs nothing.
fn needs_comment_runtime(config: &CommentsConfig) -> bool {
    use crate::config::CommentMode;
    // Every mode except None renders the <lagrange-comments> component and
    // thus needs the embedded runtime JS/CSS.
    config.is_active() && matches!(config.mode, CommentMode::Proxied | CommentMode::StaticJson)
}

/// Write the browser-side comment runtime (`lagrange-comments.js` + CSS) into
/// `<out>/assets/`.
///
/// The runtime lives in `src/comments/runtime.{js,css}` and is embedded into
/// the binary at compile time via `include_str!`, so this works for a prebuilt
/// binary installed from crates.io — no source tree or exe-sibling filesystem
/// lookup needed.
fn copy_crate_assets(out: &Path) -> Result<()> {
    let dest = out.join("assets");
    fs::create_dir_all(&dest)?;
    for (name, bytes) in EMBEDDED_ASSETS {
        fs::write(dest.join(name), bytes)?;
    }
    info!(
        "embedded {} browser runtime asset(s) → {}",
        EMBEDDED_ASSETS.len(),
        dest.display()
    );
    Ok(())
}

/// The browser-side assets embedded at compile time straight from
/// `src/comments/`. Listing them here keeps the set explicit; adding a new
/// asset means dropping the file in `src/comments/` and adding one entry.
const EMBEDDED_ASSETS: &[(&str, &str)] = &[
    ("lagrange-comments.js", include_str!("comments/runtime.js")),
    (
        "lagrange-comments.css",
        include_str!("comments/runtime.css"),
    ),
];

/// Emit a per-language boards index page when `[bbs] enabled = true`.
///
/// For each language, group every page that carries a `category` frontmatter
/// by that category, and write `<out>/<boards_path>/index.html` listing the
/// boards with their post counts and links. Pages without a category are
/// omitted (they don't belong to a board). This is a pure-static projection —
/// no new data model, just a generated listing over the same pages.
fn write_boards_index(
    out: &Path,
    multi: &BTreeMap<String, MultiPage>,
    langs: &[String],
    css: &str,
    boards_path: &str,
) -> Result<()> {
    for lang in langs {
        // Collect (category, title, url) for every page in this language that
        // has a category.
        let mut boards: BTreeMap<String, Vec<(String, String)>> = BTreeMap::new();
        for mp in multi.values() {
            let Some(page) = mp.pages.get(lang) else {
                continue;
            };
            let Some(cat) = &page.frontmatter.category else {
                continue;
            };
            let title = page.title.clone();
            let url = format!("/{}", mp.page_path);
            boards.entry(cat.clone()).or_default().push((title, url));
        }
        if boards.is_empty() {
            continue;
        }

        let dir = out.join(lang).join(boards_path);
        fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;

        let mut body = String::new();
        body.push_str("<h1>Boards</h1>\n");
        // Sort each board's posts, then render alphabetically by board name.
        for posts in boards.values_mut() {
            posts.sort();
        }
        for (cat, posts) in boards.iter() {
            body.push_str(&format!("<h2>{}</h2>\n<ul>\n", html_escape_text(cat)));
            for (title, url) in posts {
                body.push_str(&format!(
                    "  <li><a href=\"{}\">{}</a></li>\n",
                    url,
                    html_escape_text(title)
                ));
            }
            body.push_str("</ul>\n");
        }

        let html = format!(
            "<!doctype html>\n<html lang=\"{lang}\">\n<head>\n<meta charset=\"utf-8\">\n\
             <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n\
             <title>Boards</title>\n<style>\n{css}\n</style>\n</head>\n<body>\n\
             <div class=\"layout\"><main class=\"content\">\n{body}\n</main></div>\n\
             </body>\n</html>\n"
        );
        let path = dir.join("index.html");
        fs::write(&path, html).with_context(|| format!("write {}", path.display()))?;
        info!("wrote boards index for {lang} ({} board(s))", boards.len());
    }
    Ok(())
}

// ── utils ─────────────────────────────────────────────────────────────────

fn html_escape_text(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            _ => out.push(ch),
        }
    }
    out
}

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

    #[test]
    fn rewrite_nav_readme_to_index() {
        assert_eq!(rewrite_nav_link("./README.md"), "index.html");
        assert_eq!(rewrite_nav_link("./en/README.md"), "en/index.html");
    }

    #[test]
    fn rewrite_nav_fragment_preserved() {
        assert_eq!(rewrite_nav_link("./a.md#sec"), "a.html#sec");
    }

    #[test]
    fn absolute_href_passthrough() {
        assert_eq!(absolute_href("https://x.com", "en"), "https://x.com");
        assert_eq!(absolute_href("#anchor", "en"), "#anchor");
        assert_eq!(absolute_href("/abs/path", "en"), "/abs/path");
    }

    #[test]
    fn absolute_href_flat_paths() {
        assert_eq!(
            absolute_href("./guides/quickstart.md", "en"),
            "/guides/quickstart.html"
        );
        assert_eq!(absolute_href("./README.md", "en"), "/index.html");
        assert_eq!(
            absolute_href("guides/architecture.md", "zhs"),
            "/guides/architecture.html"
        );
    }
}