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
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
//! Page-shell helpers: navigation, breadcrumbs, SEO meta, feed/sitemap/robots
//! generation, and small HTML/XML escaping utilities.
//!
//! These are pure functions over the value types in [`crate::types`]. The page
//! *assembly* (full `<html>` document, theme/CSS/favicon) still lives in the
//! publish plugin and will move here in a later slice.

use crate::dates::{EPOCH_RFC3339, to_rfc822, to_rfc3339};
use crate::links::{absolutize_html, root_prefix};
use crate::types::{NavLink, PublishedPage, SiteNavNode, SiteNavigation};

/// The newest-first order a feed lists entries in.
///
/// Sorts on [`PublishedPage::published_date`] — the same chain the site's own
/// index groups and orders by — so a reader's list and the front page agree.
/// Ties fall back to the title so a set of entries sharing a day is at least
/// stable between builds.
fn feed_items(pages: &[PublishedPage]) -> Vec<&PublishedPage> {
    let mut items: Vec<&PublishedPage> = pages
        .iter()
        .filter(|p| !p.is_root && p.contents_links.is_empty() && !p.hide_from_feed)
        .collect();

    items.sort_by(|a, b| newest_first(a, b));
    items.truncate(50);
    items
}

/// Order two entries newest-first, with the undated last.
///
/// The one answer to "which of these comes first", shared with the grouped
/// index in [`crate::site`] so a site cannot list its entries in one order and
/// syndicate them in another.
///
/// Two things it has to get right, both of which a naive comparison gets wrong:
///
/// **The date is normalized before it is compared.** Sorting the raw string
/// looks equivalent, since ISO dates sort lexicographically — right up until a
/// date is not an ISO date, and a vault has ordinary ways to hand over one that
/// is not. `date_of_document: unknown` is the conventional marker for a
/// deliberately-undated record: a shoebox
/// of scans imported on one afternoon must not inherit that afternoon. The
/// chain is first-key-*present* wins, so the marker stops it here as it does in
/// a view — but `'u' > '2'`, so a descending raw-string sort put every undated
/// record *above* every dated one, at the head of the feed. Nothing validates a
/// `type: date` field, so a typo (`19430512`) or a human spelling (`May 1943`)
/// arrives the same way and sorts by its own first character.
///
/// **Undated is not a date.** The obvious repair — normalize, and let an
/// unreadable one fall back to [`EPOCH_RFC3339`] like the emitted element does
/// — is wrong for the archive this program is for. The epoch is not a floor,
/// it is 1970, so an undated scan would sort *above* every letter written
/// before it. A record with no readable date is therefore ordered as absent
/// rather than as a moment, and lands after everything that has one.
pub(crate) fn newest_first(a: &PublishedPage, b: &PublishedPage) -> std::cmp::Ordering {
    use std::cmp::Ordering;

    let key = |p: &PublishedPage| p.published_date().and_then(to_rfc3339);
    match (key(a), key(b)) {
        (Some(x), Some(y)) => y.cmp(&x),
        (Some(_), None) => Ordering::Less,
        (None, Some(_)) => Ordering::Greater,
        (None, None) => Ordering::Equal,
    }
    // Ties fall back to the title so a set of entries sharing a day — or
    // sharing no day at all — is at least stable between builds.
    .then_with(|| a.title.cmp(&b.title))
}

/// Escape HTML special characters.
pub fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#39;")
}

/// Convert a title to an anchor ID.
///
/// [`prov::link::slug`] is the one slug rule in the project, so a heading anchor
/// and the filename prov would mint for the same title agree. It drops
/// punctuation rather than turning it into a separator (`v1.0 Release` becomes
/// `v10-release`), and yields `"untitled"` for a title with nothing slug-able.
pub fn title_to_anchor(title: &str) -> String {
    prov::link::slug(title)
}

/// Render the site navigation: the mobile bar, then the sidebar.
///
/// `site_title` names the masthead — the link home at the top of the sidebar,
/// which is where a site's name goes on every other site. The front page
/// leaves the tree for it: when the tree's one root is the front page
/// (`index.html`, the destination this crate gives every root), the list
/// starts at its children, so an entry sits at the depth it has rather than
/// one deeper. A rootless forest lists as it is, under a masthead that still
/// links to `index.html`, which is where a supplied or synthesized front page
/// lands.
///
/// A node with children is a disclosure — `<details>` around a `<summary>`
/// holding the link — written `open` on the current page's ancestors and on
/// the current page's own node, and closed everywhere else. The whole tree is
/// still in the HTML: crawlable, printable, searchable with the browser's
/// find, and correct with scripting off. No state is stored anywhere; which
/// sections are open is a function of which page this is.
///
/// The link and the disclosure are separate targets: the `<a>` is the
/// summary's content, so activating it navigates, and the rest of the summary
/// — the chevron the stylesheet draws — toggles.
pub fn render_site_nav(nav: &SiteNavigation, site_title: &str, root_prefix: &str) -> String {
    if nav.tree.is_empty() {
        return String::new();
    }

    fn render_nodes(nodes: &[SiteNavNode], prefix: &str) -> String {
        let mut html = String::from("<ul class=\"nav-list\">");
        for node in nodes {
            let mut classes = Vec::new();
            if !node.children.is_empty() {
                classes.push("nav-section");
            }
            if node.is_current {
                classes.push("nav-current");
            }
            if node.is_ancestor_of_current {
                classes.push("nav-ancestor");
            }

            let class_attr = if classes.is_empty() {
                String::new()
            } else {
                format!(r#" class="{}""#, classes.join(" "))
            };

            let aria = if node.is_current {
                r#" aria-current="page""#
            } else {
                ""
            };

            let link = format!(
                r#"<a href="{prefix}{href}"{aria}>{title}</a>"#,
                prefix = prefix,
                href = html_escape(&node.href),
                aria = aria,
                title = html_escape(&node.title),
            );

            if node.children.is_empty() {
                html.push_str(&format!("<li{class_attr}>{link}</li>"));
            } else {
                let open = if node.is_current || node.is_ancestor_of_current {
                    " open"
                } else {
                    ""
                };
                html.push_str(&format!(
                    "<li{class_attr}><details{open}><summary>{link}</summary>{children}</details></li>",
                    children = render_nodes(&node.children, prefix),
                ));
            }
        }
        html.push_str("</ul>");
        html
    }

    // The front page is the masthead, not a row: its children are the top of
    // the list. A forest — no root, or a supplied front page this crate never
    // saw — lists as it stands.
    let (on_front_page, top): (bool, &[SiteNavNode]) = match nav.tree.as_slice() {
        [root] if root.href == FRONT_PAGE_DEST => (root.is_current, &root.children),
        forest => (false, forest),
    };
    let masthead_aria = if on_front_page {
        r#" aria-current="page""#
    } else {
        ""
    };
    let masthead = format!(
        r#"<a class="site-masthead" href="{prefix}{FRONT_PAGE_DEST}"{aria}>{title}</a>"#,
        prefix = root_prefix,
        aria = masthead_aria,
        title = html_escape(site_title),
    );
    let nav_list = if top.is_empty() {
        String::new()
    } else {
        format!("\n{}", render_nodes(top, root_prefix))
    };

    // The drawer is a checkbox, not a button: `.nav-toggle-state:checked`
    // slides the sidebar out with no script at all, so it opens for a reader
    // with scripting off and inside a sandboxed frame that grants none — an
    // encrypted site's reader shell renders every page in one. The script
    // this crate emits only adds what CSS cannot: closing on a click outside
    // or Escape, and scrolling the current row into view. The input precedes
    // both the bar and the nav because `~` reaches a following sibling only.
    format!(
        r#"<input class="nav-toggle-state" type="checkbox" id="nav-toggle" aria-controls="site-nav" aria-label="Menu">
<header class="site-bar">
    <label class="nav-toggle" for="nav-toggle">Menu</label>
    {masthead}
</header>
<nav class="site-nav" id="site-nav" aria-label="Site navigation">
{masthead}{nav_list}
</nav>"#,
    )
}

/// Where the site's front page lands, which is the one destination this crate
/// decides for itself (`site::dest_for`): the masthead links to it, and a
/// tree rooted there is a tree whose root is the front page.
const FRONT_PAGE_DEST: &str = "index.html";

/// The pager: links to the page before and after `current` in the nav's
/// reading order, or nothing for a page that has neither.
///
/// `rel="prev"`/`rel="next"` are what a reader mode and a search engine read a
/// sequence off. The order is [`crate::nav::reading_order`]'s — the depth-first
/// order the sidebar lists — so a page's "next" is the row below it.
pub fn render_pager(order: &[NavLink], current: &str, root_prefix: &str) -> String {
    let (prev, next) = crate::nav::neighbours(order, current);
    if prev.is_none() && next.is_none() {
        return String::new();
    }
    let link = |rel: &str, label: &str, target: &NavLink| {
        format!(
            r#"<a class="pager-{rel}" rel="{rel}" href="{prefix}{href}"><span>{label}</span> {title}</a>"#,
            prefix = root_prefix,
            href = html_escape(&target.href),
            title = html_escape(&target.title),
        )
    };
    let mut out = String::from(r#"<nav class="pager" aria-label="Pager">"#);
    if let Some(prev) = prev {
        out.push_str(&link("prev", "Previous", prev));
    }
    if let Some(next) = next {
        out.push_str(&link("next", "Next", next));
    }
    out.push_str("</nav>");
    out
}

/// Render full breadcrumb trail from root to current page.
pub fn render_full_breadcrumbs(breadcrumbs: &[NavLink], prefix: &str) -> String {
    if breadcrumbs.len() <= 1 {
        return String::new();
    }

    let items: Vec<String> = breadcrumbs
        .iter()
        .enumerate()
        .map(|(i, crumb)| {
            if i == breadcrumbs.len() - 1 {
                // Current page — no link
                format!(
                    r#"<span aria-current="page">{}</span>"#,
                    html_escape(&crumb.title)
                )
            } else {
                format!(
                    r#"<a href="{}{}">{}</a>"#,
                    prefix,
                    html_escape(&crumb.href),
                    html_escape(&crumb.title)
                )
            }
        })
        .collect();

    format!(
        r#"<nav class="breadcrumbs" aria-label="Breadcrumb">{}</nav>"#,
        items.join(r#" <span class="breadcrumb-sep">/</span> "#)
    )
}

/// Render breadcrumb navigation (parent link above the title).
pub fn render_breadcrumb(page: &PublishedPage, single_file: bool) -> String {
    let prefix = root_prefix(&page.dest_filename);
    if let Some(ref parent) = page.parent_link {
        let href = if single_file {
            format!("#{}", title_to_anchor(&parent.title))
        } else {
            format!("{}{}", prefix, parent.href)
        };
        format!(
            r#"<nav class="breadcrumb" aria-label="Breadcrumb"><a href="{}">{}</a></nav>"#,
            html_escape(&href),
            html_escape(&parent.title),
        )
    } else {
        String::new()
    }
}

/// Generate SEO meta tags for a page.
pub fn generate_seo_meta(page: &PublishedPage, site_title: &str, base_url: &str) -> String {
    let mut tags = Vec::new();

    // og:title
    tags.push(format!(
        r#"<meta property="og:title" content="{}">"#,
        html_escape(&page.title)
    ));

    // description + og:description
    if let Some(ref desc) = page.description {
        tags.push(format!(
            r#"<meta name="description" content="{}">"#,
            html_escape(desc)
        ));
        tags.push(format!(
            r#"<meta property="og:description" content="{}">"#,
            html_escape(desc)
        ));
    }

    // author
    if let Some(ref author) = page.author {
        tags.push(format!(
            r#"<meta name="author" content="{}">"#,
            html_escape(author)
        ));
    }

    // article:published_time — the date the entry is *of*, matching the order
    // the site's own index lists it in, and in the RFC 3339 the Open Graph
    // spec asks for rather than whatever the frontmatter happened to say.
    if let Some(published) = page.published_date().and_then(to_rfc3339) {
        tags.push(format!(
            r#"<meta property="article:published_time" content="{}">"#,
            html_escape(&published)
        ));
    }

    // article:modified_time
    if let Some(modified) = page.modified_date().and_then(to_rfc3339) {
        tags.push(format!(
            r#"<meta property="article:modified_time" content="{}">"#,
            html_escape(&modified)
        ));
    }

    // og:image — scan attachments for images, then fall back to first <img> in body
    let og_image = find_og_image(page);
    if let Some(img_url) = og_image {
        let full_url = if img_url.starts_with("http://") || img_url.starts_with("https://") {
            img_url
        } else if !base_url.is_empty() {
            format!(
                "{}/{}",
                base_url.trim_end_matches('/'),
                img_url.trim_start_matches('/')
            )
        } else {
            img_url
        };
        tags.push(format!(
            r#"<meta property="og:image" content="{}">"#,
            html_escape(&full_url)
        ));
    }

    // og:type
    let og_type = if page.is_root { "website" } else { "article" };
    tags.push(format!(
        r#"<meta property="og:type" content="{}">"#,
        og_type
    ));

    // og:site_name
    tags.push(format!(
        r#"<meta property="og:site_name" content="{}">"#,
        html_escape(site_title)
    ));

    // og:url + canonical
    if !base_url.is_empty() {
        let url = format!("{}/{}", base_url.trim_end_matches('/'), page.dest_filename);
        tags.push(format!(
            r#"<meta property="og:url" content="{}">"#,
            html_escape(&url)
        ));
        tags.push(format!(
            r#"<link rel="canonical" href="{}">"#,
            html_escape(&url)
        ));
    }

    tags.join("\n    ")
}

/// Find the best og:image for a page.
fn find_og_image(page: &PublishedPage) -> Option<String> {
    const IMAGE_EXTENSIONS: &[&str] = &[".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg"];

    // Check attachments for images
    for s in &page.attachments {
        let lower = s.to_lowercase();
        if IMAGE_EXTENSIONS.iter().any(|ext| lower.ends_with(ext)) {
            // An attachment is a link value like any other: unwrap `[alt](target)`
            // and resolve it against the page that carries it.
            let target = prov::Link::parse_path_only(s.trim()).target;
            return Some(
                prov::link::resolve(&page.source_path, &target)
                    .to_string_lossy()
                    .into_owned(),
            );
        }
    }

    // Fall back to first <img src="..."> in rendered body
    if let Some(pos) = page.rendered_body.find("src=\"") {
        let after = &page.rendered_body[pos + 5..];
        if let Some(end) = after.find('"') {
            return Some(after[..end].to_string());
        }
    }

    None
}

/// Generate `<link>` tags for Atom and RSS feeds.
pub fn generate_feed_link_tags(root_prefix: &str) -> String {
    format!(
        r#"<link rel="alternate" type="application/atom+xml" title="Atom Feed" href="{}feed.xml">
    <link rel="alternate" type="application/rss+xml" title="RSS Feed" href="{}rss.xml">"#,
        root_prefix, root_prefix,
    )
}

/// Generate a sitemap.xml from published pages.
pub fn generate_sitemap(pages: &[PublishedPage], base_url: &str) -> String {
    let base = base_url.trim_end_matches('/');
    let mut xml = String::from(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
"#,
    );

    for page in pages {
        let loc = format!("{}/{}", base, page.dest_filename);
        // W3C Datetime, which is what a sitemap's `lastmod` is specified as and
        // which RFC 3339 satisfies. A date the vault wrote in some other
        // spelling is left out rather than emitted for a crawler to reject.
        let lastmod = page
            .modified_date()
            .and_then(to_rfc3339)
            .unwrap_or_default();
        let priority = if page.is_root {
            "1.0"
        } else if !page.contents_links.is_empty() {
            "0.8"
        } else {
            "0.6"
        };

        xml.push_str("  <url>\n");
        xml.push_str(&format!("    <loc>{}</loc>\n", xml_escape(&loc)));
        if !lastmod.is_empty() {
            xml.push_str(&format!(
                "    <lastmod>{}</lastmod>\n",
                xml_escape(&lastmod)
            ));
        }
        xml.push_str(&format!("    <priority>{}</priority>\n", priority));
        xml.push_str("  </url>\n");
    }

    xml.push_str("</urlset>\n");
    xml
}

/// Generate robots.txt content.
pub fn generate_robots_txt(base_url: &str, is_public: bool) -> String {
    if is_public {
        format!(
            "User-agent: *\nAllow: /\nSitemap: {}/sitemap.xml\n",
            base_url.trim_end_matches('/')
        )
    } else {
        "User-agent: *\nDisallow: /\n".to_string()
    }
}

/// Generate an Atom 1.0 feed.
pub fn generate_atom_feed(
    pages: &[PublishedPage],
    site_title: &str,
    base_url: &str,
    site_description: &str,
    site_author: &str,
) -> String {
    let base = base_url.trim_end_matches('/');

    let items = feed_items(pages);

    // Atom makes the feed's own `<updated>` mandatory, so this one falls back
    // rather than being omitted.
    let feed_updated = items
        .first()
        .and_then(|p| p.modified_date())
        .and_then(to_rfc3339)
        .unwrap_or_else(|| EPOCH_RFC3339.to_string());

    let mut xml = format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>{title}</title>
  <link href="{base}/" rel="alternate"/>
  <link href="{base}/feed.xml" rel="self"/>
  <id>{base}/</id>
  <updated>{updated}</updated>
"#,
        title = xml_escape(site_title),
        base = xml_escape(base),
        updated = xml_escape(&feed_updated),
    );

    if !site_author.is_empty() {
        xml.push_str(&format!(
            "  <author><name>{}</name></author>\n",
            xml_escape(site_author)
        ));
    }
    if !site_description.is_empty() {
        xml.push_str(&format!(
            "  <subtitle>{}</subtitle>\n",
            xml_escape(site_description)
        ));
    }

    for page in &items {
        let link = format!("{}/{}", base, page.dest_filename);
        let published = page.published_date().and_then(to_rfc3339);
        // Mandatory on every entry, like the feed's own above.
        let updated = page
            .modified_date()
            .and_then(to_rfc3339)
            .unwrap_or_else(|| EPOCH_RFC3339.to_string());
        let summary = strip_html_truncate(&page.rendered_body, 280);

        xml.push_str("  <entry>\n");
        xml.push_str(&format!("    <title>{}</title>\n", xml_escape(&page.title)));
        xml.push_str(&format!(
            "    <link href=\"{}\" rel=\"alternate\"/>\n",
            xml_escape(&link)
        ));
        xml.push_str(&format!("    <id>{}</id>\n", xml_escape(&link)));
        if let Some(published) = published {
            xml.push_str(&format!(
                "    <published>{}</published>\n",
                xml_escape(&published)
            ));
        }
        xml.push_str(&format!(
            "    <updated>{}</updated>\n",
            xml_escape(&updated)
        ));
        if !summary.is_empty() {
            xml.push_str(&format!(
                "    <summary>{}</summary>\n",
                xml_escape(&summary)
            ));
        }
        // The body leaves the site here, so its page-relative links have to be
        // resolved now — a reader has no way to reconstruct the base later.
        xml.push_str(&format!(
            "    <content type=\"html\"><![CDATA[{}]]></content>\n",
            absolutize_html(&page.rendered_body, &page.dest_filename, base)
        ));
        xml.push_str("  </entry>\n");
    }

    xml.push_str("</feed>\n");
    xml
}

/// Generate an RSS 2.0 feed.
pub fn generate_rss_feed(
    pages: &[PublishedPage],
    site_title: &str,
    base_url: &str,
    site_description: &str,
    _site_author: &str,
) -> String {
    let base = base_url.trim_end_matches('/');

    let items = feed_items(pages);

    // RSS 2.0 dates are RFC 822, which is a different grammar from Atom's —
    // hence the second spelling of the same instants.
    let last_build = items
        .first()
        .and_then(|p| p.modified_date())
        .and_then(to_rfc822)
        .unwrap_or_default();

    let desc = if site_description.is_empty() {
        site_title
    } else {
        site_description
    };

    let mut xml = format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
  <title>{title}</title>
  <link>{base}/</link>
  <description>{description}</description>
  <atom:link href="{base}/rss.xml" rel="self" type="application/rss+xml"/>
"#,
        title = xml_escape(site_title),
        base = xml_escape(base),
        description = xml_escape(desc),
    );

    if !last_build.is_empty() {
        xml.push_str(&format!(
            "  <lastBuildDate>{}</lastBuildDate>\n",
            xml_escape(&last_build)
        ));
    }

    for page in &items {
        let link = format!("{}/{}", base, page.dest_filename);
        let pub_date = page.published_date().and_then(to_rfc822);

        xml.push_str("  <item>\n");
        xml.push_str(&format!("    <title>{}</title>\n", xml_escape(&page.title)));
        xml.push_str(&format!("    <link>{}</link>\n", xml_escape(&link)));
        xml.push_str(&format!(
            "    <guid isPermaLink=\"true\">{}</guid>\n",
            xml_escape(&link)
        ));
        if let Some(pub_date) = pub_date {
            xml.push_str(&format!(
                "    <pubDate>{}</pubDate>\n",
                xml_escape(&pub_date)
            ));
        }
        xml.push_str(&format!(
            "    <description><![CDATA[{}]]></description>\n",
            absolutize_html(&page.rendered_body, &page.dest_filename, base)
        ));
        xml.push_str("  </item>\n");
    }

    xml.push_str("</channel>\n</rss>\n");
    xml
}

/// Strip HTML tags and truncate to `max_len` characters.
fn strip_html_truncate(html: &str, max_len: usize) -> String {
    let mut text = String::new();
    let mut in_tag = false;

    for ch in html.chars() {
        if ch == '<' {
            in_tag = true;
            continue;
        }
        if ch == '>' {
            in_tag = false;
            continue;
        }
        if !in_tag {
            text.push(ch);
            if text.len() >= max_len {
                break;
            }
        }
    }

    text.trim().to_string()
}

/// Escape characters for XML content.
fn xml_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{NavLink, PageLayout, SiteNavNode};
    use std::path::PathBuf;

    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 test_seo_meta_basic() {
        let mut page = make_page("about.html", "About", false);
        page.description = Some("A test page".into());
        page.author = Some("Alice".into());
        let meta = generate_seo_meta(&page, "My Site", "https://example.com");

        assert!(meta.contains(r#"og:title" content="About""#));
        assert!(meta.contains(r#"name="description" content="A test page""#));
        assert!(meta.contains(r#"og:description" content="A test page""#));
        assert!(meta.contains(r#"name="author" content="Alice""#));
        assert!(meta.contains(r#"og:type" content="article""#));
        assert!(meta.contains(r#"og:site_name" content="My Site""#));
        assert!(meta.contains(r#"og:url" content="https://example.com/about.html""#));
        assert!(meta.contains(r#"canonical" href="https://example.com/about.html""#));
    }

    #[test]
    fn test_seo_meta_root_is_website_type() {
        let page = make_page("index.html", "Home", true);
        let meta = generate_seo_meta(&page, "My Site", "https://example.com");
        assert!(meta.contains(r#"og:type" content="website""#));
    }

    #[test]
    fn test_seo_meta_no_base_url() {
        let page = make_page("page.html", "Page", false);
        let meta = generate_seo_meta(&page, "Site", "");
        assert!(!meta.contains("canonical"));
        assert!(!meta.contains("og:url"));
    }

    #[test]
    fn test_sitemap_structure() {
        let root = make_page("index.html", "Home", true);
        let mut child = make_page("child.html", "Child", false);
        child.contents_links = vec![NavLink {
            href: "leaf.html".into(),
            title: "Leaf".into(),
        }];
        let leaf = make_page("leaf.html", "Leaf", false);

        let sitemap = generate_sitemap(&[root, child, leaf], "https://example.com");

        assert!(sitemap.contains("<loc>https://example.com/index.html</loc>"));
        assert!(sitemap.contains("<priority>1.0</priority>")); // root
        assert!(sitemap.contains("<priority>0.8</priority>")); // child with contents
        assert!(sitemap.contains("<priority>0.6</priority>")); // leaf
    }

    #[test]
    fn test_robots_txt_public() {
        let robots = generate_robots_txt("https://example.com", true);
        assert!(robots.contains("Allow: /"));
        assert!(robots.contains("Sitemap: https://example.com/sitemap.xml"));
    }

    #[test]
    fn test_robots_txt_private() {
        let robots = generate_robots_txt("https://example.com", false);
        assert!(robots.contains("Disallow: /"));
        assert!(!robots.contains("Sitemap"));
    }

    #[test]
    fn test_atom_feed_excludes_root_and_index_pages() {
        let root = make_page("index.html", "Home", true);
        let mut index_child = make_page("section.html", "Section", false);
        index_child.contents_links = vec![NavLink {
            href: "leaf.html".into(),
            title: "Leaf".into(),
        }];
        let leaf = make_page("leaf.html", "Leaf", false);

        let atom = generate_atom_feed(
            &[root, index_child, leaf],
            "Site",
            "https://example.com",
            "",
            "",
        );

        // Only the leaf should appear as an entry
        assert_eq!(atom.matches("<entry>").count(), 1);
        assert!(atom.contains("<title>Leaf</title>"));
        assert!(!atom.contains("<title>Home</title>"));
        assert!(!atom.contains("<title>Section</title>"));
    }

    #[test]
    fn test_atom_feed_hide_from_feed() {
        let root = make_page("index.html", "Home", true);
        let mut hidden = make_page("hidden.html", "Hidden", false);
        hidden.hide_from_feed = true;
        let visible = make_page("visible.html", "Visible", false);

        let atom = generate_atom_feed(
            &[root, hidden, visible],
            "Site",
            "https://example.com",
            "",
            "",
        );

        assert_eq!(atom.matches("<entry>").count(), 1);
        assert!(atom.contains("<title>Visible</title>"));
        assert!(!atom.contains("<title>Hidden</title>"));
    }

    #[test]
    fn test_rss_feed_structure() {
        let root = make_page("index.html", "Home", true);
        let mut leaf = make_page("post.html", "Post", false);
        leaf.created = Some("2024-01-15".into());

        let rss = generate_rss_feed(
            &[root, leaf],
            "My Blog",
            "https://example.com",
            "A blog",
            "Author",
        );

        assert!(rss.contains("<title>My Blog</title>"));
        assert!(rss.contains("<description>A blog</description>"));
        assert!(rss.contains("<title>Post</title>"));
        assert!(rss.contains("<guid isPermaLink=\"true\">https://example.com/post.html</guid>"));
        // RFC 822, not the `2024-01-15` the vault wrote: RSS specifies the
        // grammar, and readers hold it to that.
        assert!(
            rss.contains("<pubDate>Mon, 15 Jan 2024 00:00:00 +0000</pubDate>"),
            "got {rss}"
        );
    }

    /// The date chain the site's index groups by, answered the same way by the
    /// feeds. A scanned letter's `date_of_document` is the year it was written
    /// and its `created` is the day it was scanned; the feed used to order by
    /// the latter while the front page listed by the former.
    #[test]
    fn feeds_order_by_the_same_date_chain_the_index_does() {
        let mut letter = make_page("letter.html", "Letter", false);
        letter.date_of_document = Some("1944-06-06".into());
        letter.created = Some("2026-08-16".into());

        let mut note = make_page("note.html", "Note", false);
        note.created = Some("2026-01-02".into());

        let pages = [letter, note];
        let atom = generate_atom_feed(&pages, "Site", "https://ex.com", "", "");

        // The letter is *of* 1944, so it sorts below the 2026 note and is
        // published as its own date rather than its scanning date.
        assert!(
            atom.find("<title>Note</title>") < atom.find("<title>Letter</title>"),
            "got {atom}"
        );
        assert!(atom.contains("<published>1944-06-06T00:00:00Z</published>"));
        assert!(!atom.contains("1944-06-06</published>\n    <published>"));

        let rss = generate_rss_feed(&pages, "Site", "https://ex.com", "", "");
        assert!(rss.contains("<pubDate>Tue, 06 Jun 1944 00:00:00 +0000</pubDate>"));
    }

    /// `date_of_document: unknown` is the marker for a record that is
    /// undated on purpose — a shoebox of scans must not inherit the afternoon
    /// it was imported. The chain stops at the marker correctly, but a
    /// descending sort of the *raw* string put `"unknown"` above every ISO
    /// date, so the undated scans headed the feed wearing a 1970 timestamp.
    #[test]
    fn a_deliberately_undated_record_sorts_to_the_bottom() {
        let mut undated = make_page("undated.html", "Undated", false);
        undated.date_of_document = Some("unknown".into());
        // Pre-epoch on purpose. Normalizing an unreadable date to
        // `EPOCH_RFC3339` and sorting on that would place the undated scan
        // *above* this letter, because the epoch is not a floor — it is 1970,
        // and an archive of a family's papers is mostly older than that.
        let mut old = make_page("old.html", "Old", false);
        old.date_of_document = Some("1943-05-12".into());
        let mut new = make_page("new.html", "New", false);
        new.date_of_document = Some("2026-08-16".into());

        let pages = [undated, old, new];
        let atom = generate_atom_feed(&pages, "Site", "https://ex.com", "", "");

        let at = |t: &str| atom.find(&format!("<title>{t}</title>")).unwrap();
        assert!(
            at("New") < at("Old") && at("Old") < at("Undated"),
            "newest first, and the undated record last: {atom}"
        );
        // Where it sorts and what it says agree: 1970 sorts like 1970.
        assert!(!atom.contains("<published>unknown</published>"));
    }

    /// Nothing validates a `type: date` field, so a typo and a human spelling
    /// reach the feed the same way the marker does — and used to sort by their
    /// own first character, above or below the ISO dates by accident.
    #[test]
    fn an_unparseable_date_does_not_sort_by_its_spelling() {
        let mut wordy = make_page("wordy.html", "Wordy", false);
        wordy.date_of_document = Some("May 1943".into());
        let mut typo = make_page("typo.html", "Typo", false);
        typo.date_of_document = Some("19430512".into());
        let mut dated = make_page("dated.html", "Dated", false);
        dated.date_of_document = Some("2026-08-16".into());

        let pages = [wordy, typo, dated];
        let atom = generate_atom_feed(&pages, "Site", "https://ex.com", "", "");

        let at = |t: &str| atom.find(&format!("<title>{t}</title>")).unwrap();
        assert!(
            at("Dated") < at("Typo") && at("Dated") < at("Wordy"),
            "the only readable date leads: {atom}"
        );
    }

    /// Atom makes `<updated>` mandatory on the feed and on every entry, so an
    /// entry the vault gave no date at all still has to carry one.
    #[test]
    fn an_undated_entry_still_carries_a_valid_atom_updated() {
        let page = make_page("post.html", "Post", false);
        let atom = generate_atom_feed(&[page], "Site", "https://ex.com", "", "");

        assert!(atom.contains(&format!("<updated>{EPOCH_RFC3339}</updated>")));
        // …but not a `<published>` it would have had to invent.
        assert!(!atom.contains("<published>"));
    }

    /// A date the vault wrote in a spelling no feed grammar recognizes is left
    /// out rather than passed through for a validator to choke on.
    #[test]
    fn an_unreadable_date_is_omitted_not_forwarded() {
        let mut page = make_page("post.html", "Post", false);
        page.created = Some("sometime last summer".into());

        let atom = generate_atom_feed(&[page.clone()], "Site", "https://ex.com", "", "");
        assert!(!atom.contains("sometime last summer"));
        assert!(atom.contains(&format!("<updated>{EPOCH_RFC3339}</updated>")));

        let rss = generate_rss_feed(&[page.clone()], "Site", "https://ex.com", "", "");
        assert!(!rss.contains("sometime last summer"));
        assert!(!rss.contains("<pubDate>"));

        let sitemap = generate_sitemap(&[page.clone()], "https://ex.com");
        assert!(!sitemap.contains("<lastmod>"));

        let meta = generate_seo_meta(&page, "Site", "https://ex.com");
        assert!(!meta.contains("article:published_time"));
    }

    /// A sitemap's `lastmod` is a W3C Datetime, which RFC 3339 satisfies and a
    /// bare vault date does not reliably.
    #[test]
    fn sitemap_lastmod_is_a_w3c_datetime() {
        let mut page = make_page("post.html", "Post", false);
        page.updated = Some("2026-08-16".into());
        let sitemap = generate_sitemap(&[page], "https://ex.com");
        assert!(sitemap.contains("<lastmod>2026-08-16T00:00:00Z</lastmod>"));
    }

    /// Open Graph asks for RFC 3339 here too, and the published time follows
    /// the same chain the feeds do.
    #[test]
    fn seo_article_times_are_rfc3339_from_the_shared_chain() {
        let mut page = make_page("post.html", "Post", false);
        page.date_of_document = Some("2026-01-15".into());
        page.created = Some("2026-08-16".into());
        page.updated = Some("2026-08-20".into());

        let meta = generate_seo_meta(&page, "Site", "https://ex.com");
        assert!(meta.contains(r#"article:published_time" content="2026-01-15T00:00:00Z""#));
        assert!(meta.contains(r#"article:modified_time" content="2026-08-20T00:00:00Z""#));
    }

    #[test]
    fn feed_content_carries_absolute_links_and_images() {
        // A feed entry is read away from the site — in a reader, or in an email
        // built from the feed — where a page-relative href resolves to nothing.
        let root = make_page("index.html", "Home", true);
        let mut leaf = make_page("notes/entry.html", "Entry", false);
        leaf.rendered_body =
            r#"<p><a href="../other.html">o</a><img src="../_attachments/a.jpg"></p>"#.to_string();

        let pages = [root, leaf];
        let atom = generate_atom_feed(&pages, "Site", "https://ex.com", "", "");
        assert!(atom.contains(r#"href="https://ex.com/other.html""#));
        assert!(atom.contains(r#"src="https://ex.com/_attachments/a.jpg""#));
        assert!(!atom.contains(r#"href="../other.html""#));

        let rss = generate_rss_feed(&pages, "Site", "https://ex.com", "", "");
        assert!(rss.contains(r#"href="https://ex.com/other.html""#));
        assert!(rss.contains(r#"src="https://ex.com/_attachments/a.jpg""#));
    }

    // ── The sidebar ─────────────────────────────────────────────────────────

    fn nav_node(href: &str, children: Vec<SiteNavNode>) -> SiteNavNode {
        SiteNavNode {
            title: href.trim_end_matches(".html").to_string(),
            href: href.to_string(),
            is_current: false,
            is_ancestor_of_current: false,
            children,
        }
    }

    /// A tree rooted at the front page, with the reader on `b/leaf.html`.
    fn rooted_nav() -> SiteNavigation {
        let mut leaf = nav_node("b/leaf.html", vec![]);
        leaf.is_current = true;
        let mut b = nav_node("b.html", vec![leaf]);
        b.is_ancestor_of_current = true;
        let c = nav_node("c.html", vec![nav_node("c/kid.html", vec![])]);
        let mut root = nav_node("index.html", vec![nav_node("a.html", vec![]), b, c]);
        root.is_ancestor_of_current = true;
        SiteNavigation {
            tree: vec![root],
            breadcrumbs: vec![],
        }
    }

    /// The front page is the masthead, not the first row: the list starts at
    /// its children, so an entry sits at the depth it has.
    #[test]
    fn the_front_page_leaves_the_tree_for_the_masthead() {
        let html = render_site_nav(&rooted_nav(), "My Site", "../");
        assert!(
            html.contains(r#"<a class="site-masthead" href="../index.html">My Site</a>"#),
            "got {html}"
        );
        assert!(
            html.starts_with(r#"<input class="nav-toggle-state""#),
            "the drawer's state comes first, then the bar: {html}"
        );
        assert!(
            html.contains(r#"<nav class="site-nav" id="site-nav" aria-label="Site navigation">"#),
            "got {html}"
        );
        // The root's children are the top of the list, and `index.html` is
        // not a row anywhere in it.
        assert!(html.contains(r#"<ul class="nav-list"><li><a href="../a.html">a</a></li>"#));
        assert_eq!(
            html.matches("index.html").count(),
            2,
            "bar and sidebar mastheads only"
        );
        // The toggle is a checkbox ahead of both the bar and the drawer, so
        // `:checked ~` reaches them without a script.
        let state = html
            .find(r#"<input class="nav-toggle-state" type="checkbox" id="nav-toggle""#)
            .expect("the drawer state precedes the bar");
        let bar = html.find(r#"<header class="site-bar">"#).unwrap();
        let nav = html.find(r#"<nav class="site-nav""#).unwrap();
        assert!(state < bar && bar < nav, "got {html}");
        assert!(
            html.contains(r#"<label class="nav-toggle" for="nav-toggle">Menu</label>"#),
            "got {html}"
        );
    }

    /// The masthead is the current page on the front page, and nothing else
    /// is.
    #[test]
    fn the_masthead_is_current_on_the_front_page() {
        let mut nav = rooted_nav();
        nav.tree[0].is_current = true;
        nav.tree[0].is_ancestor_of_current = false;
        let html = render_site_nav(&nav, "My Site", "");
        assert!(
            html.contains(
                r#"<a class="site-masthead" href="index.html" aria-current="page">My Site</a>"#
            ),
            "got {html}"
        );
        let elsewhere = render_site_nav(&rooted_nav(), "My Site", "../");
        assert!(!elsewhere.contains(r#"site-masthead" href="../index.html" aria-current"#));
    }

    /// A node with children is a disclosure, open on the current page's
    /// branch and closed elsewhere — and the link is the summary's content, so
    /// the title navigates and the chevron opens.
    #[test]
    fn sections_are_disclosures_open_along_the_current_branch() {
        let html = render_site_nav(&rooted_nav(), "My Site", "../");
        assert!(
            html.contains(
                r#"<li class="nav-section nav-ancestor"><details open><summary><a href="../b.html">b</a></summary><ul class="nav-list"><li class="nav-current"><a href="../b/leaf.html" aria-current="page">b/leaf</a></li></ul></details></li>"#
            ),
            "the ancestor is open: {html}"
        );
        assert!(
            html.contains(
                r#"<li class="nav-section"><details><summary><a href="../c.html">c</a></summary>"#
            ),
            "the other section is closed: {html}"
        );
    }

    /// The current page's own section is open too, so a reader landing on a
    /// section's page sees what is under it.
    #[test]
    fn the_current_sections_own_disclosure_is_open() {
        let mut nav = rooted_nav();
        let root = &mut nav.tree[0];
        root.children[1].children[0].is_current = false;
        root.children[1].is_ancestor_of_current = false;
        root.children[1].is_current = true;
        let html = render_site_nav(&nav, "My Site", "");
        assert!(
            html.contains(
                r#"<li class="nav-section nav-current"><details open><summary><a href="b.html" aria-current="page">b</a></summary>"#
            ),
            "got {html}"
        );
    }

    /// A rootless forest lists as it stands, under a masthead that still
    /// links home — and a lone forest root is not mistaken for a front page.
    #[test]
    fn a_forest_lists_under_the_masthead() {
        let nav = SiteNavigation {
            tree: vec![nav_node(
                "daily.html",
                vec![nav_node("daily/mon.html", vec![])],
            )],
            breadcrumbs: vec![],
        };
        let html = render_site_nav(&nav, "Notes", "");
        assert!(html.contains(r#"<a class="site-masthead" href="index.html">Notes</a>"#));
        assert!(
            html.contains(r#"<summary><a href="daily.html">daily</a></summary>"#),
            "the forest root is a row: {html}"
        );
    }

    #[test]
    fn an_empty_tree_renders_no_nav_at_all() {
        let nav = SiteNavigation {
            tree: vec![],
            breadcrumbs: vec![],
        };
        assert_eq!(render_site_nav(&nav, "My Site", ""), "");
    }

    // ── The pager ───────────────────────────────────────────────────────────

    #[test]
    fn the_pager_links_the_neighbours_in_reading_order() {
        let order = crate::nav::reading_order(&rooted_nav().tree);
        let hrefs: Vec<&str> = order.iter().map(|l| l.href.as_str()).collect();
        assert_eq!(
            hrefs,
            [
                "index.html",
                "a.html",
                "b.html",
                "b/leaf.html",
                "c.html",
                "c/kid.html"
            ]
        );

        let middle = render_pager(&order, "b/leaf.html", "../");
        assert_eq!(
            middle,
            r#"<nav class="pager" aria-label="Pager"><a class="pager-prev" rel="prev" href="../b.html"><span>Previous</span> b</a><a class="pager-next" rel="next" href="../c.html"><span>Next</span> c</a></nav>"#
        );
        let first = render_pager(&order, "index.html", "");
        assert!(!first.contains("pager-prev"), "{first}");
        assert!(first.contains(r#"rel="next" href="a.html""#), "{first}");
        let last = render_pager(&order, "c/kid.html", "../");
        assert!(last.contains(r#"rel="prev" href="../c.html""#), "{last}");
        assert!(!last.contains("pager-next"), "{last}");
    }

    /// A page the nav does not hold is in no sequence, and a site of one page
    /// has nowhere to go.
    #[test]
    fn a_page_outside_the_order_gets_no_pager() {
        let order = crate::nav::reading_order(&rooted_nav().tree);
        assert_eq!(render_pager(&order, "hidden.html", ""), "");
        let alone = crate::nav::reading_order(&[nav_node("index.html", vec![])]);
        assert_eq!(render_pager(&alone, "index.html", ""), "");
    }

    #[test]
    fn test_feed_links() {
        let links = generate_feed_link_tags("");
        assert!(links.contains("application/atom+xml"));
        assert!(links.contains("feed.xml"));
        assert!(links.contains("application/rss+xml"));
        assert!(links.contains("rss.xml"));
    }

    #[test]
    fn test_strip_html_truncate() {
        let html = "<p>Hello <strong>world</strong>, this is a test.</p>";
        let result = strip_html_truncate(html, 11);
        assert_eq!(result, "Hello world");
    }
}