ignite-core 0.7.3

Core types for Ignite, the admin panel for Rocket.rs: resources, fields, forms and runtime resources.
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
//! Resources defined at run time, from data: their slug, fields, columns and queries are
//! values, not a Rust type, so an app can add and remove them while the panel serves.
//!
//! A static resource implements [`IgniteResource`](crate::IgniteResource) and is added with
//! `Ignite::resource`. A runtime resource is a [`RuntimeResource`] value, whose rows come from
//! a [`RuntimeData`] the app implements, and is added with [`Registries::register_runtime`]. The panel
//! serves both through the same list, form and delete flows, at the same `/admin/<slug>`
//! address, and a slug can belong to only one of them.
//!
//! ```ignore
//! register_runtime(
//!     RuntimeResource::new("books", "Books", "Book", BookData)
//!         .field(FieldDef { name: "title".into(), label: "Title".into(),
//!                           kind: FieldKindDef::Text, required: true })
//!         .column(ColumnDef { key: "title".into(), label: "Title".into(),
//!                             sortable: true, searchable: true }),
//! )?;
//! ```

use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, PoisonError};

use orbit_orm::{Database, Error};
use serde_json::{Map, Value};

use crate::action::{BulkAction, RowAction};
use crate::condition::{FieldConditions, FormContext, Operation};
use crate::field::{self as check, Block, Column, Field, FieldKind};
use crate::form::{FieldErrors, FormInput, ValidationError};
use crate::layout::FormLayout;
use crate::list::{BadgeColor, ColumnBadges, ListFilter, Tab};
use crate::policy::{ActingUser, ResourceAction};
use crate::query::{ListQuery, Page};
use crate::registries::Registries;
use crate::structure::{RepeaterSettings, Repeaters};

/// One record of a runtime resource: its values by key, as JSON. A row the panel lists or
/// edits must have a numeric `id`, and a key for each field and column it shows.
pub type Row = Map<String, Value>;

/// A rule on a record's form, given its [`FormContext`]: the operation, the record, the user
/// and the form's values, as a Filament closure is given `$record` and `$operation`.
pub type FormRule = Arc<dyn Fn(&FormContext<'_>) -> bool + Send + Sync>;

/// A line a record's form shows, from its [`FormContext`], or none.
pub type FormNotice = Arc<dyn Fn(&FormContext<'_>) -> Option<String> + Send + Sync>;

/// The future a [`RuntimeData`] method returns: boxed, so the trait can be a trait object.
/// Write the body as `Box::pin(async move { ... })`.
pub type RuntimeFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, Error>> + Send + 'a>>;

/// Where the rows of a runtime resource live. The app implements it, so Ignite assumes no
/// table layout: a custom post type can keep its rows in a shared `posts` table and its
/// values in a meta table.
///
/// The methods mirror the queries of [`IgniteResource`](crate::IgniteResource), with
/// [`Row`]s for records and for validated input. The panel calls the `*_for` methods, which
/// are given the signed-in [`ActingUser`]; by default each calls its method without the user,
/// so a source that does not depend on the user implements only those.
pub trait RuntimeData: Send + Sync + 'static {
    /// Returns one page of rows that match `query`. The sort key, when there is one, is a
    /// sortable column of the resource. The rows and the total must meet the active tab's
    /// conditions in [`ListQuery::filter`] (see [`ListFilter`](crate::ListFilter)); a
    /// `per_page` of 0 asks only for the total, to count a tab's rows.
    fn list<'a>(&'a self, db: &'a Database, query: &'a ListQuery) -> RuntimeFuture<'a, Page<Row>>;
    /// Returns the row with `id`, or `None` if there is no such row.
    fn find<'a>(&'a self, db: &'a Database, id: i64) -> RuntimeFuture<'a, Option<Row>>;
    /// Inserts a row from the validated `input` and returns it. See
    /// [`RegisteredResource::validate`] for the values `input` holds.
    ///
    /// An [`Error::UniqueViolation`] whose index is named `{slug}_{field}_unique` shows on the
    /// form as `"<label> is already taken."`, as for a static resource. Any other error is a
    /// server error. A source whose indexes are named otherwise (or that keeps values in a
    /// meta table without such an index) should return a violation with an index of that
    /// name, or check the value before it writes.
    fn create<'a>(&'a self, db: &'a Database, input: Row) -> RuntimeFuture<'a, Row>;
    /// Updates the row with `id` from the validated `input` and returns it. A key that is
    /// missing from `input`, such as a password left blank or a field the form did not send,
    /// keeps its stored value. A key whose value is `null` is an optional field the user cleared: store NULL, so the value
    /// is cleared, as a static resource does. A unique violation is reported as for
    /// [`create`](Self::create).
    fn update<'a>(&'a self, db: &'a Database, id: i64, input: Row) -> RuntimeFuture<'a, Row>;
    /// Deletes the row with `id` and returns the number of rows deleted.
    fn delete<'a>(&'a self, db: &'a Database, id: i64) -> RuntimeFuture<'a, u64>;
    /// The choices of the field `field`, as `(value, label)` pairs in display order, for a
    /// field whose kind [loads its options](FieldKindDef::loads_options): a lookup, post
    /// object, relationship, taxonomy or user field. The default is no choices.
    fn options<'a>(
        &'a self,
        db: &'a Database,
        field: &'a str,
    ) -> RuntimeFuture<'a, Vec<(String, String)>> {
        let _ = (db, field);
        Box::pin(async { Ok(Vec::new()) })
    }

    /// [`list`](Self::list) for the signed-in `user`: the panel's list calls it. Restrict the
    /// rows to the user here, as a Filament resource does in `getEloquentQuery()`, such as an
    /// author who sees only their own posts. The total counts the same rows. The default is
    /// [`list`](Self::list), for every user.
    fn list_for<'a>(
        &'a self,
        db: &'a Database,
        user: &'a ActingUser,
        query: &'a ListQuery,
    ) -> RuntimeFuture<'a, Page<Row>> {
        let _ = user;
        self.list(db, query)
    }

    /// [`find`](Self::find) for the signed-in `user`: the panel finds the record of the edit
    /// form, of its save and of the delete action with it. Return `None` for a row the user's
    /// list leaves out, so the panel answers 404, as Filament resolves a record through
    /// `getEloquentQuery()`. The default is [`find`](Self::find), for every user.
    fn find_for<'a>(
        &'a self,
        db: &'a Database,
        user: &'a ActingUser,
        id: i64,
    ) -> RuntimeFuture<'a, Option<Row>> {
        let _ = user;
        self.find(db, id)
    }

    /// [`create`](Self::create) for the signed-in `user`, such as to make them the author.
    /// The default is [`create`](Self::create).
    fn create_for<'a>(
        &'a self,
        db: &'a Database,
        user: &'a ActingUser,
        input: Row,
    ) -> RuntimeFuture<'a, Row> {
        let _ = user;
        self.create(db, input)
    }

    /// [`update`](Self::update) for the signed-in `user`, such as to keep a status the user
    /// may not set. The panel calls it only after [`find_for`](Self::find_for) found the row
    /// and the [`Policy`](crate::Policy) allowed the update. The default is
    /// [`update`](Self::update).
    fn update_for<'a>(
        &'a self,
        db: &'a Database,
        user: &'a ActingUser,
        id: i64,
        input: Row,
    ) -> RuntimeFuture<'a, Row> {
        let _ = user;
        self.update(db, id, input)
    }

    /// [`create_for`](Self::create_for) that may refuse the row with field messages, as
    /// Laravel's `ValidationException::withMessages()`: answer `Ok(Err(ValidationError))` and
    /// the panel shows the create form again with 422, each message under its field and the
    /// typed values kept. The panel calls this method; the default is
    /// [`create_for`](Self::create_for), which never refuses.
    ///
    /// ```ignore
    /// fn try_create_for<'a>(&'a self, db: &'a Database, user: &'a ActingUser, input: Row)
    ///     -> RuntimeFuture<'a, Result<Row, ValidationError>> {
    ///     Box::pin(async move {
    ///         if name_is_taken(db, &input).await? {
    ///             return Ok(Err(ValidationError::with_messages([("name", "That name is in use.")])));
    ///         }
    ///         Ok(Ok(save(db, input).await?))
    ///     })
    /// }
    /// ```
    fn try_create_for<'a>(
        &'a self,
        db: &'a Database,
        user: &'a ActingUser,
        input: Row,
    ) -> RuntimeFuture<'a, Result<Row, ValidationError>> {
        Box::pin(async move { self.create_for(db, user, input).await.map(Ok) })
    }

    /// [`find_for`](Self::find_for) by the record's key in the URL, for a resource whose
    /// records are addressed by a key other than the numeric `id`
    /// ([`RuntimeResource::record_route_key_name`], as Filament's `$recordRouteKeyName`), such
    /// as a post type's key. The default parses `key` as an id and calls
    /// [`find_for`](Self::find_for); a key that is not a whole number finds nothing.
    fn find_by_key_for<'a>(
        &'a self,
        db: &'a Database,
        user: &'a ActingUser,
        key: &'a str,
    ) -> RuntimeFuture<'a, Option<Row>> {
        match key.parse::<i64>() {
            Ok(id) => self.find_for(db, user, id),
            Err(_) => Box::pin(async { Ok(None) }),
        }
    }

    /// [`try_update_for`](Self::try_update_for) by the record's key, as
    /// [`find_by_key_for`](Self::find_by_key_for). The default parses `key` as an id.
    fn try_update_by_key_for<'a>(
        &'a self,
        db: &'a Database,
        user: &'a ActingUser,
        key: &'a str,
        input: Row,
    ) -> RuntimeFuture<'a, Result<Row, ValidationError>> {
        match key.parse::<i64>() {
            Ok(id) => self.try_update_for(db, user, id, input),
            Err(_) => Box::pin(async { Err(Error::NotFound { table: "records" }) }),
        }
    }

    /// [`delete_for`](Self::delete_for) by the record's key, as
    /// [`find_by_key_for`](Self::find_by_key_for). The default parses `key` as an id; a key
    /// that is not a whole number deletes nothing.
    fn delete_by_key_for<'a>(
        &'a self,
        db: &'a Database,
        user: &'a ActingUser,
        key: &'a str,
    ) -> RuntimeFuture<'a, u64> {
        match key.parse::<i64>() {
            Ok(id) => self.delete_for(db, user, id),
            Err(_) => Box::pin(async { Ok(0) }),
        }
    }

    /// [`update_for`](Self::update_for) that may refuse the row with field messages, as
    /// [`try_create_for`](Self::try_create_for) for the edit form. The panel calls it only
    /// after [`find_for`](Self::find_for) found the row and the policy allowed the update. The
    /// default is [`update_for`](Self::update_for), which never refuses.
    fn try_update_for<'a>(
        &'a self,
        db: &'a Database,
        user: &'a ActingUser,
        id: i64,
        input: Row,
    ) -> RuntimeFuture<'a, Result<Row, ValidationError>> {
        Box::pin(async move { self.update_for(db, user, id, input).await.map(Ok) })
    }

    /// [`delete`](Self::delete) for the signed-in `user`. The panel calls it only after
    /// [`find_for`](Self::find_for) found the row and the [`Policy`](crate::Policy) allowed
    /// the delete. The default is [`delete`](Self::delete).
    fn delete_for<'a>(
        &'a self,
        db: &'a Database,
        user: &'a ActingUser,
        id: i64,
    ) -> RuntimeFuture<'a, u64> {
        let _ = user;
        self.delete(db, id)
    }

    /// The dashboard cards of the resource for the signed-in `user`, as
    /// [`IgniteResource::stats`](crate::IgniteResource::stats). The panel shows them only to a
    /// user who may view the resource's records. The default is none.
    fn stats<'a>(
        &'a self,
        db: &'a Database,
        user: &'a ActingUser,
    ) -> RuntimeFuture<'a, Vec<crate::widget::Stat>> {
        let _ = (db, user);
        Box::pin(async { Ok(Vec::new()) })
    }

    /// [`options`](Self::options) for the signed-in `user`: the panel fills the form's
    /// selects with these choices and checks a submitted value against them, so a choice left
    /// out cannot be saved, as a Filament select whose options depend on the user. The default
    /// is [`options`](Self::options).
    fn options_for<'a>(
        &'a self,
        db: &'a Database,
        user: &'a ActingUser,
        field: &'a str,
    ) -> RuntimeFuture<'a, Vec<(String, String)>> {
        let _ = user;
        self.options(db, field)
    }

    /// The choices of the field at `field` for the form's current values, as Filament's
    /// dependent select, `options(fn (Get $get) => ...)` on a field whose controlling field is
    /// `live()`: such as a location rule's values, which depend on the rule's parameter. The
    /// panel calls it each time it shows the form, again when a live field changes (see
    /// [`FieldConditions::live`]), and when it checks a submitted value, so a choice the
    /// current values leave out cannot be saved.
    ///
    /// `field` is the field's path of names, without row numbers: `"city"` for a field of the
    /// form, `"rules.value"` for the sub-field `value` of each row of the repeater `rules`,
    /// `"content.hero.style"` for a sub-field of a flexible content block. `state` holds the
    /// current values around the field, as Filament's `$get` reads its siblings: the form's
    /// fields for a field of the form (a structured field's value as JSON), and the row's (or
    /// group's) values for a sub-field. A blank value is missing or `null`. The default is
    /// [`options_for`](Self::options_for), which does not depend on the values.
    ///
    /// A value no longer among the choices after the controlling field changed shows as not
    /// chosen, and is refused if saved, which is Filament's `afterStateUpdated` reset of the
    /// dependent field, done by the server.
    fn options_with<'a>(
        &'a self,
        db: &'a Database,
        user: &'a ActingUser,
        field: &'a str,
        state: &'a Row,
    ) -> RuntimeFuture<'a, Vec<(String, String)>> {
        let _ = state;
        self.options_for(db, user, field)
    }

    /// The tabs of the list page for the signed-in `user`, computed on each list request, as
    /// Filament's `getTabs()` is a method of the List page: such as one tab per role on a users
    /// list, which changes when a role is added. `None`, the default, keeps the resource's
    /// [`tabs`](RuntimeResource::tabs). The `tab` query parameter, the default tab and the
    /// counts work as for the declared tabs.
    fn tabs_for<'a>(
        &'a self,
        db: &'a Database,
        user: &'a ActingUser,
    ) -> RuntimeFuture<'a, Option<Vec<Tab>>> {
        let _ = (db, user);
        Box::pin(async { Ok(None) })
    }

    /// Rules on the submitted form, checked beside the fields' own checks before the row is
    /// built, as the rules of a Laravel form request: such as a password's minimum length,
    /// which the row cannot show because a password is hashed in it. `operation` is
    /// [`Operation::Create`] or [`Operation::Edit`]. Each error is keyed by the field's name and
    /// shows under it, with 422, as a field's own error. The default is none.
    fn validate_form(&self, form: &FormInput, operation: Operation) -> FieldErrors {
        let _ = (form, operation);
        FieldErrors::new()
    }
}

/// The kind of a [`FieldDef`]: every [`FieldKind`], with owned values so it can be loaded
/// from a database.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum FieldKindDef {
    /// A single line of text. See [`FieldKind::Text`].
    Text,
    /// Several lines of text. See [`FieldKind::Textarea`].
    Textarea,
    /// A password, hashed on save. See [`FieldKind::Password`].
    Password,
    /// A whole number. See [`FieldKind::Number`].
    Number,
    /// A decimal number, with the browser's step, such as `"any"` or `"0.01"`. See
    /// [`FieldKind::Decimal`].
    Decimal(String),
    /// A yes/no value. See [`FieldKind::Checkbox`].
    Checkbox,
    /// One choice from a list of `(value, label)` pairs. See [`FieldKind::Select`].
    Select(Vec<(String, String)>),
    /// One choice from options that [`RuntimeData::options`] loads. See [`FieldKind::Lookup`].
    Lookup,
    /// A calendar date. See [`FieldKind::Date`].
    Date,
    /// A date and time. See [`FieldKind::DateTime`].
    DateTime,
    /// An email address. See [`FieldKind::Email`].
    Email,
    /// A URL. See [`FieldKind::Url`].
    Url,
    /// One choice from a list of `(value, label)` pairs, as radio buttons. See
    /// [`FieldKind::Radio`].
    Radio(Vec<(String, String)>),
    /// A color, as `#rrggbb`. See [`FieldKind::Color`].
    Color,
    /// An image from the media library. See [`FieldKind::Image`].
    Image,
    /// A file from the media library. See [`FieldKind::File`].
    File,
    /// A link, as JSON text. See [`FieldKind::Link`].
    Link,
    /// Rich text, edited with the app's editor. See [`FieldKind::Wysiwyg`].
    Wysiwyg,
    /// One post, from options [`RuntimeData::options`] loads. See [`FieldKind::PostObject`].
    PostObject,
    /// Several choices from a list of `(value, label)` pairs, as checkboxes; with no pairs,
    /// from options [`RuntimeData::options`] loads. See [`FieldKind::CheckboxList`].
    CheckboxList(Vec<(String, String)>),
    /// Several choices, from options [`RuntimeData::options`] loads. See
    /// [`FieldKind::Relationship`].
    Relationship,
    /// One taxonomy term, from loaded options. See [`FieldKind::Taxonomy`].
    Taxonomy,
    /// One user, from loaded options. See [`FieldKind::User`].
    User,
    /// Rows of the given sub-fields, as JSON text. See [`FieldKind::Repeater`].
    Repeater(Vec<FieldDef>),
    /// The given sub-fields, as one JSON object. See [`FieldKind::Group`].
    Group(Vec<FieldDef>),
    /// Rows that each take one of the given blocks, as JSON text. See
    /// [`FieldKind::FlexibleContent`].
    FlexibleContent(Vec<BlockDef>),
    /// Several images from the media library, as a JSON array of ids. See
    /// [`FieldKind::Gallery`].
    Gallery,
    /// The fields of another field group, reused. See [`FieldKind::Clone`].
    Clone(Vec<FieldDef>),
}

impl FieldKindDef {
    /// Whether the field's choices come from [`RuntimeData::options`] each time its form is
    /// shown. See [`FieldKind::loads_options`].
    pub fn loads_options(&self) -> bool {
        match self {
            FieldKindDef::CheckboxList(choices) => choices.is_empty(),
            _ => matches!(
                self,
                FieldKindDef::Lookup
                    | FieldKindDef::PostObject
                    | FieldKindDef::Relationship
                    | FieldKindDef::Taxonomy
                    | FieldKindDef::User
            ),
        }
    }

    /// Whether the field holds media library ids: an image, a file or a gallery.
    pub fn uses_media(&self) -> bool {
        matches!(
            self,
            FieldKindDef::Image | FieldKindDef::File | FieldKindDef::Gallery
        )
    }
}

/// One block of a [`FieldKindDef::FlexibleContent`] field: the owned twin of [`Block`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BlockDef {
    /// The block's name, stored as the `type` of each row that uses it.
    pub name: String,
    /// The label shown when choosing the block.
    pub label: String,
    /// The block's sub-fields, in display order.
    pub fields: Vec<FieldDef>,
}

impl From<Block> for BlockDef {
    fn from(block: Block) -> Self {
        BlockDef {
            name: block.name.to_string(),
            label: block.label.to_string(),
            fields: owned_fields(block.fields),
        }
    }
}

/// Owned definitions of static sub-fields.
fn owned_fields(fields: &[Field]) -> Vec<FieldDef> {
    fields.iter().copied().map(FieldDef::from).collect()
}

/// Owned `(value, label)` pairs of static choices.
fn owned_choices(choices: &[(&str, &str)]) -> Vec<(String, String)> {
    choices
        .iter()
        .map(|(value, label)| (value.to_string(), label.to_string()))
        .collect()
}

impl From<FieldKind> for FieldKindDef {
    fn from(kind: FieldKind) -> Self {
        match kind {
            FieldKind::Text => FieldKindDef::Text,
            FieldKind::Textarea => FieldKindDef::Textarea,
            FieldKind::Password => FieldKindDef::Password,
            FieldKind::Number => FieldKindDef::Number,
            FieldKind::Decimal(step) => FieldKindDef::Decimal(step.to_string()),
            FieldKind::Checkbox => FieldKindDef::Checkbox,
            FieldKind::Select(choices) => FieldKindDef::Select(owned_choices(choices)),
            FieldKind::Lookup => FieldKindDef::Lookup,
            FieldKind::Date => FieldKindDef::Date,
            FieldKind::DateTime => FieldKindDef::DateTime,
            FieldKind::Email => FieldKindDef::Email,
            FieldKind::Url => FieldKindDef::Url,
            FieldKind::Radio(choices) => FieldKindDef::Radio(owned_choices(choices)),
            FieldKind::Color => FieldKindDef::Color,
            FieldKind::Image => FieldKindDef::Image,
            FieldKind::File => FieldKindDef::File,
            FieldKind::Link => FieldKindDef::Link,
            FieldKind::Wysiwyg => FieldKindDef::Wysiwyg,
            FieldKind::PostObject => FieldKindDef::PostObject,
            FieldKind::CheckboxList(choices) => FieldKindDef::CheckboxList(owned_choices(choices)),
            FieldKind::Relationship => FieldKindDef::Relationship,
            FieldKind::Taxonomy => FieldKindDef::Taxonomy,
            FieldKind::User => FieldKindDef::User,
            FieldKind::Repeater(fields) => FieldKindDef::Repeater(owned_fields(fields)),
            FieldKind::Group(fields) => FieldKindDef::Group(owned_fields(fields)),
            FieldKind::FlexibleContent(blocks) => {
                FieldKindDef::FlexibleContent(blocks.iter().copied().map(BlockDef::from).collect())
            }
            FieldKind::Gallery => FieldKindDef::Gallery,
            FieldKind::Clone(fields) => FieldKindDef::Clone(owned_fields(fields)),
        }
    }
}

/// One input on the form of a runtime resource: the owned twin of [`Field`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FieldDef {
    /// The form field name. It matches a key of the row.
    pub name: String,
    /// The label shown next to the input.
    pub label: String,
    /// The input type, and how the value is read.
    pub kind: FieldKindDef,
    /// Whether the form rejects a blank value.
    pub required: bool,
}

impl From<Field> for FieldDef {
    fn from(field: Field) -> Self {
        FieldDef {
            name: field.name.to_string(),
            label: field.label.to_string(),
            kind: field.kind.into(),
            required: field.required,
        }
    }
}

/// One column of the list of a runtime resource: the owned twin of [`Column`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ColumnDef {
    /// The row key the column shows. It matches a field name.
    pub key: String,
    /// The column heading.
    pub label: String,
    /// Whether the heading links to a sort by this column.
    pub sortable: bool,
    /// Whether the search box matches this column.
    pub searchable: bool,
}

impl From<Column> for ColumnDef {
    fn from(column: Column) -> Self {
        ColumnDef {
            key: column.key.to_string(),
            label: column.label.to_string(),
            sortable: column.sortable,
            searchable: column.searchable,
        }
    }
}

/// Where the panel goes after a successful save of a runtime resource's form, as Filament's
/// `getRedirectUrl()` and the panel's `resourceCreatePageRedirect()` and
/// `resourceEditPageRedirect()`. See [`RuntimeResource::redirect_after_create`] and
/// [`RuntimeResource::redirect_after_update`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RedirectAfter {
    /// The record's edit page, with the flash message: after a create, the new record's (or
    /// the list, for a user who may not edit it), as Filament's default after creating; after
    /// an update, the same page again, as Filament's default after saving (it stays on the
    /// page and shows the notification).
    Edit,
    /// The resource's list page, with the flash message: Ignite's default before 0.6.8, as
    /// Filament's `getUrl('index')`.
    List,
}

/// A resource defined by data. Build it with [`new`](Self::new) and the
/// [`field`](Self::field) and [`column`](Self::column) methods, then add it to the panel
/// with [`Registries::register_runtime`].
#[derive(Clone)]
pub struct RuntimeResource {
    /// URL segment: `"books"` serves the resource at `/admin/books`. Lowercase letters,
    /// digits, `-` and `_` only.
    pub slug: String,
    /// Heading and navigation label: `"Books"`.
    pub title: String,
    /// The name of one record, for headings such as "New Book".
    pub singular: String,
    /// Rows per page on the list view. The default is 20, as for a static resource.
    pub per_page: i64,
    /// Form fields, in display order.
    pub fields: Vec<FieldDef>,
    /// Table columns, in display order. Each column's `key` is a field name.
    pub columns: Vec<ColumnDef>,
    /// Where the rows live.
    pub data: Arc<dyn RuntimeData>,
    /// The label of the navigation entry, as Filament's `$navigationLabel`. `None`, the
    /// default, is the [`title`](Self::title).
    pub navigation_label: Option<String>,
    /// The navigation group the resource is listed under, as Filament's `$navigationGroup`.
    /// See [`IgniteResource::NAVIGATION_GROUP`](crate::IgniteResource::NAVIGATION_GROUP).
    pub navigation_group: Option<String>,
    /// The resource's place in the navigation, as Filament's `$navigationSort`: lower first.
    /// See [`IgniteResource::NAVIGATION_SORT`](crate::IgniteResource::NAVIGATION_SORT).
    pub navigation_sort: Option<i32>,
    /// The navigation entry the resource is listed under, as Filament's
    /// `$navigationParentItem`: the parent's label or slug. See
    /// [`IgniteResource::NAVIGATION_PARENT_ITEM`](crate::IgniteResource::NAVIGATION_PARENT_ITEM).
    pub navigation_parent_item: Option<String>,
    /// More navigation entries the resource is listed under, by label or slug. See
    /// [`IgniteResource::NAVIGATION_PARENT_ITEMS`](crate::IgniteResource::NAVIGATION_PARENT_ITEMS).
    pub navigation_parent_items: Vec<String>,
    /// Whether the resource has a navigation entry, as Filament's `$shouldRegisterNavigation`.
    /// The default is `true`. See
    /// [`IgniteResource::SHOULD_REGISTER_NAVIGATION`](crate::IgniteResource::SHOULD_REGISTER_NAVIGATION).
    pub should_register_navigation: bool,
    /// The name of the navigation entry's icon, such as `post`, as Filament's
    /// `$navigationIcon`. See [`IgniteResource::NAVIGATION_ICON`](crate::IgniteResource::NAVIGATION_ICON).
    pub navigation_icon: Option<String>,
    /// Whether the navigation entry lists a link to the create page. The default is `true`.
    /// See [`IgniteResource::NAVIGATION_CREATE_ITEM`](crate::IgniteResource::NAVIGATION_CREATE_ITEM).
    pub navigation_create_item: bool,
    /// The label of the create link. `None`, the default, is `"Add new"`.
    pub navigation_create_label: Option<String>,
    /// The conditions that show or hide the form's fields, and the live fields, as
    /// Filament's `visible()`, `hidden()` and `live()`. See [`FieldConditions`].
    pub conditions: FieldConditions,
    /// The layout of the create and edit forms, as Filament's layout components. See
    /// [`FormLayout`]. The default has none: the form renders as one card of fields.
    pub form_layout: FormLayout,
    /// The tabs of the list page, in display order, as Filament's `getTabs()`. See
    /// [`IgniteResource::tabs`](crate::IgniteResource::tabs). The default is none.
    pub tabs: Vec<Tab>,
    /// The key of the tab shown when the list has no `tab` parameter, as Filament's
    /// `getDefaultActiveTab()`. `None`, the default, is the first tab.
    pub default_active_tab: Option<String>,
    /// The list columns shown as coloured badges, as Filament's `badge()` and `color()`. See
    /// [`ColumnBadges`]. The default is none.
    pub column_badges: ColumnBadges,
    /// Whether each tab's count is for the current search. The default is `false`: a tab
    /// counts all its rows. See
    /// [`IgniteResource::tab_counts_follow_search`](crate::IgniteResource::tab_counts_follow_search).
    pub tab_counts_follow_search: bool,
    /// Whether a tab whose count is 0 is left out, except the default tab and the tab shown.
    /// The default is `true`. See
    /// [`IgniteResource::hide_empty_tabs`](crate::IgniteResource::hide_empty_tabs).
    pub hide_empty_tabs: bool,
    /// The actions on each row of the list page, in display order, as Filament's
    /// `recordActions()`. See [`RowAction`]. The default is none.
    pub row_actions: Vec<RowAction>,
    /// The actions on the records ticked in the list, as Filament's `toolbarActions()`. See
    /// [`BulkAction`]. The default is none: the list has no checkboxes.
    pub bulk_actions: Vec<BulkAction>,
    /// The records whose built-in Delete button is hidden (and whose delete the panel
    /// refuses). See
    /// [`IgniteResource::hide_default_delete_when`](crate::IgniteResource::hide_default_delete_when).
    /// The default is none.
    pub hide_default_delete_when: Option<ListFilter>,
    /// The settings of the form's repeaters and flexible content fields, by path, as
    /// Filament's `minItems()`, `maxItems()` and `itemLabel()`. See [`Repeaters`]. The default
    /// has none: every repeater has the default settings.
    pub repeaters: Repeaters,
    /// The records the signed-in user may only view. See
    /// [`read_only_when`](Self::read_only_when). The default is none.
    pub read_only: Option<FormRule>,
    /// The line the form of a read-only record shows. See
    /// [`read_only_notice`](Self::read_only_notice).
    pub read_only_notice: Option<FormNotice>,
    /// The row key that addresses a record in the panel's URLs, as Filament's
    /// `$recordRouteKeyName`. `None`, the default, is the numeric `id`. See
    /// [`record_route_key_name`](Self::record_route_key_name).
    pub record_route_key_name: Option<String>,
    /// Where a successful create goes. `None`, the default, is the list page, as before 0.6.8.
    /// See [`redirect_after_create`](Self::redirect_after_create).
    pub redirect_after_create: Option<RedirectAfter>,
    /// Where a successful update goes. `None`, the default, is the list page, as before 0.6.8.
    /// See [`redirect_after_update`](Self::redirect_after_update).
    pub redirect_after_update: Option<RedirectAfter>,
    /// The ability each action on the resource needs, when it is not `<slug>.<action>`. See
    /// [`ability`](Self::ability). The default is none: every action needs its default.
    pub abilities: BTreeMap<ResourceAction, String>,
    /// The ability every action on the resource needs besides its own, if any. See
    /// [`access_ability`](Self::access_ability).
    pub access_ability: Option<String>,
}

impl fmt::Debug for RuntimeResource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RuntimeResource")
            .field("slug", &self.slug)
            .field("title", &self.title)
            .field("singular", &self.singular)
            .field("per_page", &self.per_page)
            .field("fields", &self.fields)
            .field("columns", &self.columns)
            .field("navigation_label", &self.navigation_label)
            .field("navigation_group", &self.navigation_group)
            .field("navigation_sort", &self.navigation_sort)
            .field("navigation_parent_item", &self.navigation_parent_item)
            .field("navigation_parent_items", &self.navigation_parent_items)
            .field(
                "should_register_navigation",
                &self.should_register_navigation,
            )
            .field("navigation_icon", &self.navigation_icon)
            .field("navigation_create_item", &self.navigation_create_item)
            .field("navigation_create_label", &self.navigation_create_label)
            .field("conditions", &self.conditions)
            .field("form_layout", &self.form_layout)
            .field("tabs", &self.tabs)
            .field("default_active_tab", &self.default_active_tab)
            .field("column_badges", &self.column_badges)
            .field("tab_counts_follow_search", &self.tab_counts_follow_search)
            .field("hide_empty_tabs", &self.hide_empty_tabs)
            .field("row_actions", &self.row_actions)
            .field("bulk_actions", &self.bulk_actions)
            .field("hide_default_delete_when", &self.hide_default_delete_when)
            .field("repeaters", &self.repeaters)
            .field("read_only", &self.read_only.is_some())
            .field("record_route_key_name", &self.record_route_key_name)
            .field("redirect_after_create", &self.redirect_after_create)
            .field("redirect_after_update", &self.redirect_after_update)
            .field("abilities", &self.abilities)
            .field("access_ability", &self.access_ability)
            .finish_non_exhaustive()
    }
}

impl RuntimeResource {
    /// A resource at `slug` with no fields or columns yet, whose rows come from `data`.
    pub fn new(
        slug: impl Into<String>,
        title: impl Into<String>,
        singular: impl Into<String>,
        data: impl RuntimeData,
    ) -> Self {
        RuntimeResource {
            slug: slug.into(),
            title: title.into(),
            singular: singular.into(),
            per_page: 20,
            fields: Vec::new(),
            columns: Vec::new(),
            data: Arc::new(data),
            navigation_label: None,
            navigation_group: None,
            navigation_sort: None,
            navigation_parent_item: None,
            navigation_parent_items: Vec::new(),
            should_register_navigation: true,
            navigation_icon: None,
            navigation_create_item: true,
            navigation_create_label: None,
            conditions: FieldConditions::new(),
            form_layout: FormLayout::new(),
            tabs: Vec::new(),
            default_active_tab: None,
            column_badges: ColumnBadges::new(),
            tab_counts_follow_search: false,
            hide_empty_tabs: true,
            row_actions: Vec::new(),
            bulk_actions: Vec::new(),
            hide_default_delete_when: None,
            repeaters: Repeaters::new(),
            read_only: None,
            read_only_notice: None,
            record_route_key_name: None,
            redirect_after_create: None,
            redirect_after_update: None,
            abilities: BTreeMap::new(),
            access_ability: None,
        }
    }

    /// Adds a form field after the others.
    pub fn field(mut self, field: FieldDef) -> Self {
        self.fields.push(field);
        self
    }

    /// Adds a list column after the others.
    pub fn column(mut self, column: ColumnDef) -> Self {
        self.columns.push(column);
        self
    }

    /// Sets the rows per page of the list view.
    pub fn per_page(mut self, per_page: i64) -> Self {
        self.per_page = per_page;
        self
    }

    /// Sets the label of the navigation entry, as Filament's `navigationLabel`.
    pub fn navigation_label(mut self, label: impl Into<String>) -> Self {
        self.navigation_label = Some(label.into());
        self
    }

    /// Lists the resource under the navigation group `group`, as Filament's `navigationGroup`.
    pub fn navigation_group(mut self, group: impl Into<String>) -> Self {
        self.navigation_group = Some(group.into());
        self
    }

    /// Sets the resource's place in the navigation, as Filament's `navigationSort`: lower first.
    pub fn navigation_sort(mut self, sort: i32) -> Self {
        self.navigation_sort = Some(sort);
        self
    }

    /// Lists the resource under the navigation entry `parent` (its label or slug), as
    /// Filament's `navigationParentItem`. See
    /// [`IgniteResource::NAVIGATION_PARENT_ITEM`](crate::IgniteResource::NAVIGATION_PARENT_ITEM).
    pub fn navigation_parent_item(mut self, parent: impl Into<String>) -> Self {
        self.navigation_parent_item = Some(parent.into());
        self
    }

    /// Lists the resource under each of the navigation entries `parents` (labels or slugs)
    /// that the sidebar shows, as a taxonomy's screen under every post type it is attached
    /// to. See
    /// [`IgniteResource::NAVIGATION_PARENT_ITEMS`](crate::IgniteResource::NAVIGATION_PARENT_ITEMS).
    pub fn navigation_parent_items<I>(mut self, parents: I) -> Self
    where
        I: IntoIterator,
        I::Item: Into<String>,
    {
        self.navigation_parent_items
            .extend(parents.into_iter().map(Into::into));
        self
    }

    /// Whether the resource has a navigation entry, as Filament's `shouldRegisterNavigation`.
    /// See [`IgniteResource::SHOULD_REGISTER_NAVIGATION`](crate::IgniteResource::SHOULD_REGISTER_NAVIGATION).
    pub fn should_register_navigation(mut self, listed: bool) -> Self {
        self.should_register_navigation = listed;
        self
    }

    /// Sets the name of the navigation entry's icon, as Filament's `navigationIcon`: a name
    /// such as `"post"` or a custom post type's own, which the admin theme maps to its icon.
    /// See [`IgniteResource::NAVIGATION_ICON`](crate::IgniteResource::NAVIGATION_ICON).
    pub fn navigation_icon(mut self, name: impl Into<String>) -> Self {
        self.navigation_icon = Some(name.into());
        self
    }

    /// Whether the navigation entry lists a link to the create page, under the entry, in its
    /// group. See [`IgniteResource::NAVIGATION_CREATE_ITEM`](crate::IgniteResource::NAVIGATION_CREATE_ITEM).
    pub fn navigation_create_item(mut self, listed: bool) -> Self {
        self.navigation_create_item = listed;
        self
    }

    /// Sets the label of the create link, such as `"Add New Post"`. See
    /// [`IgniteResource::NAVIGATION_CREATE_LABEL`](crate::IgniteResource::NAVIGATION_CREATE_LABEL).
    pub fn navigation_create_label(mut self, label: impl Into<String>) -> Self {
        self.navigation_create_label = Some(label.into());
        self
    }

    /// Shows the field `field` only when `rule` holds, as Filament's `->visible()`. See
    /// [`FieldConditions::visible`].
    pub fn visible(
        mut self,
        field: impl Into<String>,
        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
    ) -> Self {
        self.conditions = self.conditions.visible(field, rule);
        self
    }

    /// Hides the field `field` when `rule` holds, as Filament's `->hidden()`. See
    /// [`FieldConditions::hidden`].
    pub fn hidden(
        mut self,
        field: impl Into<String>,
        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
    ) -> Self {
        self.conditions = self.conditions.hidden(field, rule);
        self
    }

    /// Shows the field `field` only on the forms of `operations`, as Filament's
    /// `->visibleOn()`.
    pub fn visible_on(mut self, field: impl Into<String>, operations: &[Operation]) -> Self {
        self.conditions = self.conditions.visible_on(field, operations);
        self
    }

    /// Hides the field `field` on the forms of `operations`, as Filament's `->hiddenOn()`.
    pub fn hidden_on(mut self, field: impl Into<String>, operations: &[Operation]) -> Self {
        self.conditions = self.conditions.hidden_on(field, operations);
        self
    }

    /// Makes the field `field` live, as Filament's `->live()`: a change to it in the browser
    /// shows the form's fields again for the new value. See [`FieldConditions::live`].
    pub fn live(mut self, field: impl Into<String>) -> Self {
        self.conditions = self.conditions.live(field);
        self
    }

    /// Gives the field `field` the default value `value` on the create form, as Filament's
    /// `->default(...)`; the edit form shows the stored value. See
    /// [`FieldConditions::default_value`].
    pub fn default_value(mut self, field: impl Into<String>, value: impl Into<Value>) -> Self {
        self.conditions = self.conditions.default_value(field, value);
        self
    }

    /// Gives the field `field` a default computed from the create form's state, as Filament's
    /// `->default(fn (Get $get) => ...)`. See [`FieldConditions::default_with`].
    pub fn default_with(
        mut self,
        field: impl Into<String>,
        rule: impl Fn(&FormContext<'_>) -> Value + Send + Sync + 'static,
    ) -> Self {
        self.conditions = self.conditions.default_with(field, rule);
        self
    }

    /// Fills the field `field` with the slug of the field `source` until the user edits it, as
    /// Filament's slug pattern. See [`FieldConditions::slug_from`].
    pub fn slug_from(mut self, field: impl Into<String>, source: impl Into<String>) -> Self {
        self.conditions = self.conditions.slug_from(field, source);
        self
    }

    /// Stops the slug field `field` from following its source on the edit form of a record
    /// with a stored slug, when `rule` holds, such as once the record is published. See
    /// [`FieldConditions::slug_locked_when`].
    pub fn slug_locked_when(
        mut self,
        field: impl Into<String>,
        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
    ) -> Self {
        self.conditions = self.conditions.slug_locked_when(field, rule);
        self
    }

    /// Sets the layout of the create and edit forms: columns, sections and groups, as
    /// Filament's layout components. See [`FormLayout`].
    pub fn form_layout(mut self, layout: FormLayout) -> Self {
        self.form_layout = layout;
        self
    }

    /// Adds a tab to the list page after the others, as a [`Tab`] in Filament's `getTabs()`.
    /// The [`RuntimeData`] list is given the active tab's conditions in
    /// [`ListQuery::filter`]: apply them with [`ListFilter::apply`](crate::ListFilter::apply)
    /// or [`ListFilter::matches`](crate::ListFilter::matches).
    pub fn tab(mut self, tab: Tab) -> Self {
        self.tabs.push(tab);
        self
    }

    /// Sets the tab shown when the list has no `tab` parameter, by its key, as Filament's
    /// `getDefaultActiveTab()`. Without it, the first tab is shown.
    pub fn default_active_tab(mut self, key: impl Into<String>) -> Self {
        self.default_active_tab = Some(key.into());
        self
    }

    /// Whether each tab's count is for the current search. The default, `false`, counts all
    /// of a tab's rows. See
    /// [`IgniteResource::tab_counts_follow_search`](crate::IgniteResource::tab_counts_follow_search).
    pub fn tab_counts_follow_search(mut self, follow: bool) -> Self {
        self.tab_counts_follow_search = follow;
        self
    }

    /// Whether a tab whose count is 0 is left out, except the default tab and the tab shown.
    /// The default is `true`; `false` renders every tab. See
    /// [`IgniteResource::hide_empty_tabs`](crate::IgniteResource::hide_empty_tabs).
    pub fn hide_empty_tabs(mut self, hide: bool) -> Self {
        self.hide_empty_tabs = hide;
        self
    }

    /// Adds an action on each row of the list, after the others, as an action in Filament's
    /// `recordActions()`. See [`RowAction`].
    pub fn row_action(mut self, action: RowAction) -> Self {
        self.row_actions.push(action);
        self
    }

    /// Adds an action on the records ticked in the list, as Filament's `BulkAction::make()` in
    /// `toolbarActions()`. See [`BulkAction`].
    pub fn bulk_action(mut self, action: BulkAction) -> Self {
        self.bulk_actions.push(action);
        self
    }

    /// Hides the built-in Delete button on the records that meet `filter`, and refuses their
    /// delete, such as `ListFilter::new().where_eq("status", "trash")` for a post in the trash.
    /// See [`IgniteResource::hide_default_delete_when`](crate::IgniteResource::hide_default_delete_when).
    pub fn hide_default_delete_when(mut self, filter: ListFilter) -> Self {
        self.hide_default_delete_when = Some(filter);
        self
    }

    /// Sets the settings of the repeater or flexible content field at `path`, such as
    /// `"members"`, or `"groups.rules"` for the repeater `rules` inside each row of `groups`:
    /// its fewest and most rows, its row label and its buttons, as Filament's `Repeater`
    /// methods. See [`RepeaterSettings`].
    pub fn repeater(mut self, path: impl Into<String>, settings: RepeaterSettings) -> Self {
        self.repeaters = self.repeaters.repeater(path, settings);
        self
    }

    /// Names the ability that allows `action` on the resource, in place of `<slug>.<action>`,
    /// as a Filament resource policy's method checks the permission it chooses: such as
    /// `ability(ResourceAction::Update, "edit_books")` for a post type whose capability type
    /// is `book`, as WordPress maps `edit_post` to `edit_books`. The ability gates the
    /// resource as a whole (its list and navigation entry for `ViewAny`, its forms and saves
    /// for `Create` and `Update`, its delete for `Delete`); a [`Policy`](crate::Policy) still
    /// decides each record. The panel registers the ability as a permission on the next
    /// signed-in request after the resource is registered (or at once with
    /// `ignite_panel::register_runtime_permissions`), so the Roles screen lists it without a
    /// restart. Several actions may share one ability.
    pub fn ability(mut self, action: ResourceAction, name: impl Into<String>) -> Self {
        self.abilities.insert(action, name.into());
        self
    }

    /// Requires the ability `name` for every action on the resource, besides each action's
    /// own, as Filament's `canAccess()` and WordPress's `manage_options` for the settings
    /// screens: a user without it does not see the navigation entry and gets 403 on every
    /// route of the resource.
    pub fn access_ability(mut self, name: impl Into<String>) -> Self {
        self.access_ability = Some(name.into());
        self
    }

    /// Addresses each record in the panel's URLs by the row key `key` instead of the numeric
    /// `id`, as Filament's `$recordRouteKeyName`: such as `"key"`, so a post type's edit form
    /// is at `/admin/post-types/book/edit`. The rows the list gives must have the key, as text
    /// or a number, and the data finds, updates and deletes them by it
    /// ([`RuntimeData::find_by_key_for`], [`try_update_by_key_for`](RuntimeData::try_update_by_key_for)
    /// and [`delete_by_key_for`](RuntimeData::delete_by_key_for)). A key that the form sets is
    /// usually locked after the first save with [`disabled_on`](Self::disabled_on), as
    /// WordPress keeps a post type's key.
    pub fn record_route_key_name(mut self, key: impl Into<String>) -> Self {
        self.record_route_key_name = Some(key.into());
        self
    }

    /// Where a successful create goes, as Filament's `getRedirectUrl()` on the Create page and
    /// the panel's `resourceCreatePageRedirect()`: [`RedirectAfter::Edit`], Filament's default,
    /// opens the new record's edit page (the list, for a user who may not edit it), and
    /// [`RedirectAfter::List`] the list page. Without this call a create goes to the list, as
    /// in 0.6.7. A dashboard form widget comes back to the dashboard either way.
    pub fn redirect_after_create(mut self, redirect: RedirectAfter) -> Self {
        self.redirect_after_create = Some(redirect);
        self
    }

    /// Where a successful update goes, as Filament's `getRedirectUrl()` on the Edit page and
    /// the panel's `resourceEditPageRedirect()`: [`RedirectAfter::Edit`], Filament's default,
    /// stays on the record's edit page with the flash message, and [`RedirectAfter::List`]
    /// goes to the list page. Without this call an update goes to the list, as in 0.6.7.
    pub fn redirect_after_update(mut self, redirect: RedirectAfter) -> Self {
        self.redirect_after_update = Some(redirect);
        self
    }

    /// Shows the field `field` but does not let the user change it when `rule` holds, as
    /// Filament's `->disabled()`. A disabled field is not saved. See
    /// [`FieldConditions::disabled`].
    pub fn disabled(
        mut self,
        field: impl Into<String>,
        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
    ) -> Self {
        self.conditions = self.conditions.disabled(field, rule);
        self
    }

    /// Disables the field `field` on the forms of `operations`, as Filament's
    /// `->disabledOn('edit')`. See [`FieldConditions::disabled_on`].
    pub fn disabled_on(mut self, field: impl Into<String>, operations: &[Operation]) -> Self {
        self.conditions = self.conditions.disabled_on(field, operations);
        self
    }

    /// Makes the records for which `rule` holds read-only for the signed-in user, as Filament's
    /// View page, a disabled form with the record's data: their edit form shows the values
    /// with every input disabled and no Save, its heading says "View", the list's button says
    /// "View", and their save (and the form's live URL) answers 403 Forbidden. `rule` is given
    /// the edit form's [`FormContext`]: the record, the user and the stored values. Such as a
    /// post type defined in code, which the admin screens may show but not change:
    ///
    /// ```ignore
    /// .read_only_when(|form| form.record().and_then(|r| r.get("origin")) != Some(&json!("admin")))
    /// ```
    pub fn read_only_when(
        mut self,
        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
    ) -> Self {
        self.read_only = Some(Arc::new(rule));
        self
    }

    /// The line the form of a read-only record shows above its fields, such as "This post type
    /// is defined in code by the theme. Change it there.", or none.
    pub fn read_only_notice(
        mut self,
        notice: impl Fn(&FormContext<'_>) -> Option<String> + Send + Sync + 'static,
    ) -> Self {
        self.read_only_notice = Some(Arc::new(notice));
        self
    }

    /// Shows the column `column` as a badge in the primary colour, as Filament's `->badge()`.
    /// See [`ColumnBadges::badge`].
    pub fn badge(mut self, column: impl Into<String>) -> Self {
        self.column_badges = self.column_badges.badge(column);
        self
    }

    /// Shows the column `column` as a badge whose colour `color` picks from the cell's state,
    /// as Filament's `->badge()->color(fn (string $state) => ...)`. See
    /// [`ColumnBadges::badge_color`].
    pub fn badge_color(
        mut self,
        column: impl Into<String>,
        color: impl Fn(&str) -> BadgeColor + Send + Sync + 'static,
    ) -> Self {
        self.column_badges = self.column_badges.badge_color(column, color);
        self
    }

    /// Shows the badge of the column `column` inside the cell of the column `target`, instead
    /// of in a column of its own. See [`ColumnBadges::badge_inside`].
    pub fn badge_inside(mut self, column: impl Into<String>, target: impl Into<String>) -> Self {
        self.column_badges = self.column_badges.badge_inside(column, target);
        self
    }

    /// Shows the badge of the column `column` only on the list's tabs `tabs`, by key. See
    /// [`ColumnBadges::badge_on_tabs`].
    pub fn badge_on_tabs<S: Into<String>>(
        mut self,
        column: impl Into<String>,
        tabs: impl IntoIterator<Item = S>,
    ) -> Self {
        self.column_badges = self.column_badges.badge_on_tabs(column, tabs);
        self
    }
}

/// Turns a submitted form into a [`Row`] for the fields `fields` that are not a resource's,
/// such as the fields an app adds to the panel's profile page, with the checks and the values of
/// [`RegisteredResource::validate_update`]: a blank password and a field the form did not send
/// are left out of the row, an optional field sent blank is `null`, and a checkbox the form did
/// not send is `false`. Each error is keyed by its field's name. A lookup's value is not checked
/// against its choices here: the panel checks it, as for a resource.
pub fn validate_fields_for_update(
    fields: &[FieldDef],
    form: &FormInput,
) -> Result<Row, FieldErrors> {
    validate_fields(fields, form, false, &BTreeSet::new(), &Repeaters::default())
}

/// The checks of [`RegisteredResource::validate`]. Each error is keyed by its field's name.
/// The fields of `hidden` are skipped: they are not checked and the row has no key for them.
fn validate_fields(
    fields: &[FieldDef],
    form: &FormInput,
    creating: bool,
    hidden: &BTreeSet<String>,
    repeaters: &Repeaters,
) -> Result<Row, FieldErrors> {
    let mut errors = FieldErrors::new();
    let mut row = Row::new();
    for field in fields.iter().filter(|f| !hidden.contains(&f.name)) {
        let name = field.name.as_str();
        let label = field.label.as_str();
        // A checkbox is never blank: an unticked checkbox is false.
        if field.kind == FieldKindDef::Checkbox {
            row.insert(name.to_string(), Value::Bool(form.checkbox(name)));
            continue;
        }
        let is_password = field.kind == FieldKindDef::Password;
        // A password is required only when creating. On an edit a blank one keeps the hash.
        let present = if field.required && (creating || !is_password) {
            check::check_required(name, label, form, &mut errors)
        } else {
            form.get(name)
        };
        let Some(text) = present else {
            // On an update, a field the form did not send keeps its stored value, and a blank
            // password keeps its hash. A field sent blank is cleared to NULL.
            let keep = !creating && (is_password || !form.has(name));
            // A repeater sent with no rows has none, which its fewest rows may refuse.
            let min = match field.kind {
                FieldKindDef::Repeater(_) | FieldKindDef::FlexibleContent(_) if !keep => {
                    repeaters.get(name).get_min_items().filter(|min| *min > 0)
                }
                _ => None,
            };
            if let (Some(min), false) = (min, errors.contains_key(name)) {
                errors.insert(
                    name.to_string(),
                    format!("{label} must have at least {min} items."),
                );
            }
            if !keep {
                row.insert(name.to_string(), Value::Null);
            }
            continue;
        };
        let value = match &field.kind {
            FieldKindDef::Password => match crate::hash_password(text) {
                Ok(hash) => Some(Value::String(hash)),
                Err(_) => {
                    errors.insert(
                        name.to_string(),
                        "Could not save this password.".to_string(),
                    );
                    None
                }
            },
            FieldKindDef::Number => {
                check::check_whole_number::<i64>(name, label, text, &mut errors).map(Value::from)
            }
            FieldKindDef::Decimal(_) => {
                check::check_decimal::<f64>(name, label, text, &mut errors).map(Value::from)
            }
            FieldKindDef::Select(choices) => {
                let text = text.trim();
                let choices: Vec<(&str, &str)> = choices
                    .iter()
                    .map(|(value, label)| (value.as_str(), label.as_str()))
                    .collect();
                check::check_choice(name, text, &choices, &mut errors)
                    .then(|| Value::String(text.to_string()))
            }
            FieldKindDef::Lookup => Some(Value::String(text.trim().to_string())),
            FieldKindDef::Date => check::check_date(name, label, text, &mut errors)
                .map(|date| Value::String(date.format("%Y-%m-%d").to_string())),
            FieldKindDef::DateTime => check::check_datetime(name, label, text, &mut errors)
                .map(|stamp| Value::String(stamp.format("%Y-%m-%d %H:%M:%S").to_string())),
            FieldKindDef::Text | FieldKindDef::Textarea | FieldKindDef::Checkbox => {
                Some(Value::String(text.to_string()))
            }
            kind => crate::value::check_value_in(
                name,
                label,
                field.required,
                kind,
                text,
                &mut errors,
                repeaters,
            )
            .map(Value::String),
        };
        if let Some(value) = value {
            row.insert(name.to_string(), value);
        }
    }
    if errors.is_empty() {
        Ok(row)
    } else {
        Err(errors)
    }
}

/// Why the registry refused a change.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RuntimeError {
    /// The slug is not one URL segment of lowercase letters, digits, `-` and `_`.
    InvalidSlug(String),
    /// Another resource, static or runtime, or one of the panel's own pages, has the slug.
    SlugTaken(String),
    /// A field name is not a lowercase identifier: lowercase ASCII letters, digits and `_`,
    /// starting with a letter, at most 64 bytes ([`MAX_FIELD_NAME`]).
    InvalidFieldName {
        /// The slug of the resource.
        slug: String,
        /// The name that was refused.
        field: String,
    },
    /// Two fields of the resource have the same name.
    DuplicateField {
        /// The slug of the resource.
        slug: String,
        /// The name used twice.
        field: String,
    },
    /// No runtime resource has the slug.
    NotRegistered(String),
}

impl fmt::Display for RuntimeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RuntimeError::InvalidSlug(slug) => write!(
                f,
                "the slug `{slug}` is not valid: use lowercase letters, digits, `-` and `_`"
            ),
            RuntimeError::SlugTaken(slug) => write!(
                f,
                "the slug `{slug}` is already used by another Ignite resource"
            ),
            RuntimeError::InvalidFieldName { slug, field } => write!(
                f,
                "the field `{field}` of the resource `{slug}` is not valid: use lowercase \
                 letters, digits and `_`, starting with a letter, at most {MAX_FIELD_NAME} bytes"
            ),
            RuntimeError::DuplicateField { slug, field } => {
                write!(f, "the resource `{slug}` has two fields named `{field}`")
            }
            RuntimeError::NotRegistered(slug) => {
                write!(f, "no runtime resource is registered at `{slug}`")
            }
        }
    }
}

impl std::error::Error for RuntimeError {}

/// A runtime resource as the registry holds it: the definition, ready for the panel.
pub struct RegisteredResource {
    resource: RuntimeResource,
}

impl RegisteredResource {
    /// Checks `resource` as [`Registries::register_runtime`] does, without adding it to the registry: its
    /// slug and its field names. The panel uses it for a resource defined by data that is part
    /// of the panel from its start (`Ignite::runtime_resource`), such as the Users screen.
    pub fn new(resource: RuntimeResource) -> Result<Self, RuntimeError> {
        check_definition(&resource)?;
        Ok(RegisteredResource { resource })
    }

    /// The definition that was registered.
    pub fn resource(&self) -> &RuntimeResource {
        &self.resource
    }

    /// The slug, as the panel's routes match it.
    pub fn slug(&self) -> &str {
        &self.resource.slug
    }

    /// The heading and navigation label.
    pub fn title(&self) -> &str {
        &self.resource.title
    }

    /// The name of one record.
    pub fn singular(&self) -> &str {
        &self.resource.singular
    }

    /// The label of the navigation entry: the navigation label, or the title.
    pub fn navigation_label(&self) -> &str {
        self.resource
            .navigation_label
            .as_deref()
            .unwrap_or(&self.resource.title)
    }

    /// The navigation group the resource is listed under, if any.
    pub fn navigation_group(&self) -> Option<&str> {
        self.resource.navigation_group.as_deref()
    }

    /// The resource's place in the navigation, if set.
    pub fn navigation_sort(&self) -> Option<i32> {
        self.resource.navigation_sort
    }

    /// The navigation entry the resource is listed under, if any.
    pub fn navigation_parent_item(&self) -> Option<&str> {
        self.resource.navigation_parent_item.as_deref()
    }

    /// Every navigation entry the resource is listed under: its parent item, then its parent
    /// items, each once, without blank names.
    pub fn navigation_parent_items(&self) -> Vec<&str> {
        crate::navigation_parents(
            self.resource.navigation_parent_item.as_deref(),
            self.resource
                .navigation_parent_items
                .iter()
                .map(String::as_str),
        )
    }

    /// Whether the resource has a navigation entry.
    pub fn should_register_navigation(&self) -> bool {
        self.resource.should_register_navigation
    }

    /// The name of the navigation entry's icon, if set.
    pub fn navigation_icon(&self) -> Option<&str> {
        self.resource.navigation_icon.as_deref()
    }

    /// The label of the navigation entry's create link, or `None` when it lists none.
    pub fn navigation_create_item(&self) -> Option<&str> {
        self.resource.navigation_create_item.then(|| {
            self.resource
                .navigation_create_label
                .as_deref()
                .unwrap_or("Add new")
        })
    }

    /// The form fields, in display order.
    pub fn fields(&self) -> &[FieldDef] {
        &self.resource.fields
    }

    /// The list columns, in display order.
    pub fn columns(&self) -> &[ColumnDef] {
        &self.resource.columns
    }

    /// Turns the submitted form into a [`Row`] for a create, or returns one message per
    /// field. It runs the same checks as a static resource, with the same messages:
    /// required fields ([`Field::check_required`](crate::Field::check_required)), whole
    /// numbers, decimals, dates, date-times and select choices. The row holds one key per
    /// field:
    ///
    /// - text, textarea, select, lookup: a string. A required value is trimmed.
    /// - email, URL, radio, color, image, file, link, wysiwyg, post object, checkbox list,
    ///   relationship,
    ///   taxonomy, user, repeater, group, flexible content, gallery, clone: the text
    ///   [`Field::check_value`](crate::Field::check_value) returns. The structured kinds
    ///   hold JSON text.
    /// - number: an integer. Decimal: a number.
    /// - checkbox: `true` or `false`; a checkbox is never blank.
    /// - date: `"YYYY-MM-DD"`. Date-time: `"YYYY-MM-DD HH:MM:SS"`.
    /// - password: the hash of the password ([`hash_password`](crate::hash_password)).
    /// - a blank field that is not required: `null`.
    ///
    /// Each error in [`FieldErrors`] is keyed by the field's name, an owned `String`.
    ///
    /// A lookup, post object, relationship, taxonomy or user value is checked against
    /// [`RuntimeData::options`] by the panel, which can read the database, and so is a media
    /// id against the registered [`MediaLibrary`](crate::MediaLibrary).
    pub fn validate(&self, form: &FormInput) -> Result<Row, FieldErrors> {
        validate_fields(
            &self.resource.fields,
            form,
            true,
            &BTreeSet::new(),
            &self.resource.repeaters,
        )
    }

    /// Turns the submitted form into a [`Row`] for an update. It is
    /// [`validate`](Self::validate), except that:
    ///
    /// - a blank password is not an error: the row leaves its key out, so the stored
    ///   password is kept;
    /// - an optional field the form did not send at all ([`FormInput::has`] is false) is left
    ///   out of the row, so its stored value is kept;
    /// - an optional field sent blank is `null`, so clearing it on the edit form clears the
    ///   stored value, as `#[derive(IgniteResource)]` does since 0.3.0;
    /// - a checkbox the form did not send is `false`, because an unticked HTML checkbox sends
    ///   nothing.
    pub fn validate_update(&self, form: &FormInput) -> Result<Row, FieldErrors> {
        validate_fields(
            &self.resource.fields,
            form,
            false,
            &BTreeSet::new(),
            &self.resource.repeaters,
        )
    }

    /// The conditions that show or hide the form's fields.
    pub fn conditions(&self) -> &FieldConditions {
        &self.resource.conditions
    }

    /// The layout of the create and edit forms.
    pub fn form_layout(&self) -> &FormLayout {
        &self.resource.form_layout
    }

    /// The tabs of the list page, in display order.
    pub fn tabs(&self) -> &[Tab] {
        &self.resource.tabs
    }

    /// The key of the tab shown when the list has no `tab` parameter, if set.
    pub fn default_active_tab(&self) -> Option<&str> {
        self.resource.default_active_tab.as_deref()
    }

    /// The list columns shown as coloured badges.
    pub fn column_badges(&self) -> &ColumnBadges {
        &self.resource.column_badges
    }

    /// Whether each tab's count is for the current search.
    pub fn tab_counts_follow_search(&self) -> bool {
        self.resource.tab_counts_follow_search
    }

    /// Whether a tab whose count is 0 is left out.
    pub fn hide_empty_tabs(&self) -> bool {
        self.resource.hide_empty_tabs
    }

    /// The actions on each row of the list, in display order.
    pub fn row_actions(&self) -> &[RowAction] {
        &self.resource.row_actions
    }

    /// The actions on the ticked records, in display order.
    pub fn bulk_actions(&self) -> &[BulkAction] {
        &self.resource.bulk_actions
    }

    /// The records whose built-in Delete button is hidden, if set.
    pub fn hide_default_delete_when(&self) -> Option<&ListFilter> {
        self.resource.hide_default_delete_when.as_ref()
    }

    /// The settings of the form's repeaters and flexible content fields.
    pub fn repeaters(&self) -> &Repeaters {
        &self.resource.repeaters
    }

    /// The ability `action` on the resource needs: the one [`RuntimeResource::ability`]
    /// names, or `<slug>.<action>`, such as `books.update`.
    pub fn ability_for(&self, action: ResourceAction) -> String {
        self.resource
            .abilities
            .get(&action)
            .cloned()
            .unwrap_or_else(|| format!("{}.{}", self.resource.slug, action.as_str()))
    }

    /// The ability every action needs besides its own, if any
    /// ([`RuntimeResource::access_ability`]).
    pub fn access_ability(&self) -> Option<&str> {
        self.resource.access_ability.as_deref()
    }

    /// Every ability `action` needs: the access ability, if any, and the action's own.
    pub fn required_abilities(&self, action: ResourceAction) -> Vec<String> {
        self.access_ability()
            .map(str::to_string)
            .into_iter()
            .chain(std::iter::once(self.ability_for(action)))
            .collect()
    }

    /// Every ability the resource's actions need, without repeats, in action order: the
    /// permissions the panel registers for it.
    pub fn ability_names(&self) -> Vec<String> {
        let mut names: Vec<String> = Vec::new();
        for action in ResourceAction::ALL {
            for name in self.required_abilities(action) {
                if !names.contains(&name) {
                    names.push(name);
                }
            }
        }
        names
    }

    /// Where a successful create goes: the
    /// [`redirect_after_create`](RuntimeResource::redirect_after_create), or the list.
    pub fn redirect_after_create(&self) -> RedirectAfter {
        self.resource
            .redirect_after_create
            .unwrap_or(RedirectAfter::List)
    }

    /// Where a successful update goes: the
    /// [`redirect_after_update`](RuntimeResource::redirect_after_update), or the list.
    pub fn redirect_after_update(&self) -> RedirectAfter {
        self.resource
            .redirect_after_update
            .unwrap_or(RedirectAfter::List)
    }

    /// The row key that addresses a record in the panel's URLs: the
    /// [`record_route_key_name`](RuntimeResource::record_route_key_name), or `id`.
    pub fn record_route_key_name(&self) -> &str {
        self.resource
            .record_route_key_name
            .as_deref()
            .unwrap_or("id")
    }

    /// Whether the record of the edit form `form` is read-only for its user
    /// ([`RuntimeResource::read_only_when`]).
    pub fn is_read_only(&self, form: &FormContext<'_>) -> bool {
        self.resource
            .read_only
            .as_ref()
            .is_some_and(|rule| rule(form))
    }

    /// The line the form of a read-only record shows, if any.
    pub fn read_only_notice(&self, form: &FormContext<'_>) -> Option<String> {
        self.resource
            .read_only_notice
            .as_ref()
            .and_then(|notice| notice(form))
    }

    /// [`validate`](Self::validate) for a form whose fields `hidden` are hidden (see
    /// [`FieldConditions::hidden_fields`]): they are not checked, a required one included, and
    /// the row has no key for them, so the source writes nothing for them. The panel calls it.
    pub fn validate_shown(
        &self,
        form: &FormInput,
        hidden: &BTreeSet<String>,
    ) -> Result<Row, FieldErrors> {
        validate_fields(
            &self.resource.fields,
            form,
            true,
            hidden,
            &self.resource.repeaters,
        )
    }

    /// [`validate_update`](Self::validate_update) for a form whose fields `hidden` are hidden:
    /// the row has no key for them, so their stored values are kept, whatever the form sent.
    pub fn validate_update_shown(
        &self,
        form: &FormInput,
        hidden: &BTreeSet<String>,
    ) -> Result<Row, FieldErrors> {
        validate_fields(
            &self.resource.fields,
            form,
            false,
            hidden,
            &self.resource.repeaters,
        )
    }
}

/// The runtime resources of one app, in registration order, and the slugs reserved for static
/// resources and for the panel's own pages. It lives in the app's
/// [`Registries`](crate::Registries).
#[derive(Default)]
pub(crate) struct RuntimeRegistry {
    resources: Vec<Arc<RegisteredResource>>,
    reserved: HashSet<String>,
}

impl Registries {
    /// Runs `f` on the registry, read-only. The lock is never held across an `.await`: every
    /// caller is synchronous.
    fn read_runtime<T>(&self, f: impl FnOnce(&RuntimeRegistry) -> T) -> T {
        f(&self
            .inner
            .runtime
            .read()
            .unwrap_or_else(PoisonError::into_inner))
    }

    /// Runs `f` on the registry, to change it.
    fn write_runtime<T>(&self, f: impl FnOnce(&mut RuntimeRegistry) -> T) -> T {
        f(&mut self
            .inner
            .runtime
            .write()
            .unwrap_or_else(PoisonError::into_inner))
    }
}

/// The longest field name a runtime resource accepts, in bytes, as for a MySQL or MariaDB
/// column name. The limit is a validation rule: names are owned by their resource and freed
/// with it.
pub const MAX_FIELD_NAME: usize = 64;

/// Whether `name` is a field name a runtime resource accepts: lowercase ASCII letters, digits
/// and `_`, starting with a letter, at most [`MAX_FIELD_NAME`] bytes, as a column name is.
fn valid_field_name(name: &str) -> bool {
    name.len() <= MAX_FIELD_NAME
        && name.bytes().next().is_some_and(|b| b.is_ascii_lowercase())
        && name
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
}

/// Whether `slug` is one URL segment the panel's `/<slug>` routes match: lowercase ASCII
/// letters, digits, `-` and `_`, as Filament's kebab-case slugs are.
fn valid_slug(slug: &str) -> bool {
    !slug.is_empty()
        && slug
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
}

impl Registries {
    /// Adds a runtime resource to this app. It shows in the navigation and the dashboard, and
    /// its list, forms and delete action answer at `/<mount>/<slug>`, from the next request on.
    /// Create its permissions (`<slug>.viewAny` and the others) in the same request with
    /// `ignite_panel::register_runtime_permissions`; otherwise the panel creates them on the
    /// next signed-in request.
    ///
    /// Refuses a slug that is not valid, a slug that a static resource, another runtime resource
    /// of this app or one of the panel's own pages (such as `login`) uses, and two fields with
    /// one name. Another app's resources are not consulted: each app has its own registry.
    pub fn register_runtime(&self, resource: RuntimeResource) -> Result<(), RuntimeError> {
        check_definition(&resource)?;
        self.write_runtime(|registry| {
            let slug = resource.slug.as_str();
            if registry.reserved.contains(slug)
                || registry.resources.iter().any(|r| r.slug() == slug)
            {
                return Err(RuntimeError::SlugTaken(resource.slug.clone()));
            }
            registry
                .resources
                .push(Arc::new(RegisteredResource { resource }));
            Ok(())
        })
    }
}

/// Checks a definition's slug and field names.
fn check_definition(resource: &RuntimeResource) -> Result<(), RuntimeError> {
    if !valid_slug(&resource.slug) {
        return Err(RuntimeError::InvalidSlug(resource.slug.clone()));
    }
    if let Some(field) = resource.fields.iter().find(|f| !valid_field_name(&f.name)) {
        return Err(RuntimeError::InvalidFieldName {
            slug: resource.slug.clone(),
            field: field.name.clone(),
        });
    }
    let mut names = HashSet::new();
    if let Some(field) = resource.fields.iter().find(|f| !names.insert(&f.name)) {
        return Err(RuntimeError::DuplicateField {
            slug: resource.slug.clone(),
            field: field.name.clone(),
        });
    }
    Ok(())
}

impl Registries {
    /// Removes the runtime resource at `slug`. From the next request on, it is gone from the
    /// navigation and its routes answer 404. Its permission rows stay, so the grants come back
    /// if the resource is registered again.
    pub fn unregister_runtime(&self, slug: &str) -> Result<(), RuntimeError> {
        self.write_runtime(|registry| {
            let before = registry.resources.len();
            registry.resources.retain(|r| r.slug() != slug);
            if registry.resources.len() == before {
                Err(RuntimeError::NotRegistered(slug.to_string()))
            } else {
                Ok(())
            }
        })
    }

    /// The runtime resource at `slug`, if one is registered.
    pub fn runtime_resource(&self, slug: &str) -> Option<Arc<RegisteredResource>> {
        self.read_runtime(|registry| {
            registry
                .resources
                .iter()
                .find(|r| r.slug() == slug)
                .cloned()
        })
    }

    /// Every runtime resource, in registration order.
    pub fn runtime_resources(&self) -> Vec<Arc<RegisteredResource>> {
        self.read_runtime(|registry| registry.resources.clone())
    }

    /// Reserves `slugs`, so no runtime resource can take them. The panel reserves the slugs of
    /// its static resources and of its own pages when it is built. Reserving a slug twice is
    /// fine. Refuses, and reserves none, when a runtime resource already has one of them.
    pub fn reserve_slugs(&self, slugs: &[&str]) -> Result<(), RuntimeError> {
        self.write_runtime(|registry| {
            if let Some(slug) = slugs
                .iter()
                .find(|slug| registry.resources.iter().any(|r| r.slug() == **slug))
            {
                return Err(RuntimeError::SlugTaken(slug.to_string()));
            }
            registry
                .reserved
                .extend(slugs.iter().map(|slug| slug.to_string()));
            Ok(())
        })
    }
}

/// Registers `resource` on the default app, as 0.7.1 did. See
/// [`Registries::register_runtime`](crate::Registries::register_runtime).
pub fn register_runtime(resource: RuntimeResource) -> Result<(), RuntimeError> {
    crate::Registries::default_app().register_runtime(resource)
}

/// Removes the runtime resource at `slug` from the default app. See
/// [`Registries::unregister_runtime`](crate::Registries::unregister_runtime).
pub fn unregister_runtime(slug: &str) -> Result<(), RuntimeError> {
    crate::Registries::default_app().unregister_runtime(slug)
}

/// The runtime resource at `slug` on the default app. See
/// [`Registries::runtime_resource`](crate::Registries::runtime_resource).
pub fn runtime_resource(slug: &str) -> Option<Arc<RegisteredResource>> {
    crate::Registries::default_app().runtime_resource(slug)
}

/// The runtime resources of the default app. See
/// [`Registries::runtime_resources`](crate::Registries::runtime_resources).
pub fn runtime_resources() -> Vec<Arc<RegisteredResource>> {
    crate::Registries::default_app().runtime_resources()
}

/// Reserves `slugs` on the default app, as 0.7.1 did. See
/// [`Registries::reserve_slugs`](crate::Registries::reserve_slugs).
pub fn reserve_slugs(slugs: &[&str]) -> Result<(), RuntimeError> {
    crate::Registries::default_app().reserve_slugs(slugs)
}

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

    struct NoData;

    impl RuntimeData for NoData {
        fn list<'a>(&'a self, _: &'a Database, _: &'a ListQuery) -> RuntimeFuture<'a, Page<Row>> {
            unreachable!()
        }
        fn find<'a>(&'a self, _: &'a Database, _: i64) -> RuntimeFuture<'a, Option<Row>> {
            unreachable!()
        }
        fn create<'a>(&'a self, _: &'a Database, _: Row) -> RuntimeFuture<'a, Row> {
            unreachable!()
        }
        fn update<'a>(&'a self, _: &'a Database, _: i64, _: Row) -> RuntimeFuture<'a, Row> {
            unreachable!()
        }
        fn delete<'a>(&'a self, _: &'a Database, _: i64) -> RuntimeFuture<'a, u64> {
            unreachable!()
        }
    }

    /// A resource with the fields `growth_title` and `growth_status`, whose label and
    /// choices change with `n`.
    fn edited(slug: &str, n: usize) -> RuntimeResource {
        RuntimeResource::new(slug, format!("Title {n}"), format!("One {n}"), NoData)
            .field(FieldDef {
                name: "growth_title".into(),
                label: format!("Title {n}"),
                kind: FieldKindDef::Text,
                required: n.is_multiple_of(2),
            })
            .field(FieldDef {
                name: "growth_status".into(),
                label: format!("Status {n}"),
                kind: FieldKindDef::Select(vec![(format!("v{n}"), format!("Value {n}"))]),
                required: false,
            })
            .column(ColumnDef {
                key: "growth_title".into(),
                label: format!("Column {n}"),
                sortable: false,
                searchable: false,
            })
    }

    // Field names are owned by their resource: editing a definition a thousand times keeps
    // nothing of the old ones, and an error is keyed by the field's own name.
    #[test]
    fn editing_a_definition_a_thousand_times_keeps_owned_names() {
        let registries = Registries::new();
        registries
            .register_runtime(edited("growth", 0))
            .expect("register");
        for n in 1..=1000 {
            registries.unregister_runtime("growth").expect("unregister");
            registries
                .register_runtime(edited("growth", n))
                .expect("register again");
            let registered = registries.runtime_resource("growth").expect("registered");
            let mut values = std::collections::HashMap::new();
            values.insert("growth_status".to_string(), "not a choice".to_string());
            let errors = registered
                .validate(&FormInput::new(values.clone()))
                .unwrap_err();
            assert!(errors.contains_key("growth_status"));
            let _ = registered.validate_update(&FormInput::new(values));
        }
        // The last registration is the only one the registry holds.
        let registered = registries.runtime_resource("growth").expect("registered");
        assert_eq!(registered.title(), "Title 1000");
        assert_eq!(
            registries
                .runtime_resources()
                .iter()
                .filter(|r| r.slug() == "growth")
                .count(),
            1
        );
        registries.unregister_runtime("growth").expect("unregister");
    }

    // Each app has its own registry: the same slug registers in two apps, and one app's
    // reserved slugs and resources are not seen by the other.
    #[test]
    fn two_registries_do_not_share_resources_or_reserved_slugs() {
        let (a, b) = (Registries::new(), Registries::new());
        a.reserve_slugs(&["taken"]).unwrap();
        a.register_runtime(edited("shared", 1)).unwrap();
        b.register_runtime(edited("shared", 2)).unwrap();
        b.register_runtime(edited("taken", 3)).unwrap();
        assert_eq!(a.runtime_resource("shared").unwrap().title(), "Title 1");
        assert_eq!(b.runtime_resource("shared").unwrap().title(), "Title 2");
        assert!(a.runtime_resource("taken").is_none());
        assert!(a.register_runtime(edited("taken", 4)).is_err());
        let clone = a.clone();
        clone.unregister_runtime("shared").unwrap();
        assert!(
            a.runtime_resource("shared").is_none(),
            "a clone is the same app"
        );
        assert!(b.runtime_resource("shared").is_some());
    }
}