iced-cube 0.0.6

Themeable application components for the iced GUI library, with Lucide icons
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
//! A JSON document shown as rows that expand and collapse.
//!
//! [`State`] flattens a [`serde_json::Value`] into nodes, or parses JSON
//! text with [`State::parse`] and keeps the error when it is not valid. It
//! holds which objects and arrays are expanded, the highlighted node and
//! the search. Its [`update`](State::update) handles pointer and keyboard
//! navigation, expanding everything or to a depth, searching and copying.
//!
//! Objects and arrays show how many members they hold, `{3}` or `[12]`.
//! Values are coloured by type from the theme's [`Tokens`], see [`syntax`],
//! and a long value ends in an ellipsis on one line. Copy it to read it in
//! full. The view only builds the rows in view, so a document with
//! thousands of nodes stays quick.
//!
//! Copying never touches the clipboard itself: [`Output::CopyValue`] holds
//! the value as pretty-printed JSON and [`Output::CopyPath`] its path, such
//! as `$.users[2].name`, for the app to write. Paths start at `$`, the
//! document, and use `["key"]` for keys that are not plain identifiers.
//!
//! The viewer resolves its keys through a [`Keymap`] of [`Action`]s while
//! it has focus, which it takes when pressed; see [`default_keymap`].

use std::collections::HashSet;
use std::fmt;
use std::ops::Range;
use std::rc::Rc;

use iced::keyboard::key::Named;
use iced::keyboard::{Key, Modifiers};
use iced::widget::{self, Space, column, container, mouse_area, row, text};
use iced::{Alignment, Border, Color, Element, Font, Length, Task, Theme, mouse};
use serde_json::Value;

use crate::data::ellipsis::ellipsis;
use crate::data::interaction::{
    Look, RowMenu, match_count_label, pressable, ringed, row_menu, scope, search_count, search_keys,
};
use crate::data::rows::rows;
use crate::feedback::alert::{self, alert};
use crate::icon::{opacity, themed};
use crate::keys::{self, Chord, Keymap};
use crate::overlay::context_menu;
use crate::overlay::dropdown_menu::{item, separator};
use crate::overlay::menu::{ICON_SIZE, ROW_PADDING};
use crate::primitives::button::Size;
use crate::primitives::icon_button::icon_button;
use crate::primitives::input::{self, input};
use crate::theme::{self, Tokens, fade, mix, radius, space, text_size};

/// Height of every row, as in a menu.
pub const ROW_HEIGHT: f32 = 32.0;
/// Width of one level of indentation, which is also the chevron's slot.
pub const INDENT: f32 = 20.0;
/// The widest a key gets before it ends in an ellipsis, by default.
pub const KEY_WIDTH: f32 = 180.0;
/// The id of the search box, unless [`State::with_search_id`] sets another.
pub const SEARCH: widget::Id = widget::Id::new("json-viewer-search");

/// A node in the document, numbered in document order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct NodeId(usize);

impl NodeId {
    /// The node's position in document order, starting at the document
    /// itself.
    pub fn index(self) -> usize {
        self.0
    }
}

/// The type of a JSON value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Kind {
    Object,
    Array,
    String,
    Number,
    Bool,
    Null,
}

impl Kind {
    pub const ALL: [Kind; 6] = [
        Kind::Object,
        Kind::Array,
        Kind::String,
        Kind::Number,
        Kind::Bool,
        Kind::Null,
    ];

    pub fn of(value: &Value) -> Kind {
        match value {
            Value::Object(_) => Kind::Object,
            Value::Array(_) => Kind::Array,
            Value::String(_) => Kind::String,
            Value::Number(_) => Kind::Number,
            Value::Bool(_) => Kind::Bool,
            Value::Null => Kind::Null,
        }
    }

    /// Whether values of this kind hold other values.
    pub fn is_container(self) -> bool {
        matches!(self, Kind::Object | Kind::Array)
    }
}

/// How a node is reached from its parent.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Segment {
    /// A member of an object.
    Key(String),
    /// An element of an array.
    Index(usize),
}

/// Why JSON text could not be read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError {
    pub message: String,
    /// Where the problem is, counted from 1.
    pub line: usize,
    pub column: usize,
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} at line {}, column {}",
            self.message, self.line, self.column
        )
    }
}

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

impl From<serde_json::Error> for ParseError {
    fn from(error: serde_json::Error) -> Self {
        let (line, column) = (error.line(), error.column());
        let full = error.to_string();
        let suffix = format!(" at line {line} column {column}");
        let message = full.strip_suffix(&suffix).unwrap_or(&full).to_owned();
        Self {
            message,
            line,
            column,
        }
    }
}

#[derive(Debug, Clone)]
struct Item {
    segment: Option<Segment>,
    parent: Option<NodeId>,
    depth: usize,
    kind: Kind,
    /// A scalar as JSON, such as `"text"` or `12`. Empty for containers.
    text: String,
    /// The lower-case key and value the search looks in.
    key_lower: Option<String>,
    text_lower: String,
    children: Vec<NodeId>,
}

/// Everything that changes a viewer.
#[derive(Debug, Clone, PartialEq)]
pub enum Event {
    /// Expands or collapses a node, as its chevron does.
    Toggle(NodeId),
    Expand(NodeId),
    Collapse(NodeId),
    /// Expands a node and everything under it.
    ExpandSubtree(NodeId),
    /// Collapses a node and everything under it.
    CollapseSubtree(NodeId),
    ExpandAll,
    CollapseAll,
    /// Expands every object and array fewer than this many levels deep and
    /// collapses the rest, so `0` collapses everything.
    ExpandToDepth(usize),
    /// The pointer pressed a row.
    Press(NodeId),
    Next,
    Previous,
    First,
    Last,
    /// Expands the highlighted node, or moves to its first child when it
    /// is already expanded.
    ExpandOrEnter,
    /// Collapses the highlighted node, or moves to its parent when it is
    /// already collapsed.
    CollapseOrLeave,
    ToggleHighlighted,
    /// Expands the highlighted node and every sibling that has children.
    ExpandSiblings,
    /// Searches keys and values for this text, ignoring case, and expands
    /// the parents of every match.
    Search(String),
    NextMatch,
    PreviousMatch,
    /// Shows only matches, their parents and what is inside them.
    OnlyMatches(bool),
    CopyValue(NodeId),
    CopyPath(NodeId),
    /// Asks the app to focus the search box.
    FocusSearch,
    /// The viewer gained or lost focus. The widget sends this itself.
    Focus(bool),
}

/// What the app may need to act on after an [`Event`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Output {
    /// A value as pretty-printed JSON, to write to the clipboard.
    CopyValue(String),
    /// A path such as `$.users[2].name`, to write to the clipboard.
    CopyPath(String),
    /// Focus the search box, with [`focus_search`].
    FocusSearch,
}

/// The document, what is expanded and highlighted, and the search.
#[derive(Debug, Clone)]
pub struct State {
    value: Value,
    items: Vec<Item>,
    roots: Vec<NodeId>,
    expanded: HashSet<NodeId>,
    highlighted: Option<NodeId>,
    focused: bool,
    query: String,
    matches: Vec<NodeId>,
    matched: HashSet<NodeId>,
    /// The ancestors of every match.
    trail: HashSet<NodeId>,
    current: Option<usize>,
    only_matches: bool,
    error: Option<ParseError>,
    search_id: widget::Id,
}

impl Default for State {
    fn default() -> Self {
        Self::new(Value::Null)
    }
}

impl State {
    /// A viewer of `value` with everything collapsed. An object or array
    /// shows its members as the top rows; anything else shows as one row.
    pub fn new(value: Value) -> Self {
        let (items, roots) = flatten(&value);
        Self {
            value,
            items,
            roots,
            expanded: HashSet::new(),
            highlighted: None,
            focused: false,
            query: String::new(),
            matches: Vec::new(),
            matched: HashSet::new(),
            trail: HashSet::new(),
            current: None,
            only_matches: false,
            error: None,
            search_id: SEARCH,
        }
    }

    /// Parses JSON text. Text that is not valid JSON gives an empty viewer
    /// that shows the [`error`](Self::error) in place of rows.
    pub fn parse(json: &str) -> Self {
        match serde_json::from_str(json) {
            Ok(value) => Self::new(value),
            Err(error) => Self {
                error: Some(error.into()),
                ..Self::new(Value::Null)
            }
            .without_rows(),
        }
    }

    fn without_rows(mut self) -> Self {
        self.items.clear();
        self.roots.clear();
        self
    }

    /// Starts with every object and array fewer than `depth` levels deep
    /// expanded.
    pub fn with_depth(mut self, depth: usize) -> Self {
        self.expand_to_depth(depth);
        self
    }

    /// Starts with only the matches shown while searching.
    pub fn with_only_matches(mut self, only_matches: bool) -> Self {
        self.only_matches = only_matches;
        self
    }

    /// The search box's widget id. Defaults to [`SEARCH`]; give each viewer
    /// its own when a window has several.
    pub fn with_search_id(mut self, id: impl Into<widget::Id>) -> Self {
        self.search_id = id.into();
        self
    }

    /// The search box's widget id, which [`focus_search`] focuses.
    pub fn search_id(&self) -> &widget::Id {
        &self.search_id
    }

    /// The whole document.
    pub fn value(&self) -> &Value {
        &self.value
    }

    /// Why the text given to [`parse`](Self::parse) is not valid JSON.
    pub fn error(&self) -> Option<&ParseError> {
        self.error.as_ref()
    }

    /// How many nodes the document holds, the document itself included.
    pub fn len(&self) -> usize {
        self.items.len()
    }

    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// The top rows.
    pub fn roots(&self) -> &[NodeId] {
        &self.roots
    }

    pub fn kind(&self, id: NodeId) -> Option<Kind> {
        self.item(id).map(|item| item.kind)
    }

    /// The key or index the node has in its parent, `None` for the document.
    pub fn segment(&self, id: NodeId) -> Option<&Segment> {
        self.item(id).and_then(|item| item.segment.as_ref())
    }

    /// The node's parent row, `None` for a top row.
    pub fn parent(&self, id: NodeId) -> Option<NodeId> {
        self.item(id).and_then(|item| item.parent)
    }

    pub fn children(&self, id: NodeId) -> &[NodeId] {
        self.item(id).map_or(&[], |item| &item.children)
    }

    /// How far the row is indented: 0 for a top row.
    pub fn depth(&self, id: NodeId) -> usize {
        self.item(id).map_or(0, |item| item.depth)
    }

    pub fn is_expanded(&self, id: NodeId) -> bool {
        self.expanded.contains(&id)
    }

    /// The node the keyboard acts on.
    pub fn highlighted(&self) -> Option<NodeId> {
        self.highlighted
    }

    pub fn is_focused(&self) -> bool {
        self.focused
    }

    /// The search text.
    pub fn query(&self) -> &str {
        &self.query
    }

    /// The nodes whose key or value contains the search text, in document
    /// order.
    pub fn matches(&self) -> &[NodeId] {
        &self.matches
    }

    pub fn is_match(&self, id: NodeId) -> bool {
        self.matched.contains(&id)
    }

    /// The match [`Event::NextMatch`] last moved to.
    pub fn current_match(&self) -> Option<NodeId> {
        self.current
            .and_then(|index| self.matches.get(index))
            .copied()
    }

    /// Whether only matches are shown: [`only_matches`](Self::only_matches)
    /// is on and there is a search.
    pub fn is_filtering(&self) -> bool {
        self.only_matches && !self.query.trim().is_empty()
    }

    /// Whether a search shows only its matches, searching or not.
    pub fn only_matches(&self) -> bool {
        self.only_matches
    }

    /// The rows on screen when scrolled through, in document order.
    pub fn visible(&self) -> Vec<NodeId> {
        let filtering = self.is_filtering();
        let mut out = Vec::new();
        let mut stack: Vec<(NodeId, bool)> =
            self.roots.iter().rev().map(|&id| (id, false)).collect();
        while let Some((id, inside)) = stack.pop() {
            let matched = self.matched.contains(&id);
            if filtering && !inside && !matched && !self.trail.contains(&id) {
                continue;
            }
            out.push(id);
            if !self.expanded.contains(&id) {
                continue;
            }
            let inside = inside || matched;
            stack.extend(self.children(id).iter().rev().map(|&child| (child, inside)));
        }
        out
    }

    /// The node's path from the document, such as `$.users[2].name` or
    /// `$["first name"]`.
    pub fn path(&self, id: NodeId) -> String {
        let mut path = String::from("$");
        for segment in self.segments(id).into_iter().rev() {
            match segment {
                Segment::Index(index) => path.push_str(&format!("[{index}]")),
                Segment::Key(key) if is_identifier(key) => {
                    path.push('.');
                    path.push_str(key);
                }
                Segment::Key(key) => {
                    let quoted = serde_json::to_string(key).unwrap_or_default();
                    path.push_str(&format!("[{quoted}]"));
                }
            }
        }
        path
    }

    /// The node's value.
    pub fn value_at(&self, id: NodeId) -> Option<&Value> {
        self.item(id)?;
        self.segments(id)
            .into_iter()
            .rev()
            .try_fold(&self.value, |value, segment| match segment {
                Segment::Key(key) => value.get(key.as_str()),
                Segment::Index(index) => value.get(*index),
            })
    }

    /// The node's value as pretty-printed JSON.
    pub fn pretty(&self, id: NodeId) -> Option<String> {
        self.value_at(id)
            .and_then(|value| serde_json::to_string_pretty(value).ok())
    }

    /// Applies an event and returns what the app may need to act on.
    pub fn update(&mut self, event: Event) -> Option<Output> {
        match event {
            Event::Toggle(id) if self.is_expanded(id) => self.collapse(id),
            Event::Toggle(id) | Event::Expand(id) => self.expand(id),
            Event::Collapse(id) => self.collapse(id),
            Event::ExpandSubtree(id) => {
                let ids: Vec<NodeId> = self
                    .subtree(id)
                    .into_iter()
                    .filter(|&id| self.has_children(id))
                    .collect();
                self.expanded.extend(ids);
            }
            Event::CollapseSubtree(id) => {
                for id in self.subtree(id) {
                    let _ = self.expanded.remove(&id);
                }
                self.reveal_highlight();
            }
            Event::ExpandAll => {
                let all: Vec<NodeId> = (0..self.items.len())
                    .map(NodeId)
                    .filter(|&id| self.has_children(id))
                    .collect();
                self.expanded.extend(all);
            }
            Event::CollapseAll => {
                self.expanded.clear();
                self.reveal_highlight();
            }
            Event::ExpandToDepth(depth) => self.expand_to_depth(depth),
            Event::Press(id) if self.item(id).is_some() => self.highlighted = Some(id),
            Event::Press(_) => {}
            Event::Next => self.step(Step::Next),
            Event::Previous => self.step(Step::Previous),
            Event::First => self.step(Step::First),
            Event::Last => self.step(Step::Last),
            Event::ExpandOrEnter => self.expand_or_enter(),
            Event::CollapseOrLeave => self.collapse_or_leave(),
            Event::ToggleHighlighted => {
                if let Some(id) = self.highlighted {
                    return self.update(Event::Toggle(id));
                }
            }
            Event::ExpandSiblings => self.expand_siblings(),
            Event::Search(query) => self.search(query),
            Event::NextMatch => self.cycle(true),
            Event::PreviousMatch => self.cycle(false),
            Event::OnlyMatches(only_matches) => self.only_matches = only_matches,
            Event::CopyValue(id) => {
                self.highlight(id);
                return self.pretty(id).map(Output::CopyValue);
            }
            Event::CopyPath(id) => {
                self.highlight(id);
                return self.item(id).map(|_| Output::CopyPath(self.path(id)));
            }
            Event::FocusSearch => return Some(Output::FocusSearch),
            Event::Focus(focused) => {
                self.focused = focused;
                if focused && self.highlighted.is_none() {
                    self.highlighted = self.roots.first().copied();
                }
            }
        }
        None
    }

    /// Turns a key press into an event through `keymap`. A symbol typed
    /// with Shift, such as `*`, also matches its chord without Shift.
    pub fn key_event(&self, keymap: &Keymap<Action>, key: &keys::Event) -> Option<Event> {
        let action = keymap.resolve_event(key).or_else(|| {
            let symbol = matches!(&key.key, Key::Character(text) if !text.chars().any(char::is_alphanumeric));
            (symbol && key.modifiers.shift())
                .then(|| keymap.resolve(&key.key, key.modifiers.difference(Modifiers::SHIFT)))
                .flatten()
        })?;
        action.event(self)
    }

    fn item(&self, id: NodeId) -> Option<&Item> {
        self.items.get(id.0)
    }

    fn has_children(&self, id: NodeId) -> bool {
        !self.children(id).is_empty()
    }

    fn highlight(&mut self, id: NodeId) {
        if self.item(id).is_some() {
            self.highlighted = Some(id);
        }
    }

    /// The segments from the node up to the document.
    fn segments(&self, id: NodeId) -> Vec<&Segment> {
        let mut segments = Vec::new();
        let mut current = Some(id);
        while let Some(node) = current {
            let Some(item) = self.item(node) else {
                break;
            };
            segments.extend(item.segment.as_ref());
            current = item.parent;
        }
        segments
    }

    /// The node and everything under it.
    fn subtree(&self, id: NodeId) -> Vec<NodeId> {
        let mut out = Vec::new();
        let mut stack = vec![id];
        while let Some(node) = stack.pop() {
            if self.item(node).is_none() {
                continue;
            }
            out.push(node);
            stack.extend(self.children(node).iter().copied());
        }
        out
    }

    fn expand(&mut self, id: NodeId) {
        if self.has_children(id) {
            let _ = self.expanded.insert(id);
        }
    }

    fn collapse(&mut self, id: NodeId) {
        if self.expanded.remove(&id) {
            self.reveal_highlight();
        }
    }

    fn expand_to_depth(&mut self, depth: usize) {
        self.expanded = (0..self.items.len())
            .map(NodeId)
            .filter(|&id| self.depth(id) < depth && self.has_children(id))
            .collect();
        self.reveal_highlight();
    }

    /// Moves a highlight hidden in a collapsed branch up to the outermost
    /// collapsed node above it.
    fn reveal_highlight(&mut self) {
        let Some(id) = self.highlighted else {
            return;
        };
        let mut target = id;
        let mut current = self.parent(id);
        while let Some(parent) = current {
            if !self.expanded.contains(&parent) {
                target = parent;
            }
            current = self.parent(parent);
        }
        self.highlighted = Some(target);
    }

    fn step(&mut self, step: Step) {
        let rows = self.visible();
        let current = self
            .highlighted
            .and_then(|id| rows.iter().position(|&row| row == id));
        let target = match (step, current) {
            (Step::First, _) | (Step::Next, None) => rows.first(),
            (Step::Last, _) | (Step::Previous, None) => rows.last(),
            (Step::Next, Some(index)) => rows.get(index + 1).or(rows.get(index)),
            (Step::Previous, Some(index)) => rows.get(index.saturating_sub(1)),
        };
        if let Some(&target) = target {
            self.highlighted = Some(target);
        }
    }

    fn expand_or_enter(&mut self) {
        let Some(id) = self.highlighted else {
            return;
        };
        if !self.is_expanded(id) {
            self.expand(id);
            return;
        }
        let first = self
            .visible()
            .into_iter()
            .find(|&row| self.parent(row) == Some(id));
        if let Some(first) = first {
            self.highlighted = Some(first);
        }
    }

    fn collapse_or_leave(&mut self) {
        let Some(id) = self.highlighted else {
            return;
        };
        if self.is_expanded(id) {
            self.collapse(id);
            return;
        }
        if let Some(parent) = self.parent(id) {
            self.highlighted = Some(parent);
        }
    }

    fn expand_siblings(&mut self) {
        let Some(id) = self.highlighted else {
            return;
        };
        let siblings = match self.parent(id) {
            Some(parent) => self.children(parent).to_vec(),
            None => self.roots.clone(),
        };
        for sibling in siblings {
            self.expand(sibling);
        }
    }

    fn search(&mut self, query: String) {
        let needle = query.trim().to_lowercase();
        self.query = query;
        self.matches.clear();
        self.matched.clear();
        self.trail.clear();
        self.current = None;
        if needle.is_empty() {
            return;
        }
        self.matches = self
            .items
            .iter()
            .enumerate()
            .filter(|(_, item)| {
                item.key_lower
                    .as_ref()
                    .is_some_and(|key| key.contains(&needle))
                    || item.text_lower.contains(&needle)
            })
            .map(|(index, _)| NodeId(index))
            .collect();
        self.matched = self.matches.iter().copied().collect();
        for &id in &self.matches {
            let mut current = self.parent(id);
            while let Some(parent) = current {
                if !self.trail.insert(parent) {
                    break;
                }
                current = self.parent(parent);
            }
        }
        self.expanded.extend(self.trail.iter().copied());
        // The nearest match: the first at or after the highlight, or else
        // the last before it.
        let at = self
            .highlighted
            .map_or(0, |from| self.matches.partition_point(|&id| id < from));
        let index = at.min(self.matches.len().saturating_sub(1));
        if let Some(&nearest) = self.matches.get(index) {
            self.current = Some(index);
            self.highlighted = Some(nearest);
        }
    }

    fn cycle(&mut self, forward: bool) {
        let count = self.matches.len();
        if count == 0 {
            return;
        }
        let index = match (self.current, forward) {
            (None, true) => 0,
            (None, false) => count - 1,
            (Some(index), true) => (index + 1) % count,
            (Some(index), false) => (index + count - 1) % count,
        };
        self.current = Some(index);
        self.highlighted = self.matches.get(index).copied();
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Step {
    Next,
    Previous,
    First,
    Last,
}

/// Whether a key can follow a dot in a path.
fn is_identifier(key: &str) -> bool {
    let mut chars = key.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    (first.is_ascii_alphabetic() || first == '_' || first == '$')
        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
}

/// The nodes of `value` in document order, and the top rows. The members
/// of an object or array that has any are the top rows; otherwise the
/// document is the only row.
fn flatten(value: &Value) -> (Vec<Item>, Vec<NodeId>) {
    let mut items = Vec::new();
    let root = push(&mut items, value, None, None, 0);
    let members = items
        .get(root.0)
        .map(|item| item.children.clone())
        .unwrap_or_default();
    if members.is_empty() {
        return (items, vec![root]);
    }
    for item in items.iter_mut().skip(1) {
        item.depth -= 1;
        if item.parent == Some(root) {
            item.parent = None;
        }
    }
    (items, members)
}

fn push(
    items: &mut Vec<Item>,
    value: &Value,
    segment: Option<Segment>,
    parent: Option<NodeId>,
    depth: usize,
) -> NodeId {
    let id = NodeId(items.len());
    let text = match value {
        Value::Object(_) | Value::Array(_) => String::new(),
        scalar => serde_json::to_string(scalar).unwrap_or_default(),
    };
    let raw = match value {
        Value::String(string) => string.as_str(),
        _ => text.as_str(),
    };
    let key_lower = match &segment {
        Some(Segment::Key(key)) => Some(key.to_lowercase()),
        _ => None,
    };
    items.push(Item {
        text_lower: raw.to_lowercase(),
        segment,
        parent,
        depth,
        kind: Kind::of(value),
        text,
        key_lower,
        children: Vec::new(),
    });
    let children: Vec<NodeId> = match value {
        Value::Object(map) => map
            .iter()
            .map(|(key, child)| {
                push(
                    items,
                    child,
                    Some(Segment::Key(key.clone())),
                    Some(id),
                    depth + 1,
                )
            })
            .collect(),
        Value::Array(list) => list
            .iter()
            .enumerate()
            .map(|(index, child)| {
                push(
                    items,
                    child,
                    Some(Segment::Index(index)),
                    Some(id),
                    depth + 1,
                )
            })
            .collect(),
        _ => Vec::new(),
    };
    if let Some(item) = items.get_mut(id.0) {
        item.children = children;
    }
    id
}

/// What a viewer keyboard shortcut does.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Action {
    Next,
    Previous,
    First,
    Last,
    Expand,
    Collapse,
    Toggle,
    ExpandSiblings,
    ExpandAll,
    CollapseAll,
    CopyValue,
    CopyPath,
    FocusSearch,
    ClearSearch,
    NextMatch,
    PreviousMatch,
}

impl Action {
    /// The [`Event`] this action sends to `state`, or `None` when it does
    /// nothing, so the key is left for others.
    pub fn event(self, state: &State) -> Option<Event> {
        let highlighted = state.highlighted();
        let searching = !state.matches().is_empty();
        match self {
            Action::Next => Some(Event::Next),
            Action::Previous => Some(Event::Previous),
            Action::First => Some(Event::First),
            Action::Last => Some(Event::Last),
            Action::Expand => highlighted.map(|_| Event::ExpandOrEnter),
            Action::Collapse => highlighted.map(|_| Event::CollapseOrLeave),
            Action::Toggle => highlighted
                .filter(|&id| state.has_children(id))
                .map(|_| Event::ToggleHighlighted),
            Action::ExpandSiblings => highlighted.map(|_| Event::ExpandSiblings),
            Action::ExpandAll => Some(Event::ExpandAll),
            Action::CollapseAll => Some(Event::CollapseAll),
            Action::CopyValue => highlighted.map(Event::CopyValue),
            Action::CopyPath => highlighted.map(Event::CopyPath),
            Action::FocusSearch => Some(Event::FocusSearch),
            Action::ClearSearch => {
                (!state.query().is_empty()).then(|| Event::Search(String::new()))
            }
            Action::NextMatch => searching.then_some(Event::NextMatch),
            Action::PreviousMatch => searching.then_some(Event::PreviousMatch),
        }
    }
}

impl keys::Action for Action {
    const ALL: &'static [Self] = &[
        Action::Next,
        Action::Previous,
        Action::First,
        Action::Last,
        Action::Expand,
        Action::Collapse,
        Action::Toggle,
        Action::ExpandSiblings,
        Action::ExpandAll,
        Action::CollapseAll,
        Action::CopyValue,
        Action::CopyPath,
        Action::FocusSearch,
        Action::ClearSearch,
        Action::NextMatch,
        Action::PreviousMatch,
    ];

    fn defaults() -> Keymap<Self> {
        default_keymap()
    }

    fn name(self) -> &'static str {
        match self {
            Action::Next => "Next",
            Action::Previous => "Previous",
            Action::First => "First",
            Action::Last => "Last",
            Action::Expand => "Expand",
            Action::Collapse => "Collapse",
            Action::Toggle => "Toggle",
            Action::ExpandSiblings => "ExpandSiblings",
            Action::ExpandAll => "ExpandAll",
            Action::CollapseAll => "CollapseAll",
            Action::CopyValue => "CopyValue",
            Action::CopyPath => "CopyPath",
            Action::FocusSearch => "FocusSearch",
            Action::ClearSearch => "ClearSearch",
            Action::NextMatch => "NextMatch",
            Action::PreviousMatch => "PreviousMatch",
        }
    }

    fn description(self) -> &'static str {
        match self {
            Action::Next => "Highlights the next row.",
            Action::Previous => "Highlights the previous row.",
            Action::First => "Highlights the first row.",
            Action::Last => "Highlights the last row.",
            Action::Expand => {
                "Expands the highlighted object or array, or moves to its first member when it is open."
            }
            Action::Collapse => {
                "Collapses the highlighted object or array, or moves to its parent when it is closed."
            }
            Action::Toggle => "Expands or collapses the highlighted object or array.",
            Action::ExpandSiblings => "Expands the highlighted node and all of its siblings.",
            Action::ExpandAll => "Expands every object and array.",
            Action::CollapseAll => "Collapses every object and array.",
            Action::CopyValue => "Copies the highlighted value as pretty-printed JSON.",
            Action::CopyPath => "Copies the path of the highlighted value.",
            Action::FocusSearch => "Moves to the search box.",
            Action::ClearSearch => "Clears the search.",
            Action::NextMatch => "Highlights the next search match.",
            Action::PreviousMatch => "Highlights the previous search match.",
        }
    }
}

/// The default viewer shortcuts:
///
/// | Keys | Action |
/// | --- | --- |
/// | `ArrowDown` | [`Action::Next`] |
/// | `ArrowUp` | [`Action::Previous`] |
/// | `Home` | [`Action::First`] |
/// | `End` | [`Action::Last`] |
/// | `ArrowRight` | [`Action::Expand`] |
/// | `ArrowLeft` | [`Action::Collapse`] |
/// | `Enter` | [`Action::Toggle`] |
/// | `*` | [`Action::ExpandSiblings`] |
/// | `Mod+Shift+ArrowRight` | [`Action::ExpandAll`] |
/// | `Mod+Shift+ArrowLeft` | [`Action::CollapseAll`] |
/// | `Mod+C` (Ctrl, or Cmd on macOS) | [`Action::CopyValue`] |
/// | `Mod+Shift+C` | [`Action::CopyPath`] |
/// | `Mod+F` | [`Action::FocusSearch`] |
/// | `Escape` | [`Action::ClearSearch`] |
/// | `F3` | [`Action::NextMatch`] |
/// | `Shift+F3` | [`Action::PreviousMatch`] |
///
/// Enter does what a double click does, as in the tree, where it activates
/// a node: here it opens or closes an object or array. Space is left free,
/// since the viewer has nothing to select, and Shift+Arrow is left alone,
/// as other views extend a selection with it. While the search box has
/// focus, Enter and F3 step to the next match and Shift+Enter and Shift+F3
/// to the previous one, Mod+F selects its text, and Escape clears it, then
/// a second Escape leaves it. The viewer resolves these itself,
/// only while it has focus, so they never clash with other components.
/// Pass a changed keymap with [`JsonViewer::keymap`].
pub fn default_keymap() -> Keymap<Action> {
    Keymap::new()
        .bind(Chord::named(Named::ArrowDown), Action::Next)
        .bind(Chord::named(Named::ArrowUp), Action::Previous)
        .bind(Chord::named(Named::Home), Action::First)
        .bind(Chord::named(Named::End), Action::Last)
        .bind(Chord::named(Named::ArrowRight), Action::Expand)
        .bind(Chord::named(Named::ArrowLeft), Action::Collapse)
        .bind(Chord::named(Named::Enter), Action::Toggle)
        .bind(Chord::character('*'), Action::ExpandSiblings)
        .bind(
            Chord::named(Named::ArrowRight).command().shift(),
            Action::ExpandAll,
        )
        .bind(
            Chord::named(Named::ArrowLeft).command().shift(),
            Action::CollapseAll,
        )
        .bind(Chord::character('c').command(), Action::CopyValue)
        .bind(Chord::character('c').command().shift(), Action::CopyPath)
        .bind(Chord::character('f').command(), Action::FocusSearch)
        .bind(Chord::named(Named::Escape), Action::ClearSearch)
        .bind(Chord::named(Named::F3), Action::NextMatch)
        .bind(Chord::named(Named::F3).shift(), Action::PreviousMatch)
}

/// An entry of the context menu from [`menu`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MenuItem {
    CopyValue,
    CopyPath,
    ExpandAll,
    CollapseAll,
}

impl MenuItem {
    pub const ALL: [MenuItem; 4] = [
        MenuItem::CopyValue,
        MenuItem::CopyPath,
        MenuItem::ExpandAll,
        MenuItem::CollapseAll,
    ];

    /// The event the entry sends for the node the menu opened on.
    pub fn event(self, id: NodeId) -> Event {
        match self {
            MenuItem::CopyValue => Event::CopyValue(id),
            MenuItem::CopyPath => Event::CopyPath(id),
            MenuItem::ExpandAll => Event::ExpandSubtree(id),
            MenuItem::CollapseAll => Event::CollapseSubtree(id),
        }
    }
}

/// A context menu to pass to [`JsonViewer::context_menu`]: copy the value
/// or its path, and expand or collapse everything inside it. Turn the
/// chosen entry into an event with [`MenuItem::event`].
pub fn menu() -> context_menu::State<MenuItem, NodeId> {
    context_menu::State::new([
        item(MenuItem::CopyValue, "Copy value").icon(crate::lucide!(Copy)),
        item(MenuItem::CopyPath, "Copy path").icon(crate::lucide!(Route)),
        separator(),
        item(MenuItem::ExpandAll, "Expand all").icon(crate::lucide!(ChevronsUpDown)),
        item(MenuItem::CollapseAll, "Collapse all").icon(crate::lucide!(ChevronsDownUp)),
    ])
}

/// The colours of keys, values and punctuation.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Syntax {
    pub key: Color,
    /// Array indices and the `{3}` and `[12]` summaries.
    pub punctuation: Color,
    pub string: Color,
    pub number: Color,
    pub boolean: Color,
    pub null: Color,
}

/// Resolves the syntax colours from the theme: strings take the success
/// colour, numbers the warning colour and booleans the primary colour,
/// drawn semibold so they stand apart from keys. In light themes strings
/// and numbers are darkened towards the text so they stay readable on a
/// white page.
pub fn syntax(tokens: &Tokens) -> Syntax {
    let readable = |colour: Color| {
        if tokens.is_dark {
            colour
        } else {
            mix(colour, tokens.foreground, 0.25)
        }
    };
    Syntax {
        key: tokens.foreground,
        punctuation: tokens.muted_foreground,
        string: readable(tokens.success),
        number: readable(tokens.warning),
        boolean: tokens.primary,
        null: tokens.muted_foreground,
    }
}

/// The colour of a value of this kind.
pub fn value_colour(tokens: &Tokens, kind: Kind) -> Color {
    let syntax = syntax(tokens);
    match kind {
        Kind::Object | Kind::Array => syntax.punctuation,
        Kind::String => syntax.string,
        Kind::Number => syntax.number,
        Kind::Bool => syntax.boolean,
        Kind::Null => syntax.null,
    }
}

/// The font of a value of this kind: semibold for booleans, so they stand
/// apart from keys when the primary colour is close to the text colour.
pub fn value_font(kind: Kind) -> Font {
    match kind {
        Kind::Bool => theme::semibold(),
        _ => theme::font(),
    }
}

/// How a row is shown.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Status {
    /// The row the keyboard acts on.
    pub highlighted: bool,
    /// Draws the focus ring on the highlighted row.
    pub focused: bool,
    pub hovered: bool,
    /// The key or value contains the search text.
    pub matched: bool,
    /// The match the search moved to last.
    pub current: bool,
    pub disabled: bool,
}

/// The colours of a row.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RowStyle {
    pub background: Option<Color>,
    pub ring: Option<Color>,
}

/// The border around the rows, as the property grid and data table have.
pub fn frame_style(tokens: &Tokens) -> container::Style {
    container::Style {
        border: Border {
            color: tokens.border,
            width: 1.0,
            radius: radius::MD.into(),
        },
        ..container::Style::default()
    }
}

/// Resolves a row's colours. The viewer selects nothing, so the highlighted
/// row only carries a ring, and only while the viewer has focus. Search
/// matches take a tint of the warning colour, stronger on the current one.
pub fn row_style(tokens: &Tokens, status: Status) -> RowStyle {
    if status.disabled {
        return RowStyle {
            background: None,
            ring: None,
        };
    }
    let background = if status.current {
        Some(fade(tokens.warning, 0.35))
    } else if status.matched {
        Some(fade(tokens.warning, 0.15))
    } else if status.hovered {
        Some(fade(tokens.accent, 0.6))
    } else {
        None
    };
    RowStyle {
        background,
        ring: (status.highlighted && status.focused).then_some(tokens.ring),
    }
}

type OnEvent<'a, Message> = dyn Fn(Event) -> Message + 'a;
type BuildMenu<'a, Message> =
    dyn FnOnce(Keymap<context_menu::Action>) -> RowMenu<'a, NodeId, Message> + 'a;

/// A JSON viewer builder. Convert it into an [`Element`] to render.
pub struct JsonViewer<'a, Message> {
    state: &'a State,
    search_bar: bool,
    placeholder: String,
    frame: bool,
    key_width: f32,
    width: Length,
    height: Length,
    keymap: Keymap<Action>,
    menu: Option<Box<BuildMenu<'a, Message>>>,
    menu_keymap: Keymap<context_menu::Action>,
    on_event: Option<Box<OnEvent<'a, Message>>>,
}

/// Renders `state`. Without [`on_event`](JsonViewer::on_event) it renders
/// disabled.
pub fn json_viewer<Message>(state: &State) -> JsonViewer<'_, Message> {
    JsonViewer {
        state,
        search_bar: false,
        placeholder: "Search".to_owned(),
        frame: true,
        key_width: KEY_WIDTH,
        width: Length::Fill,
        height: Length::Shrink,
        keymap: default_keymap(),
        menu: None,
        menu_keymap: context_menu::default_keymap(),
        on_event: None,
    }
}

impl<Message> fmt::Debug for JsonViewer<'_, Message> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("JsonViewer")
            .field("state", self.state)
            .field("search_bar", &self.search_bar)
            .field("placeholder", &self.placeholder)
            .field("frame", &self.frame)
            .field("key_width", &self.key_width)
            .field("width", &self.width)
            .field("height", &self.height)
            .field("keymap", &self.keymap)
            .finish_non_exhaustive()
    }
}

impl<'a, Message> JsonViewer<'a, Message> {
    /// Shows a search box above the rows, with the match count, buttons
    /// for the previous and next match and a toggle that shows only
    /// matches.
    pub fn search_bar(mut self, search_bar: bool) -> Self {
        self.search_bar = search_bar;
        self
    }

    /// The search box placeholder. Defaults to "Search".
    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
        self.placeholder = placeholder.into();
        self
    }

    /// Draws a 1px rounded border around the rows, as the property grid
    /// and data table have. On by default; turn it off when the viewer
    /// already sits in a card or panel.
    pub fn frame(mut self, frame: bool) -> Self {
        self.frame = frame;
        self
    }

    /// The widest a key gets before it ends in an ellipsis. Defaults to
    /// [`KEY_WIDTH`].
    pub fn key_width(mut self, width: f32) -> Self {
        self.key_width = width;
        self
    }

    pub fn width(mut self, width: impl Into<Length>) -> Self {
        self.width = width.into();
        self
    }

    /// The height of the rows. A fixed or filling height scrolls them.
    /// Defaults to shrinking to fit them.
    pub fn height(mut self, height: impl Into<Length>) -> Self {
        self.height = height.into();
        self
    }

    /// Replaces the [`default_keymap`] the focused viewer resolves keys with.
    pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
        self.keymap = keymap;
        self
    }

    pub fn on_event(mut self, on_event: impl Fn(Event) -> Message + 'a) -> Self {
        self.on_event = Some(Box::new(on_event));
        self
    }

    /// Gives every row the context menu of `menu`, keyed by node, such as
    /// the one from [`menu()`]. It opens on a right-click or a
    /// long press, and on the highlighted row with its opening chord while
    /// the viewer has focus.
    pub fn context_menu<MenuId>(
        mut self,
        menu: &'a context_menu::State<MenuId, NodeId>,
        on_event: impl Fn(context_menu::Event<MenuId, NodeId>) -> Message + 'a,
    ) -> Self
    where
        MenuId: Copy + PartialEq + 'a,
        Message: Clone + 'a,
    {
        let on_event: Rc<dyn Fn(context_menu::Event<MenuId, NodeId>) -> Message + 'a> =
            Rc::new(on_event);
        self.menu = Some(Box::new(move |keymap| row_menu(menu, keymap, on_event)));
        self
    }

    /// Replaces the context menu's default keymap.
    pub fn context_menu_keymap(mut self, keymap: Keymap<context_menu::Action>) -> Self {
        self.menu_keymap = keymap;
        self
    }

    pub fn is_enabled(&self) -> bool {
        self.on_event.is_some()
    }
}

/// Everything a row needs from the builder.
struct Context<'a, Message> {
    state: &'a State,
    key_width: f32,
    /// The row a context menu is open on.
    menu_target: Option<NodeId>,
    on_event: Option<Rc<OnEvent<'a, Message>>>,
}

impl<'a, Message> From<JsonViewer<'a, Message>> for Element<'a, Message>
where
    Message: Clone + 'a,
{
    fn from(viewer: JsonViewer<'a, Message>) -> Self {
        let JsonViewer {
            state,
            search_bar,
            placeholder,
            frame,
            key_width,
            width,
            height,
            keymap,
            menu,
            menu_keymap,
            on_event,
        } = viewer;
        if let Some(error) = state.error() {
            return container(
                alert("Invalid JSON")
                    .variant(alert::Variant::Destructive)
                    .description(error.to_string()),
            )
            .width(width)
            .into();
        }
        let on_event: Option<Rc<OnEvent<'a, Message>>> = on_event.map(Rc::from);
        let menu = menu
            .filter(|_| on_event.is_some())
            .map(|build| Rc::new(build(menu_keymap)));
        let lines = state.visible();
        let highlight = state
            .highlighted()
            .and_then(|id| lines.iter().position(|&line| line == id));
        let count = lines.len();
        let context = Rc::new(Context {
            state,
            key_width,
            menu_target: menu.as_ref().and_then(|menu| menu.target()),
            on_event: on_event.clone(),
        });

        let build = {
            let menu = menu.clone();
            move |range: Range<usize>| -> Element<'a, Message> {
                let lines = lines.get(range).unwrap_or_default();
                column(lines.iter().map(|&id| {
                    let row = row_view(&context, id);
                    match &menu {
                        Some(menu) => menu.wrap(id, row),
                        None => row,
                    }
                }))
                .into()
            }
        };
        let body: Element<'a, Message> = if count == 0 && state.is_filtering() {
            container(
                text(format!("Nothing matches \"{}\"", state.query().trim()))
                    .size(text_size::SM)
                    .wrapping(text::Wrapping::None)
                    .style(|theme: &Theme| text::Style {
                        color: Some(Tokens::of(theme).muted_foreground),
                    }),
            )
            .padding(ROW_PADDING)
            .height(ROW_HEIGHT)
            .into()
        } else {
            rows(count, ROW_HEIGHT, build)
                .highlight(highlight)
                .height(height)
                .into()
        };
        let body: Element<'a, Message> = if frame {
            container(body)
                .padding(1)
                .width(Length::Fill)
                .height(if matches!(height, Length::Fixed(_)) {
                    Length::Shrink
                } else {
                    height
                })
                .clip(true)
                .style(|theme| frame_style(&Tokens::of(theme)))
                .into()
        } else {
            body
        };
        let mut parts = column![].spacing(space::SM).width(width);
        if search_bar {
            parts = parts.push(toolbar(state, &placeholder, on_event.clone()));
        }
        let parts = parts.push(body);

        let Some(on_event) = on_event else {
            return parts.into();
        };
        let on_focus = on_event.clone();
        scope(parts)
            .on_focus(move |focused| on_focus(Event::Focus(focused)))
            .on_key(move |key| {
                let opened = menu
                    .as_ref()
                    .zip(state.highlighted())
                    .and_then(|(menu, target)| menu.key(key, target));
                opened.or_else(|| state.key_event(&keymap, key).map(&*on_event))
            })
            .into()
    }
}

/// Focuses the search box of `state`'s viewer, in answer to
/// [`Output::FocusSearch`].
pub fn focus_search<Message>(state: &State) -> Task<Message> {
    widget::operation::focus(state.search_id().clone())
}

/// The text beside the search box: "3 of 12" for the current match of all
/// matches, "12 found" before one is current, "None" when nothing matches,
/// and empty without a search.
pub fn match_label(state: &State) -> String {
    let current = state.current.map(|index| index + 1);
    match_count_label(state.query(), state.matches().len(), current)
}

fn toolbar<'a, Message: Clone + 'a>(
    state: &'a State,
    placeholder: &str,
    on_event: Option<Rc<OnEvent<'a, Message>>>,
) -> Element<'a, Message> {
    let id = state.search_id().clone();
    let send = |event: Event| on_event.as_ref().map(|on_event| on_event(event));
    let searching = !state.matches().is_empty();
    let field = {
        let on_input = on_event
            .clone()
            .map(|on_event| move |query| on_event(Event::Search(query)));
        input(placeholder, state.query())
            .id(id.clone())
            .icon(crate::lucide!(Search))
            .size(input::Size::Sm)
            .width(Length::Fill)
            .on_input_maybe(on_input)
    };
    let field = search_keys(field, id)
        .on_clear(send(Event::Search(String::new())).filter(|_| !state.query().is_empty()))
        .on_next(send(Event::NextMatch).filter(|_| searching))
        .on_previous(send(Event::PreviousMatch).filter(|_| searching));
    let count = search_count(match_label(state));
    row![
        field,
        count,
        icon_button(crate::lucide!(ChevronUp))
            .label("Previous match")
            .size(Size::Sm)
            .on_press_maybe(send(Event::PreviousMatch).filter(|_| searching)),
        icon_button(crate::lucide!(ChevronDown))
            .label("Next match")
            .size(Size::Sm)
            .on_press_maybe(send(Event::NextMatch).filter(|_| searching)),
        icon_button(crate::lucide!(ListFilter))
            .label("Only matches")
            .size(Size::Sm)
            .pressed(state.only_matches())
            .on_press_maybe(send(Event::OnlyMatches(!state.only_matches()))),
    ]
    .spacing(space::XS)
    .align_y(Alignment::Center)
    .into()
}

/// The indentation for `depth` levels.
fn indent<'a, Message: 'a>(depth: usize) -> Element<'a, Message> {
    Space::new()
        .width(INDENT * depth as f32)
        .height(Length::Fill)
        .into()
}

fn muted<'a>(content: String, enabled: bool) -> text::Text<'a> {
    text(content)
        .size(text_size::SM)
        .wrapping(text::Wrapping::None)
        .style(move |theme: &Theme| {
            let tokens = Tokens::of(theme);
            text::Style {
                color: Some(if enabled {
                    syntax(&tokens).punctuation
                } else {
                    tokens.muted_foreground
                }),
            }
        })
}

fn row_view<'a, Message: Clone + 'a>(
    context: &Context<'a, Message>,
    id: NodeId,
) -> Element<'a, Message> {
    let state = context.state;
    let Some(item) = state.item(id) else {
        return Space::new().into();
    };
    let on_event = context.on_event.as_ref();
    let enabled = on_event.is_some();
    let expanded = state.is_expanded(id);
    let highlighted = state.highlighted() == Some(id);
    let menu_open_here = context.menu_target == Some(id);
    let status = Status {
        highlighted: ringed(context.menu_target.as_ref(), &id, highlighted),
        focused: state.is_focused() || menu_open_here,
        hovered: false,
        matched: state.is_match(id),
        current: state.current_match() == Some(id),
        disabled: !enabled,
    };

    let chevron: Element<'a, Message> = if state.has_children(id) {
        let glyph = if expanded {
            crate::lucide!(ChevronDown)
        } else {
            crate::lucide!(ChevronRight)
        };
        let icon = container(themed(glyph, ICON_SIZE, opacity(enabled), |theme| {
            Tokens::of(theme).muted_foreground
        }))
        .width(INDENT)
        .height(Length::Fill)
        .center_y(Length::Fill);
        match on_event {
            Some(on_event) => mouse_area(icon)
                .on_press(on_event(Event::Toggle(id)))
                .interaction(mouse::Interaction::Pointer)
                .into(),
            None => icon.into(),
        }
    } else {
        Space::new().width(INDENT).into()
    };

    let mut content = row![]
        .spacing(space::XS)
        .align_y(Alignment::Center)
        .height(Length::Fill);
    match &item.segment {
        Some(Segment::Key(key)) => {
            let key = ellipsis(key.as_str())
                .width(Length::Shrink)
                .colour(move |theme| {
                    let tokens = Tokens::of(theme);
                    if enabled {
                        syntax(&tokens).key
                    } else {
                        tokens.muted_foreground
                    }
                });
            content = content.push(
                row![
                    container(key).max_width(context.key_width),
                    muted(":".to_owned(), enabled)
                ]
                .align_y(Alignment::Center),
            );
        }
        Some(Segment::Index(index)) => {
            content = content.push(muted(format!("{index}:"), enabled));
        }
        None => {}
    }
    let kind = item.kind;
    let value: Element<'a, Message> = match kind {
        Kind::Object | Kind::Array => {
            let (open, close) = if kind == Kind::Object {
                ('{', '}')
            } else {
                ('[', ']')
            };
            let count = item.children.len();
            let summary = if count == 0 {
                format!("{open}{close}")
            } else {
                format!("{open}{count}{close}")
            };
            row![muted(summary, enabled), Space::new().width(Length::Fill)].into()
        }
        _ => ellipsis(item.text.as_str())
            .font(value_font(kind))
            .colour(move |theme| {
                let tokens = Tokens::of(theme);
                if enabled {
                    value_colour(&tokens, kind)
                } else {
                    tokens.muted_foreground
                }
            })
            .into(),
    };
    content = content.push(value);
    if let Some(on_event) = on_event.filter(|_| highlighted) {
        content = content.push(
            row![
                icon_button(crate::lucide!(Copy))
                    .label("Copy value")
                    .size(Size::Sm)
                    .on_press(on_event(Event::CopyValue(id))),
                icon_button(crate::lucide!(Route))
                    .label("Copy path")
                    .size(Size::Sm)
                    .on_press(on_event(Event::CopyPath(id))),
            ]
            .align_y(Alignment::Center),
        );
    }

    let body = container(row![indent(item.depth), chevron, content].height(Length::Fill))
        .padding(
            iced::Padding::ZERO
                .left(ROW_PADDING.left)
                .right(ROW_PADDING.right),
        )
        .width(Length::Fill)
        .height(ROW_HEIGHT);
    let row = pressable(body, move |theme, hovered| {
        let style = row_style(&Tokens::of(theme), Status { hovered, ..status });
        Look {
            background: style.background,
            border: Border {
                color: style.ring.unwrap_or(Color::TRANSPARENT),
                width: if style.ring.is_some() { 1.0 } else { 0.0 },
                radius: radius::SM.into(),
            },
            divider: None,
        }
    });
    let Some(on_event) = on_event.cloned() else {
        return row.into();
    };
    let toggle = state.has_children(id).then(|| on_event(Event::Toggle(id)));
    row.on_press(move |_| on_event(Event::Press(id)))
        .on_double_click(toggle)
        .into()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::theme::{dark, light};
    use serde_json::json;

    /// ```text
    /// name: "Ada"
    /// tags: [2]
    ///   0: "admin"
    ///   1: "ops"
    /// address: {2}
    ///   city: "London"
    ///   first line: null
    /// active: true
    /// age: 36
    /// ```
    fn sample() -> State {
        State::new(json!({
            "name": "Ada",
            "tags": ["admin", "ops"],
            "address": { "city": "London", "first line": null },
            "active": true,
            "age": 36
        }))
    }

    fn id(state: &State, path: &str) -> NodeId {
        (0..state.len())
            .map(NodeId)
            .find(|&id| state.path(id) == path)
            .unwrap_or_else(|| panic!("no node at {path}"))
    }

    fn key(key: Key, modifiers: Modifiers) -> keys::Event {
        keys::Event { key, modifiers }
    }

    #[test]
    fn flattens_in_document_order_with_the_members_as_top_rows() {
        let state = sample();
        assert_eq!(state.len(), 10);
        let paths: Vec<String> = state.roots().iter().map(|&id| state.path(id)).collect();
        assert_eq!(
            paths,
            ["$.name", "$.tags", "$.address", "$.active", "$.age"]
        );
        let tags = id(&state, "$.tags");
        assert_eq!(state.kind(tags), Some(Kind::Array));
        assert_eq!(state.children(tags).len(), 2);
        assert_eq!(state.parent(tags), None);
        assert_eq!(state.depth(tags), 0);
        let first = state.children(tags)[0];
        assert_eq!(state.parent(first), Some(tags));
        assert_eq!(state.depth(first), 1);
        assert_eq!(state.segment(first), Some(&Segment::Index(0)));
        assert_eq!(state.visible().len(), 5, "everything starts collapsed");
    }

    #[test]
    fn a_scalar_or_an_empty_document_is_one_row() {
        for value in [json!(42), json!("hi"), json!({}), json!([]), json!(null)] {
            let state = State::new(value.clone());
            assert_eq!(state.roots(), &[NodeId(0)], "{value}");
            assert_eq!(state.path(NodeId(0)), "$");
            assert_eq!(state.value_at(NodeId(0)), Some(&value));
        }
        assert_eq!(State::default().len(), 1);
    }

    #[test]
    fn kinds_and_containers() {
        assert_eq!(Kind::ALL.len(), 6);
        assert!(Kind::Object.is_container() && Kind::Array.is_container());
        assert!(!Kind::String.is_container());
        assert_eq!(Kind::of(&json!(1.5)), Kind::Number);
        assert_eq!(Kind::of(&json!(false)), Kind::Bool);
    }

    #[test]
    fn invalid_text_keeps_the_error_and_has_no_rows() {
        let state = State::parse("{\n  \"a\": 1,\n  \"b\": }");
        let error = state.error().expect("an error");
        assert_eq!((error.line, error.column), (3, 8));
        assert_eq!(error.message, "expected value");
        assert_eq!(error.to_string(), "expected value at line 3, column 8");
        assert!(state.is_empty());
        assert!(state.visible().is_empty());

        let valid = State::parse("[1, 2]");
        assert!(valid.error().is_none());
        assert_eq!(valid.roots().len(), 2);
    }

    #[test]
    fn paths_use_dots_for_identifiers_and_brackets_otherwise() {
        let state = State::new(json!({
            "users": [{ "name": "Ada" }, { "first name": "Grace", "$id": 2, "9lives": true }]
        }));
        assert_eq!(id(&state, "$.users[0].name").index(), 3);
        let second = state.children(id(&state, "$.users"))[1];
        let paths: Vec<String> = state
            .children(second)
            .iter()
            .map(|&id| state.path(id))
            .collect();
        assert_eq!(
            paths,
            [
                "$.users[1][\"first name\"]",
                "$.users[1].$id",
                "$.users[1][\"9lives\"]"
            ]
        );
        assert!(!is_identifier(""));
        assert!(is_identifier("_a1"));
    }

    #[test]
    fn copying_gives_pretty_json_and_the_path() {
        let mut state = sample();
        let address = id(&state, "$.address");
        assert_eq!(
            state.update(Event::CopyValue(address)),
            Some(Output::CopyValue(
                "{\n  \"city\": \"London\",\n  \"first line\": null\n}".into()
            ))
        );
        assert_eq!(state.highlighted(), Some(address));
        let city = state.children(address)[0];
        assert_eq!(
            state.update(Event::CopyValue(city)),
            Some(Output::CopyValue("\"London\"".into()))
        );
        assert_eq!(
            state.update(Event::CopyPath(city)),
            Some(Output::CopyPath("$.address.city".into()))
        );
        assert_eq!(state.update(Event::CopyValue(NodeId(999))), None);
        assert_eq!(state.update(Event::CopyPath(NodeId(999))), None);
    }

    #[test]
    fn expanding_and_collapsing() {
        let mut state = sample();
        let tags = id(&state, "$.tags");
        let name = id(&state, "$.name");
        let _ = state.update(Event::Toggle(tags));
        assert!(state.is_expanded(tags));
        assert_eq!(state.visible().len(), 7);
        let _ = state.update(Event::Expand(name));
        assert!(!state.is_expanded(name), "scalars never expand");
        let _ = state.update(Event::Toggle(tags));
        assert!(!state.is_expanded(tags));

        let _ = state.update(Event::ExpandAll);
        assert_eq!(state.visible().len(), 9);
        let _ = state.update(Event::CollapseAll);
        assert_eq!(state.visible().len(), 5);

        let empty = State::new(json!({ "a": {}, "b": [] }));
        let mut empty = empty;
        let _ = empty.update(Event::ExpandAll);
        assert!(empty.visible().iter().all(|&id| !empty.is_expanded(id)));
    }

    #[test]
    fn expand_to_depth_opens_only_shallow_containers() {
        let value = json!({ "a": { "b": { "c": { "d": 1 } } } });
        let state = State::new(value.clone()).with_depth(2);
        assert_eq!(state.visible().len(), 3, "a, b and c");
        let mut state = state;
        let _ = state.update(Event::ExpandToDepth(0));
        assert_eq!(state.visible().len(), 1);
        let _ = state.update(Event::ExpandToDepth(10));
        assert_eq!(state.visible().len(), 4);
    }

    #[test]
    fn subtrees_expand_and_collapse_together() {
        let mut state = State::new(json!({ "a": { "b": { "c": 1 } }, "d": { "e": 2 } }));
        let a = id(&state, "$.a");
        let _ = state.update(Event::ExpandSubtree(a));
        assert_eq!(state.visible().len(), 4);
        let c = id(&state, "$.a.b.c");
        let _ = state.update(Event::Press(c));
        let _ = state.update(Event::CollapseSubtree(a));
        assert_eq!(state.visible().len(), 2);
        assert_eq!(state.highlighted(), Some(a), "the highlight moves up");
        let _ = state.update(Event::Expand(a));
        assert!(!state.is_expanded(id(&state, "$.a.b")));
    }

    #[test]
    fn collapsing_moves_a_hidden_highlight_to_the_outermost_closed_node() {
        let mut state = State::new(json!({ "a": { "b": { "c": 1 } } })).with_depth(5);
        let c = id(&state, "$.a.b.c");
        let _ = state.update(Event::Press(c));
        let _ = state.update(Event::CollapseAll);
        assert_eq!(state.highlighted(), Some(id(&state, "$.a")));
    }

    #[test]
    fn keyboard_navigation() {
        let mut state = sample();
        let _ = state.update(Event::Focus(true));
        assert!(state.is_focused());
        assert_eq!(state.highlighted(), Some(id(&state, "$.name")));
        let _ = state.update(Event::Next);
        let tags = id(&state, "$.tags");
        assert_eq!(state.highlighted(), Some(tags));
        let _ = state.update(Event::ExpandOrEnter);
        assert!(state.is_expanded(tags));
        let _ = state.update(Event::ExpandOrEnter);
        assert_eq!(state.highlighted(), Some(id(&state, "$.tags[0]")));
        let _ = state.update(Event::CollapseOrLeave);
        assert_eq!(state.highlighted(), Some(tags), "leaves to the parent");
        let _ = state.update(Event::CollapseOrLeave);
        assert!(!state.is_expanded(tags));
        let _ = state.update(Event::Last);
        assert_eq!(state.highlighted(), Some(id(&state, "$.age")));
        let _ = state.update(Event::Next);
        assert_eq!(state.highlighted(), Some(id(&state, "$.age")), "stays");
        let _ = state.update(Event::First);
        let _ = state.update(Event::Previous);
        assert_eq!(state.highlighted(), Some(id(&state, "$.name")));
        let _ = state.update(Event::CollapseOrLeave);
        assert_eq!(state.highlighted(), Some(id(&state, "$.name")), "no parent");

        let _ = state.update(Event::Press(tags));
        let _ = state.update(Event::ToggleHighlighted);
        assert!(state.is_expanded(tags));
        let _ = state.update(Event::ExpandSiblings);
        assert!(state.is_expanded(id(&state, "$.address")));
        let _ = state.update(Event::Focus(false));
        assert!(!state.is_focused());
    }

    #[test]
    fn search_finds_keys_and_values_and_expands_their_parents() {
        let mut state = sample();
        let _ = state.update(Event::Search("LONDON".into()));
        let city = id(&state, "$.address.city");
        assert_eq!(state.matches(), &[city]);
        assert!(state.is_expanded(id(&state, "$.address")));
        assert_eq!(state.highlighted(), Some(city));
        assert_eq!(state.current_match(), Some(city));
        assert_eq!(match_label(&state), "1 of 1");

        let _ = state.update(Event::Search("a".into()));
        let found: Vec<String> = state.matches().iter().map(|&id| state.path(id)).collect();
        assert_eq!(
            found,
            [
                "$.name",
                "$.tags",
                "$.tags[0]",
                "$.address",
                "$.active",
                "$.age"
            ]
        );
        let _ = state.update(Event::Search("1".into()));
        assert!(state.matches().is_empty(), "indices are not searched");
        assert_eq!(match_label(&state), "None");
        let _ = state.update(Event::Search("  ".into()));
        assert!(state.matches().is_empty());
        assert_eq!(match_label(&state), "");
        let _ = state.update(Event::Search("36".into()));
        assert_eq!(state.matches(), &[id(&state, "$.age")], "numbers as text");
    }

    #[test]
    fn typing_jumps_to_the_nearest_match_at_or_after_the_highlight() {
        let mut state = sample().with_depth(1);
        let address = id(&state, "$.address");
        let _ = state.update(Event::Press(address));
        let _ = state.update(Event::Search("a".into()));
        assert_eq!(state.current_match(), Some(address), "at the highlight");
        let _ = state.update(Event::Search("ag".into()));
        assert_eq!(state.current_match(), Some(id(&state, "$.age")), "after it");
        assert_eq!(match_label(&state), "2 of 2", "tags comes first");
        let _ = state.update(Event::Search("name".into()));
        assert_eq!(
            state.current_match(),
            Some(id(&state, "$.name")),
            "the last before it when nothing follows"
        );
    }

    #[test]
    fn matches_cycle_both_ways() {
        let mut state = sample();
        let _ = state.update(Event::NextMatch);
        assert_eq!(state.current_match(), None, "nothing to cycle");
        let _ = state.update(Event::Search("ad".into()));
        let matches = state.matches().to_vec();
        assert_eq!(matches.len(), 3);
        let _ = state.update(Event::NextMatch);
        assert_eq!(state.current_match(), Some(matches[1]));
        assert_eq!(state.highlighted(), Some(matches[1]));
        let _ = state.update(Event::NextMatch);
        let _ = state.update(Event::NextMatch);
        assert_eq!(state.current_match(), Some(matches[0]), "wraps");
        let _ = state.update(Event::PreviousMatch);
        assert_eq!(state.current_match(), Some(matches[2]), "wraps back");
        assert_eq!(match_label(&state), "3 of 3");
    }

    #[test]
    fn the_filter_shows_matches_their_parents_and_their_insides() {
        let mut state = State::new(json!({
            "users": [{ "name": "Ada", "role": "admin" }, { "name": "Grace" }],
            "meta": { "count": 2 }
        }))
        .with_only_matches(true);
        assert!(state.only_matches() && !state.is_filtering());
        let _ = state.update(Event::Search("grace".into()));
        assert!(state.is_filtering());
        let shown: Vec<String> = state.visible().iter().map(|&id| state.path(id)).collect();
        assert_eq!(shown, ["$.users", "$.users[1]", "$.users[1].name"]);

        let _ = state.update(Event::Search("users".into()));
        let _ = state.update(Event::Expand(id(&state, "$.users")));
        let shown: Vec<String> = state.visible().iter().map(|&id| state.path(id)).collect();
        assert_eq!(
            shown,
            ["$.users", "$.users[0]", "$.users[1]", "$.users[1].name"],
            "a match shows what is inside"
        );
        let _ = state.update(Event::OnlyMatches(false));
        assert_eq!(state.visible().len(), 5);
        let _ = state.update(Event::Search("nothing".into()));
        let _ = state.update(Event::OnlyMatches(true));
        assert!(state.visible().is_empty());
    }

    #[test]
    fn a_large_document_flattens_and_searches_quickly() {
        let users: Vec<Value> = (0..2_000)
            .map(|index| json!({ "id": index, "name": format!("user {index}"), "active": index % 2 == 0 }))
            .collect();
        let started = std::time::Instant::now();
        let mut state = State::new(json!({ "users": users }));
        assert_eq!(state.len(), 1 + 1 + 2_000 * 4);
        let _ = state.update(Event::ExpandAll);
        assert_eq!(state.visible().len(), 1 + 2_000 * 4);
        let _ = state.update(Event::Search("user 1999".into()));
        assert_eq!(state.matches().len(), 1);
        let _ = state.update(Event::Last);
        assert!(started.elapsed().as_secs() < 5, "{:?}", started.elapsed());
    }

    #[test]
    fn deeply_nested_values_are_fine() {
        let mut value = json!(1);
        for _ in 0..100 {
            value = json!([value]);
        }
        let mut state = State::new(value);
        let _ = state.update(Event::ExpandAll);
        assert_eq!(state.visible().len(), 100);
        let last = *state.visible().last().expect("a row");
        assert_eq!(state.path(last).matches('[').count(), 100);
        assert_eq!(
            state.update(Event::CopyValue(last)),
            Some(Output::CopyValue("1".into()))
        );
    }

    #[test]
    fn strings_are_shown_escaped_on_one_line() {
        let state = State::new(json!({ "note": "two\nlines \"quoted\"" }));
        let note = state.roots()[0];
        assert_eq!(
            state.item(note).map(|item| item.text.as_str()),
            Some("\"two\\nlines \\\"quoted\\\"\"")
        );
    }

    #[test]
    fn default_keymap_covers_every_action() {
        let keymap = default_keymap();
        let press = |chord: &str| {
            let chord: Chord = chord.parse().ok()?;
            keymap.resolve(chord.key(), chord.modifiers())
        };
        assert_eq!(press("ArrowDown"), Some(Action::Next));
        assert_eq!(press("ArrowUp"), Some(Action::Previous));
        assert_eq!(press("Home"), Some(Action::First));
        assert_eq!(press("End"), Some(Action::Last));
        assert_eq!(press("ArrowRight"), Some(Action::Expand));
        assert_eq!(press("ArrowLeft"), Some(Action::Collapse));
        assert_eq!(press("Enter"), Some(Action::Toggle));
        assert_eq!(press("Space"), None, "left free, as nothing is selected");
        assert_eq!(press("*"), Some(Action::ExpandSiblings));
        assert_eq!(press("Mod+Shift+ArrowRight"), Some(Action::ExpandAll));
        assert_eq!(press("Mod+Shift+ArrowLeft"), Some(Action::CollapseAll));
        assert_eq!(
            press("Shift+ArrowRight"),
            None,
            "Shift+Arrow extends a selection elsewhere"
        );
        assert_eq!(press("Shift+ArrowLeft"), None);
        assert_eq!(press("Mod+C"), Some(Action::CopyValue));
        assert_eq!(press("Mod+Shift+C"), Some(Action::CopyPath));
        assert_eq!(press("Mod+F"), Some(Action::FocusSearch));
        assert_eq!(press("Escape"), Some(Action::ClearSearch));
        assert_eq!(press("F3"), Some(Action::NextMatch));
        assert_eq!(press("Shift+F3"), Some(Action::PreviousMatch));
        for action in <Action as keys::Action>::ALL {
            assert!(!keymap.chords(action).is_empty(), "{action:?}");
            assert!(keys::Action::description(*action).ends_with('.'));
        }
        assert_eq!(Keymap::<Action>::defaults(), keymap);
    }

    #[test]
    fn keymap_overrides_and_unbinding() {
        let keymap = default_keymap()
            .unbind(&Chord::character('*'))
            .bind(Chord::character('l'), Action::Expand);
        let mut state = sample();
        let _ = state.update(Event::First);
        assert!(
            state
                .key_event(&keymap, &key(Key::Character("*".into()), Modifiers::SHIFT))
                .is_none()
        );
        assert_eq!(
            state.key_event(
                &keymap,
                &key(Key::Character("l".into()), Modifiers::empty())
            ),
            Some(Event::ExpandOrEnter)
        );
        assert!(default_keymap().clear().is_empty());
    }

    #[test]
    fn key_events_resolve_shifted_symbols_and_copy_chords() {
        let keymap = default_keymap();
        let mut state = sample();
        let _ = state.update(Event::First);
        let name = id(&state, "$.name");
        assert_eq!(
            state.key_event(&keymap, &key(Key::Character("*".into()), Modifiers::SHIFT)),
            Some(Event::ExpandSiblings)
        );
        assert_eq!(
            state.key_event(
                &keymap,
                &key(Key::Character("c".into()), Modifiers::COMMAND)
            ),
            Some(Event::CopyValue(name))
        );
        assert_eq!(
            state.key_event(
                &keymap,
                &key(
                    Key::Character("C".into()),
                    Modifiers::COMMAND | Modifiers::SHIFT
                )
            ),
            Some(Event::CopyPath(name))
        );
        assert!(
            state
                .key_event(
                    &keymap,
                    &key(Key::Character("x".into()), Modifiers::empty())
                )
                .is_none()
        );
    }

    #[test]
    fn actions_map_to_events_only_when_they_apply() {
        let mut state = sample();
        assert_eq!(Action::Next.event(&state), Some(Event::Next));
        assert_eq!(Action::Expand.event(&state), None, "nothing highlighted");
        assert_eq!(Action::CopyValue.event(&state), None);
        assert_eq!(Action::NextMatch.event(&state), None, "no search");
        assert_eq!(Action::FocusSearch.event(&state), Some(Event::FocusSearch));
        assert_eq!(Action::ClearSearch.event(&state), None, "no search");
        assert_eq!(Action::ExpandAll.event(&state), Some(Event::ExpandAll));
        assert_eq!(Action::CollapseAll.event(&state), Some(Event::CollapseAll));
        let _ = state.update(Event::First);
        assert_eq!(Action::Toggle.event(&state), None, "a scalar");
        let _ = state.update(Event::Next);
        assert_eq!(Action::Toggle.event(&state), Some(Event::ToggleHighlighted));
        assert_eq!(Action::Collapse.event(&state), Some(Event::CollapseOrLeave));
        assert_eq!(
            Action::ExpandSiblings.event(&state),
            Some(Event::ExpandSiblings)
        );
        let tags = id(&state, "$.tags");
        assert_eq!(Action::CopyPath.event(&state), Some(Event::CopyPath(tags)));
        let _ = state.update(Event::Search("o".into()));
        assert_eq!(
            Action::ClearSearch.event(&state),
            Some(Event::Search(String::new()))
        );
        assert_eq!(Action::NextMatch.event(&state), Some(Event::NextMatch));
        assert_eq!(
            Action::PreviousMatch.event(&state),
            Some(Event::PreviousMatch)
        );
        assert_eq!(state.update(Event::FocusSearch), Some(Output::FocusSearch));
    }

    #[test]
    fn menu_items_map_to_events() {
        let node = NodeId(3);
        assert_eq!(MenuItem::ALL.len(), 4);
        assert_eq!(MenuItem::CopyValue.event(node), Event::CopyValue(node));
        assert_eq!(MenuItem::CopyPath.event(node), Event::CopyPath(node));
        assert_eq!(MenuItem::ExpandAll.event(node), Event::ExpandSubtree(node));
        assert_eq!(
            MenuItem::CollapseAll.event(node),
            Event::CollapseSubtree(node)
        );
        assert!(!menu().is_open());
    }

    #[test]
    fn syntax_colours_come_from_tokens_in_both_themes() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            let syntax = syntax(&tokens);
            assert_eq!(syntax.key, tokens.foreground);
            assert_eq!(syntax.punctuation, tokens.muted_foreground);
            assert_eq!(syntax.null, tokens.muted_foreground);
            assert_ne!(syntax.string, tokens.foreground);
            assert_ne!(syntax.number, tokens.foreground);
            let colours = [syntax.string, syntax.number, syntax.boolean];
            for (index, colour) in colours.iter().enumerate() {
                assert!(colours.iter().skip(index + 1).all(|other| other != colour));
            }
            if tokens.is_dark {
                assert_eq!(syntax.string, tokens.success);
            } else {
                assert_eq!(syntax.string, mix(tokens.success, tokens.foreground, 0.25));
            }
            assert_eq!(value_colour(&tokens, Kind::Number), syntax.number);
            assert_eq!(value_colour(&tokens, Kind::Bool), syntax.boolean);
            assert_eq!(value_colour(&tokens, Kind::Null), syntax.null);
            assert_eq!(value_colour(&tokens, Kind::Object), syntax.punctuation);
            assert_eq!(value_colour(&tokens, Kind::Array), syntax.punctuation);
            assert_eq!(value_colour(&tokens, Kind::String), syntax.string);
        }
    }

    /// The WCAG contrast ratio of two opaque colours.
    fn contrast(a: Color, b: Color) -> f32 {
        let channel = |c: f32| {
            if c <= 0.039_28 {
                c / 12.92
            } else {
                ((c + 0.055) / 1.055).powf(2.4)
            }
        };
        let luminance =
            |c: Color| 0.2126 * channel(c.r) + 0.7152 * channel(c.g) + 0.0722 * channel(c.b);
        let (x, y) = (luminance(a), luminance(b));
        (x.max(y) + 0.05) / (x.min(y) + 0.05)
    }

    #[test]
    fn booleans_are_calm_and_readable_in_both_themes() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            let boolean = value_colour(&tokens, Kind::Bool);
            assert_eq!(boolean, tokens.primary);
            assert_ne!(boolean, tokens.destructive, "true is not an error");
            assert_ne!(boolean, mix(tokens.destructive, tokens.foreground, 0.25));
            let ratio = contrast(boolean, tokens.background);
            assert!(ratio >= 4.5, "dark: {}, ratio {ratio}", tokens.is_dark);
            for kind in [Kind::String, Kind::Number] {
                let ratio = contrast(value_colour(&tokens, kind), tokens.background);
                assert!(ratio >= 3.0, "{kind:?} dark: {}, {ratio}", tokens.is_dark);
            }
        }
        assert_eq!(value_font(Kind::Bool), theme::semibold());
        assert_eq!(value_font(Kind::String), theme::font());
    }

    #[test]
    fn the_frame_is_a_rounded_border() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            let style = frame_style(&tokens);
            assert_eq!(style.border.color, tokens.border);
            assert_eq!(style.border.width, 1.0);
            assert!(style.background.is_none());
        }
    }

    #[test]
    fn rows_in_every_status_and_theme() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            let idle = row_style(&tokens, Status::default());
            assert_eq!(
                idle,
                RowStyle {
                    background: None,
                    ring: None
                }
            );

            let hovered = row_style(
                &tokens,
                Status {
                    hovered: true,
                    ..Status::default()
                },
            );
            assert!(
                hovered
                    .background
                    .is_some_and(|colour| colour.a < tokens.accent.a)
            );

            let matched = row_style(
                &tokens,
                Status {
                    matched: true,
                    ..Status::default()
                },
            );
            let current = row_style(
                &tokens,
                Status {
                    matched: true,
                    current: true,
                    ..Status::default()
                },
            );
            let alpha = |style: RowStyle| style.background.map_or(0.0, |colour| colour.a);
            assert!(alpha(current) > alpha(matched) && alpha(matched) > 0.0);

            let highlighted = row_style(
                &tokens,
                Status {
                    highlighted: true,
                    matched: true,
                    ..Status::default()
                },
            );
            assert_eq!(highlighted.background, matched.background, "no fill");
            assert_eq!(highlighted.ring, None, "the ring needs focus");
            let focused = row_style(
                &tokens,
                Status {
                    highlighted: true,
                    focused: true,
                    ..Status::default()
                },
            );
            assert_eq!(focused.background, None);
            assert_eq!(focused.ring, Some(tokens.ring));
            let current_focused = row_style(
                &tokens,
                Status {
                    highlighted: true,
                    focused: true,
                    matched: true,
                    current: true,
                    ..Status::default()
                },
            );
            assert_eq!(
                current_focused.background, current.background,
                "the current match keeps its tint under the ring"
            );

            let disabled = row_style(
                &tokens,
                Status {
                    highlighted: true,
                    focused: true,
                    hovered: true,
                    matched: true,
                    current: true,
                    disabled: true,
                },
            );
            assert_eq!(
                disabled,
                RowStyle {
                    background: None,
                    ring: None
                }
            );
        }
    }

    #[test]
    fn builder_defaults_and_options() {
        let state = sample();
        let view: JsonViewer<'_, ()> = json_viewer(&state);
        assert!(!view.search_bar && !view.is_enabled());
        assert!(view.frame);
        assert_eq!(view.placeholder, "Search");
        assert_eq!((view.width, view.height), (Length::Fill, Length::Shrink));
        assert_eq!(view.key_width, KEY_WIDTH);
        assert_eq!(view.keymap, default_keymap());
        let view = view
            .search_bar(true)
            .placeholder("Find")
            .frame(false)
            .key_width(120.0)
            .width(300)
            .height(200)
            .keymap(Keymap::new())
            .context_menu_keymap(Keymap::new())
            .on_event(|_| ());
        assert!(view.search_bar && view.is_enabled() && !view.frame);
        assert_eq!(view.placeholder, "Find");
        assert_eq!(state.search_id(), &SEARCH);
        let other = sample().with_search_id("other");
        assert_eq!(other.search_id(), &widget::Id::new("other"));
        assert_eq!(view.key_width, 120.0);
        assert_eq!(view.width, Length::Fixed(300.0));
        assert!(view.keymap.is_empty() && view.menu_keymap.is_empty());
        assert!(format!("{view:?}").starts_with("JsonViewer"));
    }
}