rustango-cms 0.4.0

A page-tree content management system for Rust, built on rustango
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
//! Page types: the [`PageTypeHandler`] trait every page kind implements,
//! its inventory registry ([`find_handler`], [`registered_handlers`]),
//! and the editor-form types the handler returns ([`ExtensionField`],
//! [`TabSpec`], [`InlinePanelSpec`], [`DisplayField`]).
//!
//! `#[derive(PageType)]` generates the handler and forwards the
//! author-overridable hooks to [`PageTypeOverrides`].

use async_trait::async_trait;
use rustango::sql::{ExecError, Pool};
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Form-field metadata returned by [`PageTypeHandler::extension_fields`].
/// The admin's page-edit form renders one input per entry under the
/// "Content" section so authors can write into the type's extension
/// table without leaving the editor.
///
/// Kept stable for back-compat with v0.x handler authors. Internally
/// the admin converts to the richer [`crate::Widget`] before
/// rendering — new handlers can also return `Widget`s directly via
/// [`Self::from_widget`] for access to the full widget set (Date,
/// Color, Choice, …).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtensionField {
    /// HTML form `name` — also the key on the form submission. Used
    /// by [`PageTypeHandler::save_extension`] to pull the value back
    /// out of the posted form.
    pub name: String,
    /// Display label for the input.
    pub label: String,
    /// Render hint — picks which widget the admin draws.
    pub kind: ExtensionFieldKind,
    /// Pre-fill value (the current row's value, when editing).
    pub value: String,
    /// Optional helptext shown below the input.
    pub help: String,
    /// Optional max length (string/text inputs only).
    pub max_length: Option<u32>,
}

impl ExtensionField {
    /// Convert into a [`crate::Widget`] — the unified widget
    /// descriptor the admin renderer + the stream-block editor both
    /// consume. `options` is left empty (the admin handler
    /// populates it for `MediaPicker` widgets from the media
    /// library).
    #[must_use]
    pub fn into_widget(self) -> crate::Widget {
        crate::Widget {
            name: self.name,
            kind: self.kind.into(),
            custom_name: String::new(),
            custom_html: String::new(),
            label: self.label,
            value: self.value,
            options: Vec::new(),
            help: self.help,
            placeholder: String::new(),
            required: false,
            min: None,
            max: None,
            step: None,
            max_length: self.max_length,
            min_length: None,
            pattern: String::new(),
            read_only: false,
            allowed: Vec::new(),
            variant: String::new(),
        }
    }

    /// Wrap a [`crate::Widget`] back into the legacy
    /// [`ExtensionField`] shape — useful for handlers that author
    /// against the richer widget set but still want to return the
    /// legacy `Vec<ExtensionField>`.
    ///
    /// `max_length`, `value`, `help`, `label`, `name` are preserved.
    /// Widget kinds outside the legacy set
    /// ([`ExtensionFieldKind`]'s six variants) downgrade to
    /// [`ExtensionFieldKind::Text`] — handlers that need the full
    /// set should switch to returning `Vec<Widget>` (a follow-up
    /// trait method lands with the stream-block slice).
    #[must_use]
    pub fn from_widget(w: crate::Widget) -> Self {
        let kind = ExtensionFieldKind::from_widget_kind(w.kind);
        Self {
            name: w.name,
            label: w.label,
            kind,
            value: w.value,
            help: w.help,
            max_length: w.max_length,
        }
    }
}

/// Which admin widget to draw for an [`ExtensionField`].
///
/// Stable v0.x surface — six variants the original handler authors
/// know. The full [`crate::WidgetKind`] (25+ kinds: Date, Color,
/// Radio, Checkboxes, …) is reachable by returning [`crate::Widget`]
/// instances directly. `ExtensionFieldKind` converts cleanly via
/// `From` impls in both directions.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ExtensionFieldKind {
    /// Single-line `<input type="text">`.
    Text,
    /// Multi-line `<textarea>` — plain content.
    Textarea,
    /// Multi-line `<textarea>` with a "preview as markdown" affordance.
    /// Rendered through [`crate::markdown::render`] on the public site.
    Markdown,
    /// Media picker — value is the `cms_media.id` as a stringified
    /// integer. Empty = no selection.
    MediaPicker,
    /// `<input type="number">` for integer-shaped fields.
    Number,
    /// `<input type="url">`.
    Url,
}

impl ExtensionFieldKind {
    /// Best-effort downgrade from the richer [`crate::WidgetKind`]
    /// back to the v0.x six-variant surface. Out-of-set widgets
    /// (Date, Color, Choice, …) downgrade to [`Self::Text`]; the
    /// legacy mapping is lossless.
    #[must_use]
    pub fn from_widget_kind(k: crate::WidgetKind) -> Self {
        use crate::WidgetKind as WK;
        match k {
            WK::Text => Self::Text,
            WK::Textarea => Self::Textarea,
            WK::Markdown => Self::Markdown,
            WK::MediaPicker => Self::MediaPicker,
            WK::Number | WK::Integer | WK::Float => Self::Number,
            WK::Url => Self::Url,
            _ => Self::Text,
        }
    }
}

impl From<ExtensionFieldKind> for crate::WidgetKind {
    fn from(k: ExtensionFieldKind) -> Self {
        match k {
            ExtensionFieldKind::Text => Self::Text,
            ExtensionFieldKind::Textarea => Self::Textarea,
            ExtensionFieldKind::Markdown => Self::Markdown,
            ExtensionFieldKind::MediaPicker => Self::MediaPicker,
            ExtensionFieldKind::Number => Self::Number,
            ExtensionFieldKind::Url => Self::Url,
        }
    }
}

/// The framework-default children listing, backing
/// [`PageTypeHandler::children_query`]'s default: the same live children
/// as [`published_children`].
///
/// It used to return every child, drafts included, into the public
/// template context — so a fresh site listed unpublished titles to
/// anonymous visitors. A type that really wants drafts listed
/// overrides `children_query` with [`all_children`].
///
/// # Errors
/// Driver / query failures from the page lookup.
pub async fn default_children(
    pool: &Pool,
    page: &crate::page::Page,
) -> Result<Vec<crate::page::Page>, ExecError> {
    published_children(pool, page).await
}

/// Every immediate child, ordered `sort_order, id` — drafts, scheduled
/// and expired pages included. For admin-side listings; never the
/// public default.
///
/// # Errors
/// Driver / query failures from the page lookup.
pub async fn all_children(
    pool: &Pool,
    page: &crate::page::Page,
) -> Result<Vec<crate::page::Page>, ExecError> {
    use rustango::core::Column as _;
    use rustango::sql::FetcherPool as _;
    let id = page.id.get().copied().unwrap_or_default();
    crate::page::Page::objects()
        .where_(crate::page::Page::parent_id.eq(id))
        .order_by(&[("sort_order", false), ("id", false)])
        .fetch(pool)
        .await
}

/// Immediate children a visitor can open right now, ordered
/// `sort_order, id`: published and not expired, or scheduled and past
/// go-live — the same rule the resolver serves by
/// ([`crate::resolver::visible_now`]). Error pages are left out: they
/// are served for a status code, not listed as content (as in
/// `auto_menu`). The building block for an index/listing page's
/// [`PageTypeHandler::children_query`] override.
///
/// # Errors
/// Driver / query failures from the page lookup.
pub async fn published_children(
    pool: &Pool,
    page: &crate::page::Page,
) -> Result<Vec<crate::page::Page>, ExecError> {
    use rustango::sql::FetcherPool as _;
    published_children_qs(pool, page)
        .await
        .order_by(&[("sort_order", false), ("id", false)])
        .fetch(pool)
        .await
}

/// The [`published_children`] rows of `page`, unordered.
async fn published_children_qs(
    pool: &Pool,
    page: &crate::page::Page,
) -> rustango::query::QuerySet<crate::page::Page> {
    use crate::page::{Page, PageStatus};
    use rustango::core::Column as _;
    let id = page.id.get().copied().unwrap_or_default();
    let now = chrono::Utc::now();
    // `resolver::visible_now`, in SQL so the limit counts only listed
    // pages: published and not expired, or scheduled, past go-live and
    // not expired.
    let not_expired = || Page::expire_at.is_null().or(Page::expire_at.gt(now));
    let mut qs = Page::objects()
        .where_(Page::parent_id.eq(id))
        .where_(
            Page::status
                .eq(PageStatus::Published.as_str().to_owned())
                .and(not_expired())
                .or(Page::status
                    .eq(PageStatus::Scheduled.as_str().to_owned())
                    .and(Page::go_live_at.lte(now))
                    .and(not_expired())),
        );
    if let Some(tid) = crate::error_pages::error_page_type_id(pool).await {
        qs = qs.where_(Page::page_type_id.ne(tid));
    }
    qs
}

/// How [`published_children_page`] orders a page's children.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ChildOrder {
    /// `sort_order, id` — the editor's arrangement, as in
    /// [`published_children`].
    #[default]
    Position,
    /// Newest `published_at` first, undated pages last; newer ids first
    /// among equals. For a blog or news index.
    NewestFirst,
    /// Oldest `published_at` first, undated pages last; older ids first
    /// among equals.
    OldestFirst,
}

/// One window of a page's [`published_children`].
#[derive(Debug, Clone, Default)]
pub struct ChildrenPage {
    /// The children in this window, in the requested order.
    pub pages: Vec<crate::page::Page>,
    /// How many live children the page has in all, for "page 2 of 7".
    pub total: usize,
}

/// One window of the live children of `page`: the same rows as
/// [`published_children`], ordered by `order`, counted and paged in SQL.
///
/// [`published_children`] reads every child. An index with hundreds of
/// children should return a window from
/// [`PageTypeHandler::children_query`] instead, so the renderer's
/// follow-up reads (tags, translations, grandchildren) stay that size
/// too; the next windows can be served from a [`PageTypeHandler::routes`]
/// pattern such as `page/(?P<n>\d+)` through [`PageTypeHandler::route_context`].
///
/// ```ignore
/// async fn children_query(&self, pool: &Pool, page: &Page)
///     -> Result<Option<Vec<Page>>, ExecError>
/// {
///     let first = rustango_cms::published_children_page(
///         pool, page, rustango_cms::ChildOrder::NewestFirst, 20, 0,
///     ).await?;
///     Ok(Some(first.pages))
/// }
/// ```
///
/// There is no default cap: a cap on the default `sort_order` listing
/// would quietly drop a blog's newest posts, so the type chooses both the
/// order and the size.
///
/// # Errors
/// Driver / query failures from the count or the page lookup.
pub async fn published_children_page(
    pool: &Pool,
    page: &crate::page::Page,
    order: ChildOrder,
    limit: usize,
    offset: usize,
) -> Result<ChildrenPage, ExecError> {
    use rustango::core::NullsOrder;
    use rustango::sql::{CounterPool as _, FetcherPool as _};
    let qs = published_children_qs(pool, page).await;
    let total = usize::try_from(qs.clone().count(pool).await?).unwrap_or_default();
    let keys: &[(&'static str, bool, NullsOrder)] = match order {
        ChildOrder::Position => &[
            ("sort_order", false, NullsOrder::Default),
            ("id", false, NullsOrder::Default),
        ],
        ChildOrder::NewestFirst => &[
            ("published_at", true, NullsOrder::Last),
            ("id", true, NullsOrder::Default),
        ],
        ChildOrder::OldestFirst => &[
            ("published_at", false, NullsOrder::Last),
            ("id", false, NullsOrder::Default),
        ],
    };
    let pages = qs
        .order_by_with_nulls(keys)
        .limit(i64::try_from(limit).unwrap_or(i64::MAX))
        // A huge offset must not wrap negative (backends differ).
        .offset(i64::try_from(offset).unwrap_or(i64::MAX))
        .fetch(pool)
        .await?;
    Ok(ChildrenPage { pages, total })
}

/// A page kind registered by user code (e.g. `BlogPostPage`, `LandingPage`).
///
/// Each impl owns the typed extension table that backs its kind, the
/// template used to render it, its admin form, and the parent/child
/// type whitelist.
///
/// **Registering.** Prefer `#[derive(PageType)]`, which emits this impl
/// plus the inventory registration and forwards the overridable hooks
/// to [`PageTypeOverrides`]. A hand-written impl registers with
/// [`register_page_type!`](crate::register_page_type) and needs only the
/// four required methods (`app_label`, `type_name`, `verbose_name`,
/// `default_template`); every other hook has a no-op default.
///
/// **When hooks run.** Render hooks (`load_extension`, `public_context`,
/// `children_query`, `routes` / `route_context`) run on every public
/// request for a page of this type. Editor hooks (`widgets`,
/// `extra_tabs`, `inline_panels`, `display_fields`) run on the admin
/// edit form; `save_extension` / `save_inline_panel` on its POST, after
/// the `cms_page` row is saved; `preview_extension` on live preview.
///
/// Handlers are process-global — instances are constructed via
/// [`PageTypeHandlerRegistration::factory`] and live for the
/// lifetime of the binary. The matching DB row in
/// `cms_page_type` is per-tenant and seeded by
/// [`crate::ensure_seeded`](crate::seed::ensure_seeded).
#[async_trait]
pub trait PageTypeHandler: Send + Sync + 'static {
    /// Logical app this handler belongs to (e.g. `"cms_articles"`).
    /// Lets multiple crates contribute page types without
    /// `type_name` collisions, and groups them in the admin.
    fn app_label(&self) -> &'static str;

    /// Stable identifier — stored in `cms_page_type.type_name`. Must
    /// be globally unique across the process.
    fn type_name(&self) -> &'static str;

    /// Human-readable label for the admin UI.
    fn verbose_name(&self) -> &'static str;

    /// Default Tera template path the renderer should use. A page can
    /// override it per row via [`Page::template_override`](crate::Page::template_override).
    fn default_template(&self) -> &'static str;

    /// Page types that are allowed as a parent for instances of this
    /// type. Empty slice = no restriction (the *child-side* guard).
    fn allowed_parent_types(&self) -> &'static [&'static str] {
        &[]
    }

    /// Page types that are allowed as direct children of instances of
    /// this type. Empty slice = no restriction (the *parent-side*
    /// guard). Symmetric with [`Self::allowed_parent_types`]: both
    /// sides must agree at create / move time.
    fn allowed_child_types(&self) -> &'static [&'static str] {
        &[]
    }

    /// Whether this type is a **leaf** — it accepts no child pages at
    /// all. Distinct from `allowed_child_types() == []`, which means "no
    /// restriction" (any type may be a child). Returning `true` is the
    /// first-class way to say "this page can't have children"
    /// without the sentinel hack of whitelisting a
    /// non-existent child type. Enforced parent-side at create / move
    /// time.
    fn is_leaf(&self) -> bool {
        false
    }

    /// Whether this type may be created from the admin "Add page"
    /// menu. Defaults to `true`; abstract / programmatically-only
    /// types should override to `false`.
    fn is_creatable(&self) -> bool {
        true
    }

    /// Material-symbols icon name for the page-type picker tile.
    /// Defaults to `None` — picker renders a generic glyph. Authors
    /// set it via `#[page_type(icon = "article")]` on the
    /// `#[derive(PageType)]` struct, or by overriding this method on
    /// hand-rolled handlers.
    fn icon(&self) -> Option<&'static str> {
        None
    }

    /// One-line description shown under `verbose_name` in the
    /// page-type picker. Defaults to `None`. Authors set it via
    /// `#[page_type(description = "…")]`.
    fn description(&self) -> Option<&'static str> {
        None
    }

    /// Opt this page type in to a public RSS 2.0 / Atom 1.0 feed
    /// (powered by [`rustango::syndication`]). The returned slug is
    /// the URL path segment under `/feed/<slug>/rss.xml` +
    /// `/feed/<slug>/atom.xml`; pick something URL-friendly and
    /// distinct from other page types' slugs.
    ///
    /// Returning `None` (the default) means no feed is emitted for
    /// this type — its pages still render normally; they just
    /// don't appear in any aggregate feed.
    ///
    /// The feed lists every published, indexable [`crate::Page`]
    /// row of this type in `published_at desc` order. See
    /// [`crate::feed`] for the URL shape and content mapping.
    fn feed_kind(&self) -> Option<&'static str> {
        None
    }

    /// Opt this page type in to a multi-step approval workflow.
    /// Returns the [`Workflow`](crate::workflow::Workflow) `name` of the workflow
    /// to apply to pages of this type, or `None` to leave them on the
    /// direct-publish path.
    ///
    /// When this returns `Some("Editorial review")`, the page editor
    /// for pages of this type renders a Submit-for-review action
    /// that creates a `cms_workflow_state` row and walks the page
    /// through the workflow's tasks. Pages can only finish a
    /// workflow once the final task is approved.
    ///
    /// The workflow with the returned name must exist + be active in
    /// the tenant's `cms_workflow` table — admins create + manage
    /// workflows at `/cms-admin/workflows`. If the named workflow
    /// doesn't exist or is inactive, pages fall back to the
    /// direct-publish path.
    fn workflow_slug(&self) -> Option<&'static str> {
        None
    }

    /// Gate every page of this type behind an access requirement — the
    /// per-**type** analogue of the per-page Privacy tab. Return
    /// `None` (the default) to leave the type public; return
    /// [`crate::view_restriction::TypeViewRestriction::login`] to require
    /// any authenticated member, or
    /// [`crate::view_restriction::TypeViewRestriction::permission`] to
    /// require one of a set of permission codenames (checked through the
    /// framework permission engine).
    ///
    /// A page/subtree restriction set on an individual page (or an
    /// ancestor) is more specific and overrides this type-level default.
    /// The derive forwards to
    /// [`PageTypeOverrides::view_restriction`] automatically.
    fn view_restriction(&self) -> Option<crate::view_restriction::TypeViewRestriction> {
        None
    }

    /// Which representation this type serves on its public URL.
    ///
    /// Defaults to [`crate::page_view::PageViewMode::Auto`], which
    /// derives the answer from [`Self::default_template`]: a blank
    /// template means the type is JSON-only, anything else means HTML.
    /// Return [`crate::page_view::PageViewMode::Api`] to serve JSON at
    /// the page's own URL under `Accept: application/json` even when a
    /// template exists — the template still answers browsers.
    ///
    /// Set it declaratively with `#[page_type(view_mode = "api")]`,
    /// which also makes the otherwise-mandatory `template` attribute
    /// optional. Without the attribute the derive forwards to
    /// [`PageTypeOverrides::view_mode`].
    fn view_mode(&self) -> crate::page_view::PageViewMode {
        crate::page_view::PageViewMode::Auto
    }

    /// Load the typed extension row for a given page id and return
    /// it as JSON for the renderer's Tera context.
    ///
    /// The default implementation returns `Value::Null` — types
    /// with no extension table (e.g. a `HomePage` whose data lives
    /// entirely on the base Page row) get a null `extension` value
    /// in the template context.
    ///
    /// # Errors
    /// Driver / query failures from the extension lookup.
    async fn load_extension(&self, _pool: &Pool, _page_id: i64) -> Result<Value, ExecError> {
        Ok(Value::Null)
    }

    /// URL patterns this page type serves IN ADDITION to its
    /// canonical `url_path`.
    ///
    /// Each [`crate::routable::RouteSpec`] declares a regex pattern
    /// (matched against the suffix BELOW the page's `url_path`) and
    /// a stable name. When the public resolver can't find an exact
    /// `url_path` match it walks ancestor candidates and asks each
    /// candidate's handler whether any of its routes accept the
    /// remaining suffix. On match, the renderer dispatches to
    /// [`Self::route_context`] for handler-injected ctx, and the
    /// matched [`crate::routable::RouteMatch`] is exposed to the
    /// template as `route_name` + `route_captures`.
    ///
    /// Default: empty — page types without routable patterns pay
    /// nothing.
    fn routes(&self) -> Vec<crate::routable::RouteSpec> {
        Vec::new()
    }

    /// Handler-computed ctx injected when a routable pattern matched.
    /// Mirrors [`Self::public_context`] but receives the matched
    /// route's name + named capture groups. Override to load
    /// route-specific data — the year's posts when `archive_year`
    /// matched, the tagged posts when `tag` matched, etc.
    ///
    /// Default returns an empty map; the renderer still threads
    /// `route_name` and `route_captures` into the context so a
    /// handler that only needs the captures (no extra fetches) can
    /// stay on the default.
    ///
    /// # Errors
    /// Driver / query failures from the route-specific computation.
    async fn route_context(
        &self,
        _pool: &Pool,
        _page: &crate::page::Page,
        _matched: &crate::routable::RouteMatch,
    ) -> Result<serde_json::Map<String, Value>, ExecError> {
        Ok(serde_json::Map::new())
    }

    /// What a matched routable pattern renders: the usual template, a
    /// template of its own ([`crate::routable::RouteOutcome::Template`]),
    /// or the site's 404 page when the record the URL names does not
    /// exist ([`crate::routable::RouteOutcome::NotFound`]). Receives the
    /// map [`Self::route_context`] returned, so the choice can depend on
    /// loaded data (one template per kind of record, a missing id).
    fn route_outcome(
        &self,
        _matched: &crate::routable::RouteMatch,
        _route_ctx: &serde_json::Map<String, Value>,
    ) -> crate::routable::RouteOutcome {
        crate::routable::RouteOutcome::Render
    }

    /// Inject handler-computed values into the public render's Tera
    /// context, for hand-rolled
    /// data — e.g. a `HomePage` that exposes a `latest_posts` list
    /// to its template without baking the query into the template
    /// layer.
    ///
    /// The default returns an empty map; override in
    /// [`PageTypeOverrides`] (or hand-rolled handlers) to surface
    /// extras. Framework keys (`page`, `page_type`, `extension`,
    /// `children`, `ancestors`, `url_prefix`, `locale`,
    /// `translations`, `theme_*`, `_snippets_html`, `_stream_html`,
    /// `_pages_by_id`) are stamped AFTER the handler's keys, so
    /// `public_context` can't shadow them — pick distinct names
    /// for custom keys.
    ///
    /// # Errors
    /// Driver / query failures from the handler-side computation.
    async fn public_context(
        &self,
        _pool: &Pool,
        _page: &crate::page::Page,
    ) -> Result<serde_json::Map<String, Value>, ExecError> {
        Ok(serde_json::Map::new())
    }

    /// Build the `children` ctx var the public renderer hands to the
    /// page template — index-style pages (a blog index, an archive)
    /// lean on this to choose which children they list and in what
    /// order.
    ///
    /// The default is [`published_children`]: the live children, ordered
    /// `sort_order, id`, all of them. A type with many children should
    /// return one window from [`published_children_page`] instead, which
    /// also takes the order; the renderer's follow-up reads (tags,
    /// translations, grandchildren) are sized by what this returns.
    ///
    /// The result lands in two places in the template context:
    /// `children` (the typed list) AND a thread-local backing the
    /// `children_filtered(...)` Tera function (see [`crate::children_filtered`]),
    /// which filters and limits this list in memory.
    ///
    /// # Errors
    /// Driver / query failures from the page lookup.
    async fn children_query(
        &self,
        pool: &Pool,
        page: &crate::page::Page,
    ) -> Result<Vec<crate::page::Page>, ExecError> {
        default_children(pool, page).await
    }

    /// Describe the extension-row's fields so the admin page-editor
    /// can render a form section for them. The default returns an
    /// empty list — types without an extension table get no extra
    /// inputs in the editor.
    ///
    /// `page_id` is provided so handlers can pre-fill values from
    /// the existing row (the typical impl: load the row, then map
    /// each column into an `ExtensionField` with `value`).
    ///
    /// # Errors
    /// Driver / query failures from the extension lookup.
    async fn extension_fields(
        &self,
        _pool: &Pool,
        _page_id: i64,
    ) -> Result<Vec<ExtensionField>, ExecError> {
        Ok(Vec::new())
    }

    /// Rich-widget alternative to [`Self::extension_fields`].
    /// Returns full [`crate::Widget`] instances so handlers can
    /// expose the entire 26-kind widget catalog (Date, DatetimeTz,
    /// Color, Range, Radio, Select, Checkboxes, MultiSelect,
    /// Custom, …) instead of being limited to the legacy six
    /// [`ExtensionFieldKind`] variants.
    ///
    /// Default impl delegates to [`Self::extension_fields`] +
    /// [`ExtensionField::into_widget`], so handlers that haven't
    /// overridden this method keep working unchanged. Handlers
    /// that want the new kinds override `widgets` instead of
    /// `extension_fields`; the admin form-render path always calls
    /// `widgets`, so a single override surfaces every kind in the
    /// editor at once.
    ///
    /// # Errors
    /// Driver / query failures propagated from the handler-side
    /// computation.
    async fn widgets(&self, pool: &Pool, page_id: i64) -> Result<Vec<crate::Widget>, ExecError> {
        Ok(self
            .extension_fields(pool, page_id)
            .await?
            .into_iter()
            .map(ExtensionField::into_widget)
            .collect())
    }

    /// Declared Page↔Snippet many-to-many relations as
    /// `(relation_name, snippet_type)` pairs. Macro-generated
    /// from the struct-level `#[page_type(snippet_m2m(name = "Type", …))]`
    /// attribute; the default is none. The public renderer resolves each
    /// relation's chosen rows into `snippet_relations.<name>` so templates
    /// can iterate the related snippets.
    fn snippet_m2m_relations(&self) -> Vec<(&'static str, &'static str)> {
        Vec::new()
    }

    /// Build a virtual extension `Value` from a posted form `HashMap`
    /// without touching the persisted row. Powers the "preview
    /// unsaved changes" iframe in the page editor — the renderer
    /// substitutes the result for [`Self::load_extension`] so the
    /// preview reflects the current form state.
    ///
    /// Default impl walks [`Self::widgets`] and maps each widget's
    /// `name` to the form value, with kind-aware coercion (booleans
    /// from `"on"`/`"true"`, multi-value kinds parsed as JSON arrays,
    /// numeric kinds parsed into `serde_json::Number`). Handlers
    /// whose persisted shape differs from the widget surface should
    /// override.
    ///
    /// # Errors
    /// Driver / query failures from the widgets lookup (the
    /// form-to-JSON mapping itself is infallible).
    async fn preview_extension(
        &self,
        pool: &Pool,
        page_id: i64,
        form: &std::collections::HashMap<String, String>,
    ) -> Result<Value, ExecError> {
        let widgets = self.widgets(pool, page_id).await.unwrap_or_default();
        let mut map = serde_json::Map::new();
        for w in widgets {
            let raw = form.get(&w.name).map(String::as_str).unwrap_or_default();
            // One coercion table for page fields and builder fields (#660).
            let val = crate::page_builder::values::coerce(w.kind, raw);
            map.insert(w.name, val);
        }
        Ok(Value::Object(map))
    }

    /// Persist the posted form values into this type's extension
    /// table. Called by the admin's page-edit POST handler after the
    /// canonical `cms_page` row has been saved. Upsert keyed on
    /// `page_id` is the standard pattern.
    ///
    /// `form` is the full form HashMap; handlers should pull out
    /// only the keys whose `name` they returned from
    /// [`Self::extension_fields`].
    ///
    /// # Errors
    /// Driver / query failures from the upsert.
    async fn save_extension(
        &self,
        _pool: &Pool,
        _page_id: i64,
        _form: &std::collections::HashMap<String, String>,
    ) -> Result<(), ExecError> {
        Ok(())
    }

    /// Handler-contributed tabs appended to the page-editor's tab
    /// strip after the built-in `Content` / `Promote` / `Theme` /
    /// `Revisions` ones. Each [`TabSpec`] carries a stable `name`
    /// (used in the URL hash + localStorage for "remember last
    /// active tab"), a `label`, an optional Material-symbols `icon`
    /// + small `badge` chip, and a pre-rendered HTML body the
    /// admin template emits inside the main `<form>`.
    ///
    /// Because custom tab bodies sit inside the canonical form, any
    /// `<input name="…">` inside one shows up in the
    /// `HashMap<String, String>` handed to [`Self::save_extension`]
    /// — handlers can persist tab-scoped fields the same way they
    /// persist [`Self::widgets`] entries.
    ///
    /// Default impl returns an empty list — the built-in tabs are
    /// always present and self-contained, so handlers that don't
    /// need a custom tab pay nothing.
    ///
    /// # Errors
    /// Driver / query failures from the handler-side computation.
    async fn extra_tabs(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<TabSpec>, ExecError> {
        Ok(Vec::new())
    }

    /// Inline panels — 1-N collections of sub-rows that the page
    /// editor renders as a sortable list of cards. Each [`InlinePanelSpec`] declares the panel's
    /// stable `name`, the human `label`, the per-row `fields`, and
    /// optional cardinality bounds.
    ///
    /// Default impl returns an empty list — handlers that don't use
    /// inline panels pay nothing. Handlers that do override this
    /// method must also implement [`Self::load_inline_panel`] and
    /// [`Self::save_inline_panel`] for the rows to round-trip.
    ///
    /// Async with the pool and the page (`0` for a page not saved yet), so
    /// a panel can take its options or its locks from the database.
    ///
    /// # Errors
    /// Driver / query failures building the specs.
    async fn inline_panels(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<InlinePanelSpec>, ExecError> {
        Ok(Vec::new())
    }

    /// Fetch existing rows for `panel_name` keyed under `page_id`.
    /// Each returned `serde_json::Map` is one row; keys match the
    /// `name` of the [`InlinePanelSpec::fields`] entries.
    ///
    /// Default impl returns an empty list.
    ///
    /// # Errors
    /// Driver / query failures from the row lookup.
    async fn load_inline_panel(
        &self,
        _pool: &Pool,
        _page_id: i64,
        _panel_name: &str,
    ) -> Result<Vec<serde_json::Map<String, Value>>, ExecError> {
        Ok(Vec::new())
    }

    /// Persist the posted rows for `panel_name` under `page_id`. The
    /// admin POST handler parses inline-panel form keys
    /// (`inline__<panel_name>__<row_idx>__<field>`) into row dicts
    /// and calls this with the full set; the handler is responsible
    /// for the upsert / delete-removed semantics. Sort order is the
    /// position in the `rows` slice.
    ///
    /// Default impl is a no-op.
    ///
    /// # Errors
    /// Driver / query failures from the upsert.
    async fn save_inline_panel(
        &self,
        _pool: &Pool,
        _page_id: i64,
        _panel_name: &str,
        _rows: &[serde_json::Map<String, Value>],
    ) -> Result<(), ExecError> {
        Ok(())
    }

    /// Per-row panels: each row's id and title, in order. See
    /// [`InlinePanelSpec::per_row`](InlinePanelSpec#structfield.per_row).
    ///
    /// # Errors
    /// Driver / query failures.
    async fn inline_rows(&self, _pool: &Pool, _page_id: i64, _panel: &str) -> Result<Vec<InlineRowSummary>, ExecError> {
        Ok(Vec::new())
    }

    /// Per-row panels: one row's values, keyed by widget name (`None` id:
    /// a new row's starting values). `Ok(None)`: no such row on this page.
    ///
    /// # Errors
    /// Driver / query failures.
    async fn inline_row(
        &self,
        _pool: &Pool,
        _page_id: i64,
        _panel: &str,
        _row_id: Option<i64>,
    ) -> Result<Option<serde_json::Map<String, Value>>, ExecError> {
        Ok(None)
    }

    /// Per-row panels: store one row from its posted values (`None` id:
    /// add it). Values arrive as the browser posts them; an unchecked
    /// switch is absent.
    ///
    /// # Errors
    /// Driver / query failures (validation problems are `Invalid`).
    async fn save_inline_row(
        &self,
        _pool: &Pool,
        _page_id: i64,
        _panel: &str,
        _row_id: Option<i64>,
        _values: &serde_json::Map<String, Value>,
    ) -> Result<InlineRowSaved, ExecError> {
        Ok(InlineRowSaved::Invalid(vec![crate::admin::cms_admin::FieldError::new("_form", "This panel can't be saved.")]))
    }

    /// Per-row panels: remove one row. `Ok(false)`: refused.
    ///
    /// # Errors
    /// Driver / query failures.
    async fn delete_inline_row(&self, _pool: &Pool, _page_id: i64, _panel: &str, _row_id: i64) -> Result<bool, ExecError> {
        Ok(false)
    }

    /// Per-row panels: store a new order (`ids` first to last).
    ///
    /// # Errors
    /// Driver / query failures.
    async fn reorder_inline_rows(&self, _pool: &Pool, _page_id: i64, _panel: &str, _ids: &[i64]) -> Result<(), ExecError> {
        Ok(())
    }

    /// Computed / display-only fields shown in an "At a glance"
    /// panel at the top of the page-edit form. Each entry is a
    /// pre-rendered HTML chip (the value is `| safe`d into the
    /// template) authored by the handler from arbitrary data:
    /// row counts, word counts, derived flags, audit timestamps,
    /// linked-snippet previews, etc.
    ///
    /// This is the first-class hook for read-only computed values
    /// in the editor (static help text and plain model fields can't
    /// show them).
    /// `display_fields` runs at edit-form GET, so each value is
    /// recomputed every load and reflects the latest DB state.
    ///
    /// Default impl returns an empty list — handlers that don't
    /// need it pay nothing.
    ///
    /// # Errors
    /// Driver / query failures from any computation the handler
    /// runs against the pool.
    async fn display_fields(
        &self,
        _pool: &Pool,
        _page_id: i64,
    ) -> Result<Vec<DisplayField>, ExecError> {
        Ok(Vec::new())
    }
}

/// One computed display chip rendered in the page-edit form's "At
/// a glance" panel. See [`PageTypeHandler::display_fields`].
///
/// `html` is trusted — emitted through `| safe` in the bundled
/// template. Handlers escape user-controlled content themselves
/// (e.g. via `tera::escape_html` or by passing through
/// [`crate::markdown::render`] which sanitizes).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DisplayField {
    /// Short label, e.g. "Word count" or "Last edited".
    pub label: String,
    /// Pre-rendered HTML fragment. Emitted with `| safe`.
    pub html: String,
    /// Optional helptext shown beneath the value.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub help: String,
    /// Optional material-symbols icon name shown next to the label
    /// (e.g. `"format_list_numbered"`, `"schedule"`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
}

impl DisplayField {
    /// Smallest possible chip — just `(label, html)`. Caller adds
    /// `help` / `icon` fluently if needed.
    #[must_use]
    pub fn new(label: impl Into<String>, html: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            html: html.into(),
            help: String::new(),
            icon: None,
        }
    }

    #[must_use]
    pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
        self.icon = Some(icon.into());
        self
    }

    #[must_use]
    pub fn with_help(mut self, help: impl Into<String>) -> Self {
        self.help = help.into();
        self
    }
}

/// How a custom tab's body is supplied. Three shapes:
///
/// - `Html(s)` — pre-rendered HTML (backwards-compatible escape
///   hatch; what `TabSpec::new(..., html)` produces).
/// - `Template { path, context }` — a Tera template path + a
///   per-tab context map. The page editor renders the template
///   server-side with the standard admin chrome context PLUS the
///   spec's own `context` map merged in, and drops the resulting
///   HTML into the tab panel.
/// - `Widgets(widgets)` — declarative form fields. The editor
///   renders each [`crate::Widget`] via the same `_widget.html`
///   macro the Content tab's main stack uses, so widget visuals +
///   behavior stay identical wherever they appear.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TabBody {
    Html(String),
    Template {
        path: String,
        #[serde(default)]
        context: serde_json::Map<String, serde_json::Value>,
    },
    Widgets(Vec<crate::widget::Widget>),
    /// Field group panel. Groups widgets
    /// under a heading; `layout` picks vertical stack vs side-by-side.
    /// Optional `help` renders as a hint paragraph between the
    /// heading and the field grid.
    Group {
        heading: String,
        #[serde(default, skip_serializing_if = "String::is_empty")]
        help: String,
        #[serde(default)]
        layout: PanelLayout,
        widgets: Vec<crate::widget::Widget>,
    },
    /// Help panel. Static informational block — no form
    /// fields. The body is HTML emitted via `| safe` after CMS-side
    /// authoring; trust source is the handler author.
    Help {
        content: String,
    },
}

/// Layout direction for [`TabBody::Group`].
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PanelLayout {
    /// Stack widgets vertically (default).
    #[default]
    Column,
    /// Lay widgets out side-by-side (responsive flex; collapses to
    /// column on narrow viewports).
    Row,
}

impl PanelLayout {
    /// CSS class suffix — used by `_panel_group.html` to switch the
    /// flex direction.
    #[must_use]
    pub fn class_suffix(self) -> &'static str {
        match self {
            Self::Column => "column",
            Self::Row => "row",
        }
    }
}

/// One inline panel declaration — a 1-N relation between the page
/// and a child table the handler maintains. See
/// [`PageTypeHandler::inline_panels`]. The admin editor renders each row
/// as a card of widgets (any [`crate::Widget`] kind: selects, switches,
/// the media chooser…) with add, remove and move up / down, in the
/// Content tab or in a tab of its own ([`Self::in_tab`]).
///
/// Every row carries its `id` (when the loaded row has one) in a hidden
/// field, so [`PageTypeHandler::save_inline_panel`] can tell existing
/// rows from new ones. A loaded row's `__title` key, when set, is shown
/// as the card's heading.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InlinePanelSpec {
    /// Stable identifier — used in form field names
    /// (`inline__<name>__<row>__<field>`). Snake_case conventional.
    pub name: String,
    /// Visible label shown above the panel.
    pub label: String,
    /// Per-row field surface. Each entry renders one input per row.
    pub fields: Vec<ExtensionField>,
    /// Optional minimum row count (inclusive). When set + the editor
    /// submits fewer rows, the save handler logs a warning but
    /// doesn't reject — handlers enforce hard rules themselves.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_num: Option<usize>,
    /// Optional maximum row count (inclusive).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_num: Option<usize>,
    /// Optional helptext shown beneath the panel header.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub help: String,
    /// Optional material-symbols icon name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
    /// Per-row widgets. When non-empty they replace [`Self::fields`],
    /// giving rows every widget kind. Names are the row keys.
    #[serde(default)]
    pub widgets: Vec<crate::widget::Widget>,
    /// Render the panel in its own editor tab with this label instead
    /// of the Content tab. Panels naming the same tab share it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tab: Option<String>,
    /// What one row is called, e.g. "Cause" (the add button reads
    /// "Add cause").
    #[serde(default)]
    pub row_label: String,
    /// Editors may add rows.
    #[serde(default = "yes")]
    pub can_add: bool,
    /// Editors may remove rows.
    #[serde(default = "yes")]
    pub can_delete: bool,
    /// Editors may reorder rows (the saved order is the row order).
    #[serde(default = "yes")]
    pub can_order: bool,
    /// Per-row mode: the tab lists only each row's title; a card's fields
    /// load when it is opened, it saves with its own Save button, and add,
    /// remove and reorder take effect at once. The page's Save sends
    /// nothing for this panel. Uses the `*_inline_row*` hooks instead of
    /// [`PageTypeHandler::load_inline_panel`] / `save_inline_panel`. For
    /// panels with many rows.
    #[serde(default)]
    pub per_row: bool,
}

/// One row of a per-row inline panel, as its card header shows it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InlineRowSummary {
    pub id: i64,
    pub title: String,
}

/// What [`PageTypeHandler::save_inline_row`] did.
#[derive(Debug, Clone)]
pub enum InlineRowSaved {
    /// Stored; the row's id and the title its card should show.
    Saved { id: i64, title: String },
    /// Not stored: one message per field (`"_form"` for the whole row).
    Invalid(Vec<crate::admin::cms_admin::FieldError>),
}

fn yes() -> bool {
    true
}

impl InlinePanelSpec {
    /// Smallest valid spec — `(name, label, fields)`. Helpers below
    /// add `min` / `max` / `help` / `icon` fluently.
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        label: impl Into<String>,
        fields: Vec<ExtensionField>,
    ) -> Self {
        Self {
            name: name.into(),
            label: label.into(),
            fields,
            min_num: None,
            max_num: None,
            help: String::new(),
            icon: None,
            widgets: Vec::new(),
            tab: None,
            row_label: String::new(),
            can_add: true,
            can_delete: true,
            can_order: true,
            per_row: false,
        }
    }

    /// Per-row mode — see [`Self::per_row`](InlinePanelSpec#structfield.per_row).
    #[must_use]
    pub fn per_row(mut self) -> Self {
        self.per_row = true;
        self
    }

    /// A panel whose rows are full widgets — see [`Self::widgets`].
    #[must_use]
    pub fn with_widgets(
        name: impl Into<String>,
        label: impl Into<String>,
        widgets: Vec<crate::widget::Widget>,
    ) -> Self {
        let mut spec = Self::new(name, label, Vec::new());
        spec.widgets = widgets;
        spec
    }

    /// Show the panel in its own editor tab labelled `tab`.
    #[must_use]
    pub fn in_tab(mut self, tab: impl Into<String>) -> Self {
        self.tab = Some(tab.into());
        self
    }

    /// Name one row, e.g. "Cause".
    #[must_use]
    pub fn with_row_label(mut self, label: impl Into<String>) -> Self {
        self.row_label = label.into();
        self
    }

    /// Which row operations editors get. A panel whose rows another
    /// system owns sets `add` and `delete` to `false`.
    #[must_use]
    pub fn allow(mut self, add: bool, delete: bool, order: bool) -> Self {
        self.can_add = add;
        self.can_delete = delete;
        self.can_order = order;
        self
    }

    /// The widgets one row renders: [`Self::widgets`], or the legacy
    /// [`Self::fields`] converted.
    #[must_use]
    pub fn row_widgets(&self) -> Vec<crate::widget::Widget> {
        if self.widgets.is_empty() {
            self.fields.iter().cloned().map(ExtensionField::into_widget).collect()
        } else {
            self.widgets.clone()
        }
    }

    #[must_use]
    pub fn with_min(mut self, min: usize) -> Self {
        self.min_num = Some(min);
        self
    }

    #[must_use]
    pub fn with_max(mut self, max: usize) -> Self {
        self.max_num = Some(max);
        self
    }

    #[must_use]
    pub fn with_help(mut self, help: impl Into<String>) -> Self {
        self.help = help.into();
        self
    }

    #[must_use]
    pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
        self.icon = Some(icon.into());
        self
    }
}

/// One handler-contributed tab appended to the page-editor's
/// built-in tab strip (Content / Promote / Theme / Revisions). See
/// [`PageTypeHandler::extra_tabs`].
///
/// The body is one of [`TabBody::Html`] (pre-rendered HTML — the
/// escape hatch), [`TabBody::Template`] (Tera template path + extra
/// context — render with the standard admin context vars in scope),
/// or [`TabBody::Widgets`] (declarative widget list — rendered via
/// `_widget.html` so the form fields look identical to the Content
/// tab's stack).
///
/// Inputs declared inside the rendered HTML land in
/// [`PageTypeHandler::save_extension`]'s form HashMap automatically;
/// every variant lives inside the page-edit `<form>`.
///
/// `name` must be unique within a page's tab set. Mixing with the
/// built-in names (`content`, `promote`, `theme`, `revisions`) is
/// allowed and lets a handler override the BUILT-IN tab body without
/// forking the template; the tab JS keys off `data-tab-trigger="<name>"`
/// so identical names render the same panel.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TabSpec {
    /// Stable identifier — kebab-case is conventional. Used for
    /// `aria-controls`, URL hash links, and the per-page localStorage
    /// "remember last active tab" key.
    pub name: String,
    /// Visible label on the tab button.
    pub label: String,
    /// Optional Material-symbols icon name (e.g. `"workflow"`,
    /// `"insights"`). Rendered to the left of `label`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
    /// Optional small chip rendered after `label` (e.g. an unread
    /// count, "new", or a small status indicator).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub badge: Option<String>,
    /// What goes inside the tab panel — see [`TabBody`].
    pub body: TabBody,
}

impl TabSpec {
    /// Smallest possible spec — just `(name, label, html)`. The
    /// `html` is treated as pre-rendered + emitted via Tera's
    /// `| safe`. Backwards-compatible with the v0.2 surface.
    #[must_use]
    pub fn new(name: impl Into<String>, label: impl Into<String>, html: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            label: label.into(),
            icon: None,
            badge: None,
            body: TabBody::Html(html.into()),
        }
    }

    /// Tera-template-backed tab. The renderer mounts `path` with the
    /// standard admin context plus the per-tab context map (empty
    /// until filled with [`Self::with_context_value`]). Example:
    /// `TabSpec::template("seo", "SEO", "blog/seo_tab.html")`.
    #[must_use]
    pub fn template(
        name: impl Into<String>,
        label: impl Into<String>,
        path: impl Into<String>,
    ) -> Self {
        Self {
            name: name.into(),
            label: label.into(),
            icon: None,
            badge: None,
            body: TabBody::Template {
                path: path.into(),
                context: serde_json::Map::new(),
            },
        }
    }

    /// Widget-group-backed tab. Same rendering pipeline the Content
    /// tab uses — each widget is emitted via `_widget.html`'s macro.
    /// Inputs submit alongside the page-edit form so the handler's
    /// [`PageTypeHandler::save_extension`] picks them up by name.
    #[must_use]
    pub fn widgets(
        name: impl Into<String>,
        label: impl Into<String>,
        widgets: Vec<crate::widget::Widget>,
    ) -> Self {
        Self {
            name: name.into(),
            label: label.into(),
            icon: None,
            badge: None,
            body: TabBody::Widgets(widgets),
        }
    }

    /// Field-group tab — heading + (optional help) +
    /// widgets stacked under one section. Use [`Self::with_layout`]
    /// to switch to row layout.
    #[must_use]
    pub fn group(
        name: impl Into<String>,
        label: impl Into<String>,
        heading: impl Into<String>,
        widgets: Vec<crate::widget::Widget>,
    ) -> Self {
        Self {
            name: name.into(),
            label: label.into(),
            icon: None,
            badge: None,
            body: TabBody::Group {
                heading: heading.into(),
                help: String::new(),
                layout: PanelLayout::Column,
                widgets,
            },
        }
    }

    /// Help tab — static HTML content, no form fields.
    /// The body is emitted via `| safe`, so authors control the markup.
    #[must_use]
    pub fn help(
        name: impl Into<String>,
        label: impl Into<String>,
        content: impl Into<String>,
    ) -> Self {
        Self {
            name: name.into(),
            label: label.into(),
            icon: None,
            badge: None,
            body: TabBody::Help {
                content: content.into(),
            },
        }
    }

    /// Switch a Group-body tab to a different layout. No-op on other
    /// body variants.
    #[must_use]
    pub fn with_layout(mut self, layout: PanelLayout) -> Self {
        if let TabBody::Group {
            layout: ref mut existing,
            ..
        } = self.body
        {
            *existing = layout;
        }
        self
    }

    /// Attach help text to a Group-body tab. No-op on other body
    /// variants.
    #[must_use]
    pub fn with_help(mut self, help: impl Into<String>) -> Self {
        if let TabBody::Group {
            help: ref mut existing,
            ..
        } = self.body
        {
            *existing = help.into();
        }
        self
    }

    #[must_use]
    pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
        self.icon = Some(icon.into());
        self
    }

    #[must_use]
    pub fn with_badge(mut self, badge: impl Into<String>) -> Self {
        self.badge = Some(badge.into());
        self
    }

    /// Insert a context entry — only meaningful for the
    /// [`TabBody::Template`] variant; a no-op on `Html` / `Widgets`.
    /// Chain multiple times for multiple values.
    #[must_use]
    pub fn with_context_value(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        if let TabBody::Template { context, .. } = &mut self.body {
            context.insert(key.into(), value);
        }
        self
    }
}

/// Inventory entry — drop one of these next to each
/// `PageTypeHandler` impl (or use [`crate::register_page_type!`])
/// and it becomes discoverable at runtime via [`registered_handlers`].
pub struct PageTypeHandlerRegistration {
    pub factory: fn() -> Box<dyn PageTypeHandler>,
}

inventory::collect!(PageTypeHandlerRegistration);

/// All `PageTypeHandler`s registered in the current binary.
pub fn registered_handlers() -> impl Iterator<Item = Box<dyn PageTypeHandler>> {
    inventory::iter::<PageTypeHandlerRegistration>
        .into_iter()
        .map(|r| (r.factory)())
}

/// Look up a registered handler by `type_name`.
pub fn find_handler(type_name: &str) -> Option<Box<dyn PageTypeHandler>> {
    registered_handlers().find(|p| p.type_name() == type_name)
}

/// `true` when **any** registered handler declares a per-type
/// [`PageTypeHandler::view_restriction`] (#members). Cached — the
/// handler registry is static for the life of the process — so the
/// hot menu-filtering path can skip the per-type restriction lookup
/// entirely on binaries that gate nothing by type.
#[must_use]
pub fn any_type_view_restriction() -> bool {
    static CACHED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *CACHED.get_or_init(|| registered_handlers().any(|h| h.view_restriction().is_some()))
}

/// Optional-override trait for declarative page types defined via
/// `#[derive(PageType)]`. The derive emits the full
/// [`PageTypeHandler`] impl and delegates every author-overridable
/// method (`allowed_parent_types`, `allowed_child_types`,
/// `is_creatable`, `feed_kind`, `display_fields`, `extra_tabs`) to
/// `<Self as PageTypeOverrides>::*`. Every method has a sensible
/// default; an author that doesn't need overrides writes a one-line
/// `impl PageTypeOverrides for MyPage {}`.
///
/// ## Why a separate trait
///
/// The derive can't conditionally emit a default impl (Rust forbids
/// two impls of the same trait for the same type). Splitting the
/// overridable methods into a sibling trait gives authors a clean
/// opt-in: write the impl, override what you need, accept defaults
/// for the rest. The `PageTypeHandler` impl the derive emits handles
/// the wire-up.
#[async_trait]
pub trait PageTypeOverrides: Send + Sync + 'static {
    /// Allowed parent types — see [`PageTypeHandler::allowed_parent_types`].
    fn allowed_parent_types(&self) -> &'static [&'static str] {
        &[]
    }

    /// Allowed child types — see [`PageTypeHandler::allowed_child_types`].
    fn allowed_child_types(&self) -> &'static [&'static str] {
        &[]
    }

    /// Whether this type may be created from the admin — see
    /// [`PageTypeHandler::is_creatable`].
    fn is_creatable(&self) -> bool {
        true
    }

    /// Public feed slug — see [`PageTypeHandler::feed_kind`].
    /// The derive prefers a struct-level
    /// `#[page_type(feed_kind = "…")]` attr over this default, so
    /// most authors set it via the attribute, not by overriding here.
    fn feed_kind(&self) -> Option<&'static str> {
        None
    }

    /// Workflow opt-in slug — see [`PageTypeHandler::workflow_slug`].
    /// The derive prefers a struct-level
    /// `#[page_type(workflow = "Editorial review")]` attr over this
    /// default. Override here only when the workflow needs to be
    /// computed (e.g. choose between workflows based on tenant
    /// configuration).
    fn workflow_slug(&self) -> Option<&'static str> {
        None
    }

    /// Per-type access gate — see [`PageTypeHandler::view_restriction`].
    /// Override to require a login or a permission codename for every
    /// page of this type. The derive forwards to this automatically.
    fn view_restriction(&self) -> Option<crate::view_restriction::TypeViewRestriction> {
        None
    }

    /// Which representation this type serves — see
    /// [`PageTypeHandler::view_mode`]. Override to return
    /// [`crate::page_view::PageViewMode::Api`] when the type should
    /// answer JSON on its own URL. The derive forwards to this unless
    /// `#[page_type(view_mode = "…")]` is set, which wins.
    fn view_mode(&self) -> crate::page_view::PageViewMode {
        crate::page_view::PageViewMode::Auto
    }

    /// Computed display chips — see [`PageTypeHandler::display_fields`].
    async fn display_fields(
        &self,
        _pool: &Pool,
        _page_id: i64,
    ) -> Result<Vec<DisplayField>, ExecError> {
        Ok(Vec::new())
    }

    /// Handler-injected template ctx — see
    /// [`PageTypeHandler::public_context`]. The derive forwards to
    /// this override automatically; hand-rolled handlers can opt in
    /// via `impl PageTypeOverrides for MyHandler { … }`.
    ///
    /// With `#[derive(PageType)]`, `self` is the page's **stored row**
    /// (its extension fields as saved), so `self.<field>` reads the
    /// page's own values. A page without a saved row yet gets the
    /// type's `Default` value. The same holds for
    /// [`Self::route_context`].
    async fn public_context(
        &self,
        _pool: &Pool,
        _page: &crate::page::Page,
    ) -> Result<serde_json::Map<String, Value>, ExecError> {
        Ok(serde_json::Map::new())
    }

    /// Override the children listing this page exposes to its template —
    /// see [`PageTypeHandler::children_query`]. Return `Ok(None)` (the
    /// default) to keep the framework behavior ([`published_children`]:
    /// live children, `sort_order, id`).
    /// Return `Ok(Some(pages))` to
    /// make this type an index that lists e.g. only published children in
    /// a custom order — [`published_children`] is the common building
    /// block, and [`published_children_page`] the bounded one for an
    /// index with many children:
    ///
    /// ```ignore
    /// async fn children_query(&self, pool, page)
    ///     -> Result<Option<Vec<Page>>, ExecError>
    /// {
    ///     Ok(Some(rustango_cms::published_children(pool, page).await?))
    /// }
    /// ```
    ///
    /// The derive forwards to this override automatically.
    async fn children_query(
        &self,
        _pool: &Pool,
        _page: &crate::page::Page,
    ) -> Result<Option<Vec<crate::page::Page>>, ExecError> {
        Ok(None)
    }

    /// Routable URL patterns — see [`PageTypeHandler::routes`].
    fn routes(&self) -> Vec<crate::routable::RouteSpec> {
        Vec::new()
    }

    /// Route-specific ctx — see [`PageTypeHandler::route_context`].
    async fn route_context(
        &self,
        _pool: &Pool,
        _page: &crate::page::Page,
        _matched: &crate::routable::RouteMatch,
    ) -> Result<serde_json::Map<String, Value>, ExecError> {
        Ok(serde_json::Map::new())
    }

    /// What a matched route renders — see [`PageTypeHandler::route_outcome`].
    fn route_outcome(
        &self,
        _matched: &crate::routable::RouteMatch,
        _route_ctx: &serde_json::Map<String, Value>,
    ) -> crate::routable::RouteOutcome {
        crate::routable::RouteOutcome::Render
    }

    /// Handler-contributed tabs — see [`PageTypeHandler::extra_tabs`].
    async fn extra_tabs(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<TabSpec>, ExecError> {
        Ok(Vec::new())
    }

    /// Inline panels — see [`PageTypeHandler::inline_panels`].
    async fn inline_panels(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<InlinePanelSpec>, ExecError> {
        Ok(Vec::new())
    }

    /// A panel's rows — see [`PageTypeHandler::load_inline_panel`].
    async fn load_inline_panel(
        &self,
        _pool: &Pool,
        _page_id: i64,
        _panel_name: &str,
    ) -> Result<Vec<serde_json::Map<String, Value>>, ExecError> {
        Ok(Vec::new())
    }

    /// Store a panel's posted rows — see [`PageTypeHandler::save_inline_panel`].
    async fn save_inline_panel(
        &self,
        _pool: &Pool,
        _page_id: i64,
        _panel_name: &str,
        _rows: &[serde_json::Map<String, Value>],
    ) -> Result<(), ExecError> {
        Ok(())
    }

    /// Per-row panels: each row's id and title, in order. See
    /// [`InlinePanelSpec::per_row`](InlinePanelSpec#structfield.per_row).
    ///
    /// # Errors
    /// Driver / query failures.
    async fn inline_rows(&self, _pool: &Pool, _page_id: i64, _panel: &str) -> Result<Vec<InlineRowSummary>, ExecError> {
        Ok(Vec::new())
    }

    /// Per-row panels: one row's values, keyed by widget name (`None` id:
    /// a new row's starting values). `Ok(None)`: no such row on this page.
    ///
    /// # Errors
    /// Driver / query failures.
    async fn inline_row(
        &self,
        _pool: &Pool,
        _page_id: i64,
        _panel: &str,
        _row_id: Option<i64>,
    ) -> Result<Option<serde_json::Map<String, Value>>, ExecError> {
        Ok(None)
    }

    /// Per-row panels: store one row from its posted values (`None` id:
    /// add it). Values arrive as the browser posts them; an unchecked
    /// switch is absent.
    ///
    /// # Errors
    /// Driver / query failures (validation problems are `Invalid`).
    async fn save_inline_row(
        &self,
        _pool: &Pool,
        _page_id: i64,
        _panel: &str,
        _row_id: Option<i64>,
        _values: &serde_json::Map<String, Value>,
    ) -> Result<InlineRowSaved, ExecError> {
        Ok(InlineRowSaved::Invalid(vec![crate::admin::cms_admin::FieldError::new("_form", "This panel can't be saved.")]))
    }

    /// Per-row panels: remove one row. `Ok(false)`: refused.
    ///
    /// # Errors
    /// Driver / query failures.
    async fn delete_inline_row(&self, _pool: &Pool, _page_id: i64, _panel: &str, _row_id: i64) -> Result<bool, ExecError> {
        Ok(false)
    }

    /// Per-row panels: store a new order (`ids` first to last).
    ///
    /// # Errors
    /// Driver / query failures.
    async fn reorder_inline_rows(&self, _pool: &Pool, _page_id: i64, _panel: &str, _ids: &[i64]) -> Result<(), ExecError> {
        Ok(())
    }
}

#[cfg(all(test, feature = "sqlite"))]
mod preview_tests {
    use super::*;
    use crate::widget::{Widget, WidgetKind};

    struct Choosers;

    #[async_trait]
    impl PageTypeHandler for Choosers {
        fn app_label(&self) -> &'static str {
            "cms"
        }
        fn type_name(&self) -> &'static str {
            "Choosers"
        }
        fn verbose_name(&self) -> &'static str {
            "Choosers"
        }
        fn default_template(&self) -> &'static str {
            "c.html"
        }
        async fn widgets(&self, _pool: &Pool, _page_id: i64) -> Result<Vec<Widget>, ExecError> {
            Ok(vec![
                Widget::new(WidgetKind::PageChooser, "related", "Related"),
                Widget::new(WidgetKind::SnippetChooser, "cta", "CTA"),
                Widget::new(WidgetKind::DocumentChooser, "doc", "Doc"),
            ])
        }
    }

    /// Live preview types every chooser id as the saved page does.
    #[tokio::test]
    async fn preview_types_chooser_ids_like_the_saved_value() {
        let pool = Pool::connect("sqlite::memory:").await.expect("pool");
        let form = std::collections::HashMap::from([
            ("related".to_owned(), "7".to_owned()),
            ("cta".to_owned(), "3".to_owned()),
            ("doc".to_owned(), String::new()),
        ]);
        let v = Choosers.preview_extension(&pool, 1, &form).await.expect("preview");
        assert_eq!(v, serde_json::json!({ "related": 7, "cta": 3, "doc": null }));
    }
}