laterite-admin 0.9.16

Laterite CMF admin surface: the Axum router, session middleware, and login shell
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
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
//! Descriptor-driven create and edit forms.
//!
//! A [`FormConfig`] describes a table and its editable fields. Generic handlers
//! render an empty form (new), a populated form (edit), and persist through a
//! [`crate::persist::Persister`]: the descriptor-driven default (a parameterized
//! insert/update over the form's columns), or a named handler for a custom write.
//! A submission is checked by the framework validation engine
//! ([`laterite_core::validation`]); a failure re-renders the form with per-field
//! messages instead of writing.
//!
//! Field types resolve through the registry ([`crate::field`]); `text`,
//! `textarea`, `select`, and `reference` ship built-in. Fields needing a typed
//! stored value (a switch over a bool column, password hashing) arrive with the
//! typed-save contract.
//!
//! The primary key is a `bigint` auto-increment column the database assigns, so
//! create inserts only the descriptor's fields and never sets the id. An entity
//! with other required columns that lack defaults (for example audit timestamps)
//! is beyond this slice; those are filled by a later timestamp-aware widget.

use std::collections::HashMap;
use std::sync::Arc;

use askama::Template;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Redirect, Response};
use laterite_core::query::{bind_values, build as to_sql, text_cast};
use laterite_core::validation::{validate, FieldRules, Mode, Rule};
use laterite_core::{
    t, Actor, AnyRowExt, Db, ErrorBag, ModelListener, ModelListenerReg, Op, Record, Text,
};
use sea_query::{Alias, Expr, Query};
use serde::{Deserialize, Serialize};

use crate::field::{render_field, FieldCx, FieldValue, OverrideScope, ResolvedOptions, Surface};
use crate::persist::{self, DefaultPersister, Persister, PersisterRegistry, SaveError};
use crate::sql::valid_ident;
use crate::{not_found, render, render_error, AdminState};

/// One editable field: the column, its label, its field-type key (resolved
/// through the field-type registry), typed options for that type, the validation
/// rules it carries, and whether it holds translatable content. A serde
/// descriptor, so it is authorable as data (later YAML) as well as by builder.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct FormField {
    pub name: String,
    /// The field's label, localized at render. Serde stays a plain string.
    pub label: Text,
    /// The field-type registry key (`text`, `textarea`, or a plugin's
    /// `vendor.name`), resolved to behaviour at render time (see [`crate::field`]).
    pub field_type: String,
    /// The keys that belong to the field's type, as an object: in a file they
    /// are written on the field itself, beside its own. Null when there are none.
    pub options: serde_json::Value,
    /// Validation rules run on submit (see [`laterite_core::validation`]).
    pub rules: Vec<Rule>,
    /// Marks a field whose value is translatable content. A reserved seam: the
    /// framework stores the value verbatim; a content-translation plugin reads
    /// the flag to manage per-locale values.
    pub translatable: bool,
    /// Help text shown beneath the control, localized at render.
    pub help: Option<Text>,
    /// What Enter does in this field: `submit` (the form's rule), `off`, or
    /// `next` (moves to the next field).
    pub enter: FieldEnter,
    /// The share of the row the field takes, on a twelve-column grid.
    pub span: Span,
    /// Starts a new row, whatever room the current one has left.
    pub break_row: bool,
    /// Follows another field as it is typed, until this one is edited.
    pub preset: Option<Preset>,
    /// Submitted but never shown: a plain hidden input carrying its value. The
    /// foreign key of a related record's form is one.
    pub hidden: bool,
    /// Changes when another field's state meets a condition.
    pub trigger: Option<Trigger>,
}

/// How a preset shapes the text it copies.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PresetShape {
    /// As typed.
    Exact,
    /// Lowercase words joined by hyphens: `hello-world`.
    #[default]
    Slug,
    /// A slug with a leading slash: `/hello-world`.
    Url,
    /// A file name: spaces to hyphens, the rest kept.
    File,
}

impl PresetShape {
    /// The word the page carries, for the island.
    pub fn as_str(self) -> &'static str {
        match self {
            PresetShape::Exact => "exact",
            PresetShape::Slug => "slug",
            PresetShape::Url => "url",
            PresetShape::File => "file",
        }
    }
}

/// Fills a field from another as it is typed, until the field is edited.
///
/// In YAML, the followed field's name alone (`preset: title`, a slug), or a
/// map: `preset: { field: title, type: url }`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Preset {
    pub field: String,
    pub shape: PresetShape,
}

impl Preset {
    pub fn new(field: impl Into<String>, shape: PresetShape) -> Self {
        Self {
            field: field.into(),
            shape,
        }
    }
}

impl<'de> Deserialize<'de> for Preset {
    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Full {
            field: String,
            #[serde(rename = "type", default)]
            shape: PresetShape,
        }
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Raw {
            Field(String),
            Full(Full),
        }
        Ok(match Raw::deserialize(de)? {
            Raw::Field(field) => Preset::new(field, PresetShape::Slug),
            Raw::Full(full) => Preset::new(full.field, full.shape),
        })
    }
}

/// Changes a field when another field's state meets a condition.
///
/// ```yaml
/// send_at:
///   type: date
///   trigger: { action: show, field: is_delayed, condition: checked }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Trigger {
    /// What happens when the condition holds: `show`, `hide`, `enable`,
    /// `disable`, `empty`, `fill[value]`, or several joined by `|`.
    pub action: String,
    /// The field watched. `name[]` watches every value of a checklist.
    pub field: String,
    /// `checked`, `unchecked`, `value[x]`, `value[x][y]` (either), `value[]`
    /// (empty), `value[*]` (anything), `value[foo*]` (a prefix).
    pub condition: String,
}

impl Trigger {
    pub fn new(
        action: impl Into<String>,
        field: impl Into<String>,
        condition: impl Into<String>,
    ) -> Self {
        Self {
            action: action.into(),
            field: field.into(),
            condition: condition.into(),
        }
    }

    /// Refuses an action or condition the island does not know.
    pub fn check(&self) -> Result<(), String> {
        for action in self.action.split('|') {
            let known = matches!(action, "show" | "hide" | "enable" | "disable" | "empty")
                || (action.starts_with("fill[") && action.ends_with(']'));
            if !known {
                return Err(format!(
                    "unknown trigger action `{action}`: show, hide, enable, disable, empty or fill[value]"
                ));
            }
        }
        let known = matches!(self.condition.as_str(), "checked" | "unchecked")
            || (self.condition.starts_with("value[") && self.condition.ends_with(']'));
        if !known {
            return Err(format!(
                "unknown trigger condition `{}`: checked, unchecked or value[..]",
                self.condition
            ));
        }
        Ok(())
    }

    /// The name of the field watched, without a `[]` suffix.
    pub fn watched(&self) -> &str {
        self.field.trim_end_matches("[]")
    }
}

/// The attributes a field's wrapper carries for its preset and trigger, each
/// led by a space, empty when it has neither.
pub(crate) fn behaviour_attrs(field: &FormField) -> String {
    fn escaped(text: &str) -> String {
        text.replace('&', "&amp;")
            .replace('<', "&lt;")
            .replace('>', "&gt;")
            .replace('"', "&quot;")
    }
    let mut attrs = String::new();
    if let Some(preset) = &field.preset {
        attrs.push_str(&format!(
            r#" data-lat-preset="{}" data-lat-preset-type="{}""#,
            escaped(&preset.field),
            preset.shape.as_str()
        ));
    }
    if let Some(trigger) = &field.trigger {
        attrs.push_str(&format!(
            r#" data-lat-trigger-action="{}" data-lat-trigger-field="{}" data-lat-trigger-condition="{}""#,
            escaped(&trigger.action),
            escaped(&trigger.field),
            escaped(&trigger.condition)
        ));
    }
    attrs
}

/// The share of a row a field takes, in twelfths. Written in YAML as a
/// fraction (`1/2`, `1/3`, `2/3`, `1/4`, `3/4`), `full`, a count of columns
/// (`1` to `12`), or the words `half`, `third`, `quarter`, `left`, `right` and
/// `auto` (each a half). Fields flow left to right and wrap when a row is full.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Span(u8);

impl Span {
    /// The whole row.
    pub const FULL: Span = Span(12);

    /// `columns` twelfths of the row, clamped to 1 to 12.
    pub fn columns(columns: u8) -> Self {
        Span(columns.clamp(1, 12))
    }

    /// The twelfths this span covers.
    pub fn width(self) -> u8 {
        self.0
    }

    /// Reads the YAML spellings.
    pub fn parse(text: &str) -> Result<Self, String> {
        let columns = match text.trim() {
            "full" | "12/12" => 12,
            "1/2" | "half" | "left" | "right" | "auto" => 6,
            "1/3" | "third" => 4,
            "2/3" => 8,
            "1/4" | "quarter" => 3,
            "3/4" => 9,
            other => match other.parse::<u8>() {
                Ok(n) if (1..=12).contains(&n) => n,
                _ => {
                    return Err(format!(
                        "unknown span `{other}`, expected full, 1/2, 1/3, 2/3, 1/4, 3/4 or 1 to 12"
                    ))
                }
            },
        };
        Ok(Span(columns))
    }

    /// The CSS class the field wrapper carries; none for a full row.
    fn class(self) -> String {
        if self.0 == 12 {
            String::new()
        } else {
            format!(" lat-field--{}", self.0)
        }
    }
}

impl Default for Span {
    fn default() -> Self {
        Span::FULL
    }
}

impl Serialize for Span {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self.0 {
            12 => serializer.serialize_str("full"),
            6 => serializer.serialize_str("1/2"),
            4 => serializer.serialize_str("1/3"),
            8 => serializer.serialize_str("2/3"),
            3 => serializer.serialize_str("1/4"),
            9 => serializer.serialize_str("3/4"),
            n => serializer.serialize_u8(n),
        }
    }
}

impl<'de> Deserialize<'de> for Span {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Raw {
            Columns(u8),
            Text(String),
        }
        match Raw::deserialize(deserializer)? {
            Raw::Columns(n) if (1..=12).contains(&n) => Ok(Span(n)),
            Raw::Columns(n) => Err(serde::de::Error::custom(format!(
                "unknown span `{n}`, expected 1 to 12"
            ))),
            Raw::Text(text) => Span::parse(&text).map_err(serde::de::Error::custom),
        }
    }
}

/// The wrapper classes a field's layout adds: its span, and a row break.
pub(crate) fn layout_classes(span: Span, break_row: bool) -> String {
    let mut classes = span.class();
    if break_row {
        classes.push_str(" lat-field--break");
    }
    classes
}

/// What Enter does in a form's single-line fields.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EnterPolicy {
    /// Submits the form. Cmd/Ctrl+Enter submits from a textarea as well.
    #[default]
    Submit,
    /// Enter never submits; Cmd/Ctrl+Enter still does.
    Off,
}

/// Where the cursor goes when a form opens.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FormFocus {
    /// A new record opens with the cursor in its first field. A refused save
    /// comes back with the cursor in the first field it refused.
    #[default]
    Auto,
    /// The cursor is left where the browser puts it.
    Off,
}

/// What Enter does in one field, over the form's [`EnterPolicy`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FieldEnter {
    /// The form's rule.
    #[default]
    Submit,
    /// Nothing.
    Off,
    /// Focus moves to the next field.
    Next,
}

impl FieldEnter {
    /// The `data-lat-enter` value the field wrapper carries; empty for the
    /// form's rule.
    fn attribute(self) -> &'static str {
        match self {
            FieldEnter::Submit => "",
            FieldEnter::Off => "off",
            FieldEnter::Next => "next",
        }
    }
}

impl Default for FormConfig {
    /// Everything a descriptor file leaves to the resource level: the entity,
    /// the path and the id column are filled in when the file is read.
    fn default() -> Self {
        Self {
            entity: String::new(),
            title: Text::new(""),
            base_path: String::new(),
            id_field: "id".to_string(),
            fields: Vec::new(),
            enter: EnterPolicy::default(),
            confirm_leave: true,
            focus: FormFocus::default(),
            persist: None,
            timestamps: false,
            done_path: None,
        }
    }
}

impl Default for FormField {
    /// A text field, named by the key it is written under.
    fn default() -> Self {
        Self::of("", Text::new(""), "text")
    }
}

impl<'de> Deserialize<'de> for FormField {
    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
        struct Entry;
        impl<'de> serde::de::Visitor<'de> for Entry {
            type Value = FormField;

            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("a field: its own keys and its type's")
            }

            fn visit_map<A: serde::de::MapAccess<'de>>(
                self,
                map: A,
            ) -> Result<FormField, A::Error> {
                let mut field = FormField::default();
                let theirs = crate::keyed::split_entry(map, |key, map| {
                    match key {
                        "name" => field.name = map.next_value()?,
                        "label" => field.label = map.next_value()?,
                        "type" => field.field_type = map.next_value()?,
                        "rules" => field.rules = map.next_value()?,
                        "translatable" => field.translatable = map.next_value()?,
                        "help" => field.help = map.next_value()?,
                        "enter" => field.enter = map.next_value()?,
                        "span" => field.span = map.next_value()?,
                        "break" => field.break_row = map.next_value()?,
                        "preset" => field.preset = map.next_value()?,
                        "trigger" => field.trigger = map.next_value()?,
                        "hidden" => field.hidden = map.next_value()?,
                        _ => return Ok(false),
                    }
                    Ok(true)
                })?;
                field.options = theirs;
                if let Some(trigger) = &field.trigger {
                    trigger.check().map_err(serde::de::Error::custom)?;
                }
                Ok(field)
            }

            /// A key written bare (`title:`) is a field with every default.
            fn visit_unit<E: serde::de::Error>(self) -> Result<FormField, E> {
                Ok(FormField::default())
            }
        }
        de.deserialize_map(Entry)
    }
}

impl Serialize for FormField {
    fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        let mut map = ser.serialize_map(None)?;
        map.serialize_entry("name", &self.name)?;
        map.serialize_entry("label", &self.label)?;
        map.serialize_entry("type", &self.field_type)?;
        map.serialize_entry("rules", &self.rules)?;
        map.serialize_entry("translatable", &self.translatable)?;
        map.serialize_entry("help", &self.help)?;
        map.serialize_entry("enter", &self.enter)?;
        map.serialize_entry("span", &self.span)?;
        map.serialize_entry("break", &self.break_row)?;
        if let Some(preset) = &self.preset {
            map.serialize_entry("preset", preset)?;
        }
        if self.hidden {
            map.serialize_entry("hidden", &true)?;
        }
        if let Some(trigger) = &self.trigger {
            map.serialize_entry("trigger", trigger)?;
        }
        crate::keyed::serialize_theirs(&mut map, &self.options)?;
        map.end()
    }
}

impl crate::keyed::Keyed for FormField {
    fn key(&self) -> &str {
        &self.name
    }
    fn set_key(&mut self, key: String) {
        self.name = key;
    }
}

impl FormField {
    /// A field of a registered type by key.
    pub fn of(name: &str, label: impl Into<Text>, field_type: &str) -> Self {
        Self {
            name: name.to_string(),
            label: label.into(),
            field_type: field_type.to_string(),
            options: serde_json::Value::Null,
            rules: Vec::new(),
            translatable: false,
            help: None,
            enter: FieldEnter::default(),
            span: Span::default(),
            break_row: false,
            preset: None,
            trigger: None,
            hidden: false,
        }
    }

    /// Follows `field` as it is typed, shaped as `shape`, until this field is
    /// edited.
    pub fn preset(mut self, field: &str, shape: PresetShape) -> Self {
        self.preset = Some(Preset::new(field, shape));
        self
    }

    /// Changes when `trigger`'s condition holds on the field it watches.
    pub fn trigger(mut self, trigger: Trigger) -> Self {
        self.trigger = Some(trigger);
        self
    }

    pub fn text(name: &str, label: impl Into<Text>) -> Self {
        Self::of(name, label, "text")
    }

    pub fn textarea(name: &str, label: impl Into<Text>) -> Self {
        Self::of(name, label, "textarea")
    }

    /// A reference field: a picker over a registered picker source (a `vendor.name`
    /// key), which the field searches and resolves against. Builds the `source`
    /// option so a descriptor needs no raw JSON.
    pub fn reference(name: &str, label: impl Into<Text>, source: &str) -> Self {
        Self::of(name, label, "reference").options(serde_json::json!({ "source": source }))
    }

    /// A dropdown over a fixed set of `(value, label)` choices.
    pub fn select(name: &str, label: impl Into<Text>, options: Vec<(&str, &str)>) -> Self {
        Self::of(name, label, "select").options(Self::choices(options))
    }

    /// The same choices rendered as radio buttons.
    pub fn radio(name: &str, label: impl Into<Text>, options: Vec<(&str, &str)>) -> Self {
        Self::of(name, label, "radio").options(Self::choices(options))
    }

    /// A checkbox over a boolean column.
    pub fn switch(name: &str, label: impl Into<Text>) -> Self {
        Self::of(name, label, "switch")
    }

    /// A calendar date, stored as `YYYY-MM-DD`.
    pub fn date(name: &str, label: impl Into<Text>) -> Self {
        Self::of(name, label, "date")
    }

    /// A password: hashed on save, never rendered back, and left alone when the
    /// field is submitted blank on an edit.
    pub fn password(name: &str, label: impl Into<Text>) -> Self {
        Self::of(name, label, "password")
    }

    /// A list of rows, each holding `fields`, stored as an array of objects.
    pub fn repeater(name: &str, label: impl Into<Text>, fields: Vec<FormField>) -> Self {
        Self::of(name, label, "repeater").options(serde_json::json!({ "fields": fields }))
    }

    /// A repeater whose rows collapse to the line that names them, opening one
    /// at a time. `summary_field` names the sub-field that titles a row; unset,
    /// the first one does.
    ///
    /// Use it when a row holds more than one or two fields: rendered inline
    /// those become columns, and a row of four is already unreadable. A single
    /// narrow column is better left inline, where collapsing would hide the one
    /// thing worth seeing.
    pub fn repeater_list(
        name: &str,
        label: impl Into<Text>,
        fields: Vec<FormField>,
        summary_field: Option<&str>,
    ) -> Self {
        Self::of(name, label, "repeater").options(serde_json::json!({
            "fields": fields,
            "display": "list",
            "summary_field": summary_field,
        }))
    }

    /// The options blob the choice-shaped types read.
    fn choices(options: Vec<(&str, &str)>) -> serde_json::Value {
        let options: Vec<serde_json::Value> = options
            .into_iter()
            .map(|(value, label)| serde_json::json!({ "value": value, "label": label }))
            .collect();
        serde_json::json!({ "options": options })
    }

    /// Sets the field type's typed options (the type validates them at render).
    pub fn options(mut self, options: serde_json::Value) -> Self {
        self.options = options;
        self
    }

    /// Requires a non-empty value in every mode.
    pub fn required(mut self) -> Self {
        self.rules.push(Rule::Required);
        self
    }

    /// Requires a non-empty value in one mode only (for example a password set on
    /// create but left unchanged on edit).
    pub fn required_on(mut self, mode: Mode) -> Self {
        self.rules.push(Rule::RequiredOn(mode));
        self
    }

    /// Requires the value to be unique in this field's column (a DB probe that
    /// ignores the edited row on update).
    pub fn unique(mut self) -> Self {
        self.rules.push(Rule::Unique);
        self
    }

    /// Caps the value's length.
    pub fn max_length(mut self, n: usize) -> Self {
        self.rules.push(Rule::MaxLength(n));
        self
    }

    /// Requires at least `n` characters when the value is non-empty.
    pub fn min_length(mut self, n: usize) -> Self {
        self.rules.push(Rule::MinLength(n));
        self
    }

    /// Requires a syntactically valid email address.
    pub fn email(mut self) -> Self {
        self.rules.push(Rule::Email);
        self
    }

    /// Marks this field as translatable content (see [`FormField::translatable`]).
    pub fn translatable(mut self) -> Self {
        self.translatable = true;
        self
    }

    /// Help text shown beneath the control.
    pub fn help(mut self, text: impl Into<Text>) -> Self {
        self.help = Some(text.into());
        self
    }

    /// The share of the row this field takes.
    pub fn span(mut self, span: Span) -> Self {
        self.span = span;
        self
    }

    /// Starts a new row.
    pub fn break_row(mut self) -> Self {
        self.break_row = true;
        self
    }
}

/// A form descriptor: which table, its editable fields, the id column, and the
/// base path the form lives under (`{base_path}/new`, `{base_path}/{id}/edit`).
///
/// Built with [`FormConfig::new`] plus its builder methods. Non-exhaustive so the
/// framework can learn something new about a form after 1.0 without a major bump.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
#[non_exhaustive]
pub struct FormConfig {
    pub entity: String,
    /// The screen title, localized at render. Serde stays a plain string.
    pub title: Text,
    pub base_path: String,
    pub id_field: String,
    #[serde(
        deserialize_with = "crate::keyed::deserialize",
        serialize_with = "crate::keyed::serialize"
    )]
    pub fields: Vec<FormField>,
    /// What Enter does in the form's single-line fields. Default `submit`.
    #[serde(default)]
    pub enter: EnterPolicy,
    /// Ask before leaving the form with changes unsaved. Default `true`.
    pub confirm_leave: bool,
    /// Where the cursor goes when the form opens. Default `auto`.
    pub focus: FormFocus,
    /// The registered persister that writes this form (a dotted `vendor.name`),
    /// or `None` for the built-in descriptor insert/update. See [`crate::persist`].
    pub persist: Option<String>,
    /// Stamp `created_at` and `updated_at` on write. Opt in per form, because
    /// the columns have to exist on this entity's table.
    #[serde(default)]
    pub timestamps: bool,
    /// Where a save and a cancel return to, when it is not the list under
    /// `base_path`: a related record's form returns to its parent. Set by the
    /// router, never by a descriptor.
    #[serde(skip)]
    pub(crate) done_path: Option<String>,
}

impl FormConfig {
    /// A form over `entity`, mounted under `base_path`, keyed by `id_field`.
    ///
    /// The four arguments are the ones with no sensible default; everything else
    /// is opt-in through a builder method, so a later field costs nothing.
    pub fn new(
        entity: impl Into<String>,
        title: impl Into<Text>,
        base_path: impl Into<String>,
        id_field: impl Into<String>,
        fields: Vec<FormField>,
    ) -> Self {
        Self {
            enter: Default::default(),
            confirm_leave: true,
            focus: FormFocus::default(),
            entity: entity.into(),
            title: title.into(),
            base_path: base_path.into(),
            id_field: id_field.into(),
            fields,
            persist: None,
            timestamps: false,
            done_path: None,
        }
    }

    /// Writes this form through a registered persister instead of the built-in
    /// descriptor insert/update.
    pub fn persist(mut self, name: impl Into<String>) -> Self {
        self.persist = Some(name.into());
        self
    }

    /// Whether leaving the form with changes unsaved asks first. Default `true`.
    pub fn confirm_leave(mut self, ask: bool) -> Self {
        self.confirm_leave = ask;
        self
    }

    /// Where the cursor goes when the form opens.
    pub fn focus(mut self, focus: FormFocus) -> Self {
        self.focus = focus;
        self
    }

    /// Stamps `created_at` and `updated_at` on write. Opt in, because the
    /// columns have to exist on this entity's table.
    pub fn timestamps(mut self) -> Self {
        self.timestamps = true;
        self
    }

    fn idents_valid(&self) -> bool {
        valid_ident(&self.entity)
            && valid_ident(&self.id_field)
            && self.fields.iter().all(|f| valid_ident(&f.name))
    }
}

/// A [`FormConfig`] with each field's options resolved once, at router build.
/// Handlers carry this so option resolution and intrinsic-rule merging happen a
/// single time (not per render), and a malformed option or unregistered type
/// aborts boot rather than degrading silently to plain text.
#[derive(Clone)]
pub(crate) struct PreparedForm {
    pub(crate) config: FormConfig,
    /// Parallel to `config.fields`.
    fields: Vec<PreparedField>,
    /// The write handler: the named persister, or the built-in default.
    persister: Arc<dyn Persister>,
    /// Listeners for this form's entity, in registration order.
    listeners: Vec<Arc<dyn ModelListener>>,
    /// Offer "Save and continue editing" beside Save: a resource with relation
    /// sections wants to land on the edit page, where the sections are.
    pub(crate) stay: bool,
}

/// One field's boot-resolved state: its typed options and its merged rules (the
/// type's intrinsic rules ahead of the descriptor's own).
#[derive(Clone)]
struct PreparedField {
    /// Resolved once at boot, so the save and load hooks need no lookup.
    field_type: Arc<dyn crate::field::FieldType>,
    opts: ResolvedOptions,
    rules: Vec<Rule>,
}

impl PreparedForm {
    /// The write handler this form resolved to.
    pub(crate) fn persister(&self) -> Arc<dyn Persister> {
        self.persister.clone()
    }

    /// Whether the form declares `field`.
    pub(crate) fn has_field(&self, field: &str) -> bool {
        self.config.fields.iter().any(|f| f.name == field)
    }

    /// The widget assets `field`'s type declares.
    pub(crate) fn field_assets(&self, field: &str) -> Vec<&'static str> {
        self.config
            .fields
            .iter()
            .zip(&self.fields)
            .find(|(f, _)| f.name == field)
            .map(|(_, pf)| pf.field_type.assets(&pf.opts))
            .unwrap_or_default()
    }

    /// One field's bare control holding `value`, as the form would render it,
    /// for a place outside the form such as an editable cell. `None` when the
    /// form has no such field.
    pub(crate) fn control(
        &self,
        state: &AdminState,
        field: &str,
        dom_id: &str,
        value: &str,
        shell: &crate::Shell,
    ) -> Option<String> {
        let (f, pf) = self
            .config
            .fields
            .iter()
            .zip(&self.fields)
            .find(|(f, _)| f.name == field)?;
        let value = FieldValue::Text(value.to_string());
        let label = shell.tt(&f.label);
        let cx = FieldCx {
            name: &f.name,
            id: dom_id,
            label: &label,
            value: &value,
            required: has_required(&pf.rules),
            max_length: max_length(&pf.rules),
            opts: &pf.opts,
            base: &shell.base,
            i18n: shell.i18n(),
        };
        let ft = state.field_types.get(&f.field_type)?;
        let scope = OverrideScope {
            surface: Surface::Field,
            view_key: &f.field_type,
            resource: Some(&self.config.base_path),
            field: Some(&f.name),
        };
        Some(render_field(ft.as_ref(), state.overrides.as_ref(), &scope, &cx).into_string())
    }

    /// Resolves every field against the registry. Returns the offending field
    /// and reason (for a boot abort) when a type is unregistered or rejects its
    /// options.
    pub(crate) fn prepare(
        config: FormConfig,
        field_types: &crate::field::FieldRegistry,
        persisters: &PersisterRegistry,
        listeners: &[ModelListenerReg],
    ) -> Result<Self, String> {
        let mut fields = Vec::with_capacity(config.fields.len());
        for f in &config.fields {
            let names = || config.fields.iter().map(|other| other.name.as_str());
            if let Some(preset) = &f.preset {
                if !names().any(|n| n == preset.field) {
                    return Err(format!(
                        "field `{}` presets from `{}`, which is not in this form",
                        f.name, preset.field
                    ));
                }
            }
            if let Some(trigger) = &f.trigger {
                trigger
                    .check()
                    .map_err(|e| format!("field `{}`: {e}", f.name))?;
                if !names().any(|n| n == trigger.watched()) {
                    return Err(format!(
                        "field `{}` watches `{}`, which is not in this form",
                        f.name,
                        trigger.watched()
                    ));
                }
            }
            let ft = field_types.get(&f.field_type).ok_or_else(|| {
                format!(
                    "field `{}` uses unregistered type `{}`",
                    f.name, f.field_type
                )
            })?;
            crate::field::check_field_keys(f, ft.as_ref())
                .map_err(|e| format!("field `{}` (`{}`): {e}", f.name, f.field_type))?;
            let opts = ft
                .resolve_options(&f.options, field_types)
                .map_err(|e| format!("field `{}` (`{}`): {e}", f.name, f.field_type))?;
            let mut rules = ft.intrinsic_rules(&opts);
            rules.extend(f.rules.clone());
            fields.push(PreparedField {
                field_type: ft.clone(),
                opts,
                rules,
            });
        }
        let persister: Arc<dyn Persister> = match &config.persist {
            Some(key) => persisters
                .get(key)
                .cloned()
                .ok_or_else(|| format!("form names unregistered persister `{key}`"))?,
            None => Arc::new(DefaultPersister::from_config(&config)),
        };
        // The framework's own listeners run first, so a contributed one can see
        // or override what they set.
        let mut resolved: Vec<Arc<dyn ModelListener>> = Vec::new();
        if config.timestamps {
            resolved.push(Arc::new(laterite_core::Timestamps));
        }
        resolved.extend(
            listeners
                .iter()
                .filter(|reg| reg.matches(&config.entity))
                .map(|reg| reg.listener.clone()),
        );
        let listeners = resolved;
        Ok(Self {
            config,
            fields,
            persister,
            listeners,
            stay: false,
        })
    }
}

/// The submission as a record, carrying only the fields the descriptor declares.
/// A request cannot introduce an attribute this way, so the persister may widen
/// its write to whatever the record holds; only registered listeners add keys.
///
/// Each value passes through its field type, which decides what gets stored and
/// may leave the attribute out entirely (a blank password on an edit).
fn declared_record(
    form: &PreparedForm,
    data: &HashMap<String, String>,
    mode: Mode,
) -> Result<Record, String> {
    let mut rec = Record::new(&form.config.entity);
    for (field, prepared) in form.config.fields.iter().zip(&form.fields) {
        let submitted = crate::field::SubmittedField::new(&field.name, data);
        if let Some(value) = prepared
            .field_type
            .to_attr(&submitted, &prepared.opts, mode)?
        {
            rec.set(field.name.clone(), value);
        }
    }
    Ok(rec)
}

/// The submission with every field present under its own name.
///
/// A field of several controls submits keys of its own and none under its name.
/// Its type gathers them into one value, so the rules see the field and a
/// refused save is re-rendered from what the operator entered. A key already
/// present is left as submitted.
pub(crate) fn gathered(
    form: &PreparedForm,
    mut data: HashMap<String, String>,
) -> HashMap<String, String> {
    for (field, prepared) in form.config.fields.iter().zip(&form.fields) {
        if data.contains_key(&field.name) {
            continue;
        }
        let value = prepared.field_type.submitted(
            &crate::field::SubmittedField::new(&field.name, &data),
            &prepared.opts,
        );
        if let Some(value) = value {
            data.insert(field.name.clone(), value);
        }
    }
    data
}

/// The merged validation rules for every field, in order.
fn merged_field_rules(form: &PreparedForm) -> Vec<FieldRules> {
    form.config
        .fields
        .iter()
        .zip(&form.fields)
        // The rules carry the label's source string; the validation message re-wraps
        // it as a nested Text, so it localizes at render like any other label.
        .map(|(f, pf)| FieldRules::new(f.name.clone(), f.label.source(), pf.rules.clone()))
        .collect()
}

/// The write a submit and a [`FormHandle`] share: `data` (already gathered)
/// validated against the merged rules, shaped into the declared record and saved
/// through the listeners and the persister. `id` names the row an edit updates;
/// `None` creates. Returns the record as saved, its id set on a create.
pub(crate) async fn write(
    db: &Db,
    form: &PreparedForm,
    data: &HashMap<String, String>,
    id: Option<&str>,
    actor: &Actor,
) -> Result<Record, SaveError> {
    let (mut rec, op) = prepare(db, form, data, id).await?;
    persist::save(
        persist::SaveRequest {
            db,
            listeners: &form.listeners,
            persister: form.persister.as_ref(),
            actor,
            op,
            id,
        },
        &mut rec,
    )
    .await?;
    link_media(
        db,
        form,
        data,
        rec.id()
            .map(|i| i.to_string())
            .or_else(|| id.map(str::to_string)),
    )
    .await;
    Ok(rec)
}

/// Writes the links a saved record's media fields hold, under each field's
/// name, so the library knows who uses a file. A type that holds no media
/// says so and is skipped; a failure is logged, never a failed save.
async fn link_media(
    db: &Db,
    form: &PreparedForm,
    data: &HashMap<String, String>,
    owner_id: Option<String>,
) {
    let Some(owner_id) = owner_id else {
        return;
    };
    for (field, prepared) in form.config.fields.iter().zip(&form.fields) {
        let submitted = data.get(&field.name).map(String::as_str);
        let Some(ids) = prepared.field_type.linked_media(submitted, &prepared.opts) else {
            continue;
        };
        let owner = laterite_media::Owner {
            owner_type: &form.config.entity,
            owner_id: &owner_id,
            field: &field.name,
        };
        if let Err(e) = laterite_media::link::set(db, owner, &ids).await {
            tracing::warn!(error = %e, entity = %form.config.entity, field = %field.name, "media links could not be written");
        }
    }
}

/// The write up to the point of writing: the data validated and shaped into
/// the record, with the operation it would be. What a check runs, and what a
/// write runs first.
async fn prepare(
    db: &Db,
    form: &PreparedForm,
    data: &HashMap<String, String>,
    id: Option<&str>,
) -> Result<(Record, Op), SaveError> {
    if !form.config.idents_valid() {
        return Err(SaveError::Failed(format!(
            "form `{}` names an invalid entity or field identifier",
            form.config.entity
        )));
    }
    let (mode, op) = match id {
        None => (Mode::Create, Op::Create),
        Some(_) => (Mode::Update, Op::Update),
    };
    let bag = validate(
        db,
        &form.config.entity,
        &form.config.id_field,
        &merged_field_rules(form),
        data,
        mode,
        id,
    )
    .await
    .map_err(|e| SaveError::Failed(e.to_string()))?;
    if !bag.is_empty() {
        return Err(SaveError::Invalid(bag));
    }
    let mut rec = declared_record(form, data, mode).map_err(|e| {
        tracing::error!(entity = %form.config.entity, error = %e, "preparing the write failed");
        SaveError::Failed(e)
    })?;
    if let Some(n) = id.and_then(|id| id.parse::<i64>().ok()) {
        rec.set_id(n);
    }
    Ok((rec, op))
}

/// The forms the resources mounted, keyed by each resource's path as its
/// descriptor declares it, relative to the admin root.
pub(crate) type Forms = Arc<HashMap<String, Arc<PreparedForm>>>;

/// A resource's form, written through from code.
///
/// Runs what the form's own submit runs, with no request in hand: the values
/// are validated against the form's rules, shaped by its field types and saved
/// through its listeners and persister, so an importer or a sync writes exactly
/// what an operator could have typed, audited the same way. A screen reaches one
/// through [`crate::routes::RouteCtx::form`].
#[derive(Clone)]
pub struct FormHandle {
    db: Db,
    form: Arc<PreparedForm>,
}

impl FormHandle {
    pub(crate) fn new(db: Db, form: Arc<PreparedForm>) -> Self {
        Self { db, form }
    }

    /// The table the form writes.
    pub fn entity(&self) -> &str {
        &self.form.config.entity
    }

    /// The primary key column.
    pub fn id_field(&self) -> &str {
        &self.form.config.id_field
    }

    /// The fields the form declares, in order. `data` is keyed by their names.
    pub fn fields(&self) -> &[FormField] {
        &self.form.config.fields
    }

    /// Validates `data` as a submission and saves a new record, returning its id.
    ///
    /// `data` holds each field's value under the field's name, as the form's
    /// control submits it; a field left out is blank. `Invalid` carries the
    /// per-field messages a refused submit would show.
    pub async fn create(
        &self,
        data: HashMap<String, String>,
        actor: &Actor,
    ) -> Result<i64, SaveError> {
        let data = gathered(&self.form, data);
        let rec = write(&self.db, &self.form, &data, None, actor).await?;
        rec.id()
            .ok_or_else(|| SaveError::Failed("the persister returned no id".to_string()))
    }

    /// The record `id` as the edit form shows it: each stored value back through
    /// its field type, keyed by field name. `None` when no record has that id.
    /// Lay a partial `data` over it before [`update`](Self::update) to change
    /// some fields and keep the rest.
    pub async fn load(&self, id: i64) -> Result<Option<HashMap<String, String>>, SaveError> {
        load_values(&self.db, &self.form, &id.to_string())
            .await
            .map_err(|e| SaveError::Failed(e.to_string()))
    }

    /// What [`create`](Self::create) or [`update`](Self::update) would do with
    /// `data`, with nothing written: the rules and the field conversions run,
    /// the listeners and the persister do not. `id` names the record an edit
    /// would change; `None` checks as a create.
    pub async fn check(
        &self,
        id: Option<i64>,
        data: HashMap<String, String>,
    ) -> Result<(), SaveError> {
        let data = gathered(&self.form, data);
        let id = id.map(|id| id.to_string());
        prepare(&self.db, &self.form, &data, id.as_deref())
            .await
            .map(|_| ())
    }

    /// Validates `data` as an edit of the record `id` and saves it. Every field
    /// is written, so a field left out of `data` is stored blank.
    pub async fn update(
        &self,
        id: i64,
        data: HashMap<String, String>,
        actor: &Actor,
    ) -> Result<(), SaveError> {
        let data = gathered(&self.form, data);
        write(&self.db, &self.form, &data, Some(&id.to_string()), actor)
            .await
            .map(|_| ())
    }
}

/// The longest value the rules accept, when they set one.
pub(crate) fn max_length(rules: &[Rule]) -> Option<usize> {
    rules
        .iter()
        .filter_map(|r| match r {
            Rule::MaxLength(n) => Some(*n),
            _ => None,
        })
        .min()
}

/// Whether any rule marks the field required.
fn has_required(rules: &[Rule]) -> bool {
    rules
        .iter()
        .any(|r| matches!(r, Rule::Required | Rule::RequiredOn(_)))
}

/// Renders an empty create form.
pub(crate) fn new_form(
    state: &AdminState,
    form: &PreparedForm,
    shell: crate::Shell,
    pending: Vec<String>,
) -> Response {
    let mut page = build(
        state,
        form,
        &format!("{}/new", form.config.base_path),
        None,
        &HashMap::new(),
        &ErrorBag::default(),
        &shell,
    );
    page.pending = pending;
    render(page)
}

/// Where a save goes: the edit page when the operator asked to stay, else the
/// form's done path or its list.
fn after_save(form: &PreparedForm, data: &HashMap<String, String>, id: Option<i64>) -> String {
    let stay = data.get("then").map(String::as_str) == Some("stay");
    match (stay, id) {
        (true, Some(id)) => format!("{}/{}/edit", form.config.base_path, id),
        _ => form
            .config
            .done_path
            .clone()
            .unwrap_or_else(|| form.config.base_path.clone()),
    }
}

/// Persists a new record, then redirects to the list. Re-renders with per-field
/// errors when validation fails.
pub(crate) async fn create(
    state: &AdminState,
    form: &PreparedForm,
    data: HashMap<String, String>,
    shell: crate::Shell,
    user: &laterite_auth::AuthenticatedUser,
    session: &crate::session::SessionHandle,
    headers: &axum::http::HeaderMap,
) -> Response {
    if !form.config.idents_valid() {
        return render_error();
    }
    let htmx = is_htmx(headers);
    let action = format!("{}/new", form.config.base_path);
    let mut data = gathered(form, data);
    let then = data.remove("then");
    let actor = Actor::from(user);
    match write(&state.db, form, &data, None, &actor).await {
        // The audit entry is written by the framework's audit listener, which
        // runs on every entity after the commit.
        Ok(rec) => {
            session.push_flash(crate::session::FlashLevel::Success, t!("Saved."));
            let mut choice = HashMap::new();
            if let Some(then) = then {
                choice.insert("then".to_string(), then);
            }
            saved_response(htmx, &after_save(form, &choice, rec.id()))
        }
        // A refused submission re-renders the form with per-field errors as 422,
        // the cross-surface "validation failure" status.
        Err(SaveError::Invalid(bag)) => {
            invalid_response(htmx, state, form, &action, None, &data, &bag, &shell)
        }
        Err(SaveError::Failed(msg)) => {
            tracing::error!(error = %msg, "admin create failed");
            render(build(
                state,
                form,
                &action,
                Some(t!("Could not save. Check the values and try again.")),
                &data,
                &ErrorBag::default(),
                &shell,
            ))
        }
    }
}

/// Renders a form populated with an existing record.
pub(crate) async fn edit_form(
    state: &AdminState,
    form: &PreparedForm,
    id: String,
    shell: crate::Shell,
    sections: Vec<RelationSection>,
) -> Response {
    if !form.config.idents_valid() {
        return render_error();
    }
    let values = match load_values(&state.db, form, &id).await {
        Ok(Some(values)) => values,
        Ok(None) => return not_found(),
        Err(_) => return render_error(),
    };

    let mut page = build(
        state,
        form,
        &format!("{}/{}/edit", form.config.base_path, id),
        None,
        &values,
        &ErrorBag::default(),
        &shell,
    );
    page.sections = sections;
    render(page)
}

/// The stored record `id` as control values: each column back through its
/// field type, since what a column holds and what its control shows are not
/// always the same string. `None` when no record has that id.
pub(crate) async fn load_values(
    db: &Db,
    form: &PreparedForm,
    id: &str,
) -> Result<Option<HashMap<String, String>>, sqlx::Error> {
    // Scope the sea-query builder so it is dropped before the await below: its
    // identifiers are reference-counted (not `Send`), and a live builder across
    // the await would make the caller's future non-`Send`.
    let (sql, values) = {
        let cast = text_cast(db.backend);
        let mut select = Query::select();
        for field in &form.config.fields {
            select.expr_as(
                Expr::col(Alias::new(&field.name)).cast_as(Alias::new(cast)),
                Alias::new(&field.name),
            );
        }
        select.from(Alias::new(&form.config.entity)).and_where(
            Expr::col(Alias::new(&form.config.id_field))
                .cast_as(Alias::new(cast))
                .eq(id.to_string()),
        );
        to_sql(db.backend, select)
    };
    let Some(row) = bind_values(sqlx::query(&sql), values)
        .fetch_optional(&db.pool)
        .await?
    else {
        return Ok(None);
    };
    Ok(Some(
        form.config
            .fields
            .iter()
            .zip(&form.fields)
            .map(|(f, prepared)| {
                let stored = row.get_text_opt(f.name.as_str()).ok().flatten();
                let value = prepared
                    .field_type
                    .to_control(stored.as_deref(), &prepared.opts);
                (f.name.clone(), value)
            })
            .collect(),
    ))
}

/// Persists an edited record, then redirects to the list. Re-renders with
/// per-field errors when validation fails.
// The generic handlers thread the request's pieces explicitly rather than through
// a context struct; the list is long but each argument is named at the call site.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn update(
    state: &AdminState,
    form: &PreparedForm,
    id: String,
    data: HashMap<String, String>,
    shell: crate::Shell,
    user: &laterite_auth::AuthenticatedUser,
    session: &crate::session::SessionHandle,
    headers: &axum::http::HeaderMap,
) -> Response {
    if !form.config.idents_valid() {
        return render_error();
    }
    let htmx = is_htmx(headers);
    let action = format!("{}/{}/edit", form.config.base_path, id);
    let mut data = gathered(form, data);
    let then = data.remove("then");
    let actor = Actor::from(user);
    match write(&state.db, form, &data, Some(&id), &actor).await {
        Ok(_) => {
            session.push_flash(crate::session::FlashLevel::Success, t!("Saved."));
            let mut choice = HashMap::new();
            if let Some(then) = then {
                choice.insert("then".to_string(), then);
            }
            saved_response(htmx, &after_save(form, &choice, id.parse().ok()))
        }
        // A refused submission re-renders the form with per-field errors as 422,
        // the cross-surface "validation failure" status.
        Err(SaveError::Invalid(bag)) => {
            invalid_response(htmx, state, form, &action, None, &data, &bag, &shell)
        }
        Err(SaveError::Failed(msg)) => {
            tracing::error!(error = %msg, "admin update failed");
            render(build(
                state,
                form,
                &action,
                Some(t!("Could not save. Check the values and try again.")),
                &data,
                &ErrorBag::default(),
                &shell,
            ))
        }
    }
}

/// The 422 response for a failed save. An HTMX submit gets the form alone, which
/// replaces the form in place; anything else gets the whole page, so the admin
/// still works with scripting off.
#[allow(clippy::too_many_arguments)]
/// A form page posting to `action`, holding `values`: the shape another screen
/// borrows when it edits one thing a record owns, such as its tree parent.
pub(crate) fn page(
    state: &AdminState,
    form: &PreparedForm,
    action: &str,
    values: &HashMap<String, String>,
    shell: &crate::Shell,
) -> Response {
    render(build(
        state,
        form,
        action,
        None,
        values,
        &ErrorBag::default(),
        shell,
    ))
}

/// The 422 for a submission the list's own checks refused, shaped like a
/// failed save: the form again with the messages against their fields.
#[allow(clippy::too_many_arguments)]
pub(crate) fn refused(
    htmx: bool,
    state: &AdminState,
    form: &PreparedForm,
    action: &str,
    error: Option<Text>,
    values: &HashMap<String, String>,
    bag: &ErrorBag,
    shell: &crate::Shell,
) -> Response {
    invalid_response(htmx, state, form, action, error, values, bag, shell)
}

#[allow(clippy::too_many_arguments)]
fn invalid_response(
    htmx: bool,
    state: &AdminState,
    form: &PreparedForm,
    action: &str,
    error: Option<Text>,
    values: &HashMap<String, String>,
    bag: &ErrorBag,
    shell: &crate::Shell,
) -> Response {
    let page = build(state, form, action, error, values, bag, shell);
    let body = if htmx {
        render(FormFragment {
            shell: page.shell,
            action: page.action,
            cancel_path: page.cancel_path,
            error: page.error,
            fields: page.fields,
            stay: page.stay,
            enter_off: page.enter_off,
            refused: page.refused,
            leave_off: page.leave_off,
            focus: page.focus,
        })
    } else {
        render(page)
    };
    (StatusCode::UNPROCESSABLE_ENTITY, body).into_response()
}

/// Where to send the browser after a successful save. HTMX will not follow a
/// 303 usefully (it would swap the redirected page into the form), so it gets
/// the header it understands instead.
pub(crate) fn saved_response(htmx: bool, to: &str) -> Response {
    if htmx {
        ([("HX-Redirect", to)], StatusCode::NO_CONTENT).into_response()
    } else {
        Redirect::to(to).into_response()
    }
}

/// Whether this request came from HTMX rather than a plain form post.
pub(crate) fn is_htmx(headers: &axum::http::HeaderMap) -> bool {
    headers.contains_key("hx-request")
}

fn build(
    state: &AdminState,
    form: &PreparedForm,
    action: &str,
    error: Option<Text>,
    values: &HashMap<String, String>,
    bag: &ErrorBag,
    shell: &crate::Shell,
) -> FormTemplate {
    let fields = form
        .config
        .fields
        .iter()
        .zip(&form.fields)
        .map(|(f, pf)| {
            let value = FieldValue::Text(values.get(&f.name).cloned().unwrap_or_default());
            let required = has_required(&pf.rules);
            // Localize the label once: the field type sees it (aria/inline labels)
            // and the framework chrome renders it.
            let label = shell.tt(&f.label);
            let cx = FieldCx {
                name: &f.name,
                id: &f.name,
                label: &label,
                value: &value,
                required,
                max_length: max_length(&pf.rules),
                opts: &pf.opts,
                base: &shell.base,
                i18n: shell.i18n(),
            };
            // The type is registered (prepare validated it); the lookup here is
            // only to render.
            let control = if f.hidden {
                format!(
                    r#"<input type="hidden" name="{}" value="{}">"#,
                    escape_attr(&f.name),
                    escape_attr(values.get(&f.name).map(String::as_str).unwrap_or_default())
                )
            } else {
                match state.field_types.get(&f.field_type) {
                    Some(ft) => {
                        let scope = OverrideScope {
                            surface: Surface::Field,
                            view_key: &f.field_type,
                            resource: Some(&form.config.base_path),
                            field: Some(&f.name),
                        };
                        render_field(ft.as_ref(), state.overrides.as_ref(), &scope, &cx)
                            .into_string()
                    }
                    None => String::new(),
                }
            };
            FieldView {
                id: f.name.clone(),
                label,
                control,
                required,
                enter: f.enter.attribute(),
                layout: layout_classes(f.span, f.break_row),
                attrs: behaviour_attrs(f),
                hidden: f.hidden,
                // Localize each per-field message through the request translator.
                errors: bag.messages(&f.name).iter().map(|m| shell.tt(m)).collect(),
            }
        })
        .collect();
    // Collect the widget assets the rendered field types declare, deduped and
    // resolved to URLs for the head. Most declare none (their widgets ship in
    // core laterite.js).
    let keys: Vec<&str> = form
        .config
        .fields
        .iter()
        .zip(&form.fields)
        .filter_map(|(f, pf)| {
            state
                .field_types
                .get(&f.field_type)
                .map(|ft| ft.assets(&pf.opts))
        })
        .flatten()
        .collect();
    // Localize the title and banner before the shell is moved into the template.
    let shell_title = shell.tt(&form.config.title);
    let refused = error.is_some() || !bag.is_empty();
    let error = error.map(|m| shell.tt(&m));
    let mut shell = shell.clone();
    shell.assets = crate::page_assets(&keys, &shell.base, &state.assets, &state.asset_urls);
    FormTemplate {
        shell,
        title: shell_title,
        action: action.to_string(),
        cancel_path: form
            .config
            .done_path
            .clone()
            .unwrap_or_else(|| form.config.base_path.clone()),
        error,
        fields,
        stay: form.stay,
        sections: Vec::new(),
        pending: Vec::new(),
        enter_off: form.config.enter == EnterPolicy::Off,
        refused,
        leave_off: !form.config.confirm_leave,
        focus: match form.config.focus {
            FormFocus::Off => "off",
            // A new record has nothing in it yet, so the first field is where
            // the operator starts. An edit opens for reading first.
            FormFocus::Auto if action.ends_with("/new") => "first",
            FormFocus::Auto => "",
        },
    }
}

struct FieldView {
    /// DOM id for the control and its label's `for`.
    id: String,
    label: String,
    /// The control HTML, rendered by the field-type registry (override-aware).
    /// The framework owns the surrounding chrome (label, required marker, errors).
    control: String,
    required: bool,
    errors: Vec<String>,
    /// The field's own Enter rule (`off`, `next`), or empty for the form's.
    enter: &'static str,
    /// Wrapper classes for the span and a row break, each led by a space.
    layout: String,
    /// The wrapper's preset and trigger attributes, each led by a space.
    attrs: String,
    /// A hidden input with no chrome around it.
    hidden: bool,
}

/// One relation on an edit page: its heading, its New link and the list region.
pub(crate) struct RelationSection {
    /// The section's toolbar: its title and the New or Attach button.
    pub toolbar: crate::html::Markup,
    pub html: crate::html::Markup,
}

pub(crate) fn escape_attr(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('"', "&quot;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

/// Just the form element, for an HTMX submit that failed validation: the
/// response replaces the form in place rather than reloading the page.
#[derive(Template)]
#[template(path = "_form_fields.html")]
struct FormFragment {
    shell: crate::Shell,
    action: String,
    cancel_path: String,
    error: Option<String>,
    fields: Vec<FieldView>,
    stay: bool,
    /// Enter never submits this form.
    enter_off: bool,
    /// The form holds a submission that was not saved.
    refused: bool,
    /// Leaving with changes unsaved does not ask.
    leave_off: bool,
    /// `first`, `off`, or empty for the default.
    focus: &'static str,
}

#[derive(Template)]
#[template(path = "form.html")]
struct FormTemplate {
    shell: crate::Shell,
    title: String,
    action: String,
    cancel_path: String,
    error: Option<String>,
    fields: Vec<FieldView>,
    /// Offer "Save and continue editing".
    stay: bool,
    /// The related records, one section each, on an edit page.
    sections: Vec<RelationSection>,
    /// The relations a create page cannot show yet, by section title.
    pending: Vec<String>,
    /// Enter never submits this form.
    enter_off: bool,
    /// The form holds a submission that was not saved.
    refused: bool,
    /// Leaving with changes unsaved does not ask.
    leave_off: bool,
    /// `first`, `off`, or empty for the default.
    focus: &'static str,
}

/// A field as a value form renders it: the label, the control its type drew,
/// the help, and the wrapper's layout classes and behaviour attributes.
pub struct ValueFieldView {
    pub label: String,
    pub help: Option<String>,
    /// The control, rendered by the field's own type.
    pub control: String,
    /// Wrapper classes for the span and a row break, each led by a space.
    pub layout: String,
    /// The wrapper's preset and trigger attributes, each led by a space.
    pub attrs: String,
}

#[derive(Template)]
#[template(path = "_value_fields.html")]
struct ValueFieldsTemplate {
    fields: Vec<ValueFieldView>,
}

/// A form over a JSON object: the declared fields rendered with their stored
/// values, and a submission collected back through the field types into an
/// object with every declared key. The settings screens are one, a theme's
/// settings another. Built from a [`RouteCtx`](crate::routes::RouteCtx) with
/// [`value_form`](crate::routes::RouteCtx::value_form).
pub struct ValueForm {
    fields: Vec<FormField>,
    types: Arc<crate::field::FieldRegistry>,
    overrides: Arc<dyn crate::field::OverrideResolver>,
    /// What an override is scoped to (a settings code, a theme code).
    scope: String,
}

impl ValueForm {
    /// Checks every field's type is registered and its options resolve. The
    /// error names the field and the type, for a form declared at runtime.
    pub(crate) fn new(
        fields: &[FormField],
        types: Arc<crate::field::FieldRegistry>,
        overrides: Arc<dyn crate::field::OverrideResolver>,
        scope: &str,
    ) -> Result<Self, Text> {
        for field in fields {
            let Some(ft) = types.get(&field.field_type) else {
                return Err(Text::dynamic(format!(
                    "field {:?} uses unregistered type {:?}",
                    field.name, field.field_type
                )));
            };
            if ft.resolve_options(&field.options, &types).is_err() {
                return Err(Text::dynamic(format!(
                    "field {:?} has malformed options",
                    field.name
                )));
            }
        }
        Ok(Self {
            fields: fields.to_vec(),
            types,
            overrides,
            scope: scope.to_string(),
        })
    }

    /// The fields, in order.
    pub fn fields(&self) -> &[FormField] {
        &self.fields
    }

    /// Each field over `stored`, ready for a template.
    pub fn views(&self, stored: &serde_json::Value, shell: &crate::Shell) -> Vec<ValueFieldView> {
        value_views(
            &self.fields,
            &self.types,
            self.overrides.as_ref(),
            stored,
            shell,
            &self.scope,
        )
    }

    /// The fields over `stored` as one `.lat-fields` block, for a form a screen
    /// builds by hand around it.
    pub fn render(&self, stored: &serde_json::Value, shell: &crate::Shell) -> crate::html::Markup {
        let template = ValueFieldsTemplate {
            fields: self.views(stored, shell),
        };
        crate::html::Markup::from_template(&template).unwrap_or_default()
    }

    /// A submission as the stored object: every declared key, each value
    /// through its field type. A type that refuses its input refuses the whole.
    pub fn collect(&self, data: &HashMap<String, String>) -> Result<serde_json::Value, Text> {
        value_collect(&self.fields, &self.types, data)
    }
}

/// Each of `fields` over `stored`, rendered by its type with overrides scoped
/// to `scope`.
pub(crate) fn value_views(
    fields: &[FormField],
    types: &crate::field::FieldRegistry,
    overrides: &dyn crate::field::OverrideResolver,
    stored: &serde_json::Value,
    shell: &crate::Shell,
    scope: &str,
) -> Vec<ValueFieldView> {
    fields
        .iter()
        .map(|f| {
            let label = shell.tt(&f.label);
            let control = match types.get(&f.field_type) {
                Some(ft) => {
                    let opts = ft
                        .resolve_options(&f.options, types)
                        .unwrap_or_else(|_| ResolvedOptions::none());
                    let value = match stored.get(&f.name) {
                        Some(serde_json::Value::Array(rows)) => {
                            FieldValue::Json(serde_json::Value::Array(rows.clone()))
                        }
                        Some(serde_json::Value::String(text)) => {
                            FieldValue::Text(ft.to_control(Some(text), &opts))
                        }
                        Some(serde_json::Value::Null) | None => {
                            FieldValue::Text(ft.to_control(None, &opts))
                        }
                        Some(other) => {
                            FieldValue::Text(ft.to_control(Some(&other.to_string()), &opts))
                        }
                    };
                    let cx = FieldCx {
                        name: &f.name,
                        id: &f.name,
                        label: &label,
                        value: &value,
                        required: false,
                        max_length: max_length(&f.rules),
                        opts: &opts,
                        base: &shell.base,
                        i18n: shell.i18n(),
                    };
                    let scope = OverrideScope {
                        surface: Surface::Field,
                        view_key: &f.field_type,
                        resource: Some(scope),
                        field: Some(&f.name),
                    };
                    render_field(ft.as_ref(), overrides, &scope, &cx).into_string()
                }
                None => String::new(),
            };
            ValueFieldView {
                label,
                help: f.help.as_ref().map(|h| shell.tt(h)),
                control,
                layout: layout_classes(f.span, f.break_row),
                attrs: behaviour_attrs(f),
            }
        })
        .collect()
}

/// A submission over `fields` as a JSON object with every declared key.
pub(crate) fn value_collect(
    fields: &[FormField],
    types: &crate::field::FieldRegistry,
    data: &HashMap<String, String>,
) -> Result<serde_json::Value, Text> {
    let mut object = serde_json::Map::new();
    for field in fields {
        let Some(field_type) = types.get(&field.field_type) else {
            return Err(t!("This screen uses a field type that is not registered."));
        };
        let opts = field_type
            .resolve_options(&field.options, types)
            .map_err(|_| t!("This screen has a malformed field."))?;
        let submitted = crate::field::SubmittedField::new(&field.name, data);
        let value = match field_type.to_attr(&submitted, &opts, Mode::Update) {
            Ok(Some(value)) => attr_to_json(value),
            Ok(None) => serde_json::Value::String(String::new()),
            Err(_) => return Err(t!("Check the values and try again.")),
        };
        object.insert(field.name.clone(), value);
    }
    Ok(serde_json::Value::Object(object))
}

/// A field type's attribute value as settings JSON stores it.
pub(crate) fn attr_to_json(value: laterite_core::AttrValue) -> serde_json::Value {
    use laterite_core::AttrValue;
    match value {
        AttrValue::Null => serde_json::Value::String(String::new()),
        AttrValue::Bool(b) => serde_json::Value::Bool(b),
        AttrValue::Int(i) => serde_json::Value::from(i),
        AttrValue::Float(f) => serde_json::Value::from(f),
        AttrValue::Json(j) => j,
        other => serde_json::Value::String(other.to_text().unwrap_or_default()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::http::StatusCode;
    use laterite_core::strata::{
        async_trait, ColumnDef, CoreResult, Migration, MigrationSet, Schema, Table,
    };
    use laterite_core::testing::{connect_test, TestGuard};
    use laterite_core::Db;
    use laterite_core::SaveCx;

    /// A minimal table for exercising the generic insert/update path in isolation,
    /// defined as a portable migration so the test runs on any backend.
    struct CreateSamples;
    #[async_trait(?Send)]
    impl Migration for CreateSamples {
        fn name(&self) -> &str {
            "0001_create_samples"
        }
        async fn up(&self, s: &mut Schema<'_>) -> CoreResult<()> {
            s.exec(
                Table::create()
                    .table(Alias::new("samples"))
                    .if_not_exists()
                    .col(
                        ColumnDef::new(Alias::new("id"))
                            .big_integer()
                            .not_null()
                            .auto_increment()
                            .primary_key(),
                    )
                    .col(ColumnDef::new(Alias::new("code")).text().not_null())
                    .col(ColumnDef::new(Alias::new("name")).text().not_null())
                    // Nullable, so a form that does not opt into timestamps
                    // still inserts.
                    .col(ColumnDef::new(Alias::new("created_at")).text())
                    .col(ColumnDef::new(Alias::new("updated_at")).text())
                    .to_owned(),
            )
            .await
        }
    }

    fn config() -> PreparedForm {
        let config = FormConfig {
            enter: Default::default(),
            confirm_leave: true,
            focus: Default::default(),
            entity: "samples".to_string(),
            title: "Sample".into(),
            base_path: "/admin/samples".to_string(),
            id_field: "id".to_string(),
            fields: vec![
                FormField::text("code", "Code").required().unique(),
                FormField::text("name", "Name").required(),
            ],
            persist: None,
            timestamps: false,
            done_path: None,
        };
        PreparedForm::prepare(
            config,
            &crate::field::builtin_registry(),
            &PersisterRegistry::new(),
            &[],
        )
        .unwrap()
    }

    /// The whole delete path against a real table: the row is read, the
    /// listeners run, the row goes, and the after-stage sees what went.
    #[tokio::test]
    async fn a_delete_removes_the_row_through_the_pipeline() {
        use crate::persist::{delete, DefaultPersister, DeleteRequest};

        let (db, _guard) = test_db().await;
        let st = state(db.clone());
        let form = config();

        let mut data = HashMap::new();
        data.insert("code".to_string(), "c1".to_string());
        data.insert("name".to_string(), "Chair".to_string());
        create(
            &st,
            &form,
            data,
            crate::Shell::test(),
            &crate::audit::test_actor(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .await;
        assert_eq!(
            fetch_text(&db, "name", "c1").await.as_deref(),
            Some("Chair")
        );

        let id = row_id(&db, "c1").await;
        let persister = DefaultPersister::from_config(&form.config);
        let rec = delete(DeleteRequest {
            db: &db,
            listeners: &[],
            persister: &persister,
            actor: &laterite_core::Actor::system("test"),
            entity: "samples",
            id: &id,
        })
        .await
        .expect("deleted");

        // Gone from the table, and the caller learns what it removed.
        assert_eq!(fetch_text(&db, "name", "c1").await, None);
        assert_eq!(rec.text("code"), Some("c1"));
    }

    /// The stored id for a row, as text, the shape the delete path takes.
    async fn row_id(db: &Db, code: &str) -> String {
        let stmt = Query::select()
            .expr_as(
                Expr::col(Alias::new("id")).cast_as(Alias::new(text_cast(db.backend))),
                Alias::new("v"),
            )
            .from(Alias::new("samples"))
            .and_where(Expr::col(Alias::new("code")).eq(code))
            .to_owned();
        let (sql, values) = laterite_core::query::build(db.backend, stmt);
        let row = bind_values(sqlx::query(&sql), values)
            .fetch_one(&db.pool)
            .await
            .unwrap();
        row.get_text("v").unwrap()
    }

    pub(super) fn state(db: Db) -> AdminState {
        AdminState::new(
            laterite_auth::AuthService::new(db.clone(), laterite_auth::AuthConfig::default()),
            db,
        )
    }

    /// A fresh test database holding a minimal `samples` table, on whichever
    /// backend the run targets. Hold the returned guard for the test's lifetime.
    pub(super) async fn test_db() -> (Db, TestGuard) {
        let samples = MigrationSet::new("test.samples", vec![Box::new(CreateSamples)]);
        connect_test(&[samples]).await
    }

    /// Reads a single text column from the one row matching `code`, so a test can
    /// assert what was persisted without depending on the read path under test.
    pub(super) async fn fetch_text(db: &Db, column: &str, code: &str) -> Option<String> {
        let stmt = Query::select()
            .expr_as(
                Expr::col(Alias::new(column)).cast_as(Alias::new(text_cast(db.backend))),
                Alias::new("v"),
            )
            .from(Alias::new("samples"))
            .and_where(Expr::col(Alias::new("code")).eq(code))
            .to_owned();
        let (sql, values) = to_sql(db.backend, stmt);
        let row = bind_values(sqlx::query(&sql), values)
            .fetch_optional(&db.pool)
            .await
            .unwrap()?;
        row.get_text_opt("v").ok().flatten()
    }

    async fn body_of(resp: Response) -> String {
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        String::from_utf8(bytes.to_vec()).unwrap()
    }

    async fn count(db: &Db) -> i64 {
        sqlx::query_scalar("select count(*) from samples")
            .fetch_one(&db.pool)
            .await
            .unwrap()
    }

    fn data(pairs: &[(&str, &str)]) -> HashMap<String, String> {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect()
    }

    /// The header htmx sets on every request it makes.
    pub(super) fn htmx_headers() -> axum::http::HeaderMap {
        let mut h = axum::http::HeaderMap::new();
        h.insert("hx-request", "true".parse().unwrap());
        h
    }

    #[tokio::test]
    async fn create_then_fetch() {
        let (db, _guard) = test_db().await;
        let cfg = config();
        let st = state(db.clone());

        let resp = create(
            &st,
            &cfg,
            data(&[("code", "editor"), ("name", "Content Editor")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);

        assert_eq!(
            fetch_text(&db, "name", "editor").await.as_deref(),
            Some("Content Editor")
        );
    }

    #[tokio::test]
    async fn update_changes_the_row() {
        let (db, _guard) = test_db().await;
        let cfg = config();
        let st = state(db.clone());
        create(
            &st,
            &cfg,
            data(&[("code", "editor"), ("name", "Editor")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .await;

        let id = fetch_text(&db, "id", "editor")
            .await
            .expect("row should exist after create");

        // The code is unchanged, so its unique rule must ignore the edited row.
        let resp = update(
            &st,
            &cfg,
            id,
            data(&[("code", "editor"), ("name", "Senior Editor")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);

        assert_eq!(
            fetch_text(&db, "name", "editor").await.as_deref(),
            Some("Senior Editor")
        );
    }

    #[tokio::test]
    async fn create_re_renders_with_a_required_message_and_inserts_nothing() {
        let (db, _guard) = test_db().await;
        let cfg = config();
        let st = state(db.clone());

        let resp = create(
            &st,
            &cfg,
            data(&[("code", ""), ("name", "No Code")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .await;
        // Re-renders the form (200), does not redirect.
        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
        assert_eq!(count(&db).await, 0);
        // The per-field message is rendered.
        assert!(body_of(resp).await.contains("Code is required."));
    }

    #[tokio::test]
    async fn create_rejects_a_duplicate_unique_value() {
        let (db, _guard) = test_db().await;
        let cfg = config();
        let st = state(db.clone());
        create(
            &st,
            &cfg,
            data(&[("code", "editor"), ("name", "Editor")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .await;

        // A second row with the same code is refused by the unique rule.
        let resp = create(
            &st,
            &cfg,
            data(&[("code", "editor"), ("name", "Other")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
        assert_eq!(count(&db).await, 1);
        assert!(body_of(resp).await.contains("already taken"));
    }

    #[tokio::test]
    async fn text_email_input_rejects_a_bad_address_via_its_intrinsic_rule() {
        let (db, _guard) = test_db().await;
        let st = state(db.clone());
        // The `name` column is a text field with the `email` input, which
        // contributes Rule::Email without the descriptor listing it.
        let cfg = PreparedForm::prepare(
            FormConfig {
                enter: Default::default(),
                confirm_leave: true,
                focus: Default::default(),
                entity: "samples".to_string(),
                title: "Sample".into(),
                base_path: "/admin/samples".to_string(),
                id_field: "id".to_string(),
                fields: vec![
                    FormField::text("code", "Code").required(),
                    FormField::of("name", "Email", "text")
                        .options(serde_json::json!({ "input": "email" }))
                        .required(),
                ],
                persist: None,
                timestamps: false,
                done_path: None,
            },
            &st.field_types,
            &PersisterRegistry::new(),
            &[],
        )
        .unwrap();

        let resp = create(
            &st,
            &cfg,
            data(&[("code", "c1"), ("name", "nope")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
        assert_eq!(count(&db).await, 0);

        let resp = create(
            &st,
            &cfg,
            data(&[("code", "c1"), ("name", "a@b.test")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        assert_eq!(count(&db).await, 1);
    }

    #[test]
    fn prepare_rejects_an_unregistered_field_type() {
        let config = FormConfig {
            enter: Default::default(),
            confirm_leave: true,
            focus: Default::default(),
            entity: "samples".to_string(),
            title: "Sample".into(),
            base_path: "/admin/samples".to_string(),
            id_field: "id".to_string(),
            fields: vec![FormField::of("place", "Place", "no.such.type")],
            persist: None,
            timestamps: false,
            done_path: None,
        };
        let Err(err) = PreparedForm::prepare(
            config,
            &crate::field::builtin_registry(),
            &PersisterRegistry::new(),
            &[],
        ) else {
            panic!("expected prepare to reject an unregistered type");
        };
        assert!(err.contains("no.such.type"), "{err}");
    }

    #[test]
    fn prepare_rejects_a_malformed_option() {
        // The text field's `input` option is a string; a wrong JSON type for it
        // aborts prepare naming the field.
        let config = FormConfig {
            enter: Default::default(),
            confirm_leave: true,
            focus: Default::default(),
            entity: "samples".to_string(),
            title: "Sample".into(),
            base_path: "/admin/samples".to_string(),
            id_field: "id".to_string(),
            fields: vec![
                FormField::of("email", "Email", "text").options(serde_json::json!({ "input": 7 }))
            ],
            persist: None,
            timestamps: false,
            done_path: None,
        };
        let Err(err) = PreparedForm::prepare(
            config,
            &crate::field::builtin_registry(),
            &PersisterRegistry::new(),
            &[],
        ) else {
            panic!("expected prepare to reject a malformed option");
        };
        assert!(err.contains("`email`"), "{err}");
    }

    /// A persister that inserts a row then fails. The pipeline owns the
    /// transaction, so the insert must roll back with it.
    struct RollbackPersister;
    #[laterite_core::strata::async_trait]
    impl Persister for RollbackPersister {
        async fn create(&self, cx: &mut SaveCx<'_>, _rec: &Record) -> Result<i64, SaveError> {
            let backend = cx.backend();
            let insert = Query::insert()
                .into_table(Alias::new("samples"))
                .columns([Alias::new("code"), Alias::new("name")])
                .values_panic(["rolled".into(), "back".into()])
                .to_owned();
            let (sql, values) = to_sql(backend, insert);
            bind_values(sqlx::query(&sql), values)
                .execute(cx.conn())
                .await
                .map_err(|e| SaveError::Failed(e.to_string()))?;
            Err(SaveError::Failed("deliberate".to_string()))
        }
        async fn update(
            &self,
            _cx: &mut SaveCx<'_>,
            _id: &str,
            _rec: &Record,
        ) -> Result<(), SaveError> {
            Ok(())
        }
    }

    /// A persister that always rejects create with a per-field validation error.
    struct RejectingPersister;
    #[laterite_core::strata::async_trait]
    impl Persister for RejectingPersister {
        async fn create(&self, _cx: &mut SaveCx<'_>, _rec: &Record) -> Result<i64, SaveError> {
            let mut bag = ErrorBag::default();
            bag.add("code", t!("Code is not allowed here."));
            Err(SaveError::Invalid(bag))
        }
        async fn update(
            &self,
            _cx: &mut SaveCx<'_>,
            _id: &str,
            _rec: &Record,
        ) -> Result<(), SaveError> {
            Ok(())
        }
    }

    fn config_with(persister: &str) -> FormConfig {
        FormConfig {
            enter: Default::default(),
            confirm_leave: true,
            focus: Default::default(),
            entity: "samples".to_string(),
            title: "Sample".into(),
            base_path: "/admin/samples".to_string(),
            id_field: "id".to_string(),
            fields: vec![
                FormField::text("code", "Code").required(),
                FormField::text("name", "Name").required(),
            ],
            persist: Some(persister.to_string()),
            timestamps: false,
            done_path: None,
        }
    }

    #[test]
    fn prepare_rejects_an_unregistered_persister() {
        let Err(err) = PreparedForm::prepare(
            config_with("no.such.persister"),
            &crate::field::builtin_registry(),
            &PersisterRegistry::new(),
            &[],
        ) else {
            panic!("expected prepare to reject an unregistered persister");
        };
        assert!(err.contains("no.such.persister"), "{err}");
    }

    #[tokio::test]
    async fn a_persister_transaction_rolls_back_on_error() {
        let (db, _guard) = test_db().await;
        let st = state(db.clone());
        let mut persisters = PersisterRegistry::new();
        persisters.insert("test.rollback".to_string(), Arc::new(RollbackPersister));
        let form = PreparedForm::prepare(
            config_with("test.rollback"),
            &st.field_types,
            &persisters,
            &[],
        )
        .unwrap();

        let resp = create(
            &st,
            &form,
            data(&[("code", "rolled"), ("name", "back")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .await;
        // The persister failed, so the form re-renders (200) and its in-tx insert
        // rolled back: no row landed.
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(count(&db).await, 0);
    }

    #[tokio::test]
    async fn a_persister_invalid_error_re_renders_422() {
        let (db, _guard) = test_db().await;
        let st = state(db.clone());
        let mut persisters = PersisterRegistry::new();
        persisters.insert("test.reject".to_string(), Arc::new(RejectingPersister));
        let form = PreparedForm::prepare(
            config_with("test.reject"),
            &st.field_types,
            &persisters,
            &[],
        )
        .unwrap();

        let resp = create(
            &st,
            &form,
            data(&[("code", "editor"), ("name", "Editor")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
        assert!(body_of(resp).await.contains("Code is not allowed here."));
    }
}

#[cfg(test)]
mod timestamp_tests {
    use super::tests::*;
    use super::*;
    use laterite_core::listeners::{CREATED_AT, UPDATED_AT};
    use laterite_core::Actor;

    fn timestamped(on: bool) -> FormConfig {
        FormConfig {
            enter: Default::default(),
            confirm_leave: true,
            focus: Default::default(),
            entity: "samples".to_string(),
            title: "Sample".into(),
            base_path: "/admin/samples".to_string(),
            id_field: "id".to_string(),
            fields: vec![
                FormField::text("code", "Code").required(),
                FormField::text("name", "Name").required(),
            ],
            persist: None,
            timestamps: on,
            done_path: None,
        }
    }

    async fn create_through_pipeline(db: &laterite_core::Db, on: bool) -> Record {
        let form = PreparedForm::prepare(
            timestamped(on),
            &crate::field::builtin_registry(),
            &PersisterRegistry::new(),
            &[],
        )
        .unwrap();
        let mut data = HashMap::new();
        data.insert("code".to_string(), "c1".to_string());
        data.insert("name".to_string(), "Chair".to_string());
        let mut rec = declared_record(&form, &data, Mode::Create).unwrap();
        let actor = Actor::system("test");
        persist::save(
            persist::SaveRequest {
                db,
                listeners: &form.listeners,
                persister: form.persister.as_ref(),
                actor: &actor,
                op: Op::Create,
                id: None,
            },
            &mut rec,
        )
        .await
        .expect("the insert should succeed");
        rec
    }

    #[tokio::test]
    async fn opting_in_stamps_the_row() {
        let (db, _guard) = test_db().await;
        let rec = create_through_pipeline(&db, true).await;
        assert!(rec.datetime(CREATED_AT).is_some());
        assert!(rec.datetime(UPDATED_AT).is_some());
        // The stamp reached the table, not just the record.
        assert!(fetch_text(&db, CREATED_AT, "c1").await.is_some());
    }

    #[tokio::test]
    async fn leaving_it_off_writes_no_timestamps() {
        let (db, _guard) = test_db().await;
        let rec = create_through_pipeline(&db, false).await;
        assert!(rec.get(CREATED_AT).is_none());
        assert_eq!(fetch_text(&db, CREATED_AT, "c1").await, None);
    }
}

#[cfg(test)]
mod htmx_tests {
    use super::tests::*;
    use super::*;
    use axum::http::StatusCode;

    /// A submission missing a required field, so validation refuses it.
    fn invalid() -> HashMap<String, String> {
        let mut d = HashMap::new();
        d.insert("code".to_string(), String::new());
        d.insert("name".to_string(), "No code".to_string());
        d
    }

    fn valid() -> HashMap<String, String> {
        let mut d = HashMap::new();
        d.insert("code".to_string(), "c1".to_string());
        d.insert("name".to_string(), "Chair".to_string());
        d
    }

    async fn post(data: HashMap<String, String>, headers: axum::http::HeaderMap) -> Response {
        let (db, _guard) = test_db().await;
        let st = state(db);
        let form = PreparedForm::prepare(
            FormConfig {
                enter: Default::default(),
                confirm_leave: true,
                focus: Default::default(),
                entity: "samples".to_string(),
                title: "Sample".into(),
                base_path: "/admin/samples".to_string(),
                id_field: "id".to_string(),
                fields: vec![
                    FormField::text("code", "Code").required(),
                    FormField::text("name", "Name").required(),
                ],
                persist: None,
                timestamps: false,
                done_path: None,
            },
            &st.field_types,
            &PersisterRegistry::new(),
            &[],
        )
        .unwrap();
        create(
            &st,
            &form,
            data,
            crate::Shell::test(),
            &crate::audit::test_actor(),
            &crate::session::SessionHandle::from_blob(None),
            &headers,
        )
        .await
    }

    async fn body_of(resp: Response) -> String {
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        String::from_utf8(bytes.to_vec()).unwrap()
    }

    #[tokio::test]
    async fn an_htmx_submit_that_fails_returns_the_form_alone() {
        let resp = post(invalid(), htmx_headers()).await;
        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
        let html = body_of(resp).await;
        assert!(html.contains("<form"), "the form comes back");
        assert!(html.contains("lat-field__error"), "with its errors");
        // A fragment, not a page: swapping a whole document into the form would
        // nest the admin inside itself.
        assert!(!html.contains("<body"), "no page chrome");
    }

    #[tokio::test]
    async fn a_plain_submit_that_fails_returns_the_whole_page() {
        let resp = post(invalid(), axum::http::HeaderMap::new()).await;
        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
        let html = body_of(resp).await;
        assert!(html.contains("<body"), "the admin still works without htmx");
        assert!(html.contains("lat-field__error"));
    }

    #[tokio::test]
    async fn an_htmx_submit_that_succeeds_redirects_by_header() {
        let resp = post(valid(), htmx_headers()).await;
        // htmx cannot follow a 303 usefully; it reads this header instead.
        assert_eq!(resp.status(), StatusCode::NO_CONTENT);
        assert_eq!(resp.headers().get("HX-Redirect").unwrap(), "/admin/samples");
    }

    #[tokio::test]
    async fn a_plain_submit_that_succeeds_still_redirects() {
        let resp = post(valid(), axum::http::HeaderMap::new()).await;
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
    }
}