autumn-web 0.10.0

An opinionated, convention-over-configuration web framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
//! Widget story gallery: a browsable `/_stories` UI plus a CI anti-rot
//! registry for the built-in maud widgets (issue #1526).
//!
//! Mirrors the mail-preview registry precedent (`crate::mail::MailPreview` /
//! `MailPreviewRegistry`): each story is a zero-arg pure `fn() -> Markup`
//! paired with the source snippet that produced it, collected into a
//! `StoryRegistry` served at `GET /_stories` (grouped index) and
//! `GET /_stories/{slug}` (live render + Source + Rendered HTML tabs).
//!
//! Two switches gate the gallery:
//!
//! 1. **Registration** — `AppBuilder::with_story_gallery(StoryGallery::builtin())`
//!    installs the [`StoryRegistry`](crate::stories::StoryRegistry) on
//!    [`AppState`](crate::AppState).
//! 2. **Config** — the routes mount only when the resolved config has
//!    `[stories] enabled = true` ([`StoriesConfig`](crate::stories::StoriesConfig),
//!    default **false**).
//!    Unlike the dev-only mail preview, stories may be enabled in *any*
//!    profile (a public showcase is a supported use); safe because stories
//!    only ever render synthetic demo data.
//!
//! Author stories with the [`story!`](crate::stories::story) macro — its
//! block is both executed for the live render and captured byte-for-byte as
//! the displayed snippet. See `docs/guide/stories.md`.

use std::sync::Arc;

use axum::response::{Html, IntoResponse, Response};
use serde::Deserialize;
use thiserror::Error;

use crate::AppState;

/// Author a widget story: `story!{ "Group", "Name", { ... } }`.
pub use autumn_macros::story;

mod builtin;

/// Stable root path for the widget story gallery.
pub const STORIES_PATH: &str = "/_stories";

/// Route template for a single story's detail page.
const STORY_DETAIL_PATH: &str = "/_stories/{slug}";

/// Demo backend for the "Active search" story. See [`demo_search`].
#[cfg(feature = "widgets-search")]
const STORIES_DEMO_SEARCH_PATH: &str = "/_stories/demo/search";

/// Demo backend for the busy states in the "Button", "Spinner" and
/// "Skeleton" stories (#3406). See [`demo_save`].
const STORIES_DEMO_SAVE_PATH: &str = "/_stories/demo/save";

/// How long [`demo_save`] waits, so the busy state is visible.
const STORIES_DEMO_SAVE_DELAY: std::time::Duration = std::time::Duration::from_millis(800);

/// Demo backend for the "Autocomplete" story. See [`demo_tag_search`].
#[cfg(feature = "widgets-search")]
const STORIES_DEMO_TAG_SEARCH_PATH: &str = "/_stories/demo/tags/search";
/// Demo backend for the "Tags input" story (#3410). See [`demo_tag_suggest`].
#[cfg(feature = "widgets-search")]
const STORIES_DEMO_TAG_SUGGEST_PATH: &str = "/_stories/demo/tags/suggest";

/// Demo backend for the "Tags input" story (#3410), mounted at
/// [`STORIES_DEMO_TAG_SUGGEST_PATH`]. It returns the tags that contain `q`.
/// The value of each option is its name. When no tag has the exact name,
/// it adds a [`autocomplete_create_option`](crate::widgets::autocomplete_create_option).
#[cfg(feature = "widgets-search")]
async fn demo_tag_suggest(
    crate::extract::Query(DemoQuery { q }): crate::extract::Query<DemoQuery>,
) -> Html<String> {
    const TAGS: &[&str] = &["rust", "web", "axum", "htmx"];
    let typed = q.trim();
    let query = typed.to_lowercase();
    let matches: Vec<&str> = TAGS
        .iter()
        .copied()
        .filter(|tag| !query.is_empty() && tag.contains(&query))
        .collect();
    let exact = matches.contains(&query.as_str());
    let markup = maud::html! {
        @for tag in &matches {
            (crate::widgets::autocomplete_option(tag, tag))
        }
        @if !typed.is_empty() && !exact {
            (crate::widgets::autocomplete_create_option(
                typed,
                &format!("Create \u{201c}{typed}\u{201d}"),
            ))
        }
    };
    Html(markup.into_string())
}

/// Demo backend for the "Infinite feed" story's sentinel. See
/// [`demo_infinite_feed`].
#[cfg(feature = "widgets-social")]
const STORIES_DEMO_FEED_PATH: &str = "/_stories/demo/posts/feed";

/// Derive a URL slug from a story name: lowercase, alphanumeric runs joined
/// by single `-`, everything else (punctuation, whitespace, non-ASCII)
/// treated as a separator.
fn slugify(name: &str) -> String {
    let mut slug = String::with_capacity(name.len());
    let mut pending_separator = false;
    for c in name.chars() {
        if c.is_ascii_alphanumeric() {
            if pending_separator && !slug.is_empty() {
                slug.push('-');
            }
            pending_separator = false;
            slug.push(c.to_ascii_lowercase());
        } else {
            pending_separator = true;
        }
    }
    slug
}

/// A zero-arg, pure widget render example shown in the `/_stories` gallery.
///
/// Construct with the [`story!`](crate::stories::story) macro, which captures
/// the render block's source text so the displayed snippet is provably the
/// code that rendered. `render` is a plain `fn() -> Markup` pointer: no `Db`,
/// no `AppState`, no request data can be smuggled in.
#[derive(Clone)]
pub struct Story {
    group: &'static str,
    name: &'static str,
    slug: String,
    render: fn() -> maud::Markup,
    source: &'static str,
}

impl std::fmt::Debug for Story {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Story")
            .field("group", &self.group)
            .field("name", &self.name)
            .field("slug", &self.slug)
            .finish_non_exhaustive()
    }
}

impl Story {
    /// Register a story. Prefer the [`story!`](crate::stories::story) macro,
    /// which fills in `source` from the render block automatically.
    ///
    /// # Panics
    ///
    /// Panics when `name` produces an empty URL slug (e.g. a name made
    /// entirely of punctuation) — a programmer error better caught loudly at
    /// construction time than as a broken route.
    #[must_use]
    pub fn new(
        group: &'static str,
        name: &'static str,
        render: fn() -> maud::Markup,
        source: &'static str,
    ) -> Self {
        let slug = slugify(name);
        assert!(
            !slug.is_empty(),
            "story name {name:?} (group {group:?}) produces an empty slug; \
             use a name with at least one alphanumeric character"
        );
        Self {
            group,
            name,
            slug,
            render,
            source,
        }
    }

    /// Sidebar group this story is listed under.
    #[must_use]
    pub const fn group(&self) -> &'static str {
        self.group
    }

    /// Human-readable story name.
    #[must_use]
    pub const fn name(&self) -> &'static str {
        self.name
    }

    /// URL slug derived from the name (`/_stories/{slug}`).
    #[must_use]
    pub fn slug(&self) -> &str {
        &self.slug
    }

    /// Source snippet that produced the render (shown in the Source tab).
    #[must_use]
    pub const fn source(&self) -> &'static str {
        self.source
    }

    /// Render the story's markup.
    ///
    /// # Errors
    ///
    /// Returns [`StoryRenderError::Panicked`] when the render function
    /// panics, so one broken story cannot unwind through the gallery.
    pub fn render(&self) -> Result<maud::Markup, StoryRenderError> {
        std::panic::catch_unwind(self.render).map_err(|_| StoryRenderError::Panicked {
            slug: self.slug.clone(),
        })
    }
}

/// Story gallery render errors.
#[derive(Debug, Error)]
pub enum StoryRenderError {
    /// The story's render function panicked.
    #[error("story `{slug}` panicked while rendering")]
    Panicked {
        /// Slug of the panicking story.
        slug: String,
    },
}

/// Immutable collection of registered stories, stored on
/// [`AppState`] as an extension by
/// [`AppBuilder::with_story_gallery`](crate::app::AppBuilder::with_story_gallery).
#[derive(Debug, Clone, Default)]
pub struct StoryRegistry {
    stories: Arc<Vec<Story>>,
    /// Extra stylesheet URLs each gallery page links (#3400).
    stylesheets: Arc<Vec<String>>,
    /// Extra script URLs each gallery page loads with `defer` (#3400).
    scripts: Arc<Vec<String>>,
}

impl StoryRegistry {
    /// Create a registry from story registrations.
    ///
    /// # Panics
    ///
    /// Panics when two stories share a slug (slugs derive from names), since
    /// one would shadow the other in routing — rename one of the stories.
    #[must_use]
    pub fn new(stories: Vec<Story>) -> Self {
        let mut seen: std::collections::HashMap<&str, &Story> = std::collections::HashMap::new();
        for story in &stories {
            if let Some(existing) = seen.insert(story.slug(), story) {
                panic!(
                    "duplicate story slug `{}`: `{}` / `{}` collides with `{}` / `{}`; \
                     story slugs derive from names, so rename one of them",
                    story.slug(),
                    existing.group(),
                    existing.name(),
                    story.group(),
                    story.name(),
                );
            }
        }
        Self {
            stories: Arc::new(stories),
            stylesheets: Arc::default(),
            scripts: Arc::default(),
        }
    }

    /// Registered stories, in registration order.
    #[must_use]
    pub fn stories(&self) -> &[Story] {
        &self.stories
    }

    /// Extra stylesheet URLs that each gallery page links, after the core
    /// widget stylesheet.
    #[must_use]
    pub fn stylesheets(&self) -> &[String] {
        &self.stylesheets
    }

    /// Extra script URLs that each gallery page loads with `defer`, after
    /// the widget runtime.
    #[must_use]
    pub fn scripts(&self) -> &[String] {
        &self.scripts
    }

    /// Look a story up by its URL slug.
    fn find(&self, slug: &str) -> Option<&Story> {
        self.stories.iter().find(|story| story.slug() == slug)
    }

    /// Stories grouped for the index sidebar: groups in first-seen order,
    /// stories in registration order within each group (deterministic,
    /// author-controlled).
    fn grouped(&self) -> Vec<(&'static str, Vec<&Story>)> {
        let mut grouped: Vec<(&'static str, Vec<&Story>)> = Vec::new();
        for story in self.stories.iter() {
            match grouped
                .iter_mut()
                .find(|(group, _)| *group == story.group())
            {
                Some((_, stories)) => stories.push(story),
                None => grouped.push((story.group(), vec![story])),
            }
        }
        grouped
    }
}

/// Registry of every built-in widget story: >=1 story per gallery-visible
/// widget in [`crate::widgets`], enforced by the CI coverage gate
/// (`autumn/tests/integration/stories.rs`).
#[must_use]
pub fn builtin() -> StoryRegistry {
    StoryRegistry::new(builtin::all_stories())
}

/// Builder-side collection of stories, registered with
/// [`AppBuilder::with_story_gallery`](crate::app::AppBuilder::with_story_gallery).
///
/// Start from [`StoryGallery::builtin`] to serve the framework widget set,
/// or [`StoryGallery::new`] for an app-only gallery, then [`extend`](Self::extend)
/// with stories authored via the [`story!`](crate::stories::story) macro.
#[derive(Debug, Clone, Default)]
pub struct StoryGallery {
    stories: Vec<Story>,
    stylesheets: Vec<String>,
    scripts: Vec<String>,
}

impl StoryGallery {
    /// Create an empty, builtin-free gallery (app stories only).
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a gallery seeded with every built-in widget story.
    #[must_use]
    pub fn builtin() -> Self {
        Self {
            stories: builtin::all_stories(),
            ..Self::default()
        }
    }

    /// Append stories (e.g. custom app widgets authored with
    /// [`story!`](crate::stories::story)).
    #[must_use]
    pub fn extend(mut self, stories: impl IntoIterator<Item = Story>) -> Self {
        self.stories.extend(stories);
        self
    }

    /// Link the stylesheet at `href` on each gallery page.
    ///
    /// The link comes after the core widget stylesheet. A widget pack uses this for its own CSS. A second
    /// call with the same `href` does nothing.
    #[must_use]
    pub fn stylesheet(mut self, href: impl Into<String>) -> Self {
        push_unique(&mut self.stylesheets, href.into());
        self
    }

    /// Load the script at `src` with `defer` on each gallery page.
    ///
    /// The script comes after the widget runtime. A widget pack uses this for its own JS. A second call
    /// with the same `src` does nothing.
    #[must_use]
    pub fn script(mut self, src: impl Into<String>) -> Self {
        push_unique(&mut self.scripts, src.into());
        self
    }

    /// Add the stories and the asset links of `other` after the ones in
    /// `self`. Duplicate story slugs panic later, when the registry is built.
    #[must_use]
    pub fn merge(mut self, other: Self) -> Self {
        self.stories.extend(other.stories);
        for href in other.stylesheets {
            push_unique(&mut self.stylesheets, href);
        }
        for src in other.scripts {
            push_unique(&mut self.scripts, src);
        }
        self
    }

    /// Stories collected so far, in registration order.
    #[must_use]
    pub fn stories(&self) -> &[Story] {
        &self.stories
    }

    /// Extra stylesheet URLs, in registration order.
    #[must_use]
    pub fn stylesheets(&self) -> &[String] {
        &self.stylesheets
    }

    /// Extra script URLs, in registration order.
    #[must_use]
    pub fn scripts(&self) -> &[String] {
        &self.scripts
    }

    /// The gallery's axum sub-router (`GET /_stories`, `GET /_stories/{slug}`).
    ///
    /// The framework mounts this automatically when the resolved config has
    /// `[stories] enabled = true`; handlers read the [`StoryRegistry`] from
    /// the [`AppState`] extension installed by
    /// [`AppBuilder::with_story_gallery`](crate::app::AppBuilder::with_story_gallery),
    /// so manual mounters must install that extension too.
    pub fn routes<S>() -> axum::Router<S>
    where
        S: Clone + Send + Sync + 'static,
        AppState: axum::extract::FromRef<S>,
    {
        story_router()
    }

    /// Freeze the gallery into the registry stored on `AppState`.
    ///
    /// # Panics
    ///
    /// Panics on duplicate slugs — see [`StoryRegistry::new`].
    pub(crate) fn into_registry(self) -> StoryRegistry {
        StoryRegistry {
            stylesheets: Arc::new(self.stylesheets),
            scripts: Arc::new(self.scripts),
            ..StoryRegistry::new(self.stories)
        }
    }
}

/// Push `value` when `list` does not hold it yet.
fn push_unique(list: &mut Vec<String>, value: String) {
    if !list.contains(&value) {
        list.push(value);
    }
}

/// Widget story gallery settings (`[stories]` section in `autumn.toml`).
///
/// **Off by default, opt-in in any profile** — unlike the dev-only mail
/// preview, a public showcase is a supported use (stories only ever render
/// synthetic demo data). Profile overrides come free from the standard
/// config layering, and `AUTUMN_STORIES__ENABLED` overrides from the
/// environment:
///
/// ```toml
/// [stories]
/// enabled = false
///
/// # Dev-only gallery: mounted under `autumn dev`, 404 in prod.
/// [profile.dev.stories]
/// enabled = true
/// ```
#[derive(Debug, Clone, Default, Deserialize)]
pub struct StoriesConfig {
    /// Whether the `/_stories` gallery routes are mounted. Default `false`.
    #[serde(default)]
    pub enabled: bool,
}

/// Path and handler name of each demo backend that [`story_router`] mounts.
/// The route listing and the router's path reservation read this list. A
/// router test checks that each path in it is mounted. A family's demo routes
/// exist only when its feature is on (#3408).
pub(crate) fn demo_routes() -> Vec<(&'static str, &'static str)> {
    #[allow(unused_mut, reason = "each family extend has its own #[cfg]")]
    let mut routes = vec![(STORIES_DEMO_SAVE_PATH, "story_gallery_demo_save")];
    #[cfg(feature = "widgets-search")]
    routes.extend([
        (STORIES_DEMO_SEARCH_PATH, "story_gallery_demo_search"),
        (
            STORIES_DEMO_TAG_SEARCH_PATH,
            "story_gallery_demo_tag_search",
        ),
        (
            STORIES_DEMO_TAG_SUGGEST_PATH,
            "story_gallery_demo_tag_suggest",
        ),
    ]);
    #[cfg(feature = "widgets-social")]
    routes.push((STORIES_DEMO_FEED_PATH, "story_gallery_demo_infinite_feed"));
    routes
}

/// Build the gallery sub-router. Mounted by `build_router` when
/// `config.stories.enabled` is true; handlers read the [`StoryRegistry`]
/// from the `AppState` extension (mail-preview precedent).
pub(crate) fn story_router<S>() -> axum::Router<S>
where
    S: Clone + Send + Sync + 'static,
    AppState: axum::extract::FromRef<S>,
{
    let router = axum::Router::new()
        .route(
            STORIES_PATH,
            axum::routing::get(
                |axum::extract::State(state): axum::extract::State<AppState>,
                 nonce: Option<crate::security::CspNonce>| async move {
                    story_index_response(&state, nonce.as_ref())
                },
            ),
        )
        .route(
            STORY_DETAIL_PATH,
            axum::routing::get(
                |axum::extract::Path(slug): axum::extract::Path<String>,
                 axum::extract::State(state): axum::extract::State<AppState>,
                 nonce: Option<crate::security::CspNonce>| async move {
                    story_detail_response(&state, &slug, nonce.as_ref())
                },
            ),
        )
        .route(STORIES_DEMO_SAVE_PATH, axum::routing::get(demo_save));
    // Demo backends for the two typeahead stories (Active search,
    // Autocomplete) — see `demo_search`/`demo_tag_search` below for why
    // these two specifically get real handlers where every other
    // story's action URL stays a synthetic 404-on-submit (already the
    // documented pattern for e.g. Confirm action / Avatar). Namespaced
    // under `/_stories/demo/*`, the same convention `confirm_action`'s
    // story already uses (`/_stories/demo/delete-post`), so a real app's
    // own routes can never collide with these. A family's demo routes
    // exist only when its feature is on (#3408).
    #[cfg(feature = "widgets-search")]
    let router = router
        .route(STORIES_DEMO_SEARCH_PATH, axum::routing::get(demo_search))
        .route(
            STORIES_DEMO_TAG_SEARCH_PATH,
            axum::routing::get(demo_tag_search),
        )
        .route(
            STORIES_DEMO_TAG_SUGGEST_PATH,
            axum::routing::get(demo_tag_suggest),
        );
    #[cfg(feature = "widgets-social")]
    let router = router.route(
        STORIES_DEMO_FEED_PATH,
        axum::routing::get(demo_infinite_feed),
    );
    router
}

/// The backend of the busy-state demos (#3406): it waits, then answers
/// "Saved.". The wait lets a visitor see `aria-busy`, the button spinner
/// and the `hx-indicator` skeleton. It is a GET, so it needs no CSRF token
/// and changes nothing.
async fn demo_save() -> Html<&'static str> {
    tokio::time::sleep(STORIES_DEMO_SAVE_DELAY).await;
    Html("Saved.")
}

/// Query params `demo_search` and `demo_tag_search` both accept — the `q`
/// param [`ActiveSearchConfig`](crate::widgets::ActiveSearchConfig) and
/// [`AutocompleteConfig`](crate::widgets::AutocompleteConfig) both default
/// `param_name`/`query_param` to.
#[derive(serde::Deserialize)]
#[cfg(feature = "widgets-search")]
struct DemoQuery {
    #[serde(default)]
    q: String,
}

/// Demo backend for the "Active search" story's action — mounted at
/// [`STORIES_DEMO_SEARCH_PATH`]. Filters a small fixed post list
/// case-insensitively by `q`, returning the same
/// [`active_search_empty_state`](crate::widgets::active_search_empty_state)
/// the story documents for the no-matches case.
#[cfg(feature = "widgets-search")]
async fn demo_search(
    crate::extract::Query(DemoQuery { q }): crate::extract::Query<DemoQuery>,
) -> Html<String> {
    const POSTS: &[&str] = &[
        "The Long Autumn",
        "Falling Leaves",
        "Autumn in Practice",
        "Shipping Widgets",
    ];
    let query = q.to_lowercase();
    let matches: Vec<&str> = POSTS
        .iter()
        .copied()
        .filter(|title| query.is_empty() || title.to_lowercase().contains(&query))
        .collect();
    let markup = if matches.is_empty() {
        crate::widgets::active_search_empty_state("No posts matched your search.")
    } else {
        maud::html! {
            ul class="story-demo-results" {
                @for title in matches {
                    li { (title) }
                }
            }
        }
    };
    Html(markup.into_string())
}

/// Demo backend for the "Autocomplete" story's `/tags/search`-shaped action
/// — mounted at [`STORIES_DEMO_TAG_SEARCH_PATH`]. Filters a small fixed tag
/// list case-insensitively by the `q` query param, rendering matches with
/// the same [`autocomplete_option`](crate::widgets::autocomplete_option) /
/// [`autocomplete_empty_state`](crate::widgets::autocomplete_empty_state)
/// the story's source already documents.
#[cfg(feature = "widgets-search")]
async fn demo_tag_search(
    crate::extract::Query(DemoQuery { q }): crate::extract::Query<DemoQuery>,
) -> Html<String> {
    const TAGS: &[(&str, &str)] = &[("42", "rust"), ("7", "web"), ("13", "axum"), ("21", "htmx")];
    let query = q.to_lowercase();
    let matches: Vec<(&str, &str)> = TAGS
        .iter()
        .copied()
        .filter(|(_, label)| query.is_empty() || label.to_lowercase().contains(&query))
        .collect();
    let markup = if matches.is_empty() {
        crate::widgets::autocomplete_empty_state("No matching tags.")
    } else {
        maud::html! {
            @for (value, label) in matches {
                (crate::widgets::autocomplete_option(value, label))
            }
        }
    };
    Html(markup.into_string())
}

/// Demo backend for the "Infinite feed" story's sentinel — mounted at
/// [`STORIES_DEMO_FEED_PATH`].
///
/// Exists only so loading `htmx.min.js` (needed for the two typeahead
/// demos above) doesn't turn this *specific* story into a visible
/// regression: unlike every other action URL in the gallery, this one's
/// [`FeedMode::Reveal`](crate::widgets::FeedMode::Reveal) sentinel fires
/// `hx-trigger="revealed, click"` — htmx auto-requests it the moment the
/// element scrolls into view, no click required, so visiting the story page
/// alone would have 404-swapped it without the visitor doing anything. This
/// always returns a terminal page (no further cursor), matching what the
/// story's own `feed_page` snippet already documents as "the last page".
#[cfg(feature = "widgets-social")]
async fn demo_infinite_feed() -> Html<String> {
    let markup = crate::widgets::feed_page(
        maud::html! {
            article class="post" { h3 { "Loaded live via a real request." } }
        },
        None,
        &crate::widgets::FeedConfig::new(STORIES_DEMO_FEED_PATH),
    );
    Html(markup.into_string())
}

fn registry_from_state(state: &AppState) -> StoryRegistry {
    state
        .extension::<StoryRegistry>()
        .map(|registry| (*registry).clone())
        .unwrap_or_default()
}

fn story_index_response(state: &AppState, nonce: Option<&crate::security::CspNonce>) -> Response {
    Html(render_story_index(&registry_from_state(state), nonce).into_string()).into_response()
}

fn story_detail_response(
    state: &AppState,
    slug: &str,
    nonce: Option<&crate::security::CspNonce>,
) -> Response {
    let registry = registry_from_state(state);
    let Some(story) = registry.find(slug) else {
        let page = story_page(
            &registry,
            "Story not found",
            &maud::html! {
                main class="story-content" {
                    h1 { "Story not found" }
                    p {
                        "No story is registered under the slug " code { (slug) } ". "
                        a href=(STORIES_PATH) { "Back to the gallery" }
                    }
                }
            },
            nonce,
        );
        return (http::StatusCode::NOT_FOUND, Html(page.into_string())).into_response();
    };

    match story.render() {
        Ok(rendered) => Html(render_story_detail(&registry, story, &rendered, nonce).into_string())
            .into_response(),
        Err(error) => {
            let page = story_page(
                &registry,
                "Story failed to render",
                &maud::html! {
                    main class="story-content" {
                        h1 { "Story failed to render" }
                        p { (error.to_string()) }
                        p { a href=(STORIES_PATH) { "Back to the gallery" } }
                    }
                },
                nonce,
            );
            (
                http::StatusCode::INTERNAL_SERVER_ERROR,
                Html(page.into_string()),
            )
                .into_response()
        }
    }
}

/// Gallery chrome layered on top of the framework widget stylesheet
/// (`WIDGETS_CSS_PATH`, linked before this `<style>` in `<head>`, so this
/// block's declarations win the cascade at equal specificity).
///
/// The chrome uses the shipped [`crate::ui::tokens`] and does not redefine a
/// color token, so each preview shows the widgets as an app gets them, in
/// both schemes. [`theme_switch`] and [`density_switch`] change the scheme
/// and the density with `:root:has(#… :checked)` rules (#3396).
const STORY_GALLERY_CSS: &str = r"
body {
    margin: 0;
    font-family: var(--font-family);
    color: var(--text);
    background: var(--bg);
    transition: background-color 0.15s ease, border-color 0.15s ease, color 0.15s ease;
}

:root:has(#story-theme-light:checked) { color-scheme: light; }
:root:has(#story-theme-dark:checked) { color-scheme: dark; }
:root:has(#story-density-compact:checked) { --density-scale: 0.75; }
:root:has(#story-density-spacious:checked) { --density-scale: 1.25; }

.story-switches { display: flex; flex-wrap: wrap; gap: var(--space-4); padding: 0.6rem 1.25rem; border-bottom: 1px solid var(--border); background: var(--surface); }
.story-switch { display: flex; align-items: center; gap: 0.4rem; margin: 0; padding: 0; border: 0; }
.story-switch legend { float: left; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-muted); margin-right: 0.25rem; padding: 0; }
.story-switch input[type='radio'] { position: absolute; opacity: 0; width: 1px; height: 1px; }
.story-switch label { padding: 0.3rem 0.75rem; border-radius: var(--radius-full); border: 1px solid var(--control-border); font-size: 0.8rem; line-height: 1; cursor: pointer; color: var(--text-muted); }
.story-switch input[type='radio']:checked + label { background: var(--primary); border-color: var(--primary); color: var(--on-primary); }
.story-switch input[type='radio']:focus-visible + label { outline: 2px solid var(--primary); outline-offset: 2px; }

.story-layout { display: flex; gap: 2rem; align-items: flex-start; }
.story-sidebar { flex: 0 0 14rem; padding: 1.25rem; border-right: 1px solid var(--border); min-height: 100vh; background: var(--surface); }
.story-sidebar h2 { font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-muted); margin: 1.5rem 0 0.35rem; }
.story-sidebar h2:first-child { margin-top: 0; }
.story-sidebar ul { list-style: none; margin: 0; padding: 0; }
.story-sidebar li { margin: 0.15rem 0; }
.story-sidebar a { color: var(--text); text-decoration: none; border-radius: 0.35rem; padding: 0.15rem 0.4rem; display: block; }
.story-sidebar a:hover { background: var(--primary-light); color: var(--primary); }
.story-content { flex: 1 1 auto; padding: 1.75rem 2rem 3rem; max-width: 60rem; }
.story-content h1 { margin-top: 0; }
.story-breadcrumb { color: var(--text-muted); font-size: 0.85rem; }
.story-breadcrumb a { color: var(--primary); }
.story-preview { padding: 1.75rem; border: 1px solid var(--border); border-radius: var(--radius); margin-bottom: 1.5rem; background: var(--surface); color: var(--text); box-shadow: var(--shadow); }
.story-content pre { background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius); padding: 1rem; overflow-x: auto; }
.story-empty { padding: 2rem; border: 1px dashed var(--border); border-radius: var(--radius); color: var(--text-muted); }
";

/// Scheme options: `(radio id suffix, visible label)`. `"system"` is checked
/// by default and follows the OS.
const STORY_THEMES: [(&str, &str); 3] =
    [("system", "System"), ("light", "Light"), ("dark", "Dark")];

/// Density options: `(radio id suffix, visible label)`. `"comfortable"` is
/// checked by default.
const STORY_DENSITIES: [(&str, &str); 3] = [
    ("compact", "Compact"),
    ("comfortable", "Comfortable"),
    ("spacious", "Spacious"),
];

/// One radio group. Each radio's `:checked` state is matched by a
/// `:root:has(#story-{group}-… :checked)` rule in [`STORY_GALLERY_CSS`].
/// No JavaScript, so it holds under a strict `script-src` CSP.
fn radio_switch(
    group: &str,
    legend: &str,
    options: &[(&str, &str)],
    default: &str,
) -> maud::Markup {
    maud::html! {
        fieldset class=(format!("story-switch story-{group}-switch")) {
            legend { (legend) }
            @for (value, label) in options {
                @let id = format!("story-{group}-{value}");
                input type="radio" name=(format!("story-{group}")) id=(id)
                    checked[*value == default];
                label for=(id) { (label) }
            }
        }
    }
}

/// Scheme switcher: System / Light / Dark. Sets `color-scheme` on `:root`,
/// which selects one side of each `light-dark()` token.
fn theme_switch() -> maud::Markup {
    radio_switch("theme", "Theme", &STORY_THEMES, "system")
}

/// Density switcher: Compact / Comfortable / Spacious. Sets
/// `--density-scale` on `:root`, which scales the `--space-*` tokens.
fn density_switch() -> maud::Markup {
    radio_switch("density", "Density", &STORY_DENSITIES, "comfortable")
}

/// Full HTML document shell: framework widget stylesheet + htmx + widget
/// runtime script + gallery chrome, then the widget pack stylesheets and
/// scripts from `registry` (#3400).
///
/// Loads two same-origin scripts (both always mounted under the `htmx`
/// feature), in this order so `defer` preserves it regardless of download
/// timing:
///
/// 1. `htmx.min.js` — every `hx-get`/`hx-post`-driven widget (active search,
///    autocomplete, reaction controls, comment threads, the infinite feed
///    sentinel, …) renders correct `hx-*` attributes either way (see each
///    story's "Rendered HTML" tab), but they stay inert without htmx itself
///    on the page to process them.
/// 2. `autumn-widgets.js` — the framework's own `data-*`-hook runtime for
///    `modal_trigger`, `confirm_action`, `nav_bar`, and the autocomplete
///    widget's selection wiring.
///
/// Neither script needs a CSP nonce itself: the framework's default policy
/// keeps `'self'` in `script-src` in both plain and nonce modes. htmx does,
/// though, indirectly — it injects its own default loading-indicator
/// `<style>` at startup, and needs the nonce told to it via an
/// `htmx-config` meta tag (its documented mechanism) or that injected tag
/// has none and nonce-mode `style-src` (no `'unsafe-inline'`) blocks it
/// (review follow-up).
///
/// Most widgets' action URLs stay synthetic 404s-on-submit by design (e.g.
/// Confirm action, Bulk actions) — see each story's own comment. Two
/// typeahead stories (Active search, Autocomplete) get real demo backends
/// instead (`demo_search`, `demo_tag_search`), since a search box that
/// visibly does nothing while typing reads as broken rather than as a
/// deliberately-inert mockup; the Infinite feed story gets one too
/// (`demo_infinite_feed`) purely to stop its auto-firing `revealed` trigger
/// from 404-swapping on page load — see that function's doc comment.
///
/// When the security layer's per-request CSP nonce is active
/// (`security.headers.csp_nonce.enabled = true`, which drops
/// `'unsafe-inline'` from `style-src`), the inline gallery stylesheet carries
/// the request's nonce so browsers don't block it; without the layer no
/// `nonce` attribute is emitted.
fn story_page(
    registry: &StoryRegistry,
    title: &str,
    body: &maud::Markup,
    nonce: Option<&crate::security::CspNonce>,
) -> maud::Markup {
    #[cfg(feature = "htmx")]
    let scripts: &[&str] = &[
        crate::htmx::HTMX_JS_PATH,
        crate::htmx::AUTUMN_WIDGETS_JS_PATH,
    ];
    #[cfg(not(feature = "htmx"))]
    let scripts: &[&str] = &[];
    // The Flash story needs the flash stylesheet (#3398).
    #[cfg(feature = "flash")]
    let stylesheets: &[&str] = &[crate::flash::FLASH_CSS_PATH];
    #[cfg(not(feature = "flash"))]
    let stylesheets: &[&str] = &[];
    maud::html! {
        (maud::DOCTYPE)
        html lang="en" {
            head {
                meta charset="utf-8";
                meta name="viewport" content="width=device-width, initial-scale=1";
                title { (title) " — Autumn stories" }
                link rel="stylesheet" href=(crate::ui::WIDGETS_CSS_PATH);
                @for href in stylesheets {
                    link rel="stylesheet" href=(href);
                }
                // Widget pack stylesheets (#3400), after the core one.
                @for href in registry.stylesheets() {
                    link rel="stylesheet" href=(href);
                }
                @if let Some(n) = nonce {
                    meta name="htmx-config" content=(format!(r#"{{"inlineStyleNonce":"{}"}}"#, n.value()));
                }
                @for src in scripts {
                    script src=(src) defer {}
                }
                // Widget pack scripts (#3400), after the widget runtime.
                @for src in registry.scripts() {
                    script src=(src) defer {}
                }
                style nonce=[nonce.map(crate::security::CspNonce::value)] {
                    (maud::PreEscaped(STORY_GALLERY_CSS))
                }
            }
            body {
                div class="story-switches" {
                    (theme_switch())
                    (density_switch())
                }
                (body)
            }
        }
    }
}

/// Render the grouped `/_stories` index page.
fn render_story_index(
    registry: &StoryRegistry,
    nonce: Option<&crate::security::CspNonce>,
) -> maud::Markup {
    story_page(
        registry,
        "Widget stories",
        &maud::html! {
            div class="story-layout" {
                nav class="story-sidebar" aria-label="Stories" {
                    @for (group, stories) in registry.grouped() {
                        h2 { (group) }
                        ul {
                            @for story in stories {
                                li {
                                    a href=(format!("{STORIES_PATH}/{}", story.slug())) {
                                        (story.name())
                                    }
                                }
                            }
                        }
                    }
                }
                main class="story-content" {
                    h1 { "Widget stories" }
                    @if registry.stories().is_empty() {
                        div class="story-empty" {
                            p {
                                "No stories are registered. Add "
                                code { ".with_story_gallery(StoryGallery::builtin())" }
                                " to your " code { "AppBuilder" }
                                " to serve the built-in widget gallery, or "
                                code { "StoryGallery::new().extend([...])" }
                                " for app-only stories."
                            }
                        }
                    } @else {
                        p {
                            "Every entry renders live from a zero-arg widget example; "
                            "its detail page shows the exact source that produced it. "
                            "Pick a story from the sidebar."
                        }
                    }
                }
            }
        },
        nonce,
    )
}

/// Render a single story's detail page: live render above Source and
/// Rendered HTML tabs (dogfooding the [`crate::widgets::tabs`] widget).
///
/// `rendered` is the story's markup, rendered exactly once by the caller
/// (which also owns the render-failure response), so the preview and the
/// Rendered HTML tab always show the same output.
fn render_story_detail(
    registry: &StoryRegistry,
    story: &Story,
    rendered: &maud::Markup,
    nonce: Option<&crate::security::CspNonce>,
) -> maud::Markup {
    let rendered_html = rendered.clone().into_string();
    story_page(
        registry,
        story.name(),
        &maud::html! {
            main class="story-content" {
                p class="story-breadcrumb" {
                    a href=(STORIES_PATH) { "Widget stories" }
                    " / " (story.group())
                }
                h1 { (story.name()) }
                section class="story-preview" { (rendered) }
                (crate::widgets::tabs(
                    "story-tabs",
                    None,
                    &[
                        (
                            "story-source",
                            "Source",
                            // A focusable, named region: a keyboard user can scroll a
                            // wide snippet.
                            maud::html! {
                                pre tabindex="0" role="region" aria-label="Source code" {
                                    code { (story.source()) }
                                }
                            },
                        ),
                        (
                            "story-html",
                            "Rendered HTML",
                            maud::html! {
                                pre tabindex="0" role="region" aria-label="Rendered HTML code" {
                                    code { (rendered_html) }
                                }
                            },
                        ),
                    ],
                ))
            }
        },
        nonce,
    )
}

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

    fn demo_markup() -> maud::Markup {
        maud::html! { p { "demo" } }
    }

    fn demo_story(group: &'static str, name: &'static str) -> Story {
        Story::new(group, name, demo_markup, r#"maud::html! { p { "demo" } }"#)
    }

    // U1 (AC1): slug derivation folds case, joins alphanumeric runs with `-`,
    // and treats punctuation/whitespace/non-ASCII as separators.
    #[test]
    fn slugify_handles_spaces_punctuation_unicode() {
        assert_eq!(slugify("Data table"), "data-table");
        assert_eq!(slugify("Nav / Links!"), "nav-links");
        assert_eq!(slugify("HERO"), "hero");
        // Non-ASCII acts as a separator and never leaks into the URL.
        assert_eq!(slugify("Δ delta"), "delta");
        assert_eq!(slugify("  Stat   Card  "), "stat-card");
    }

    // U1 (AC1): a name that slugifies to nothing is a programmer error caught
    // loudly at construction time, not a broken route.
    #[test]
    #[should_panic(expected = "slug")]
    fn story_new_panics_on_name_that_slugifies_to_empty() {
        let _ = Story::new("Display", "!!!", demo_markup, "demo()");
    }

    // U2 (AC1): lookup is by slug.
    #[test]
    fn registry_find_matches_slug() {
        let registry = StoryRegistry::new(vec![
            demo_story("Display", "Data table"),
            demo_story("Display", "Card"),
        ]);
        assert_eq!(registry.stories().len(), 2);
        let found = registry
            .find("data-table")
            .expect("data-table slug should resolve");
        assert_eq!(found.name(), "Data table");
        assert_eq!(found.group(), "Display");
        assert!(registry.find("nope").is_none());
    }

    // U2 (AC1, R7): duplicate slugs would let one story shadow another in
    // routing — refuse them at registry construction.
    #[test]
    #[should_panic(expected = "duplicate")]
    fn registry_new_panics_on_duplicate_slug() {
        let _ = StoryRegistry::new(vec![
            demo_story("Display", "Card"),
            demo_story("Marketing", "Card"),
        ]);
    }

    // U3 (AC1, R17): index grouping is deterministic — groups in first-seen
    // order, stories in registration order within a group.
    #[test]
    fn grouped_preserves_first_seen_group_and_registration_order() {
        let registry = StoryRegistry::new(vec![
            demo_story("Display", "Data table"),
            demo_story("Forms", "Active search"),
            demo_story("Display", "Card"),
        ]);
        let grouped = registry.grouped();
        let groups: Vec<&str> = grouped.iter().map(|(group, _)| *group).collect();
        assert_eq!(groups, ["Display", "Forms"]);
        let display_names: Vec<&str> = grouped[0].1.iter().map(|s| s.name()).collect();
        assert_eq!(display_names, ["Data table", "Card"]);
    }

    // U4 (AC7): builder-side gallery — builtin-free constructor, seeded
    // constructor, and extend with a custom `story!`.
    #[test]
    fn gallery_new_is_empty_builtin_is_seeded_extend_appends() {
        assert!(
            StoryGallery::new().into_registry().stories().is_empty(),
            "StoryGallery::new() must start builtin-free"
        );

        let builtin_count = builtin().stories().len();
        assert!(builtin_count > 0, "builtin registry must not be empty");
        assert_eq!(
            StoryGallery::builtin().into_registry().stories().len(),
            builtin_count,
            "StoryGallery::builtin() must be seeded with exactly the builtin stories"
        );

        let custom = crate::stories::story! {
            "App",
            "Greeting",
            {
                maud::html! { span { "hi" } }
            }
        };
        let registry = StoryGallery::builtin().extend([custom]).into_registry();
        assert_eq!(registry.stories().len(), builtin_count + 1);
        assert!(
            registry.find("greeting").is_some(),
            "extended custom story must be findable by its slug"
        );
    }

    fn panicking_story() -> maud::Markup {
        panic!("story exploded on purpose")
    }

    // U5 (AC8, R4): a panicking story surfaces as an error, it does not
    // unwind through the gallery.
    #[test]
    fn story_render_catches_panic() {
        let boom = Story::new("Display", "Boom", panicking_story, "panicking_story()");
        let err = boom
            .render()
            .expect_err("panic must be caught and reported as an error");
        assert!(
            matches!(err, StoryRenderError::Panicked { .. }),
            "expected StoryRenderError::Panicked, got {err:?}"
        );

        let fine = Story::new("Display", "Fine", demo_markup, "demo()");
        assert!(fine.render().is_ok());
    }

    // U6 (AC4): the index page links the framework widget stylesheet, loads
    // the widget runtime script, and lists stories grouped in the sidebar.
    #[test]
    fn index_page_links_widgets_css_and_groups_stories() {
        assert_eq!(STORIES_PATH, "/_stories");

        let registry = StoryRegistry::new(vec![
            demo_story("Display", "Data table"),
            demo_story("Forms", "Active search"),
        ]);
        let page = render_story_index(&registry, None).into_string();
        let dom = crate::test_html::parse(&page);

        let css_selector = crate::test_html::SelectorList::parse(&format!(
            "link[href=\"{}\"]",
            crate::ui::WIDGETS_CSS_PATH
        ))
        .expect("selector parses");
        assert!(
            !css_selector.matches(&dom).is_empty(),
            "index must link the framework widget stylesheet: {page}"
        );

        #[cfg(feature = "htmx")]
        {
            let js_selector = crate::test_html::SelectorList::parse(&format!(
                "script[src=\"{}\"]",
                crate::htmx::AUTUMN_WIDGETS_JS_PATH
            ))
            .expect("selector parses");
            assert!(
                !js_selector.matches(&dom).is_empty(),
                "index must load the widget runtime script so interactive \
                 stories (modal, confirm-action, nav-bar) work live: {page}"
            );
        }

        let link_selector =
            crate::test_html::SelectorList::parse("a[href=\"/_stories/data-table\"]")
                .expect("selector parses");
        assert!(
            !link_selector.matches(&dom).is_empty(),
            "index must link each story detail page: {page}"
        );

        assert!(
            page.contains("Display") && page.contains("Forms"),
            "sidebar must show group headings: {page}"
        );
    }

    // U7 (AC4): the detail page shows the live render plus Source and
    // Rendered HTML tabs (dogfooding the `tabs` widget).
    #[test]
    fn detail_page_has_live_render_source_tab_and_html_tab() {
        let story = crate::stories::story! {
            "Display",
            "Proof",
            {
                maud::html! { p class="proof-marker" { "live proof" } }
            }
        };
        let rendered = story.render().expect("proof story renders");
        let page =
            render_story_detail(&StoryRegistry::default(), &story, &rendered, None).into_string();
        let dom = crate::test_html::parse(&page);

        let preview = crate::test_html::SelectorList::parse(".story-preview .proof-marker")
            .expect("selector parses");
        let matches = preview.matches(&dom);
        assert!(
            !matches.is_empty(),
            "live render must appear inside .story-preview: {page}"
        );
        assert!(
            matches[0].text().contains("live proof"),
            "live render must contain the story's output: {page}"
        );

        let tabs = crate::test_html::SelectorList::parse(".autumn-tabs").expect("selector parses");
        assert!(
            !tabs.matches(&dom).is_empty(),
            "detail page must use the tabs widget for Source / Rendered HTML: {page}"
        );

        #[cfg(feature = "htmx")]
        {
            let js_selector = crate::test_html::SelectorList::parse(&format!(
                "script[src=\"{}\"]",
                crate::htmx::AUTUMN_WIDGETS_JS_PATH
            ))
            .expect("selector parses");
            assert!(
                !js_selector.matches(&dom).is_empty(),
                "detail page must load the widget runtime script: {page}"
            );
            // #2353: without htmx, `hx-*` stories do nothing on the detail page.
            let htmx_selector = crate::test_html::SelectorList::parse(&format!(
                "script[src=\"{}\"]",
                crate::htmx::HTMX_JS_PATH
            ))
            .expect("selector parses");
            assert!(
                !htmx_selector.matches(&dom).is_empty(),
                "detail page must load htmx.min.js: {page}"
            );
        }

        assert!(
            page.contains("maud::html!"),
            "Source tab must show the captured snippet: {page}"
        );
        assert!(
            page.contains("&lt;p"),
            "Rendered HTML tab must show the escaped markup: {page}"
        );
    }

    // #3400: `merge` appends stories and keeps one copy of each asset link.
    #[test]
    fn gallery_merge_appends_stories_and_dedupes_asset_links() {
        let first = StoryGallery::new()
            .extend([demo_story("Display", "Card")])
            .stylesheet("/a.css")
            .script("/a.js");
        let second = StoryGallery::new()
            .extend([demo_story("Pack", "Swatch picker")])
            .stylesheet("/a.css")
            .stylesheet("/b.css")
            .script("/b.js");
        let merged = first.merge(second);
        let slugs: Vec<&str> = merged.stories().iter().map(Story::slug).collect();
        assert_eq!(slugs, ["card", "swatch-picker"]);
        assert_eq!(merged.stylesheets(), ["/a.css", "/b.css"]);
        assert_eq!(merged.scripts(), ["/a.js", "/b.js"]);

        let registry = merged.into_registry();
        assert_eq!(registry.stylesheets(), ["/a.css", "/b.css"]);
        assert_eq!(registry.scripts(), ["/a.js", "/b.js"]);
    }

    // #3400: a pack story needs the pack CSS and JS. Each gallery page links
    // them after the core stylesheet and the widget runtime.
    #[test]
    fn gallery_pages_link_pack_assets_after_core_assets() {
        let registry = StoryGallery::new()
            .extend([demo_story("Pack", "Swatch picker")])
            .stylesheet("/static/_plugins/swatch/swatch.css")
            .script("/static/_plugins/swatch/swatch.js")
            .into_registry();
        let story = &registry.stories()[0];
        let rendered = story.render().expect("demo story renders");
        for page in [
            render_story_index(&registry, None).into_string(),
            render_story_detail(&registry, story, &rendered, None).into_string(),
        ] {
            let core_css = page
                .find(crate::ui::WIDGETS_CSS_PATH)
                .expect("core stylesheet");
            let pack_css = page
                .find(r#"<link rel="stylesheet" href="/static/_plugins/swatch/swatch.css">"#)
                .unwrap_or_else(|| panic!("pack stylesheet missing: {page}"));
            assert!(core_css < pack_css, "pack CSS must follow core CSS: {page}");
            let pack_js = page
                .find(r#"<script src="/static/_plugins/swatch/swatch.js" defer></script>"#)
                .unwrap_or_else(|| panic!("pack script missing: {page}"));
            #[cfg(feature = "htmx")]
            assert!(
                page.find(crate::htmx::AUTUMN_WIDGETS_JS_PATH)
                    .is_some_and(|core_js| core_js < pack_js),
                "pack JS must follow the widget runtime: {page}"
            );
            let _ = pack_js;
        }
    }

    // U8 (AC4/AC5, R12): enabled-but-unregistered renders a helpful empty
    // state pointing at AppBuilder::with_story_gallery, not a 500/blank page.
    #[test]
    fn index_empty_state_mentions_with_story_gallery() {
        let page = render_story_index(&StoryRegistry::default(), None).into_string();
        assert!(
            page.contains("with_story_gallery"),
            "empty state must explain how to register stories: {page}"
        );
    }

    // ── Strict balanced-HTML check over the gallery chrome ──────────────
    //
    // The integration harness (tests/integration/stories.rs) runs this
    // discipline over each story *fragment*; the full index/detail pages can
    // only be rendered here (`render_story_*` are private), so a minimal
    // copy of the strict checker lives in this module too. Unlike the
    // lenient `crate::test_html` parser, it refuses auto-closing.

    /// Panics when `html` is not well-formed (mismatched, unclosed, or
    /// stray-closed tags).
    fn assert_balanced_html(html: &str, context: &str) {
        const VOID_ELEMENTS: &[&str] = &[
            "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param",
            "source", "track", "wbr",
        ];
        const RAW_TEXT_ELEMENTS: &[&str] = &["script", "style", "textarea", "title"];

        let bytes = html.as_bytes();
        let mut stack: Vec<String> = Vec::new();
        let mut i = 0;

        while i < bytes.len() {
            if bytes[i] != b'<' {
                i += 1;
                continue;
            }
            if html[i..].starts_with("<!--") {
                let end = html[i + 4..]
                    .find("-->")
                    .unwrap_or_else(|| panic!("unterminated comment in {context}:\n{html}"));
                i += 4 + end + 3;
                continue;
            }
            if html[i..].starts_with("<!") {
                // Doctype or other declaration.
                let end = html[i..]
                    .find('>')
                    .unwrap_or_else(|| panic!("unterminated declaration in {context}:\n{html}"));
                i += end + 1;
                continue;
            }

            let closing = html[i..].starts_with("</");
            let name_start = i + if closing { 2 } else { 1 };
            let name_len = html[name_start..]
                .find(|c: char| !(c.is_ascii_alphanumeric() || c == '-'))
                .unwrap_or(html.len() - name_start);
            let name = html[name_start..name_start + name_len].to_ascii_lowercase();
            assert!(
                !name.is_empty(),
                "malformed tag at byte {i} in {context}:\n{html}"
            );

            // Find the true end of the tag, skipping `>` inside quoted attrs.
            let mut j = name_start + name_len;
            let mut quote: Option<u8> = None;
            while j < bytes.len() {
                match (quote, bytes[j]) {
                    (Some(q), c) if c == q => quote = None,
                    (None, b'"') => quote = Some(b'"'),
                    (None, b'\'') => quote = Some(b'\''),
                    (None, b'>') => break,
                    _ => {}
                }
                j += 1;
            }
            assert!(
                j < bytes.len(),
                "unterminated tag <{name} in {context}:\n{html}"
            );
            let self_closing = j > 0 && bytes[j - 1] == b'/';

            if closing {
                let open = stack.pop().unwrap_or_else(|| {
                    panic!("closing </{name}> with no open tag in {context}:\n{html}")
                });
                assert_eq!(
                    open, name,
                    "mismatched close tag in {context}: expected </{open}>, found </{name}>:\n{html}"
                );
                i = j + 1;
                continue;
            }

            if !self_closing && !VOID_ELEMENTS.contains(&name.as_str()) {
                if RAW_TEXT_ELEMENTS.contains(&name.as_str()) {
                    // Skip raw content up to the matching close tag.
                    let close = format!("</{name}");
                    let rest_start = j + 1;
                    let end = html[rest_start..]
                        .to_ascii_lowercase()
                        .find(&close)
                        .unwrap_or_else(|| {
                            panic!("unclosed raw-text element <{name}> in {context}:\n{html}")
                        });
                    let close_gt = html[rest_start + end..]
                        .find('>')
                        .unwrap_or_else(|| panic!("unterminated </{name}> in {context}:\n{html}"));
                    i = rest_start + end + close_gt + 1;
                    continue;
                }
                stack.push(name);
            }
            i = j + 1;
        }

        assert!(
            stack.is_empty(),
            "unclosed tags {stack:?} in {context}:\n{html}"
        );
    }

    // Guard the duplicated checker itself: a broken checker must not
    // green-light rotten gallery chrome.
    #[test]
    fn balanced_html_checker_rejects_malformed_markup() {
        assert_balanced_html(
            r#"<!DOCTYPE html><div class="a > b"><p>ok<br></p></div>"#,
            "self-test",
        );
        for bad in ["<div><p></div>", "<div>", "</div>"] {
            let result = std::panic::catch_unwind(|| assert_balanced_html(bad, "self-test"));
            assert!(result.is_err(), "checker should reject {bad}");
        }
    }

    // U9 (AC4/AC8): the gallery chrome itself — grouped index, empty-state
    // index, and every builtin detail page — is strictly balanced HTML, not
    // just the story fragments the integration harness checks.
    #[test]
    fn gallery_index_and_detail_pages_render_balanced_html() {
        let registry = builtin();
        assert_balanced_html(
            &render_story_index(&registry, None).into_string(),
            "story index page",
        );
        assert_balanced_html(
            &render_story_index(&StoryRegistry::default(), None).into_string(),
            "empty-state index page",
        );
        for story in registry.stories() {
            let rendered = story
                .render()
                .unwrap_or_else(|err| panic!("builtin story `{}` failed: {err}", story.slug()));
            assert_balanced_html(
                &render_story_detail(&registry, story, &rendered, None).into_string(),
                &format!("detail page for `{}`", story.slug()),
            );
        }
    }

    // U10 (review follow-up): when the security layer's per-request CSP nonce
    // is active, `style-src` drops `'unsafe-inline'`, so the gallery's inline
    // stylesheet must carry the request nonce or browsers block it. Without
    // the layer no nonce attribute is emitted.
    #[test]
    fn story_pages_apply_csp_nonce_to_inline_style() {
        let nonce = crate::security::CspNonce::new_for_tests("test-nonce-value");
        let registry = StoryRegistry::new(vec![demo_story("Display", "Card")]);

        let index = render_story_index(&registry, Some(&nonce)).into_string();
        assert!(
            index.contains(r#"<style nonce="test-nonce-value">"#),
            "index inline style must carry the CSP nonce: {index}"
        );

        let story = &registry.stories()[0];
        let rendered = story.render().expect("demo story renders");
        let detail = render_story_detail(&registry, story, &rendered, Some(&nonce)).into_string();
        assert!(
            detail.contains(r#"<style nonce="test-nonce-value">"#),
            "detail inline style must carry the CSP nonce: {detail}"
        );

        let plain = render_story_index(&registry, None).into_string();
        assert!(
            plain.contains("<style>") && !plain.contains("nonce="),
            "without the security layer no nonce attribute is emitted: {plain}"
        );
    }

    // U16 (interactivity follow-up): htmx injects its own default loading-
    // indicator <style> at startup; under nonce-mode CSP it needs that
    // nonce told to it via an htmx-config meta tag (its documented
    // mechanism), or the tag it injects has none and gets blocked the same
    // way the reported CSP violation did.
    #[cfg(feature = "htmx")]
    #[test]
    fn story_pages_tell_htmx_the_csp_nonce_via_meta_tag() {
        let nonce = crate::security::CspNonce::new_for_tests("test-nonce-value");
        let registry = StoryRegistry::new(vec![demo_story("Display", "Card")]);

        let with_nonce = render_story_index(&registry, Some(&nonce)).into_string();
        assert!(
            with_nonce.contains(
                r#"<meta name="htmx-config" content="{&quot;inlineStyleNonce&quot;:&quot;test-nonce-value&quot;}">"#
            ),
            "story page must tell htmx the CSP nonce via htmx-config: {with_nonce}"
        );

        let plain = render_story_index(&registry, None).into_string();
        assert!(
            !plain.contains("htmx-config"),
            "without the security layer no htmx-config meta tag is needed: {plain}"
        );
    }

    // U11, reworked by #3396: every story page has a scheme switcher
    // (System / Light / Dark) and a density switcher (Compact / Comfortable /
    // Spacious). Each radio id matches a `:root:has(#… :checked)` rule in
    // `STORY_GALLERY_CSS`, so a switch needs no JavaScript and no inline
    // script or event handler (strict `script-src` CSP).
    #[test]
    fn theme_and_density_switchers_are_radios_wired_to_css() {
        let registry = StoryRegistry::new(vec![demo_story("Display", "Card")]);
        let index = render_story_index(&registry, None).into_string();
        let dom = crate::test_html::parse(&index);

        for (group, options, default, css) in [
            (
                "theme",
                &STORY_THEMES[..],
                "system",
                &[
                    ("light", "color-scheme: light;"),
                    ("dark", "color-scheme: dark;"),
                ][..],
            ),
            (
                "density",
                &STORY_DENSITIES[..],
                "comfortable",
                &[
                    ("compact", "--density-scale: 0.75;"),
                    ("spacious", "--density-scale: 1.25;"),
                ][..],
            ),
        ] {
            let fieldset =
                crate::test_html::SelectorList::parse(&format!("fieldset.story-{group}-switch"))
                    .expect("selector parses");
            assert!(
                !fieldset.matches(&dom).is_empty(),
                "no {group} switcher: {index}"
            );

            for (value, label) in options {
                let radio_id = format!("story-{group}-{value}");
                let radio = crate::test_html::SelectorList::parse(&format!(
                    "input[type=\"radio\"][name=\"story-{group}\"]#{radio_id}"
                ))
                .expect("selector parses");
                assert!(
                    !radio.matches(&dom).is_empty(),
                    "no radio {radio_id}: {index}"
                );
                let label_el =
                    crate::test_html::SelectorList::parse(&format!("label[for=\"{radio_id}\"]"))
                        .expect("selector parses");
                let labels = label_el.matches(&dom);
                assert!(
                    labels.first().is_some_and(|l| l.text().contains(label)),
                    "label for {radio_id} must read {label:?}: {index}"
                );
            }
            assert!(
                index.contains(&format!(r#"id="story-{group}-{default}" checked"#)),
                "{default} must be checked server-side: {index}"
            );
            for (value, declaration) in css {
                let rule = format!(":root:has(#story-{group}-{value}:checked) {{ {declaration} }}");
                assert!(STORY_GALLERY_CSS.contains(&rule), "missing `{rule}`");
            }
        }

        assert!(
            !index.contains("<script>")
                && !index.contains(" onclick=")
                && !index.contains(" onchange="),
            "the switchers must stay pure CSS: {index}"
        );
    }

    /// #3396: the gallery shows the shipped tokens. It must not redefine a
    /// color token, or the dark scheme would not show.
    #[test]
    fn gallery_css_does_not_override_color_tokens() {
        for line in STORY_GALLERY_CSS.lines() {
            let line = line.trim_start();
            assert!(
                !line.starts_with("--") || line.starts_with("--density-scale"),
                "gallery redefines a token: {line}"
            );
        }
        assert!(
            !STORY_GALLERY_CSS.contains("color: #fff"),
            "use var(--on-primary)"
        );
    }

    // U12 (interactivity follow-up): every hx-*-driven widget stayed inert
    // because htmx.min.js was never loaded, only the framework's own
    // data-*-hook runtime was. Both must load, htmx first (both `defer`, so
    // document order fixes execution order — autumn-widgets.js's
    // autocomplete wiring can assume htmx is already present).
    #[cfg(feature = "htmx")]
    #[test]
    fn story_page_loads_htmx_before_the_widgets_runtime() {
        let page = render_story_index(&StoryRegistry::default(), None).into_string();
        let htmx_at = page
            .find(crate::htmx::HTMX_JS_PATH)
            .expect("story page must load htmx.min.js");
        let widgets_at = page
            .find(crate::htmx::AUTUMN_WIDGETS_JS_PATH)
            .expect("story page must load autumn-widgets.js");
        assert!(
            htmx_at < widgets_at,
            "htmx.min.js must appear before autumn-widgets.js so `defer` \
             preserves that execution order: {page}"
        );
    }

    // U13 (interactivity follow-up): the two typeahead stories point at real
    // demo backends now (not the synthetic 404-on-submit URLs most other
    // stories use), and since the URL is a plain string literal in the
    // story's own source — not a reference to the route const, which would
    // show up literally in the public "Source" tab — nothing else catches
    // the two drifting apart. Guard it here instead.
    #[cfg(feature = "widgets-search")]
    #[test]
    fn typeahead_stories_point_at_their_registered_demo_routes() {
        let registry = builtin();
        let active_search = registry
            .find("active-search")
            .expect("active-search story exists");
        assert!(
            active_search.source().contains(STORIES_DEMO_SEARCH_PATH),
            "Active search story must point at STORIES_DEMO_SEARCH_PATH \
             ({STORIES_DEMO_SEARCH_PATH}): {}",
            active_search.source()
        );

        let autocomplete = registry
            .find("autocomplete")
            .expect("autocomplete story exists");
        assert!(
            autocomplete.source().contains(STORIES_DEMO_TAG_SEARCH_PATH),
            "Autocomplete story must point at STORIES_DEMO_TAG_SEARCH_PATH \
             ({STORIES_DEMO_TAG_SEARCH_PATH}): {}",
            autocomplete.source()
        );
    }

    #[cfg(feature = "widgets-social")]
    #[test]
    fn feed_story_points_at_its_registered_demo_route() {
        let registry = builtin();
        let feed = registry
            .find("infinite-feed")
            .expect("infinite-feed story exists");
        assert!(
            feed.source().contains(STORIES_DEMO_FEED_PATH),
            "Infinite feed story must point at STORIES_DEMO_FEED_PATH \
             ({STORIES_DEMO_FEED_PATH}), or its Reveal-mode sentinel \
             404-swaps on page load with no visitor action: {}",
            feed.source()
        );
    }

    // U14 (interactivity follow-up): the demo handlers backing those routes
    // actually filter, case-insensitively, and fall back to the same empty
    // states the stories document.
    #[cfg(feature = "widgets-search")]
    #[tokio::test]
    async fn demo_search_filters_case_insensitively_with_empty_state_fallback() {
        let hit = demo_search(crate::extract::Query(DemoQuery {
            q: "AUTUMN".to_owned(),
        }))
        .await
        .0;
        assert!(hit.contains("The Long Autumn"), "{hit}");
        assert!(hit.contains("Autumn in Practice"), "{hit}");
        assert!(!hit.contains("Falling Leaves"), "{hit}");

        let miss = demo_search(crate::extract::Query(DemoQuery {
            q: "nonexistent".to_owned(),
        }))
        .await
        .0;
        assert!(
            miss.contains("No posts matched your search."),
            "no-match query must fall back to active_search_empty_state: {miss}"
        );
    }

    #[cfg(feature = "widgets-search")]
    #[tokio::test]
    async fn demo_tag_search_filters_case_insensitively_with_empty_state_fallback() {
        let hit = demo_tag_search(crate::extract::Query(DemoQuery { q: "RU".to_owned() }))
            .await
            .0;
        assert!(hit.contains("rust"), "{hit}");
        assert!(!hit.contains("axum"), "{hit}");

        let miss = demo_tag_search(crate::extract::Query(DemoQuery {
            q: "nonexistent".to_owned(),
        }))
        .await
        .0;
        assert!(
            miss.contains("No matching tags."),
            "no-match query must fall back to autocomplete_empty_state: {miss}"
        );
    }

    // The "Tags input" demo (#3410): the value of each option is its name,
    // and a "create" entry follows when no tag has the exact name.
    #[cfg(feature = "widgets-search")]
    #[tokio::test]
    async fn demo_tag_suggest_lists_matches_then_a_create_entry() {
        let some = demo_tag_suggest(crate::extract::Query(DemoQuery { q: "A".to_owned() }))
            .await
            .0;
        assert!(some.contains(r#"data-value="axum""#), "{some}");
        assert!(!some.contains(r#"data-value="rust""#), "{some}");
        assert!(some.contains("data-ac-create"), "{some}");
        assert!(some.contains(r#"data-label="A""#), "the typed text: {some}");

        let new_tag = demo_tag_suggest(crate::extract::Query(DemoQuery {
            q: " zig ".to_owned(),
        }))
        .await
        .0;
        assert!(!new_tag.contains(r#"data-value="rust""#), "{new_tag}");
        assert!(new_tag.contains(r#"data-value="zig""#), "{new_tag}");
        assert!(new_tag.contains("Create \u{201c}zig\u{201d}"), "{new_tag}");
    }

    #[cfg(feature = "widgets-search")]
    #[tokio::test]
    async fn demo_tag_suggest_has_no_create_entry_for_an_exact_or_empty_query() {
        let exact = demo_tag_suggest(crate::extract::Query(DemoQuery {
            q: "Web".to_owned(),
        }))
        .await
        .0;
        assert!(exact.contains(r#"data-value="web""#), "{exact}");
        assert!(!exact.contains("data-ac-create"), "{exact}");

        let empty = demo_tag_suggest(crate::extract::Query(DemoQuery { q: "  ".to_owned() }))
            .await
            .0;
        assert!(empty.is_empty(), "{empty}");
    }

    #[cfg(feature = "widgets-search")]
    #[test]
    fn tags_input_story_points_at_its_registered_demo_route() {
        let registry = builtin();
        let tags = registry
            .find("tags-input")
            .expect("tags-input story exists");
        assert!(
            tags.source().contains(STORIES_DEMO_TAG_SUGGEST_PATH),
            "Tags input story must point at {STORIES_DEMO_TAG_SUGGEST_PATH}: {}",
            tags.source()
        );
        assert!(
            demo_routes()
                .iter()
                .any(|(path, _)| *path == STORIES_DEMO_TAG_SUGGEST_PATH),
            "the demo route is listed"
        );
    }

    // U15 (interactivity follow-up): the feed demo must terminate (no
    // further sentinel) — otherwise it would just keep auto-firing.
    #[cfg(feature = "widgets-social")]
    #[tokio::test]
    async fn demo_infinite_feed_returns_a_terminal_page_with_no_further_sentinel() {
        let body = demo_infinite_feed().await.0;
        assert!(body.contains("Loaded live via a real request."), "{body}");
        assert!(
            !body.contains("autumn-feed__sentinel"),
            "a next_cursor of None must emit no further sentinel, or the \
             `revealed` trigger keeps auto-firing forever: {body}"
        );
    }
}