zeyn 0.0.8

Rust web framework for data heavy applications, written by AI agents and reviewed by people
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
use crate::action::{
    Action, ActionMeta, Aggregate, AggregateRequest, Cursor, DEFAULT_PAGE_SIZE, DataQuery, Filter,
    MAX_FILTER_CHOICES, MAX_FILTER_TEXT, MAX_FILTERS, MAX_PAGE_SIZE, Page, PageRequest, Result,
    Sort, Total,
};
use crate::ctx::Outcome;
use crate::ctx::{BoxFuture, Ctx};
use crate::i18n::Text;
use crate::model::{Field, FieldMeta, Model, Valid};
use crate::render::{Render, attr, escape, escape_into};
use crate::screen::Icon;
use crate::screen::RowCall;
use crate::screen::{Component, Effect, GridSource, LoadedPage, Node, ScreenDef};
use crate::time::{Date, DateTime, LocalDateTime, Time, TimeZone};
use crate::value::{
    ChoiceType, FieldKind, FieldType, IsBool, IsMoment, Money, SupportsMinMaxTotal, SupportsSum,
    Value,
};
use serde::Deserialize;
use serde::Serialize;
use serde_json::json;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};

mod column;
mod memory;

pub use column::DataGridColumn;

#[cfg(any(feature = "postgres", feature = "oracle"))]
pub(crate) use memory::{Cond, Key, TextOp};
pub use memory::{position_cursor, total};

/// Where sorting and filtering happen.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DataMode {
    /// Data comes to the client once; sorting and filtering run in the browser.
    #[default]
    Client,
    /// Every page, sort and filter is requested from the server. For large data.
    Server,
}

impl DataMode {
    fn code(self) -> &'static str {
        match self {
            DataMode::Client => "client",
            DataMode::Server => "server",
        }
    }
}

/// Rows of a virtual grid's first block rendered live in the page (enough for a tall screen
/// plus the overscan); the rest of the block waits in a `<template>` until it scrolls into view.
pub const VIRTUAL_LIVE_ROWS: usize = 64;

/// Fewest columns (with the selection, detail and row action columns) for which a virtual grid
/// sends its whole first block in the `<template>`, so the browser styles and lays out only the
/// columns the runtime keeps in view. Matches `COLV_MIN` of the browser runtime
/// (`assets/zeyn/grid-cells.js`), where column windowing starts.
pub const VIRTUAL_WIDE_COLUMNS: usize = 40;

/// How a grid loads rows beyond the first batch.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Paging {
    /// Numbered pages with a pager. The default.
    Pages { size: u32 },
    /// Loads the next batch when the user scrolls near the end, using a cursor so rows are not
    /// repeated or skipped while data changes. A "Load more" button stays for keyboard and screen
    /// reader users.
    Infinite { batch: u32 },
    /// All rows at once, still capped at [`MAX_PAGE_SIZE`] by the server. For short lists.
    None,
    /// One scrollable list over all rows, however many. Only the visible rows are in the page;
    /// blocks of `block` rows are fetched by offset as the user scrolls and kept in a cache.
    /// Rows have a fixed height so any position can be reached at once.
    Virtual { row_height: u32, block: u32 },
}

impl Default for Paging {
    fn default() -> Self {
        Paging::Pages {
            size: DEFAULT_PAGE_SIZE,
        }
    }
}

/// Keeps a size between 1 and [`MAX_PAGE_SIZE`].
const fn bounded(size: u32) -> u32 {
    if size == 0 {
        1
    } else if size > MAX_PAGE_SIZE {
        MAX_PAGE_SIZE
    } else {
        size
    }
}

impl Paging {
    /// Numbered pages of `size` rows.
    pub const fn pages(size: u32) -> Self {
        Paging::Pages {
            size: bounded(size),
        }
    }

    /// Infinite scroll loading `batch` rows at a time.
    pub const fn infinite(batch: u32) -> Self {
        Paging::Infinite {
            batch: bounded(batch),
        }
    }

    /// No paging.
    pub const fn none() -> Self {
        Paging::None
    }

    /// Virtual scrolling with 32 px rows, fetched in blocks of 200. For very large lists. The
    /// server sends the first block; rows after [`VIRTUAL_LIVE_ROWS`] go in an inert `<template>`
    /// so the browser styles and lays out only what fits on a screen. A grid with
    /// [`VIRTUAL_WIDE_COLUMNS`] columns or more puts every row there and the runtime inserts the
    /// rows once it has chosen the columns in view.
    pub const fn virtual_scroll() -> Self {
        Paging::Virtual {
            row_height: 32,
            block: 200,
        }
    }

    /// Virtual scrolling with a custom row height in pixels.
    pub const fn virtual_rows(row_height: u32) -> Self {
        Paging::Virtual {
            row_height: if row_height < 20 { 20 } else { row_height },
            block: 200,
        }
    }

    fn code(self) -> &'static str {
        match self {
            Paging::Pages { .. } => "pages",
            Paging::Infinite { .. } => "infinite",
            Paging::None => "none",
            Paging::Virtual { .. } => "virtual",
        }
    }

    fn size(self) -> u32 {
        match self {
            Paging::Pages { size } => size,
            Paging::Infinite { batch } => batch,
            Paging::None => MAX_PAGE_SIZE,
            Paging::Virtual { block, .. } => bounded(block),
        }
    }
}

/// Row highlight.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RowStyle {
    Warning,
    Danger,
    Success,
    Muted,
}

impl RowStyle {
    fn css(self) -> &'static str {
        match self {
            RowStyle::Warning => "z-row-warning",
            RowStyle::Danger => "z-row-danger",
            RowStyle::Success => "z-row-success",
            RowStyle::Muted => "z-row-muted",
        }
    }
}

/// Side a column is pinned to. `Start` is the left in left to right languages.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Pin {
    Start,
    End,
}

impl Pin {
    fn code(self) -> &'static str {
        match self {
            Pin::Start => "start",
            Pin::End => "end",
        }
    }
}

/// Most columns pinned to one side.
pub const MAX_PINNED: usize = 3;
/// Narrowest and widest column a user may set, in pixels.
pub const COLUMN_WIDTH: (u32, u32) = (48, 1200);

/// One shown column of a view: field, width set by the user and pin.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ColumnView {
    pub field: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub width: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pin: Option<Pin>,
}

/// How a user arranged a grid: shown columns in order with widths and pins, sort and filters.
/// Comes from the client, so the grid cleans it with its own columns before any use.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct DataGridView {
    /// Shown columns in order. Empty means the grid's own layout.
    #[serde(default)]
    pub columns: Vec<ColumnView>,
    #[serde(default)]
    pub sort: Vec<Sort>,
    #[serde(default)]
    pub filters: Vec<Filter>,
}

/// Where saved grid views live, one per user and grid. Register one with `App::datagrid_views`.
///
/// `grid` is a key built by the server from the tenant, the screen and the node; `user` is the
/// signed in user. Implementations store the view as JSON in a table or a key value store.
pub trait DataGridViewStore: Send + Sync + 'static {
    fn load(&self, user: &str, grid: &str) -> BoxFuture<Result<Option<DataGridView>>>;

    /// Saves a view, or deletes it when `view` is `None`.
    fn save(&self, user: &str, grid: &str, view: Option<DataGridView>) -> BoxFuture<Result<()>>;
}

/// Saved views in memory, lost on restart. For development, tests and samples.
#[derive(Clone, Default)]
pub struct MemoryViewStore(Arc<Mutex<HashMap<(String, String), DataGridView>>>);

impl DataGridViewStore for MemoryViewStore {
    fn load(&self, user: &str, grid: &str) -> BoxFuture<Result<Option<DataGridView>>> {
        let found = self
            .0
            .lock()
            .map(|m| {
                m.get(&(user.to_string(), grid.to_string()))
                    .cloned()
            })
            .map_err(poisoned);
        Box::pin(async move { found })
    }

    fn save(&self, user: &str, grid: &str, view: Option<DataGridView>) -> BoxFuture<Result<()>> {
        let key = (user.to_string(), grid.to_string());
        let done = self.0.lock().map(|mut m| match view {
            Some(v) => {
                m.insert(key, v);
            }
            None => {
                m.remove(&key);
            }
        });
        let done = done.map_err(poisoned);
        Box::pin(async move { done })
    }
}

fn poisoned<T>(_: T) -> crate::action::Error {
    crate::action::Error::Internal("view store lock is poisoned".into())
}

/// A column as shown in one render: which column, its width and its pin.
struct Shown {
    index: usize,
    width: Option<u32>,
    pin: Option<Pin>,
}

/// Color of a badge. Tones follow the theme, so they work in light and dark mode.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Tone {
    #[default]
    Neutral,
    Info,
    Success,
    Warning,
    Danger,
    Brand,
}

impl Tone {
    pub(crate) fn code(self) -> &'static str {
        match self {
            Tone::Neutral => "neutral",
            Tone::Info => "info",
            Tone::Success => "success",
            Tone::Warning => "warning",
            Tone::Danger => "danger",
            Tone::Brand => "brand",
        }
    }
}

/// Draws the content of a grid cell from the column's typed value. The extension point for
/// app specific cells; closures `Fn(&T, &Render) -> String` are renderers too.
///
/// The returned HTML goes into the cell as is: escape user data with [`crate::render::escape`]
/// or [`Render::value`]. Exports and copy use the plain value, not this HTML.
///
/// ```ignore
/// DataGrid::of(search_products).column(Product::code).cell(|code: &String, _r: &Render| {
///     format!("<code>{}</code>", zeyn::render::escape(code))
/// })
/// ```
pub trait CellRenderer<T>: Send + Sync + 'static {
    fn render(&self, value: &T, r: &Render) -> String;
}

impl<T, F> CellRenderer<T> for F
where
    F: Fn(&T, &Render) -> String + Send + Sync + 'static,
{
    fn render(&self, value: &T, r: &Render) -> String {
        self(value, r)
    }
}

type CellFn<E> = Box<dyn Fn(&E, &Render) -> String + Send + Sync>;
type RunFn<E> =
    Box<dyn Fn(&E) -> Box<dyn FnOnce(Ctx) -> BoxFuture<Result<()>> + Send> + Send + Sync>;

/// Most rows one bulk action may cover; larger selections are refused.
pub const MAX_BULK: usize = 10_000;

/// Actions that take the keys of selected rows: their input is `Vec<K>`, where `K` is the type of
/// the key field given to `bulk_action`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be a bulk action over `{K}` keys",
    label = "this action's input is not `Vec<{K}>`",
    note = "a bulk action takes the selected keys: declare its first argument as `Vec<{K}>`, the type of the key field you pass"
)]
pub trait BulkAction<K>: Action {}

impl<K, A: Action<Input = Vec<K>>> BulkAction<K> for A {}

type BulkFn = Box<
    dyn Fn(Vec<serde_json::Value>) -> Option<Box<dyn FnOnce(Ctx) -> BoxFuture<Result<()>> + Send>>
        + Send
        + Sync,
>;

/// A button in the selection bar that runs an action with the selected keys.
struct BulkDef {
    label: Text,
    meta: ActionMeta,
    run: BulkFn,
}

/// A button on every row that runs an action with input built from the row.
struct RowAction<E> {
    label: Text,
    icon: Option<Icon>,
    meta: ActionMeta,
    run: RunFn<E>,
}

/// Runs action `A` with `input` and turns a failed outcome into an error.
fn runner<A>(input: A::Input) -> Box<dyn FnOnce(Ctx) -> BoxFuture<Result<()>> + Send>
where
    A: Action,
    A::Output: Outcome,
{
    Box::new(move |ctx| {
        Box::pin(async move {
            let output = A::call(ctx, input).await?;
            output.failure().map_or(Ok(()), Err)
        })
    })
}

/// Key of a row as text: the value of the model's `#[key]` field.
/// Appends [`key_text`] escaped for an attribute, without a new string for numbers and text.
fn key_into(out: &mut String, value: &Value) {
    match value {
        Value::Int(n) => {
            use std::fmt::Write;
            let _ = write!(out, "{n}");
        }
        Value::Text(s) => escape_into(out, s),
        other => escape_into(out, &key_text(other)),
    }
}

fn key_text(value: &Value) -> String {
    match value {
        Value::Int(n) => n.to_string(),
        Value::Text(s) => s.clone(),
        Value::Choice(c) => c.to_string(),
        Value::Null => String::new(),
        other => serde_json::to_string(other).unwrap_or_default(),
    }
}

type ValueFn<E> = Box<dyn Fn(&E) -> Value + Send + Sync>;
type StyleFn<E> = Box<dyn Fn(&E) -> Option<RowStyle> + Send + Sync>;
type OpenFn<E> = Box<dyn Fn(&E) -> Effect + Send + Sync>;
pub(crate) type FetchFn<E> = fn(Ctx, DataQuery) -> BoxFuture<Result<Page<E>>>;

struct Column<E> {
    meta: &'static FieldMeta,
    value: ValueFn<E>,
    width: Option<u32>,
    flex: Option<u32>,
    filter: bool,
    sort: bool,
    aggregates: Vec<Aggregate>,
    pin: Option<Pin>,
    hidden: bool,
    cell: Option<CellFn<E>>,
    editable: bool,
}

/// Data grid. Its data source is an action that takes a `DataQuery` and returns `Page<E>`.
///
/// Example:
/// ```ignore
/// DataGrid::of(search_products).column(Product::code).width(120).filter()
/// ```
pub struct DataGrid<E: Model> {
    action: ActionMeta,
    fetch: FetchFn<E>,
    mode: DataMode,
    paging: Paging,
    columns: Vec<Column<E>>,
    row_style: Option<StyleFn<E>>,
    on_open: Option<OpenFn<E>>,
    row_actions: Vec<RowAction<E>>,
    selectable: bool,
    bulk: Vec<BulkDef>,
    row_menu: Option<MenuFn<E>>,
    save: Option<SaveDef<E>>,
    export: Option<(crate::action::Access, usize)>,
    detail: Option<DetailDef<E>>,
    scope: Vec<Filter>,
    default_sort: Vec<crate::action::Sort>,
    group_by: Vec<&'static FieldMeta>,
    tree: Option<&'static FieldMeta>,
}

/// Most levels a tree grid opens.
pub const MAX_TREE_DEPTH: usize = 32;

/// Where rows sit in a grouped or tree grid.
#[derive(Default)]
struct Branch<'a> {
    depth: usize,
    path: &'a [Option<String>],
    parents: &'a [String],
}

type ParamsFn<E> = Box<dyn Fn(&E) -> serde_json::Value + Send + Sync>;

/// The screen a row expands into and how its params are built from the row.
struct DetailDef<E> {
    screen: &'static str,
    access: crate::action::Access,
    params: ParamsFn<E>,
}

/// A value in the fixed machine form group paths and scopes use: numbers and money as `1234.56`,
/// dates and times in ISO form, choices by value. `None` for an empty value.
pub(crate) fn value_key(value: &Value) -> Option<String> {
    match value {
        Value::Null => None,
        Value::Money(m) => {
            let a = m.minor.unsigned_abs();
            Some(format!(
                "{}{}.{:02}",
                if m.minor < 0 { "-" } else { "" },
                a / 100,
                a % 100
            ))
        }
        other => Some(key_text(other)),
    }
}

/// Filter that keeps rows whose `meta` field equals `key` (from [`value_key`]), or is empty when
/// `key` is `None`.
pub(crate) fn key_filter(meta: &FieldMeta, key: Option<&str>) -> Filter {
    let Some(key) = key else {
        return Filter::blank(meta.name, true);
    };
    match meta.kind {
        FieldKind::Text | FieldKind::Custom { .. } => Filter {
            field: meta.name.to_string(),
            equals: Some(key.to_string()),
            ..Filter::default()
        },
        FieldKind::Choice(_) => Filter::any_of(meta.name, [key]),
        FieldKind::Bool => Filter::is(meta.name, key == "true"),
        _ => Filter::range(meta.name, Some(key), Some(key)),
    }
}

/// One column of a typed export: the label in the user's language and the width in pixels.
#[derive(Clone, Debug, PartialEq)]
pub struct ExportColumn {
    pub label: String,
    pub width: Option<u32>,
    /// Whether the column holds numbers or money, which printed exports align right.
    pub numeric: bool,
}

/// Most rows an export holds unless the grid sets another limit.
pub const DEFAULT_EXPORT_LIMIT: usize = 100_000;

/// Quotes one CSV cell (RFC 4180) and defuses spreadsheet formulas in text that is not a number:
/// at the start and after every character a spreadsheet may split cells on (`,`, `;`, tab), since
/// the list separator depends on the reader's locale.
fn csv_cell(value: &str) -> String {
    let numeric = |s: &str| {
        !s.is_empty()
            && s.chars()
                .all(|c| c.is_ascii_digit() || ".,- +".contains(c))
    };
    let formula = |s: &str| s.starts_with(['=', '+', '-', '@', '\t', '\r']) && !numeric(s);
    let mut v = String::with_capacity(value.len() + 2);
    let mut rest = value;
    loop {
        if formula(rest) {
            v.push('\'');
        }
        match rest.find([',', ';', '\t']) {
            Some(i) => {
                v.push_str(&rest[..=i]);
                rest = &rest[i + 1..];
            }
            None => {
                v.push_str(rest);
                break;
            }
        }
    }
    if v.contains([',', ';', '\t', '"', '\r', '\n']) {
        format!("\"{}\"", v.replace('"', "\"\""))
    } else {
        v
    }
}

/// The masked text of a masked field's value, as its grid cell shows it.
fn masked(meta: &FieldMeta, value: &Value) -> String {
    crate::audit::plain(value)
        .map(|v| crate::privacy::masked_text(meta, &v))
        .unwrap_or_default()
}

/// A value as the user reads it, escaped for HTML.
fn plain_html(value: &Value, kind: &FieldKind, r: &Render) -> String {
    escape(&plain(value, kind, r))
}

/// A value as plain text the user reads: money with the symbol, dates in the locale, choices by
/// label, yes and no in the user's language.
fn plain(value: &Value, kind: &FieldKind, r: &Render) -> String {
    match value {
        Value::Null => String::new(),
        Value::Bool(b) => r.i18n.text(
            r.locale,
            &Text::key(if *b { "zeyn.yes" } else { "zeyn.no" }),
        ),
        Value::Int(n) => n.to_string(),
        Value::Text(s) if matches!(kind, FieldKind::Choices(_)) => {
            crate::ui::choices_text(s, kind, r)
        }
        Value::Text(s) => s.clone(),
        Value::Money(m) => m.format(r.locale),
        Value::Date(d) => d.format(r.locale),
        Value::Time(t) => t.format(r.locale),
        Value::LocalDateTime(l) => l.format(r.locale),
        Value::DateTime(d) => d.format(r.tz, r.locale),
        Value::Decimal(x) => format!("{x:.2}"),
        Value::Number(d) => d.format(r.locale),
        Value::Choice(c) => match kind {
            FieldKind::Choice(options) => options
                .iter()
                .find(|o| o.value == *c)
                .map(|o| {
                    r.i18n
                        .text(r.locale, &Text::key_or(o.key, o.label))
                })
                .unwrap_or_else(|| c.to_string()),
            _ => c.to_string(),
        },
    }
}

type SaveRun<E> =
    Box<dyn Fn(Valid<E>) -> Box<dyn FnOnce(Ctx) -> BoxFuture<Result<()>> + Send> + Send + Sync>;

/// The action that saves inline edits.
struct SaveDef<E: Model> {
    meta: ActionMeta,
    run: SaveRun<E>,
}

type MenuFn<E> = Box<dyn Fn(&E) -> crate::menu::ContextMenu + Send + Sync>;

pub(crate) fn fetch_via<A, E>(ctx: Ctx, query: DataQuery) -> BoxFuture<Result<Page<E>>>
where
    A: Action<Input = DataQuery, Output = Result<Page<E>>>,
    E: Model,
{
    Box::pin(async move { A::call(ctx, query).await? })
}

impl<E: Model> DataGrid<E> {
    /// DataGrid that loads its rows from the given action.
    pub fn of<A>(_source: A) -> Self
    where
        A: Action<Input = DataQuery, Output = Result<Page<E>>>,
    {
        Self {
            action: A::META,
            fetch: fetch_via::<A, E>,
            mode: DataMode::default(),
            paging: Paging::default(),
            columns: Vec::new(),
            row_style: None,
            on_open: None,
            row_actions: Vec::new(),
            selectable: false,
            bulk: Vec::new(),
            row_menu: None,
            save: None,
            export: None,
            detail: None,
            scope: Vec::new(),
            default_sort: Vec::new(),
            group_by: Vec::new(),
            tree: None,
        }
    }

    /// Groups rows by `field` on the server; call again to group inside each group. The grid
    /// shows a header row per group with its value, row count and the column totals over the
    /// group, and loads a group's rows (or subgroups) when the user opens it, a page at a time.
    /// The top level pages over groups. The grid's action answers `DataQuery::group` with
    /// `Page::groups`; `DataQuery::apply` does it for in memory data. Virtual grids do not group.
    /// Masked fields never group a grid, because a group shows its value: such a call is ignored
    /// and logged.
    pub fn group_by<T: FieldType>(mut self, field: Field<E, T>) -> Self {
        let meta = field.meta();
        if meta.mask.is_some() {
            tracing::warn!(
                "grid of `{}` cannot group by the masked field `{}`; ignored",
                E::NAME,
                meta.name
            );
            return self;
        }
        if !self
            .group_by
            .iter()
            .any(|m| m.name == meta.name)
        {
            self.group_by.push(meta);
        }
        self
    }

    /// Shows rows as a tree by their parent key: rows whose `parent` is empty at the top, and the
    /// children of a row loaded when the user opens it, a page at a time, to any depth (at most
    /// [`MAX_TREE_DEPTH`]). The parent field must be optional; empty means a top row. Filters and
    /// sorting apply at every level, totals cover every matching row. Tree grids do not group
    /// and show no row details; virtual grids show no tree.
    pub fn tree<K: FieldType>(mut self, parent: Field<E, Option<K>>) -> Self
    where
        Option<K>: FieldType,
    {
        self.tree = Some(parent.meta());
        self
    }

    /// Whether rows are grouped or in a tree.
    fn nested(&self) -> bool {
        !matches!(self.paging, Paging::Virtual { .. })
            && (self.tree.is_some() || !self.group_by.is_empty())
    }

    /// Lets every row expand into a screen built from the row, loaded only when the user opens
    /// it: `.detail(|o: &Order| (order_lines, OrderParams { id: o.id }))`. Params of the wrong type
    /// do not compile. The detail can hold anything a screen holds, such as another grid with its
    /// own detail, to any depth. The expander shows only for users who may open the screen, and
    /// the server checks the screen's permission again when it loads, as for any screen. The
    /// params travel through the browser like a window's, so the detail screen checks that the
    /// user may see the record they name.
    ///
    /// Virtual grids (`Paging::Virtual`) keep every row at one fixed height and show no expander;
    /// use pages or infinite paging for grids with details.
    pub fn detail<S: ScreenDef>(
        mut self,
        detail: impl Fn(&E) -> (S, S::Params) + Send + Sync + 'static,
    ) -> Self {
        self.detail = Some(DetailDef {
            screen: S::META.name,
            access: S::META.access,
            params: Box::new(move |row| {
                serde_json::to_value(detail(row).1).unwrap_or(serde_json::Value::Null)
            }),
        });
        self
    }

    /// The order rows come in before the user sorts: `.sort_by(Order::id, true)` for newest
    /// first. The header shows it, and clicking that column only switches between ascending and
    /// descending; other columns go back to this order on their third click. Call it again to add
    /// further keys. The action still receives it in `DataQuery::sort`.
    pub fn sort_by<T: FieldType>(mut self, field: Field<E, T>, desc: bool) -> Self {
        self.default_sort
            .push(crate::action::Sort {
                field: field.meta().name.to_string(),
                desc,
            });
        self
    }

    /// Keeps only the rows whose `field` equals `value`, on every request, whatever the client
    /// sends: `.scope(OrderLine::order_id, params.id)` for the lines of one order. The filter goes
    /// first in `DataQuery::filters`, so a data layer that reads the filters keeps it. Text
    /// compares ignoring case.
    pub fn scope<T: FieldType>(mut self, field: Field<E, T>, value: T) -> Self {
        self.scope.push(key_filter(
            field.meta(),
            value_key(&value.to_value()).as_deref(),
        ));
        self
    }

    /// Whether rows show the detail expander for this page's user.
    fn expandable(&self, r: &Render) -> bool {
        !matches!(self.paging, Paging::Virtual { .. })
            && !(self.nested() && self.tree.is_some())
            && self
                .detail
                .as_ref()
                .is_some_and(|d| r.can(&d.access))
    }

    /// Cells before the first data column: the detail expander and the selection box.
    fn lead(&self, r: &Render) -> usize {
        usize::from(self.expandable(r)) + usize::from(self.selectable)
    }

    /// Puts the grid's scope filters in front of the client's.
    fn scoped(&self, query: &mut DataQuery) {
        if !self.scope.is_empty() {
            query
                .filters
                .splice(0..0, self.scope.iter().cloned());
        }
    }

    /// Lets users export every row that matches their filters as CSV, in their column layout and
    /// language. The server pages through the grid's action and streams the file, up to
    /// [`DEFAULT_EXPORT_LIMIT`] rows. Exporting needs the grid's read access. The toolbar's
    /// `Export::Csv` button uses this export when the grid has it.
    pub fn exportable(mut self) -> Self {
        self.export = Some((self.action.access, DEFAULT_EXPORT_LIMIT));
        self
    }

    /// Like `exportable`, but exporting also needs `permission`.
    pub fn export_permission(mut self, permission: &'static str) -> Self {
        let limit = self
            .export
            .map_or(DEFAULT_EXPORT_LIMIT, |e| e.1);
        self.export = Some((crate::action::Access::Permission(permission), limit));
        self
    }

    /// Most rows one export may hold; bigger results are cut there. At most 1,000,000.
    pub fn export_limit(mut self, rows: usize) -> Self {
        let access = self
            .export
            .map_or(self.action.access, |e| e.0);
        self.export = Some((access, rows.clamp(1, 1_000_000)));
        self
    }

    /// Lets users edit cells of the columns marked `editable()` in place, saved with `save`, an
    /// action that takes `Valid<E>` like a form's. The server loads the row again by key, applies
    /// only the editable columns and the row version (`#[version]`) the client sends, validates
    /// and runs the action; a changed row comes back as a conflict. F2 or a double click on an
    /// editable cell starts editing, Enter saves, Escape cancels, Ctrl+Z undoes the last save.
    pub fn edit_with<A>(mut self, _save: A) -> Self
    where
        A: crate::form::FormAction<E> + Action<Input = Valid<E>>,
        A::Output: Outcome,
    {
        self.save = Some(SaveDef {
            meta: A::META,
            run: Box::new(|valid| runner::<A>(valid)),
        });
        self
    }

    /// Indexes in `E::fields()` of the columns users may edit: marked `editable()`, not keys, read
    /// only fields or row versions.
    fn editable_fields(&self) -> Vec<usize> {
        self.columns
            .iter()
            .filter(|c| c.editable && !c.meta.key && !c.meta.readonly && !c.meta.version)
            .filter_map(|c| {
                E::fields()
                    .iter()
                    .position(|f| f.name == c.meta.name)
            })
            .collect()
    }

    /// Whether the page's user may save inline edits.
    fn can_edit(&self, r: &Render) -> bool {
        self.save
            .as_ref()
            .is_some_and(|s| r.can(&s.meta.access))
    }

    /// Context menu of each row, built on the server from the row. Right click, Shift+F10 or the
    /// context menu key opens it. See [`crate::ContextMenu`].
    pub fn row_menu(
        mut self,
        menu: impl Fn(&E) -> crate::menu::ContextMenu + Send + Sync + 'static,
    ) -> Self {
        self.row_menu = Some(Box::new(menu));
        self
    }

    /// DataGrid with a column for every field of the model except the row version, in declaration
    /// order, and filter boxes on text and choice columns. The quickest list for a simple model.
    pub fn auto<A>(source: A) -> Self
    where
        A: Action<Input = DataQuery, Output = Result<Page<E>>>,
    {
        let mut grid = Self::of(source);
        for (i, meta) in E::fields()
            .iter()
            .enumerate()
            .filter(|(_, m)| !m.version)
        {
            let filter = matches!(
                meta.kind,
                crate::value::FieldKind::Text | crate::value::FieldKind::Choice(_)
            );
            grid.columns.push(Column {
                meta,
                value: Box::new(move |e: &E| e.value_at(i).unwrap_or(Value::Null)),
                width: None,
                flex: None,
                filter,
                sort: true,
                aggregates: Vec::new(),
                pin: None,
                hidden: false,
                cell: None,
                editable: false,
            });
        }
        grid
    }

    pub fn mode(mut self, mode: DataMode) -> Self {
        self.mode = mode;
        self
    }

    /// Paging style. Numbered pages of 50 rows unless set.
    pub fn paging(mut self, paging: Paging) -> Self {
        self.paging = paging;
        self
    }

    /// Adds a column. The following settings (`width`, `filter`...) apply to it.
    pub fn column<T: FieldType + 'static>(mut self, field: Field<E, T>) -> DataGridColumn<E, T> {
        self.columns.push(Column {
            meta: field.meta(),
            value: Box::new(move |e| field.get(e).to_value()),
            width: None,
            flex: None,
            filter: false,
            sort: true,
            aggregates: Vec::new(),
            pin: None,
            hidden: false,
            cell: None,
            editable: false,
        });
        DataGridColumn {
            grid: self,
            field,
            _type: PhantomData,
        }
    }

    /// Picks a highlight per row.
    pub fn row_style(
        mut self,
        style: impl Fn(&E) -> Option<RowStyle> + Send + Sync + 'static,
    ) -> Self {
        self.row_style = Some(Box::new(style));
        self
    }

    /// What happens when a row is opened (double click or Enter).
    pub fn on_open(mut self, open: impl Fn(&E) -> Effect + Send + Sync + 'static) -> Self {
        self.on_open = Some(Box::new(open));
        self
    }

    /// Adds a button to every row that runs `action` with input built from the row:
    /// `.row_action(t!("stock.archive"), archive_product, |p| p.id)`. The button only shows for
    /// users with the action's permission. When pressed, the server loads the row again by its key
    /// through the grid's action, builds the input from it, checks the permission again and runs
    /// the action; the client never sends the input.
    pub fn row_action<A>(
        mut self,
        label: impl Into<Text>,
        _action: A,
        input: impl Fn(&E) -> A::Input + Send + Sync + 'static,
    ) -> Self
    where
        A: Action,
        A::Output: Outcome,
    {
        self.row_actions.push(RowAction {
            label: label.into(),
            icon: None,
            meta: A::META,
            run: Box::new(move |row| runner::<A>(input(row))),
        });
        self
    }

    /// Adds a checkbox to every row and a selection bar above the grid. Shift selects a range,
    /// the header box selects the page, and the bar offers every row that matches the filters.
    pub fn selectable(mut self) -> Self {
        self.selectable = true;
        self
    }

    /// Adds a button to the selection bar that runs `action` with the keys of the selected rows:
    /// `.bulk_action(t!("stock.archive"), archive_products, Product::id)` where `archive_products`
    /// takes `Vec<ProductId>`. Makes the grid selectable. The button shows only for users with the
    /// action's permission, which the server checks again. When the user picks every matching
    /// row, the server collects the keys itself (at most [`MAX_BULK`]). Keys picked one by one come
    /// from the client, so the action must check that the user may change each record, as an API
    /// action would.
    pub fn bulk_action<A, K>(
        mut self,
        label: impl Into<Text>,
        _action: A,
        _key: Field<E, K>,
    ) -> Self
    where
        A: BulkAction<K> + Action<Input = Vec<K>>,
        A::Output: Outcome,
        K: serde::de::DeserializeOwned + Send + 'static,
    {
        self.selectable = true;
        self.bulk.push(BulkDef {
            label: label.into(),
            meta: A::META,
            run: Box::new(|keys| {
                let keys: Vec<K> = keys
                    .into_iter()
                    .map(serde_json::from_value)
                    .collect::<std::result::Result<_, _>>()
                    .ok()?;
                Some(runner::<A>(keys))
            }),
        });
        self
    }

    /// Icon of the last added row action.
    pub fn icon(mut self, icon: Icon) -> Self {
        if let Some(a) = self.row_actions.last_mut() {
            a.icon = Some(icon);
        }
        self
    }

    /// Index of the `#[key]` field, if the model has one.
    fn key_index() -> Option<usize> {
        E::fields().iter().position(|f| f.key)
    }

    /// Effect produced when the row is opened.
    pub fn open_effect(&self, row: &E) -> Option<Effect> {
        self.on_open.as_ref().map(|f| f(row))
    }

    /// Renders rows as HTML in English. For tests and tools; the server uses the user's language.
    pub fn rows_html(&self, rows: &[E]) -> String {
        self.rows(
            rows,
            &Render::english("grid"),
            &self.layout(None),
            &Branch::default(),
        )
    }

    /// Shown columns for a view: the view's columns that exist, in its order, with starts pinned
    /// first and ends last; or the grid's own columns without the hidden ones.
    fn layout(&self, view: Option<&DataGridView>) -> Vec<Shown> {
        let mut shown: Vec<Shown> = match view.filter(|v| !v.columns.is_empty()) {
            Some(v) => {
                let mut out: Vec<Shown> = Vec::new();
                for cv in v
                    .columns
                    .iter()
                    .take(self.columns.len())
                {
                    let Some(index) = self
                        .columns
                        .iter()
                        .position(|c| c.meta.name == cv.field)
                    else {
                        continue;
                    };
                    if out.iter().any(|s| s.index == index) {
                        continue;
                    }
                    let width = cv
                        .width
                        .map(|w| w.clamp(COLUMN_WIDTH.0, COLUMN_WIDTH.1))
                        .or(self.columns[index].width);
                    out.push(Shown {
                        index,
                        width,
                        pin: cv.pin,
                    });
                }
                out
            }
            None => self
                .columns
                .iter()
                .enumerate()
                .filter(|(_, c)| !c.hidden)
                .map(|(index, c)| Shown {
                    index,
                    width: c.width,
                    pin: c.pin,
                })
                .collect(),
        };
        for side in [Pin::Start, Pin::End] {
            let mut n = 0;
            for s in shown
                .iter_mut()
                .filter(|s| s.pin == Some(side))
            {
                n += 1;
                if n > MAX_PINNED {
                    s.pin = None;
                }
            }
        }
        let rank = |s: &Shown| match s.pin {
            Some(Pin::Start) => 0,
            None => 1,
            Some(Pin::End) => 2,
        };
        shown.sort_by_key(rank);
        shown
    }

    /// Cleans a view from the client: unknown fields, repeats and out of range widths go, sort and
    /// filters keep only what the grid allows and the limits.
    fn clean(&self, view: DataGridView) -> DataGridView {
        let columns = self
            .layout(Some(&view))
            .into_iter()
            .map(|s| ColumnView {
                field: self.columns[s.index]
                    .meta
                    .name
                    .to_string(),
                width: s.width,
                pin: s.pin,
            })
            .collect();
        let mut query = DataQuery {
            sort: view.sort,
            filters: view.filters,
            ..DataQuery::default()
        };
        self.allow(&mut query, None);
        query.filters.retain(|f| {
            let short = |s: &Option<String>| {
                s.as_deref()
                    .is_none_or(|t| t.chars().count() <= MAX_FILTER_TEXT)
            };
            f.contains.chars().count() <= MAX_FILTER_TEXT
                && short(&f.starts_with)
                && short(&f.equals)
                && short(&f.from)
                && short(&f.to)
                && f.any_of.len() <= MAX_FILTER_CHOICES
                && f.any_of
                    .iter()
                    .all(|v| v.chars().count() <= MAX_FILTER_TEXT)
        });
        DataGridView {
            columns,
            sort: query.sort,
            filters: query.filters,
        }
    }

    /// Keeps the totals, filters and sort keys this grid offers, within the limits. With a ctx,
    /// filters and sorts on masked fields the user may not reveal go too, so every read of the
    /// grid (pages, exports, bulk runs, saved views, agents) is cleaned the same way.
    fn allow(&self, query: &mut DataQuery, ctx: Option<&Ctx>) {
        if let Some(ctx) = ctx {
            crate::privacy::strip_masked(query, E::fields(), ctx);
        }
        let allowed = self.aggregate_requests();
        query
            .aggregates
            .retain(|a| allowed.contains(a));
        query.aggregates.dedup();
        let sortable = |name: &str| {
            self.columns
                .iter()
                .any(|c| c.sort && c.meta.name == name)
        };
        let filterable = |name: &str| {
            self.columns
                .iter()
                .any(|c| c.filter && c.meta.name == name)
        };
        query
            .filters
            .retain(|f| filterable(&f.field) && !f.is_empty());
        query.filters.truncate(MAX_FILTERS);
        let mut seen = Vec::new();
        query.sort.retain(|s| {
            sortable(&s.field) && !seen.contains(&s.field) && {
                seen.push(s.field.clone());
                true
            }
        });
        query.sort.truncate(MAX_SORT);
    }

    /// Header row for the shown columns.
    fn head_row(&self, r: &Render, cols: &[Shown]) -> String {
        let mut out = String::from("<tr>");
        if self.expandable(r) {
            out.push_str(&format!(
                r#"<th scope="col" class="z-expand-col" data-pin="start"><span class="z-sr-only">{}</span></th>"#,
                r.text(&Text::key("zeyn.grid.details"))
            ));
        }
        if self.selectable {
            out.push_str(&format!(
                r#"<th scope="col" class="z-select-col" data-pin="start"><input type="checkbox" data-zeyn-select-all aria-label="{}"></th>"#,
                r.text(&Text::key("zeyn.grid.select_page"))
            ));
        }
        for (pos, s) in cols.iter().enumerate() {
            let c = &self.columns[s.index];
            let mut style = String::new();
            if let Some(w) = s.width {
                style.push_str(&format!("width:{w}px;"));
            }
            if let Some(f) = c.flex.filter(|_| s.width.is_none()) {
                style.push_str(&format!("--z-flex:{f};"));
            }
            let num = matches!(
                c.meta.kind,
                FieldKind::Integer | FieldKind::Money | FieldKind::Decimal
            );
            let class = if num { r#" class="z-num""# } else { "" };
            let sort = if c.sort {
                r#" aria-sort="none""#
            } else {
                r#" data-sort="off""#
            };
            out.push_str(&format!(
                r#"<th scope="col"{class} data-field="{}"{sort} aria-colindex="{}""#,
                c.meta.name,
                pos + 1 + self.lead(r)
            ));
            if !style.is_empty() {
                out.push_str(&format!(r#" style="{style}""#));
            }
            if let Some(p) = s.pin {
                out.push_str(&format!(r#" data-pin="{}""#, p.code()));
            }
            if self.can_edit(r) && c.editable && !c.meta.readonly && !c.meta.key && !c.meta.version
            {
                out.push_str(&format!(r#" data-edit="{}""#, filter_kind(&c.meta.kind)));
                if c.meta.optional {
                    out.push_str(r#" data-optional="true""#);
                }
                if let (FieldKind::Choice(options), false) = (c.meta.kind, c.filter) {
                    let list: Vec<serde_json::Value> = options
                        .iter()
                        .map(|o| json!({ "value": o.value, "label": r.i18n.text(r.locale, &Text::key_or(o.key, o.label)) }))
                        .collect();
                    out.push_str(&format!(r#" data-options="{}""#, attr(&list)));
                }
            }
            if c.filter {
                out.push_str(&format!(r#" data-filter="{}""#, filter_kind(&c.meta.kind)));
                if let FieldKind::Choice(options) = c.meta.kind {
                    let list: Vec<serde_json::Value> = options
                        .iter()
                        .map(|o| json!({ "value": o.value, "label": r.i18n.text(r.locale, &Text::key_or(o.key, o.label)) }))
                        .collect();
                    out.push_str(&format!(r#" data-options="{}""#, attr(&list)));
                }
            }
            out.push_str(&format!(">{}</th>", r.label(c.meta)));
        }
        if !self.row_actions.is_empty() {
            out.push_str(&format!(
                r#"<th scope="col" class="z-actions-col" data-pin="end" aria-colindex="{}"><span class="z-sr-only">{}</span></th>"#,
                cols.len() + 1 + self.lead(r),
                r.text(&Text::key("zeyn.grid.actions"))
            ));
        }
        out.push_str("</tr>");
        out
    }

    /// The `<tr>` of each row. Work that is the same for every row (access checks, labels, the
    /// row action cell, which columns are editable) is done once, and cells are written straight
    /// into the output without a string per cell.
    fn rows(&self, rows: &[E], r: &Render, cols: &[Shown], b: &Branch) -> String {
        use std::fmt::Write;
        let mut out = String::with_capacity(rows.len() * (cols.len() + 1) * 32);
        let nested = self.nested();
        let tree = nested && self.tree.is_some();
        let edit = self.can_edit(r);
        let key_at = Self::key_index();
        let version_at = edit
            .then(|| {
                E::fields()
                    .iter()
                    .position(|f| f.version)
            })
            .flatten();
        let detail = self
            .detail
            .as_ref()
            .filter(|_| self.expandable(r));
        let expand_cell = detail.map(|_| {
            format!(
                r#"<td class="z-expand"><button type="button" class="z-expander" data-zeyn-expand aria-expanded="false" aria-label="{}" tabindex="-1"></button></td>"#,
                r.text(&Text::key("zeyn.grid.details"))
            )
        });
        let select_cell = self.selectable.then(|| {
            format!(
                r#"<td class="z-row-select"><input type="checkbox" data-zeyn-select tabindex="-1" aria-label="{}"></td>"#,
                r.text(&Text::key("zeyn.grid.select_row"))
            )
        });
        let tree_toggle = tree.then(|| {
            format!(
                r#"<button type="button" class="z-expander" data-zeyn-expand aria-expanded="false" aria-label="{}" tabindex="-1"></button>"#,
                r.text(&Text::key("zeyn.grid.children"))
            )
        });
        let actions_cell = (!self.row_actions.is_empty()).then(|| {
            let mut cell = String::from(r#"<td class="z-row-actions">"#);
            for (i, a) in self.row_actions.iter().enumerate().filter(|(_, a)| r.can(&a.meta.access)) {
                let label = r.text(&a.label);
                let icon = a.icon.map(Icon::html).unwrap_or_default();
                let _ = write!(
                    cell,
                    r#"<button type="button" class="z-row-action" data-zeyn-run="a{i}" tabindex="-1">{icon}<span>{label}</span></button>"#
                );
            }
            cell.push_str("</td>");
            cell
        });
        let editable: Vec<bool> = cols
            .iter()
            .map(|s| {
                let c = &self.columns[s.index];
                edit && c.editable
                    && !c.meta.readonly
                    && !c.meta.key
                    && !c.meta.version
                    && c.meta.mask.is_none()
            })
            .collect();
        for row in rows {
            if let (true, Some(ctx)) = (E::SENSITIVE, r.ctx) {
                ctx.record_read(row);
            }
            out.push_str("<tr");
            let mut toggle = "";
            if nested {
                let _ = write!(
                    out,
                    r#" aria-level="{}" data-zeyn-level="{}""#,
                    b.depth + 1,
                    b.depth
                );
            }
            if tree {
                let key = key_at
                    .and_then(|i| row.value_at(i))
                    .and_then(|v| value_key(&v));
                toggle = match key.filter(|k| b.parents.contains(k) && b.depth + 1 < MAX_TREE_DEPTH)
                {
                    Some(k) => {
                        let mut path = b.path.to_vec();
                        path.push(Some(k));
                        let _ = write!(
                            out,
                            r#" aria-expanded="false" data-zeyn-path="{}""#,
                            attr(&path)
                        );
                        tree_toggle
                            .as_deref()
                            .unwrap_or_default()
                    }
                    None => r#"<span class="z-tree-spacer" aria-hidden="true"></span>"#,
                };
            }
            if let Some(style) = self
                .row_style
                .as_ref()
                .and_then(|f| f(row))
            {
                let _ = write!(out, r#" class="{}""#, style.css());
            }
            if let Some(effect) = self.open_effect(row) {
                let _ = write!(
                    out,
                    r#" tabindex="-1" data-zeyn-effect="{}""#,
                    attr(&effect)
                );
            }
            if let Some(k) = key_at.and_then(|i| row.value_at(i)) {
                out.push_str(r#" data-zeyn-key=""#);
                key_into(&mut out, &k);
                out.push('"');
            }
            if let Some(v) = version_at.and_then(|i| row.value_at(i)) {
                out.push_str(r#" data-zeyn-version=""#);
                key_into(&mut out, &v);
                out.push('"');
            }
            if let Some(menu) = self.row_menu.as_ref().map(|f| f(row)) {
                let items = menu.to_json(r);
                if items
                    .as_array()
                    .is_some_and(|a| !a.is_empty())
                {
                    let _ = write!(out, r#" data-zeyn-menu="{}""#, attr(&items));
                }
            }
            if let Some(d) = detail {
                let target = json!({ "screen": d.screen, "params": (d.params)(row) });
                let _ = write!(
                    out,
                    r#" aria-expanded="false" data-zeyn-detail="{}""#,
                    attr(&target)
                );
            }
            out.push('>');
            out.push_str(
                expand_cell
                    .as_deref()
                    .unwrap_or_default(),
            );
            out.push_str(
                select_cell
                    .as_deref()
                    .unwrap_or_default(),
            );
            for (n, s) in cols.iter().enumerate() {
                let c = &self.columns[s.index];
                let value = (c.value)(row);
                let num = matches!(value, Value::Int(_) | Value::Money(_));
                let first = tree && n == 0;
                out.push_str(match (num, first) {
                    (true, true) => r#"<td class="z-num z-tree-cell""#,
                    (true, false) => r#"<td class="z-num""#,
                    (false, true) => r#"<td class="z-tree-cell""#,
                    (false, false) => "<td",
                });
                if editable[n] {
                    out.push_str(r#" data-v=""#);
                    escape_into(&mut out, &crate::form::edit_value(&value, r.locale, r.tz));
                    out.push('"');
                }
                out.push('>');
                if first {
                    let _ = write!(
                        out,
                        r#"<span class="z-tree" style="--z-level:{}">{toggle}<span>"#,
                        b.depth
                    );
                }
                match (c.meta.mask, &c.cell) {
                    (Some(_), _) => out.push_str(&crate::privacy::cell(r, c.meta, &value, row)),
                    (None, Some(cell)) => out.push_str(&cell(row, r)),
                    (None, None) => r.value_into(&mut out, &value, &c.meta.kind),
                }
                if first {
                    out.push_str("</span></span>");
                }
                out.push_str("</td>");
            }
            out.push_str(
                actions_cell
                    .as_deref()
                    .unwrap_or_default(),
            );
            out.push_str("</tr>");
        }
        out
    }

    fn render_with(&self, out: &mut String, r: &Render, page: Option<&LoadedPage>) {
        let scope = r.scope;
        let view = page.and_then(|p| p.view.as_ref());
        let cols = self.layout(view);
        if self.selectable {
            let t = |k: &str| r.text(&Text::key(format!("zeyn.grid.{k}")));
            out.push_str(&format!(
                r#"<div class="z-bulk" data-zeyn-bulk data-testid="{scope}.grid.selection" data-text-selected="{}" data-text-all="{}" data-text-all-selected="{}" hidden><span class="z-bulk-count" aria-live="polite"></span><button type="button" class="z-link" data-zeyn-select-matching hidden></button>"#,
                t("selected_count"),
                t("select_matching"),
                t("all_selected"),
            ));
            for (i, b) in self
                .bulk
                .iter()
                .enumerate()
                .filter(|(_, b)| r.can(&b.meta.access))
            {
                out.push_str(&format!(
                    r#"<button type="button" class="z-button" data-zeyn-bulk-run="{i}" data-testid="{scope}.grid.bulk-{i}">{}</button>"#,
                    r.text(&b.label)
                ));
            }
            out.push_str(&format!(
                r#"<button type="button" class="z-button" data-zeyn-select-clear>{}</button></div>"#,
                t("clear_selection")
            ));
        }
        let grid_text = |key: &str| r.text(&Text::key(format!("zeyn.grid.{key}")));
        out.push_str(&format!(
            r#"<div class="z-grid" data-zeyn-grid data-testid="{scope}.grid" data-zeyn-action="{}" data-zeyn-mode="{}" data-zeyn-paging="{}" data-zeyn-page-size="{}" data-zeyn-openable="{}" data-zeyn-text-range="{}" data-zeyn-text-range-total="{}" data-zeyn-text-loaded="{}""#,
            self.action.name,
            self.mode.code(),
            self.paging.code(),
            self.paging.size(),
            self.on_open.is_some(),
            grid_text("range"),
            grid_text("range_total"),
            grid_text("loaded"),
        ));
        if let Paging::Virtual { row_height, .. } = self.paging {
            out.push_str(&format!(
                r#" data-zeyn-row-height="{row_height}" style="--z-row-height:{row_height}px""#
            ));
        }
        if let Some(p) = page {
            out.push_str(&format!(
                r#" data-zeyn-offset="{}" data-zeyn-count="{}""#,
                p.offset, p.count
            ));
            if let Some(t) = p.total {
                out.push_str(&format!(r#" data-zeyn-total="{t}""#));
            }
            if let Some(n) = &p.next {
                out.push_str(&format!(r#" data-zeyn-next="{}""#, escape(&n.0)));
            }
        }
        out.push_str(&format!(r#" data-zeyn-texts="{}""#, attr(&grid_texts(r))));
        let all: Vec<serde_json::Value> = self
            .columns
            .iter()
            .map(|c| json!({ "field": c.meta.name, "label": r.i18n.text(r.locale, &c.meta.label_text()), "hidden": c.hidden, "pin": c.pin, "width": c.width }))
            .collect();
        out.push_str(&format!(r#" data-zeyn-columns="{}""#, attr(&all)));
        if let Some(v) = view {
            out.push_str(&format!(r#" data-zeyn-view="{}""#, attr(v)));
        }
        if !self.default_sort.is_empty() {
            out.push_str(&format!(
                r#" data-zeyn-sort-default="{}""#,
                attr(&self.default_sort)
            ));
        }
        if page.is_some_and(|p| p.saved_views) {
            out.push_str(r#" data-zeyn-views="server""#);
        }
        if self.export.is_some_and(|e| r.can(&e.0)) {
            out.push_str(match (cfg!(feature = "xlsx"), cfg!(feature = "pdf")) {
                (true, true) => r#" data-zeyn-exportable="csv xlsx pdf""#,
                (true, false) => r#" data-zeyn-exportable="csv xlsx""#,
                (false, true) => r#" data-zeyn-exportable="csv pdf""#,
                (false, false) => r#" data-zeyn-exportable="csv""#,
            });
        }
        if self.can_edit(r)
            && let Some(v) = E::fields().iter().find(|f| f.version)
        {
            out.push_str(&format!(r#" data-zeyn-version-field="{}""#, v.name));
        }
        out.push_str(&format!(
            r#"><table role="{}" aria-colcount="{}"><thead>{}</thead><tbody data-zeyn-rows>"#,
            if self.nested() { "treegrid" } else { "grid" },
            self.columns.len() + usize::from(!self.row_actions.is_empty()) + self.lead(r),
            self.head_row(r, &cols)
        ));
        let mut later = String::new();
        let shown = self.lead(r) + cols.len() + usize::from(!self.row_actions.is_empty());
        let live_rows = if shown >= VIRTUAL_WIDE_COLUMNS {
            0
        } else {
            VIRTUAL_LIVE_ROWS
        };
        if let Some(p) = page {
            match (self.paging, p.items.downcast_ref::<Vec<E>>()) {
                (Paging::Virtual { .. }, Some(rows))
                    if p.groups.is_none() && rows.len() > live_rows =>
                {
                    let branch = Branch {
                        depth: p.depth,
                        path: &p.path,
                        parents: &p.parents,
                    };
                    out.push_str(&self.rows(&rows[..live_rows], r, &cols, &branch));
                    later = self.rows(&rows[live_rows..], r, &cols, &branch);
                }
                _ => out.push_str(&self.rows_html_erased(p, r)),
            }
        }
        out.push_str("</tbody>");
        if self
            .columns
            .iter()
            .any(|c| !c.aggregates.is_empty())
        {
            out.push_str("<tfoot data-zeyn-foot>");
            out.push_str(
                &self.foot_row(
                    r,
                    page.map(|p| p.totals.as_slice())
                        .unwrap_or_default(),
                    &cols,
                ),
            );
            out.push_str("</tfoot>");
        }
        out.push_str("</table>");
        if !later.is_empty() {
            out.push_str("<template data-zeyn-rows-later>");
            out.push_str(&later);
            out.push_str("</template>");
        }
        match self.paging {
            Paging::Pages { .. } => out.push_str(&format!(
                r#"<nav class="z-pager" aria-label="{}" data-testid="{scope}.pager"><button type="button" class="z-button" data-zeyn-page="prev" data-testid="{scope}.pager.prev" aria-label="{}" disabled>&lsaquo;</button><span class="z-page-info" aria-live="polite" data-zeyn-page-info></span><button type="button" class="z-button" data-zeyn-page="next" data-testid="{scope}.pager.next" aria-label="{}">&rsaquo;</button></nav>"#,
                grid_text("pagination"),
                grid_text("previous"),
                grid_text("next"),
            )),
            Paging::Infinite { .. } => out.push_str(&format!(
                r#"<div class="z-more" data-zeyn-more><button type="button" class="z-button" data-testid="{scope}.grid.load-more">{}</button><span class="z-sr-only" aria-live="polite" data-zeyn-page-info></span></div>"#,
                grid_text("load_more"),
            )),
            Paging::Virtual { .. } => out.push_str(&format!(
                r#"<p class="z-sr-only" aria-live="polite" data-zeyn-page-info data-testid="{scope}.grid.position"></p>"#
            )),
            Paging::None => {}
        }
        out.push_str("</div>");
    }

    /// Footer row with one cell per column. Cells of columns with totals carry `data-field` and
    /// `data-agg` (space separated ops) and show each total with its localized name.
    fn foot_row(&self, r: &Render, totals: &[Total], cols: &[Shown]) -> String {
        let mut out = String::from("<tr>");
        for _ in 0..self.lead(r) {
            out.push_str("<td></td>");
        }
        for c in cols
            .iter()
            .map(|s| &self.columns[s.index])
        {
            out.push_str(&self.total_cell(c, totals, r));
        }
        if !self.row_actions.is_empty() {
            out.push_str("<td></td>");
        }
        out.push_str("</tr>");
        out
    }

    /// The cell of one column with its totals, or an empty cell.
    fn total_cell(&self, c: &Column<E>, totals: &[Total], r: &Render) -> String {
        if c.aggregates.is_empty() {
            return "<td></td>".to_string();
        }
        let ops: Vec<&str> = c
            .aggregates
            .iter()
            .map(|a| a.code())
            .collect();
        let num = matches!(
            c.meta.kind,
            FieldKind::Integer | FieldKind::Money | FieldKind::Decimal
        );
        let class = if num { r#" class="z-num""# } else { "" };
        let mut out = format!(
            r#"<td{class} data-field="{}" data-agg="{}">"#,
            c.meta.name,
            ops.join(" ")
        );
        for op in &c.aggregates {
            let value = totals
                .iter()
                .find(|t| t.field == c.meta.name && t.op == *op)
                .map(|t| match t.value {
                    Value::Int(n) => grouped(n, r.locale),
                    ref v => r.value(v, &c.meta.kind),
                })
                .unwrap_or_default();
            out.push_str(&format!(
                r#"<span class="z-agg" data-op="{}"><span class="z-agg-label">{}</span> <span class="z-agg-value">{value}</span></span>"#,
                op.code(),
                r.text(&Text::key(format!("zeyn.grid.agg.{}", op.code()))),
            ));
        }
        out.push_str("</td>");
        out
    }

    /// Header rows of groups at `depth`: the expander, column label, value and row count span
    /// the columns up to the first one with totals; the totals of each group follow under their
    /// columns.
    fn group_rows(
        &self,
        groups: &[crate::action::Group],
        r: &Render,
        cols: &[Shown],
        depth: usize,
        path: &[Option<String>],
    ) -> String {
        let Some(meta) = self.group_by.get(depth) else {
            return String::new();
        };
        let lead = self.lead(r);
        let first = cols
            .iter()
            .position(|s| {
                !self.columns[s.index]
                    .aggregates
                    .is_empty()
            })
            .unwrap_or(cols.len());
        let mut out = String::new();
        for g in groups {
            let mut here = path.to_vec();
            here.push(value_key(&g.value));
            let shown = match g.value {
                Value::Null => r.text(&Text::key("zeyn.grid.blank")),
                ref v => plain_html(v, &meta.kind, r),
            };
            let label = r.label(meta);
            let count = r.text(
                &Text::key("zeyn.grid.group_count").arg("n", grouped(g.count as i64, r.locale)),
            );
            out.push_str(&format!(
                r#"<tr class="z-group" aria-level="{level}" data-zeyn-level="{depth}" aria-expanded="false" data-zeyn-path="{}"><td colspan="{}"><span class="z-group-head" style="--z-level:{depth}"><button type="button" class="z-expander" data-zeyn-expand aria-expanded="false" aria-label="{label}: {shown}" tabindex="-1"></button><span class="z-group-label">{label}: <strong>{shown}</strong></span> <span class="z-group-count">{count}</span></span></td>"#,
                attr(&here),
                (lead + first).max(1),
                level = depth + 1,
            ));
            for s in &cols[first..] {
                out.push_str(&self.total_cell(&self.columns[s.index], &g.totals, r));
            }
            if !self.row_actions.is_empty() {
                out.push_str("<td></td>");
            }
            out.push_str("</tr>");
        }
        out
    }

    /// Totals the columns declare, as a query asks for them.
    fn aggregate_requests(&self) -> Vec<AggregateRequest> {
        self.columns
            .iter()
            .flat_map(|c| {
                c.aggregates
                    .iter()
                    .map(|op| AggregateRequest {
                        field: c.meta.name.to_string(),
                        op: *op,
                    })
            })
            .collect()
    }

    fn rows_html_erased(&self, page: &LoadedPage, r: &Render) -> String {
        let cols = self.layout(page.view.as_ref());
        if let Some(groups) = &page.groups {
            return self.group_rows(groups, r, &cols, page.depth, &page.path);
        }
        let branch = Branch {
            depth: page.depth,
            path: &page.path,
            parents: &page.parents,
        };
        page.items
            .downcast_ref::<Vec<E>>()
            .map(|rows| self.rows(rows, r, &cols, &branch))
            .unwrap_or_default()
    }

    /// Loads the groups or rows under `path` of a grouped or tree grid. Group values and parent
    /// keys become filters in front of the client's; a tree also asks which of the loaded rows
    /// have children (one grouped query on the parent field) and, at the top, the totals over
    /// every matching row.
    fn fetch_nested(
        &self,
        ctx: Ctx,
        mut query: DataQuery,
        path: Vec<Option<String>>,
    ) -> BoxFuture<Result<LoadedPage>> {
        use crate::action::Error;
        self.allow(&mut query, Some(&ctx));
        query.time_zone = ctx.time_zone();
        let depth = path.len();
        let mut fixed = self.scope.clone();
        let user = query.filters.clone();
        match self.tree {
            Some(parent) => {
                if depth >= MAX_TREE_DEPTH || path.iter().any(Option::is_none) {
                    return Box::pin(async { Err(Error::NotFound) });
                }
                fixed.push(key_filter(
                    parent,
                    path.last()
                        .cloned()
                        .flatten()
                        .as_deref(),
                ));
            }
            None => {
                if depth > self.group_by.len() {
                    return Box::pin(async { Err(Error::NotFound) });
                }
                for (meta, key) in self.group_by.iter().zip(&path) {
                    fixed.push(key_filter(meta, key.as_deref()));
                }
                if let Some(meta) = self.group_by.get(depth) {
                    query.group = Some(meta.name.to_string());
                    query.aggregates = self.aggregate_requests();
                }
            }
        }
        query.filters.splice(0..0, fixed);
        let offset = match &query.page {
            PageRequest::Offset { offset, .. } => *offset,
            PageRequest::After { .. } => 0,
        };
        let fetch = self.fetch;
        let parent = self.tree;
        let scope = self.scope.clone();
        Box::pin(async move {
            let grouped = query.group.is_some();
            let totals_query = (parent.is_some() && depth == 0 && !query.aggregates.is_empty())
                .then(|| DataQuery {
                    page: PageRequest::Offset {
                        offset: 0,
                        limit: 1,
                    },
                    filters: scope
                        .iter()
                        .cloned()
                        .chain(user.iter().cloned())
                        .collect(),
                    aggregates: query.aggregates.clone(),
                    time_zone: query.time_zone,
                    ..DataQuery::default()
                });
            let page = fetch(ctx.clone(), query.clone()).await?;
            let mut parents = Vec::new();
            if let (Some(parent), Some(ki)) = (parent, Self::key_index()) {
                let keys: Vec<String> = page
                    .items
                    .iter()
                    .filter_map(|row| row.value_at(ki))
                    .filter_map(|v| value_key(&v))
                    .collect();
                if !keys.is_empty() {
                    let mut filters = scope.clone();
                    filters.extend(user.iter().cloned());
                    filters.push(Filter::any_of(parent.name, keys));
                    let ask = DataQuery {
                        page: PageRequest::Offset {
                            offset: 0,
                            limit: MAX_PAGE_SIZE,
                        },
                        filters,
                        group: Some(parent.name.to_string()),
                        time_zone: query.time_zone,
                        ..DataQuery::default()
                    };
                    parents = fetch(ctx.clone(), ask)
                        .await?
                        .groups
                        .iter()
                        .filter_map(|g| value_key(&g.value))
                        .collect();
                }
            }
            let totals = match totals_query {
                Some(q) => fetch(ctx, q).await?.totals,
                None => page.totals,
            };
            Ok(LoadedPage {
                count: if grouped {
                    page.groups.len()
                } else {
                    page.items.len()
                },
                total: page.total,
                next: page.next,
                offset,
                totals,
                items: Box::new(page.items),
                view: None,
                saved_views: false,
                depth,
                path,
                groups: grouped.then_some(page.groups),
                parents,
            })
        })
    }
}

impl<E: Model> GridSource for DataGrid<E> {
    fn action(&self) -> ActionMeta {
        self.action
    }

    fn first_query(&self, view: Option<&DataGridView>) -> DataQuery {
        let page = match self.paging {
            Paging::Infinite { batch } => PageRequest::After {
                cursor: None,
                limit: batch,
            },
            other => PageRequest::Offset {
                offset: 0,
                limit: other.size(),
            },
        };
        DataQuery {
            page,
            with_total: !matches!(self.paging, Paging::Infinite { .. }),
            aggregates: self.aggregate_requests(),
            sort: view
                .map(|v| v.sort.clone())
                .filter(|s| !s.is_empty())
                .unwrap_or_else(|| self.default_sort.clone()),
            filters: view
                .map(|v| v.filters.clone())
                .unwrap_or_default(),
            ..DataQuery::default()
        }
    }

    fn clean_view(&self, view: DataGridView) -> DataGridView {
        self.clean(view)
    }

    fn head_html(&self, r: &Render, view: Option<&DataGridView>) -> String {
        self.head_row(r, &self.layout(view))
    }

    fn find_row(&self, ctx: Ctx, key: String) -> BoxFuture<Result<LoadedPage>> {
        let Some(i) = Self::key_index() else {
            return Box::pin(async { Err(crate::action::Error::NotFound) });
        };
        let meta = &E::fields()[i];
        let filter = match meta.kind {
            FieldKind::Id | FieldKind::Integer => Filter::range(meta.name, Some(&key), Some(&key)),
            _ => Filter {
                field: meta.name.to_string(),
                equals: Some(key),
                ..Filter::default()
            },
        };
        let mut query = DataQuery {
            page: PageRequest::Offset {
                offset: 0,
                limit: 5,
            },
            filters: vec![filter],
            time_zone: ctx.time_zone(),
            ..DataQuery::default()
        };
        self.scoped(&mut query);
        let fetch = self.fetch;
        Box::pin(async move {
            let page = fetch(ctx, query).await?;
            Ok(LoadedPage {
                count: page.items.len(),
                total: page.total,
                next: None,
                offset: 0,
                totals: Vec::new(),
                items: Box::new(page.items),
                view: None,
                saved_views: false,
                depth: 0,
                path: Vec::new(),
                groups: None,
                parents: Vec::new(),
            })
        })
    }

    fn bulk_call(&self, index: usize, keys: Vec<serde_json::Value>) -> Option<RowCall> {
        let b = self.bulk.get(index)?;
        Some(RowCall {
            meta: b.meta,
            run: (b.run)(keys)?,
        })
    }

    fn bulk_meta(&self, index: usize) -> Option<ActionMeta> {
        self.bulk.get(index).map(|b| b.meta)
    }

    fn key_json(&self, key: &str) -> Option<serde_json::Value> {
        let meta = &E::fields()[Self::key_index()?];
        match meta.kind {
            FieldKind::Id | FieldKind::Integer => key
                .parse::<i64>()
                .ok()
                .map(serde_json::Value::from),
            _ => Some(serde_json::Value::String(key.to_string())),
        }
    }

    fn page_keys(&self, page: &LoadedPage) -> Vec<serde_json::Value> {
        let Some(i) = Self::key_index() else {
            return Vec::new();
        };
        page.items
            .downcast_ref::<Vec<E>>()
            .map(|rows| {
                rows.iter()
                    .filter_map(|r| r.value_at(i))
                    .filter_map(|v| serde_json::to_value(v).ok())
                    .collect()
            })
            .unwrap_or_default()
    }

    fn export_access(&self) -> Option<crate::action::Access> {
        self.export.map(|e| e.0)
    }

    fn export_limit(&self) -> usize {
        self.export.map_or(0, |e| e.1)
    }

    fn csv_head(&self, r: &Render, view: Option<&DataGridView>) -> String {
        let cols = self.layout(view);
        let line: Vec<String> = cols
            .iter()
            .map(|s| {
                csv_cell(
                    &r.i18n
                        .text(r.locale, &self.columns[s.index].meta.label_text()),
                )
            })
            .collect();
        format!("{}\r\n", line.join(","))
    }

    fn csv_rows(&self, page: &LoadedPage, r: &Render) -> String {
        let cols = self.layout(page.view.as_ref());
        let Some(rows) = page.items.downcast_ref::<Vec<E>>() else {
            return String::new();
        };
        let mut out = String::new();
        for row in rows {
            let line: Vec<String> = cols
                .iter()
                .map(|s| {
                    let c = &self.columns[s.index];
                    let v = (c.value)(row);
                    csv_cell(&if c.meta.mask.is_some() {
                        masked(c.meta, &v)
                    } else {
                        plain(&v, &c.meta.kind, r)
                    })
                })
                .collect();
            out.push_str(&line.join(","));
            out.push_str("\r\n");
        }
        out
    }

    fn export_columns(&self, r: &Render, view: Option<&DataGridView>) -> Vec<ExportColumn> {
        self.layout(view)
            .iter()
            .map(|s| {
                let meta = &self.columns[s.index].meta;
                let numeric = matches!(
                    meta.kind,
                    FieldKind::Integer | FieldKind::Money | FieldKind::Decimal
                ) && meta.mask.is_none();
                ExportColumn {
                    label: r
                        .i18n
                        .text(r.locale, &meta.label_text()),
                    width: s.width,
                    numeric,
                }
            })
            .collect()
    }

    fn export_text(&self, page: &LoadedPage, r: &Render) -> Vec<Vec<String>> {
        let cols = self.layout(page.view.as_ref());
        let Some(rows) = page.items.downcast_ref::<Vec<E>>() else {
            return Vec::new();
        };
        rows.iter()
            .map(|row| {
                cols.iter()
                    .map(|s| {
                        let c = &self.columns[s.index];
                        let v = (c.value)(row);
                        if c.meta.mask.is_some() {
                            masked(c.meta, &v)
                        } else {
                            plain(&v, &c.meta.kind, r)
                        }
                    })
                    .collect()
            })
            .collect()
    }

    fn export_values(&self, page: &LoadedPage, r: &Render) -> Vec<Vec<Value>> {
        let cols = self.layout(page.view.as_ref());
        let Some(rows) = page.items.downcast_ref::<Vec<E>>() else {
            return Vec::new();
        };
        rows.iter()
            .map(|row| {
                cols.iter()
                    .map(|s| {
                        let c = &self.columns[s.index];
                        match (c.value)(row) {
                            v if c.meta.mask.is_some() => Value::Text(masked(c.meta, &v)),
                            v @ Value::Choice(_) => Value::Text(plain(&v, &c.meta.kind, r)),
                            Value::DateTime(d) => Value::LocalDateTime(d.local(r.tz)),
                            v => v,
                        }
                    })
                    .collect()
            })
            .collect()
    }

    fn edit_call(
        &self,
        page: &LoadedPage,
        key: &str,
        values: &serde_json::Map<String, serde_json::Value>,
        locale: &str,
        tz: TimeZone,
    ) -> Result<RowCall> {
        use crate::action::Error;
        let save = self
            .save
            .as_ref()
            .ok_or(Error::NotFound)?;
        let i = Self::key_index().ok_or(Error::NotFound)?;
        let rows = page
            .items
            .downcast_ref::<Vec<E>>()
            .ok_or(Error::NotFound)?;
        let row = rows
            .iter()
            .find(|r| {
                r.value_at(i)
                    .is_some_and(|v| key_text(&v) == key)
            })
            .ok_or(Error::NotFound)?;
        let editable = self.editable_fields();
        let fields = E::fields();
        let allowed = |name: &str| {
            fields
                .iter()
                .enumerate()
                .any(|(j, f)| f.name == name && (f.version || editable.contains(&j)))
        };
        if values.is_empty() || values.keys().any(|k| !allowed(k)) {
            return Err(Error::Forbidden);
        }
        let valid =
            crate::form::Form::with_fields(row.clone(), &editable).read(values, locale, tz)?;
        Ok(RowCall {
            meta: save.meta,
            run: (save.run)(valid),
        })
    }

    fn row_html(&self, page: &LoadedPage, key: &str, r: &Render) -> Option<String> {
        let i = Self::key_index()?;
        let rows = page.items.downcast_ref::<Vec<E>>()?;
        let row = rows.iter().find(|row| {
            row.value_at(i)
                .is_some_and(|v| key_text(&v) == key)
        })?;
        Some(self.rows(
            std::slice::from_ref(row),
            r,
            &self.layout(page.view.as_ref()),
            &Branch::default(),
        ))
    }

    fn row_call(&self, page: &LoadedPage, key: &str, item: &str) -> Option<RowCall> {
        let i = Self::key_index()?;
        let rows = page.items.downcast_ref::<Vec<E>>()?;
        let row = rows.iter().find(|r| {
            r.value_at(i)
                .is_some_and(|v| key_text(&v) == key)
        })?;
        if let Some(path) = item.strip_prefix('m') {
            return self.row_menu.as_ref()?(row).take(path);
        }
        let index: usize = item.strip_prefix('a')?.parse().ok()?;
        let action = self.row_actions.get(index)?;
        Some(RowCall {
            meta: action.meta,
            run: (action.run)(row),
        })
    }

    fn fetch(&self, ctx: Ctx, mut query: DataQuery) -> BoxFuture<Result<LoadedPage>> {
        self.allow(&mut query, Some(&ctx));
        self.scoped(&mut query);
        query.time_zone = ctx.time_zone();
        let fetch = self.fetch;
        let offset = match &query.page {
            PageRequest::Offset { offset, .. } => *offset,
            PageRequest::After { .. } => 0,
        };
        Box::pin(async move {
            let page = fetch(ctx, query).await?;
            Ok(LoadedPage {
                count: page.items.len(),
                total: page.total,
                next: page.next,
                offset,
                totals: page.totals,
                items: Box::new(page.items),
                view: None,
                saved_views: false,
                depth: 0,
                path: Vec::new(),
                groups: None,
                parents: Vec::new(),
            })
        })
    }

    fn fetch_at(
        &self,
        ctx: Ctx,
        query: DataQuery,
        path: Vec<Option<String>>,
    ) -> BoxFuture<Result<LoadedPage>> {
        if self.nested() {
            self.fetch_nested(ctx, query, path)
        } else {
            self.fetch(ctx, query)
        }
    }

    fn rows_html(&self, page: &LoadedPage, r: &Render) -> String {
        self.rows_html_erased(page, r)
    }

    fn render_loaded(&self, out: &mut String, r: &Render, page: &LoadedPage) {
        self.render_with(out, r, Some(page));
    }

    fn foot_html(&self, page: &LoadedPage, r: &Render) -> Option<String> {
        let has = self
            .columns
            .iter()
            .any(|c| !c.aggregates.is_empty());
        (has && !page.totals.is_empty())
            .then(|| self.foot_row(r, &page.totals, &self.layout(page.view.as_ref())))
    }

    fn fields(&self) -> &'static [FieldMeta] {
        E::fields()
    }

    fn sensitive_model(&self) -> Option<&'static str> {
        E::SENSITIVE.then_some(E::NAME)
    }

    /// Reveals a masked column of one row. The row is loaded like a row action's, through the
    /// grid's scope, so only rows the grid shows can be revealed.
    fn reveal(
        &self,
        ctx: Ctx,
        key: String,
        field: String,
    ) -> BoxFuture<Result<Option<crate::privacy::Revealed>>> {
        if !self
            .columns
            .iter()
            .any(|c| c.meta.name == field && c.meta.mask.is_some())
        {
            return Box::pin(async { Ok(None) });
        }
        let find = self.find_row(ctx, key.clone());
        Box::pin(async move {
            let page = find.await?;
            let rows = page.items.downcast_ref::<Vec<E>>();
            let row = rows.and_then(|rows| {
                rows.iter().find(|r| {
                    crate::audit::RecordRef::of(*r)
                        .id
                        .as_deref()
                        == Some(key.as_str())
                })
            });
            Ok(row.and_then(|row| crate::privacy::reveal_in(row, &field)))
        })
    }

    fn tool_schema(&self) -> serde_json::Value {
        let fields: Vec<&str> = self
            .columns
            .iter()
            .map(|c| c.meta.name)
            .collect();
        let filterable: Vec<&str> = self
            .columns
            .iter()
            .filter(|c| c.filter)
            .map(|c| c.meta.name)
            .collect();
        json!({
            "type": "object",
            "properties": {
                "page": {
                    "type": "object",
                    "description": "Which rows to return. Use type offset with offset and limit (max 500).",
                    "properties": {
                        "type": { "type": "string", "enum": ["offset", "after"] },
                        "offset": { "type": "integer", "minimum": 0 },
                        "limit": { "type": "integer", "minimum": 1, "maximum": MAX_PAGE_SIZE },
                        "cursor": { "type": ["string", "null"] }
                    },
                    "required": ["type", "limit"]
                },
                "sort": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": { "field": { "type": "string", "enum": fields }, "desc": { "type": "boolean" } },
                        "required": ["field", "desc"]
                    }
                },
                "filters": {
                    "type": "array",
                    "description": "Every set condition must hold. Numbers as 1234.56, dates as YYYY-MM-DD (a whole day in the user's time zone for moments), times as HH:MM.",
                    "items": {
                        "type": "object",
                        "properties": {
                            "field": { "type": "string", "enum": filterable },
                            "contains": { "type": "string" },
                            "starts_with": { "type": "string" },
                            "equals": { "type": "string" },
                            "from": { "type": "string" },
                            "to": { "type": "string" },
                            "any_of": { "type": "array", "items": { "type": "string" } },
                            "is": { "type": "boolean" }
                        },
                        "required": ["field"]
                    }
                },
                "with_total": { "type": "boolean" },
                "aggregates": {
                    "type": "array",
                    "description": "Column totals over all matching rows. Only the totals the grid shows are computed.",
                    "items": {
                        "type": "object",
                        "properties": {
                            "field": { "type": "string", "enum": fields },
                            "op": { "type": "string", "enum": ["sum", "avg", "min", "max", "count"] }
                        },
                        "required": ["field", "op"]
                    }
                }
            }
        })
    }
}

impl<E: Model> Component for DataGrid<E> {
    fn render(&self, out: &mut String, r: &Render) {
        self.render_with(out, r, None);
    }

    fn schema(&self) -> serde_json::Value {
        json!({
            "type": "grid",
            "model": E::NAME,
            "action": self.action,
            "mode": self.mode,
            "paging": self.paging,
            "openable": self.on_open.is_some(),
            "columns": self.columns.iter().map(|c| json!({
                "field": c.meta.name,
                "label": c.meta.label,
                "kind": c.meta.kind,
                "width": c.width,
                "flex": c.flex,
                "filter": c.filter,
                "aggregates": c.aggregates,
                "pin": c.pin,
                "hidden": c.hidden,
            })).collect::<Vec<_>>(),
            "row_actions": self.row_actions.iter().map(|a| json!({ "label": a.label, "action": a.meta })).collect::<Vec<_>>(),
            "detail": self.detail.as_ref().map(|d| d.screen),
            "group_by": self.group_by.iter().map(|m| m.name).collect::<Vec<_>>(),
            "tree": self.tree.map(|m| m.name),
        })
    }

    fn grid(&self) -> Option<&dyn GridSource> {
        Some(self)
    }
}

impl<E: Model> From<DataGrid<E>> for Node {
    fn from(g: DataGrid<E>) -> Self {
        Node::new(g)
    }
}

/// Whole number with the locale's group separator: `4.680` in `tr`, `4,680` in `en`.
fn grouped(n: i64, locale: &str) -> String {
    match n.checked_mul(100) {
        Some(h) => {
            let text = Money::new(h, Default::default()).format_plain(locale);
            text[..text.len() - 3].to_string()
        }
        None => n.to_string(),
    }
}

/// Most sort keys one query may carry.
pub const MAX_SORT: usize = 4;

/// Filter input the runtime shows for a column kind.
fn filter_kind(kind: &FieldKind) -> &'static str {
    match kind {
        FieldKind::Integer | FieldKind::Id => "number",
        FieldKind::Money | FieldKind::Decimal => "money",
        FieldKind::Date => "date",
        FieldKind::DateTime | FieldKind::LocalDateTime => "datetime",
        FieldKind::Time => "time",
        FieldKind::Choice(_) => "choice",
        FieldKind::Bool => "bool",
        FieldKind::Text | FieldKind::Custom { .. } | FieldKind::Choices(_) => "text",
    }
}

/// Localized texts the runtime needs for grid controls, sent once on the grid root.
fn grid_texts(r: &Render) -> serde_json::Value {
    let keys = [
        "filter",
        "from",
        "to",
        "all",
        "contains",
        "starts_with",
        "equals",
        "match",
        "selected",
        "clear",
        "sorted",
    ];
    let mut map = serde_json::Map::new();
    for k in keys {
        map.insert(
            k.to_string(),
            json!(
                r.i18n
                    .text(r.locale, &Text::key(format!("zeyn.grid.filter.{k}")))
            ),
        );
    }
    let menu = [
        "options",
        "resize",
        "sort_asc",
        "sort_desc",
        "sort_clear",
        "pin_start",
        "pin_end",
        "unpin",
        "move_prev",
        "move_next",
        "hide",
        "columns",
        "reset",
        "filter",
    ];
    for k in menu {
        map.insert(
            format!("menu_{k}"),
            json!(
                r.i18n
                    .text(r.locale, &Text::key(format!("zeyn.grid.menu.{k}")))
            ),
        );
    }
    map.insert(
        "done".into(),
        json!(
            r.i18n
                .text(r.locale, &Text::key("zeyn.grid.done"))
        ),
    );
    for k in [
        "saved",
        "undo",
        "undone",
        "empty",
        "error",
        "retry",
        "copied",
        "details",
        "loading",
        "load_more",
        "copied_cells",
        "paste_confirm",
        "pasted",
        "paste_failed",
        "paste_readonly",
        "paste_too_many",
    ] {
        map.insert(
            k.into(),
            json!(
                r.i18n
                    .text(r.locale, &Text::key(format!("zeyn.grid.{k}")))
            ),
        );
    }
    map.insert(
        "yes".into(),
        json!(
            r.i18n
                .text(r.locale, &Text::key("zeyn.yes"))
        ),
    );
    map.insert(
        "no".into(),
        json!(
            r.i18n
                .text(r.locale, &Text::key("zeyn.no"))
        ),
    );
    serde_json::Value::Object(map)
}