flower-core 0.4.0

Frontend-neutral structural editing model for config files, over fig.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
//! The frontend-neutral editor model and its structural operations.
//!
//! `Model` is generic over a [`Backend`]: it builds path-addressed [`EditOp`]s,
//! applies them through the backend, and re-derives its view from
//! [`Backend::to_value`] after each change. It owns no editor, no format, no
//! filesystem, and no terminal — the backend owns the document; the embedder
//! owns file I/O and rendering.

use std::collections::{HashMap, HashSet};

use anyhow::Result;
use fig::Value;

use crate::backend::{Backend, EditOp};
use crate::page::{self, InlineBudget, Page, PageItem};
use crate::schema::{FieldRule, Schema};
use crate::tree::{self, Row, Seg};
use fig_schema::{Issue, SegPat, Validation};

/// Which projection the frontend is navigating: the whole-document
/// [`tree`](crate::tree), or one [`page`](crate::page) at a time.
///
/// The document is unaffected — both are views over the same `Value`, and every
/// edit is path-addressed, so switching mid-session changes what you can see and
/// nothing about what you can do.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ViewMode {
    /// Every visible node at once, indented by depth. Best when the whole
    /// document fits on a screen and you want to read it as a document.
    #[default]
    Tree,
    /// One container at a time, pushed and popped. Best when it doesn't.
    Pages,
}

/// Interaction mode: normal navigation, or editing a scalar's text.
pub enum Mode {
    Normal,
    Editing {
        buffer: String,
        /// The scalar being edited. Held here rather than re-read from the
        /// selection on commit, so an edit belongs to a *node* and not to
        /// whichever list the cursor happens to be in — the two projections
        /// index differently, and a commit must not care which one opened it.
        path: Vec<Seg>,
    },
}

pub struct Model<B> {
    backend: B,

    /// Derived view state, rebuilt from `backend.to_value()` after every edit.
    value: Value,
    pub rows: Vec<Row>,
    collapsed: HashSet<Vec<Seg>>,
    /// Top-level mapping keys to hide from the row projection (but keep in the
    /// document). Empty for a standalone config; a prov/diaryx embedder passes the
    /// managed-key set so those fields stay lossless and out of view.
    hidden: HashSet<String>,
    /// Top-level mapping keys the *workspace* maintains: shown, but not editable.
    ///
    /// The complement of [`hidden`](Self::hidden), for the other kind of managed
    /// field. A hidden key is edited through some other affordance (a title bar,
    /// a link view) and would only clutter the list; a derived key — a recomputed
    /// timestamp, a content hash — has no other affordance because *nothing*
    /// edits it by hand: the workspace overwrites it on the next write. Hiding
    /// those two alike leaves a user wondering where a field they can see in the
    /// file went, so a derived key keeps its row and declines edits instead.
    derived: HashSet<String>,
    /// Top-level mapping keys the page projection lists *below* the rest — a
    /// page's "advanced" section (see [`page::PageItem::demoted`]).
    ///
    /// The third answer to "who edits this field?", after `hidden` (something
    /// else does, and its row would only clutter) and `derived` (nothing does).
    /// A demoted key is edited here like any other; it is just not what the
    /// reader came for. Relations, identity, a title the title bar owns: real
    /// fields, worth showing, worth showing last.
    ///
    /// Holds the union with [`derived`](Self::derived), maintained by
    /// [`set_demoted`](Self::set_demoted) — a key nothing can meaningfully edit
    /// is the clearest case there is for sinking it below the ones you can.
    demoted: HashSet<String>,
    /// The schema governing this document, if any — from the backend
    /// ([`Backend::schema`]) or injected by the embedder ([`Model::set_schema`]).
    /// Drives type-directed parsing and commit-time value validation; absent, the
    /// model behaves exactly as before.
    schema: Option<Schema>,

    /// The selected row of the **tree** projection — an index into
    /// [`rows`](Self::rows), and meaningless against a page.
    ///
    /// Private, and the one piece of cursor state that is. A row index only says
    /// what it means in the projection it was read from, and a public field
    /// cannot check which projection a caller is in — so writing it goes through
    /// [`select_row`](Self::select_row), which can.
    selected: usize,
    pub mode: Mode,
    /// The last thing that happened worth saying out loud — almost always a
    /// refusal (`rejected: ...`, `only mapping keys can be renamed`).
    ///
    /// Empty until something happens. A frontend draws this in whatever it uses
    /// for a status line, and an empty string is what lets it draw *nothing*:
    /// a bar that opens holding a word nobody asked for teaches the reader to
    /// stop reading it, which is the one thing a refusal channel cannot afford.
    pub status: String,
    pub dirty: bool,

    // ── page view ─────────────────────────────────────────────────────────
    /// Which projection is being navigated. Both are kept live: the model has no
    /// idea how much width the frontend has, and rebuilding the unused one costs
    /// a walk of a tree that was just rebuilt anyway.
    view: ViewMode,
    /// How much of a container's subtree the page projection inlines rather
    /// than drills ([`page::InlineBudget`]). The default is the settings-menu
    /// rule; an embedder that knows its room raises it
    /// ([`set_inline_budget`](Self::set_inline_budget)).
    inline_budget: InlineBudget,
    /// The container the page view is currently listing. Empty is the root.
    focus: Vec<Seg>,
    /// The page at [`focus`](Self::focus).
    page: Page,
    /// The root's page. Kept for the "is there anything to navigate at all?"
    /// question ([`pages_would_degenerate`](Self::pages_would_degenerate)), which
    /// is about the document rather than about where you are in it.
    root_page: Page,
    /// The page one level out from [`focus`](Self::focus) — the list you were
    /// looking at when you opened the current one.
    ///
    /// A two-pane frontend shows this on the left, so the pair of panes is a
    /// window sliding along the lineage rather than a fixed sidebar: the left is
    /// always the page the right came out of, at every depth.
    parent_page: Page,
    /// The selected item on [`page`](Self::page).
    page_selected: usize,
    /// Where the cursor was on each page we have left, so popping back restores
    /// it rather than dumping you at the top.
    ///
    /// Only a fallback: coming back normally re-finds the child you drilled into,
    /// which survives edits that shift indices. This is what answers when that
    /// child is *gone* — you opened a key and deleted it — and the cursor would
    /// otherwise have nothing to return to.
    page_memory: HashMap<Vec<Seg>, usize>,
}

impl<B: Backend> Model<B> {
    /// Build a model over `backend`.
    pub fn new(backend: B) -> Result<Self> {
        Self::with_hidden(backend, Vec::new())
    }

    /// Build a model that hides the given **top-level** mapping keys from the row
    /// projection while keeping them in the document (see
    /// [`tree::build_rows`](crate::tree::build_rows)). For an embedder whose
    /// format reserves some top-level keys (prov/diaryx-managed frontmatter).
    pub fn with_hidden(backend: B, hidden: Vec<String>) -> Result<Self> {
        Self::with_managed(backend, hidden, Vec::new())
    }

    /// Build a model over `backend` distinguishing the two kinds of managed key:
    /// `hidden` ones produce no row (edited through another affordance), while
    /// `derived` ones keep their row but decline every edit (the workspace
    /// maintains them — see [`derived`](Self::derived)).
    ///
    /// A key in both is hidden: no row means nothing to mark read-only.
    pub fn with_managed(backend: B, hidden: Vec<String>, derived: Vec<String>) -> Result<Self> {
        Self::with_collapsed(backend, hidden, derived, Vec::new())
    }

    /// Build a model whose containers at `collapsed` arrive **shut**, before the
    /// first row list is ever built.
    ///
    /// A document can have one field nobody reads as a list: an index document's
    /// `contents` is one row per child — ninety-five of them in a year index,
    /// ahead of the four fields anyone types by hand. Such a section wants to open
    /// as a summary, not a wall you scroll past. Toggling it afterwards through
    /// [`activate`](Self::activate) would work, but that is the *interactive*
    /// door: it moves the selection and rebuilds the row list once per container.
    /// Seeding the set here costs neither — the paths are in place before
    /// `reload`, so the opening frame is already correct.
    ///
    /// A path that names a scalar (or nothing at all) is inert rather than an
    /// error, so a caller can name the keys it *wants* collapsed without first
    /// checking which of them turned out to be containers.
    pub fn with_collapsed(
        backend: B,
        hidden: Vec<String>,
        derived: Vec<String>,
        collapsed: Vec<Vec<Seg>>,
    ) -> Result<Self> {
        // The backend supplies the schema when it knows one (a prov backend);
        // otherwise it stays `None` until an embedder injects one.
        let schema = backend.schema();
        let mut model = Model {
            backend,
            value: Value::Null,
            rows: Vec::new(),
            collapsed: collapsed.into_iter().collect(),
            hidden: hidden.into_iter().collect(),
            // Every derived key starts demoted; `set_demoted` adds the
            // embedder's own to that floor rather than replacing it.
            demoted: derived.iter().cloned().collect(),
            derived: derived.into_iter().collect(),
            schema,
            selected: 0,
            mode: Mode::Normal,
            // Nothing has happened yet, so there is nothing to report. See
            // `status`.
            status: String::new(),
            dirty: false,
            view: ViewMode::default(),
            inline_budget: InlineBudget::default(),
            focus: Vec::new(),
            page: Page::default(),
            root_page: Page::default(),
            parent_page: Page::default(),
            page_selected: 0,
            page_memory: HashMap::new(),
        };
        model.reload()?;
        Ok(model)
    }

    /// Name the top-level keys the page projection sinks below the rest.
    ///
    /// Out-of-band like [`set_schema`](Self::set_schema), and for the same
    /// reason: it is presentation the *embedder* knows and the document does
    /// not. A diaryx host knows `part_of` is drawn by the sidebar and `id` by
    /// nothing at all; the fig-backed model reading the same frontmatter has no
    /// way to tell either from a field somebody typed.
    ///
    /// Adds to the derived keys already demoted rather than replacing them, so a
    /// caller names only what the constructor did not. Rebuilds the pages, so
    /// the next [`page`](Self::page) already reflects it.
    ///
    /// Root keys, matched exactly. A path is demoted when its *first* segment is
    /// one of these, so naming a container demotes everything under it.
    pub fn set_demoted(&mut self, keys: Vec<String>) {
        self.demoted.extend(keys);
        self.rebuild_pages();
    }

    /// Set how much of a container's subtree the page projection inlines rather
    /// than drills.
    ///
    /// Out-of-band like [`set_demoted`](Self::set_demoted), and for the same
    /// reason: the right amount is a fact about the *room* the pages are drawn
    /// in — a frontmatter panel wants the whole document on one page, a narrow
    /// pane over a deep config wants a page per level — and only the embedder
    /// knows which it is. Rebuilds the pages, so the next
    /// [`page`](Self::page) already reflects it.
    ///
    /// The cursor stays on the row it was on, by path rather than by index — a
    /// budget is the one setting that changes how many rows a page has, so the
    /// index under the cursor is exactly what it invalidates. Raising the budget
    /// far enough turns row three of a list into the third field of its first
    /// entry, and a reader who resized a window did not ask to be moved.
    pub fn set_inline_budget(&mut self, budget: InlineBudget) {
        let was_on = self.page_item().map(|i| i.path.clone());
        self.inline_budget = budget;
        self.rebuild_pages();
        if let Some(path) = was_on
            && let Some(i) = self.page.position_of(&path)
        {
            self.page_selected = i;
        }
    }

    /// The inline budget the page projection is currently built with.
    pub fn inline_budget(&self) -> InlineBudget {
        self.inline_budget
    }

    /// Set the inline budget from the room a page actually has
    /// ([`InlineBudget::fitting`]) — `room` being how many rows a frontend can
    /// draw items into, once its own chrome has taken what it needs.
    ///
    /// [`set_inline_budget`](Self::set_inline_budget) is the embedder deciding;
    /// this is the embedder *measuring*, which is the same decision made against
    /// the one fact that turns out to settle it. A frontend that can be resized
    /// calls this whenever the room changes, which is cheap to do every frame:
    /// the pages are rebuilt only when the answer moves.
    pub fn fit_to_room(&mut self, room: usize) {
        let budget = InlineBudget::fitting(&self.value, room);
        if budget != self.inline_budget {
            self.set_inline_budget(budget);
        }
    }

    /// Open the document at the first page that says something.
    ///
    /// A document whose root holds one container — `{repo: [...]}`, and every
    /// file that is one list under one key — has a root page with a single drill
    /// row on it, naming the thing you are obviously about to open. That is the
    /// same page [`PageItem::descend_to`] exists to skip, arrived at from
    /// outside rather than from a row, and the reasons match: it costs a
    /// navigation step to be told the name of the file you just opened.
    ///
    /// Called once, by the frontend, after the budget is set — it is a decision
    /// about where to *start*, not a property of the projection, and re-running
    /// it on every rebuild would take the root page away from a reader who had
    /// pressed `h` to reach it. Nothing is lost either way: the root page is one
    /// step out, and the row's own ops are the ops of the container this lands
    /// in.
    pub fn enter_document(&mut self) {
        while self.page.items.len() == 1 && self.page.items[0].is_drill() {
            self.focus = self.page.items[0].descend_to.clone();
            self.page_selected = 0;
            self.rebuild_pages();
        }
    }

    /// Whether the node at `path` sits under a demoted top-level key — the
    /// page projection's own [`is_derived`](Self::is_derived).
    pub fn is_demoted(&self, path: &[Seg]) -> bool {
        matches!(path.first(), Some(Seg::Key(k)) if self.demoted.contains(k))
    }

    /// Inject a schema out-of-band — the embedder precedent, mirroring
    /// [`with_hidden`](Self::with_hidden). For a host whose backend does not
    /// supply one but that *knows* the governing schema (a diaryx host feeding a
    /// fig-backed frontmatter block plus its resolved workspace config).
    pub fn set_schema(&mut self, schema: Schema) {
        self.schema = Some(schema);
    }

    /// The schema governing the document, if any.
    pub fn schema(&self) -> Option<&Schema> {
        self.schema.as_ref()
    }

    /// The schema rule governing the node at `path`, if any — for a frontend
    /// deciding a widget (a picker for an enum field) or presentation.
    pub fn rule_at(&self, path: &[Seg]) -> Option<&FieldRule> {
        self.schema.as_ref().and_then(|s| s.rule_for(path))
    }

    /// The kind of the document root, for a frontend deciding how to add a
    /// top-level entry: `"map"`, `"seq"`, or `"scalar"`.
    pub fn root_kind(&self) -> &'static str {
        match self.value {
            Value::Map(_) => "map",
            Value::Seq(_) => "seq",
            _ => "scalar",
        }
    }

    /// How many of the hidden top-level keys are actually present in the document
    /// — for a "N managed fields" affordance.
    pub fn hidden_present(&self) -> usize {
        match &self.value {
            Value::Map(entries) => entries
                .iter()
                .filter(|(k, _)| matches!(k, Value::Str(s) if self.hidden.contains(s)))
                .count(),
            _ => 0,
        }
    }

    /// Whether the node at `path` sits under a workspace-maintained (derived)
    /// top-level key — for a frontend rendering it read-only rather than as an
    /// editable control. Edits to it are declined at the commit funnel regardless.
    pub fn is_derived(&self, path: &[Seg]) -> bool {
        matches!(path.first(), Some(Seg::Key(k)) if self.derived.contains(k))
    }

    /// The schema-declared top-level fields the document does **not** yet carry
    /// — what an "add field" affordance offers, so a declared field is reachable
    /// before it exists.
    ///
    /// Rows are projected from the *document*
    /// ([`build_rows`](crate::tree::build_rows)), so a field the schema declares
    /// but the document omits has no row and is otherwise unreachable: the user
    /// would have to know the key and type it exactly. This closes that gap —
    /// it is the schema's half of the row list, and the reason a declared type
    /// is worth writing down for a field that is empty.
    ///
    /// Only a rule addressing exactly one top-level key names an addable field:
    /// an each-item or subtree rule governs *within* a field rather than naming
    /// one. Hidden (managed) keys are never offered — the embedder reserves
    /// those. Order follows the schema's own rule order, so a caller can present
    /// them as declared.
    pub fn addable_fields(&self) -> Vec<&FieldRule> {
        let Some(schema) = &self.schema else {
            return Vec::new();
        };
        // Only a map root can take a top-level key at all.
        let Value::Map(entries) = &self.value else {
            return Vec::new();
        };
        let present: HashSet<&str> = entries
            .iter()
            .filter_map(|(k, _)| match k {
                Value::Str(s) => Some(s.as_str()),
                _ => None,
            })
            .collect();
        let mut seen = HashSet::new();
        schema
            .rules()
            .iter()
            .filter(|rule| {
                let [SegPat::Key(name)] = rule.at.0.as_slice() else {
                    return false;
                };
                !present.contains(name.as_str())
                    && !self.hidden.contains(name)
                    && seen.insert(name.as_str())
            })
            .collect()
    }

    /// The canonical serialized document — what the embedder writes on save.
    pub fn source_snapshot(&self) -> String {
        self.backend.source().unwrap_or_default()
    }

    /// The backend, for backend-specific reads (e.g. a prov backend's body).
    pub fn backend(&self) -> &B {
        &self.backend
    }

    /// The backend, for backend-specific operations that do **not** change the
    /// metadata tree flower renders (e.g. replacing a prov document's prose
    /// body). An op that *does* change the metadata leaves the view stale — go
    /// through the model's own edit methods for those.
    pub fn backend_mut(&mut self) -> &mut B {
        &mut self.backend
    }

    pub fn set_status(&mut self, s: impl Into<String>) {
        self.status = s.into();
    }

    /// Clear the dirty flag after the embedder has persisted the source.
    pub fn mark_saved(&mut self) {
        self.dirty = false;
    }

    // ── view derivation ───────────────────────────────────────────────────────

    /// Re-derive `value` + `rows` from the backend's current tree.
    fn reload(&mut self) -> Result<()> {
        self.value = self
            .backend
            .to_value()
            .map_err(|e| anyhow::anyhow!("reading value tree: {e}"))?;
        self.rebuild_rows();
        self.rebuild_pages();
        Ok(())
    }

    fn rebuild_rows(&mut self) {
        self.rows = tree::build_rows(&self.value, &self.collapsed, &self.hidden);
        if self.selected >= self.rows.len() {
            self.selected = self.rows.len().saturating_sub(1);
        }
    }

    /// Re-derive the focused page and the root page from `value`.
    ///
    /// Runs on every reload, whichever view is active: see
    /// [`view`](Self::view) for why both projections are kept live.
    fn rebuild_pages(&mut self) {
        self.reanchor_focus();
        self.root_page = page::build_page(
            &self.value,
            &[],
            &self.hidden,
            &self.demoted,
            self.inline_budget,
        );
        self.page = if self.focus.is_empty() {
            self.root_page.clone()
        } else {
            page::build_page(
                &self.value,
                &self.focus,
                &self.hidden,
                &self.demoted,
                self.inline_budget,
            )
        };
        self.parent_page = if self.focus.is_empty() {
            Page::default()
        } else {
            // The pane you came out of is the pane you *actually* came out of.
            //
            // One level out is the wrong answer once a row can compress: opening
            // `exports › journal` skips the `exports` page precisely because it
            // holds nothing but that one row, and drawing it on the left would
            // spend half a wide layout on the page the compression existed to
            // spare you. So walk out past every level a row compressed past, and
            // stop at the page that actually lists the row that was tapped.
            let mut parent = &self.focus[..self.focus.len() - 1];
            while !parent.is_empty()
                && page::is_compressed_past(&self.value, parent, &self.hidden, self.inline_budget)
            {
                parent = &parent[..parent.len() - 1];
            }
            page::build_page(
                &self.value,
                parent,
                &self.hidden,
                &self.demoted,
                self.inline_budget,
            )
        };
        if self.page_selected >= self.page.items.len() {
            self.page_selected = self.page.items.len().saturating_sub(1);
        }
    }

    /// Walk `focus` back to the nearest ancestor that is still a container.
    ///
    /// The focus is the one piece of page state the document can invalidate from
    /// underneath: delete the key you are standing inside, or replace it with a
    /// scalar, and the page has nothing to list. Popping to the nearest surviving
    /// ancestor is what a settings menu does when a section disappears — you end
    /// up one level out, rather than on a blank page or back at the root.
    fn reanchor_focus(&mut self) {
        while !self.focus.is_empty()
            && !tree::value_at(&self.value, &self.focus).is_some_and(page::is_container)
        {
            self.focus.pop();
        }
    }

    fn selected_row(&self) -> Option<&Row> {
        self.rows.get(self.selected)
    }

    /// The path of whatever is selected in the **active** view.
    ///
    /// The seam that lets one set of edit operations serve both projections: an
    /// edit is a path plus a value, and which list the user picked that path from
    /// is not something [`commit`](Self::commit) should have to know.
    pub fn selected_path(&self) -> Option<Vec<Seg>> {
        match self.view {
            ViewMode::Tree => self.selected_row().map(|r| r.path.clone()),
            ViewMode::Pages => self.page_item().map(|i| i.path.clone()),
        }
    }

    /// Re-anchor selection onto `path` after a rebuild, or clamp if it's gone.
    ///
    /// Re-anchors *both* projections, because an edit made from either one moves
    /// the node in both, and the view the user is not currently looking at is the
    /// one they will switch to expecting their cursor to still be somewhere sane.
    fn select_path(&mut self, path: &[Seg]) {
        if let Some(i) = self.rows.iter().position(|r| r.path == path) {
            self.selected = i;
        } else if self.selected >= self.rows.len() {
            self.selected = self.rows.len().saturating_sub(1);
        }
        // A path off the current page (an edit by path elsewhere in the document,
        // or the anchor of a delete that was the page's own container) leaves the
        // page cursor where it was, clamped by `rebuild_pages`.
        if let Some(i) = self.page.position_of(path) {
            self.page_selected = i;
        }
    }

    // ── navigation ────────────────────────────────────────────────────────────

    /// The selected row of the tree projection — an index into
    /// [`rows`](Self::rows).
    pub fn selected(&self) -> usize {
        self.selected
    }

    /// Put the tree cursor on `index`, clamped to the row list.
    ///
    /// **Switches to the tree projection first**, and that is the point of the
    /// method rather than a side effect. A row index is a coordinate in the row
    /// list a caller last rendered; it names nothing on a page. A host driving
    /// both surfaces — a metadata pane beside a settings page — would otherwise
    /// hand a row index to a model still standing in the page projection, where
    /// the very next [`delete_selected`](Self::delete_selected) reads the *page*
    /// cursor and quietly removes a different node.
    ///
    /// So the vocabularies assert. Every method that establishes a cursor names
    /// the projection its coordinates belong to ([`page_enter`](Self::page_enter)
    /// and the rest do the same for pages), and the methods that merely *read* a
    /// cursor stay neutral — a delete deletes what is selected, in whichever view
    /// the user is actually looking at.
    ///
    /// A no-op when the model is already in the tree.
    pub fn select_row(&mut self, index: usize) {
        self.set_view(ViewMode::Tree);
        self.selected = if self.rows.is_empty() {
            0
        } else {
            index.min(self.rows.len() - 1)
        };
    }

    pub fn move_down(&mut self) {
        // Tree vocabulary: assert the projection these coordinates belong to.
        self.set_view(ViewMode::Tree);
        if self.selected + 1 < self.rows.len() {
            self.selected += 1;
        }
    }

    pub fn move_up(&mut self) {
        // Tree vocabulary: assert the projection these coordinates belong to.
        self.set_view(ViewMode::Tree);
        self.selected = self.selected.saturating_sub(1);
    }

    /// `l`: expand a collapsed container, else step into its first child.
    pub fn expand_or_enter(&mut self) {
        // Tree vocabulary: assert the projection these coordinates belong to.
        self.set_view(ViewMode::Tree);
        let Some(row) = self.selected_row() else {
            return;
        };
        if row.is_container() {
            if !row.expanded {
                let path = row.path.clone();
                self.collapsed.remove(&path);
                self.rebuild_rows();
                self.select_path(&path);
            } else if self.selected + 1 < self.rows.len()
                && self.rows[self.selected + 1].depth > row.depth
            {
                self.selected += 1;
            }
        }
    }

    /// `h`: collapse an expanded container, else step out to the parent row.
    pub fn collapse_or_leave(&mut self) {
        // Tree vocabulary: assert the projection these coordinates belong to.
        self.set_view(ViewMode::Tree);
        let Some(row) = self.selected_row() else {
            return;
        };
        if row.is_container() && row.expanded {
            let path = row.path.clone();
            self.collapsed.insert(path.clone());
            self.rebuild_rows();
            self.select_path(&path);
            return;
        }
        // Step out: the nearest earlier row at a shallower depth is the parent.
        let depth = row.depth;
        if depth == 0 {
            return;
        }
        for i in (0..self.selected).rev() {
            if self.rows[i].depth < depth {
                self.selected = i;
                return;
            }
        }
    }

    // ── page view ─────────────────────────────────────────────────────────

    /// Which projection is active.
    pub fn view(&self) -> ViewMode {
        self.view
    }

    /// Switch projection, carrying the cursor across so the node you were on in
    /// one view is the node you are on in the other.
    ///
    /// Without that, switching would be a jump cut: you fold down to one key in
    /// the tree, switch to pages, and land at the top of the root page with no
    /// idea where your key went. Carrying the selection makes the two views two
    /// ways of looking at one position, which is the only reading under which
    /// having both is worth it.
    pub fn set_view(&mut self, view: ViewMode) {
        if view == self.view {
            return;
        }
        let was = self.selected_path();
        self.view = view;
        if let Some(path) = was {
            match view {
                ViewMode::Pages => self.focus_on(&path),
                // The tree may have the node folded away inside a shut ancestor;
                // open the lineage so there is a row to land on.
                ViewMode::Tree => {
                    for i in 0..path.len() {
                        self.collapsed.remove(&path[..i]);
                    }
                    self.rebuild_rows();
                    self.select_path(&path);
                }
            }
        }
    }

    /// Toggle between the tree and the page view.
    pub fn toggle_view(&mut self) {
        self.set_view(match self.view {
            ViewMode::Tree => ViewMode::Pages,
            ViewMode::Pages => ViewMode::Tree,
        });
    }

    /// The page currently being listed.
    pub fn page(&self) -> &Page {
        &self.page
    }

    /// The root's page.
    pub fn root_page(&self) -> &Page {
        &self.root_page
    }

    /// The page one level out — what a two-pane frontend draws on the left. Empty
    /// when [`focus`](Self::focus) is the root, which has no parent.
    pub fn parent_page(&self) -> &Page {
        &self.parent_page
    }

    /// The container the page view is listing. Empty is the document root.
    pub fn focus(&self) -> &[Seg] {
        &self.focus
    }

    /// The index of the selected item on [`page`](Self::page).
    pub fn page_selected(&self) -> usize {
        self.page_selected
    }

    /// The selected page item, if the page has any.
    pub fn page_item(&self) -> Option<&PageItem> {
        self.page.items.get(self.page_selected)
    }

    /// Whether a two-pane layout would waste one pane on this document.
    ///
    /// A document whose root has nothing to drill into — a flat list of keys, a
    /// sequence of scalars, anything a generous budget has poured onto one page
    /// — has no navigation to put in a sidebar, and splitting the width for it
    /// would cost half the room and buy nothing. A frontend checks this to fall
    /// back to a single full-width pane.
    ///
    /// The second case is the same waste one level along: when the page the
    /// cursor is on is the one that leads the split
    /// ([`page_leads_the_split`](Self::page_leads_the_split)), the right pane is
    /// a preview of what the cursor would open, and a page with nothing to open
    /// has no preview to put there.
    pub fn pages_would_degenerate(&self) -> bool {
        if !self.root_page.has_drills() {
            return true;
        }
        self.page_leads_the_split() && !self.page.has_drills()
    }

    /// Whether the page the cursor is on belongs in the *left* pane, with the
    /// right one previewing what the cursor would open.
    ///
    /// Two panes are two consecutive levels of one lineage, and the left one is
    /// the outermost that offers a choice. Usually that is the page the current
    /// one was opened from. But a page can be opened from one that has a single
    /// row on it — the root of `{repo: [...]}`, or any level
    /// [`enter_document`](Self::enter_document) started past — and drawing that
    /// on the left spends half the width on a row nobody can choose between.
    /// Then this page leads instead, and the pane that would have repeated its
    /// parent previews its child.
    pub fn page_leads_the_split(&self) -> bool {
        self.focus.is_empty() || !self.parent_page.has_choice()
    }

    /// Point the page view at whichever page *lists* `path`, with the cursor on
    /// it — the by-path counterpart to drilling, and how a view switch carries
    /// the selection across.
    ///
    /// It searches from the root outward rather than from `path` inward, because
    /// more than one page can contain a node and the outermost is the right one:
    /// an inlined group's member is listed on the grandparent's page (that is what
    /// inlining means), and also on the group's own page, which is a place page
    /// navigation would never have left you. A path that doesn't resolve is inert.
    pub fn focus_on(&mut self, path: &[Seg]) {
        // Page vocabulary, like the rest. Re-entrant from `set_view`, which calls
        // this to carry the cursor across — but by then `view` is already
        // `Pages`, so the call below returns immediately rather than recursing.
        self.set_view(ViewMode::Pages);
        if tree::value_at(&self.value, path).is_none() {
            return;
        }
        let mut focus: Vec<Seg> = Vec::new();
        while focus.len() < path.len()
            && page::build_page(
                &self.value,
                &focus,
                &self.hidden,
                &self.demoted,
                self.inline_budget,
            )
            .position_of(path)
            .is_none()
        {
            focus.push(path[focus.len()].clone());
        }
        self.focus = focus;
        self.rebuild_pages();
        self.page_selected = self.page.position_of(path).unwrap_or(0);
    }

    /// The page listing the container at `path`, without going there.
    ///
    /// [`page`](Self::page) is where the user *is*; this is any other level, built
    /// on demand and thrown away. A frontend whose navigation is a stack needs it:
    /// the OS asks "what is the screen for this path element?" for levels the
    /// model is not focused on, and answering by moving the focus would make
    /// rendering a screen a navigation.
    ///
    /// Total, like [`build_page`](crate::page::build_page): a path that doesn't
    /// resolve, or that names a scalar, yields an empty page.
    pub fn page_at(&self, path: &[Seg]) -> Page {
        page::build_page(
            &self.value,
            path,
            &self.hidden,
            &self.demoted,
            self.inline_budget,
        )
    }

    /// The page the selected item *would* open.
    ///
    /// A two-pane frontend showing the root's categories on the left has nothing
    /// to put on the right until you have drilled into something — and an empty
    /// half-screen is a poor advertisement for splitting the width. Previewing
    /// the selected category's page fills it with the thing you are about to open
    /// anyway, which is what a settings sidebar does. `None` for a scalar, which
    /// has no page.
    pub fn peek_page(&self) -> Option<Page> {
        let item = self.page_item()?;
        if !item.is_drill() {
            return None;
        }
        // The page it would *open*, which for a compressed row is the far end of
        // the chain — previewing the single-row page in between would put the
        // pane's whole purpose (showing what you are about to open) to work
        // showing the name you are pointing at.
        Some(self.page_at(&item.descend_to))
    }

    /// `j` in the page view.
    pub fn page_move_down(&mut self) {
        // Page vocabulary: assert the projection this cursor belongs to.
        self.set_view(ViewMode::Pages);
        if self.page_selected + 1 < self.page.items.len() {
            self.page_selected += 1;
        }
    }

    /// `k` in the page view.
    pub fn page_move_up(&mut self) {
        // Page vocabulary: assert the projection this cursor belongs to.
        self.set_view(ViewMode::Pages);
        self.page_selected = self.page_selected.saturating_sub(1);
    }

    /// `l`/`Enter` in the page view: open the selected container as a page, or
    /// begin editing the selected scalar.
    ///
    /// A group header opens too. Its members are already on screen, so opening it
    /// shows nothing new — but it is the door to operating on the group as a
    /// container (append, insert, reorder) rather than on the members, and a
    /// container that is visible but cannot be entered is a worse surprise than a
    /// page that repeats what you could already see.
    pub fn page_enter(&mut self) {
        // Page vocabulary: assert the projection this cursor belongs to.
        self.set_view(ViewMode::Pages);
        let Some(item) = self.page_item() else {
            return;
        };
        if item.is_scalar() {
            self.begin_edit();
            return;
        }
        // A group header opens nothing (see `PageItem::is_drill`), so `l` on one
        // does the next most useful thing and steps onto its first member — the
        // same "into its children" this key means everywhere else.
        if !item.is_drill() {
            if let Some(first) = self.page.items[self.page_selected + 1..]
                .iter()
                .position(|i| i.inset > 0)
            {
                self.page_selected += 1 + first;
            }
            return;
        }
        // `descend_to`, not `path`: a compressed row names a chain of containers
        // that hold only each other, and opening it lands on the far end — the
        // first page with more on it than the name you just tapped. They are the
        // same path for every other row.
        let target = item.descend_to.clone();
        self.page_memory
            .insert(self.focus.clone(), self.page_selected);
        self.focus = target;
        self.page_selected = 0;
        self.rebuild_pages();
    }

    /// `h`/`Esc` in the page view: pop back to the page that *listed* the row you
    /// opened, restoring the cursor to it.
    ///
    /// One level out is the wrong answer once a row can compress, for the same
    /// reason it is the wrong left pane
    /// ([`rebuild_pages`](Self::rebuild_pages)): opening `exports › journal`
    /// deliberately skips the `exports` page because it holds nothing but that
    /// one row, and handing it back on the way out makes leaving cost two steps
    /// where arriving cost one — on a page whose only row is the name of the
    /// place you just left. So this walks out past every level a row compressed
    /// past, and lands where the row was tapped.
    ///
    /// Nothing becomes unreachable by it. A compressed row's
    /// [`path`](PageItem::path) is the outermost container, so renaming,
    /// deleting, reordering and adding to `exports` are all still that row's ops
    /// on the page this lands on — the skipped page never held anything else.
    pub fn page_back(&mut self) {
        // Page vocabulary: assert the projection this cursor belongs to.
        self.set_view(ViewMode::Pages);
        if self.focus.is_empty() {
            self.status = "already at the top".to_string();
            return;
        }
        let child = std::mem::take(&mut self.focus);
        let mut parent = &child[..child.len() - 1];
        while !parent.is_empty()
            && page::is_compressed_past(&self.value, parent, &self.hidden, self.inline_budget)
        {
            parent = &parent[..parent.len() - 1];
        }
        self.focus = parent.to_vec();
        self.rebuild_pages();
        // Prefer re-finding the child: an index it holds is correct after edits
        // that shifted the page, which a remembered index would not be. The
        // memory answers only when the child is gone — see `page_memory`.
        self.page_selected = self
            .page
            .position_of(&child)
            .or_else(|| {
                self.page_memory
                    .get(&self.focus)
                    .copied()
                    .filter(|i| *i < self.page.items.len())
            })
            .unwrap_or(0);
    }

    /// Whether the container at `path` is collapsed. Answers for a node with no
    /// row too (one nested inside another collapsed container), which
    /// [`Row::expanded`](crate::Row) cannot.
    pub fn is_collapsed(&self, path: &[Seg]) -> bool {
        self.collapsed.contains(path)
    }

    /// Collapse or expand the container at `path`, leaving the selection where the
    /// user put it — the by-path, non-interactive counterpart to
    /// [`activate`](Self::activate).
    ///
    /// `activate` folds *the selected row*, so driving it from a path means moving
    /// the selection first and putting it back after. This doesn't: it re-anchors
    /// onto whatever was selected before, and only falls back to `path` itself when
    /// the selection was a descendant that the fold just took off screen.
    ///
    /// A path naming a scalar (or nothing) is inert — see
    /// [`with_collapsed`](Self::with_collapsed).
    pub fn set_collapsed(&mut self, path: &[Seg], collapsed: bool) {
        let changed = if collapsed {
            self.collapsed.insert(path.to_vec())
        } else {
            self.collapsed.remove(path)
        };
        if !changed {
            return;
        }
        let was = self.selected_row().map(|r| r.path.clone());
        self.rebuild_rows();
        if let Some(was) = was {
            // A row swallowed by the fold has no path to return to; its nearest
            // surviving ancestor is the container the user just shut.
            if collapsed && was.len() > path.len() && was.starts_with(path) {
                self.select_path(path);
            } else {
                self.select_path(&was);
            }
        }
    }

    /// `Enter`/`Space`: toggle a container's expansion, or edit a scalar.
    pub fn activate(&mut self) {
        let Some(row) = self.selected_row() else {
            return;
        };
        if row.is_container() {
            let path = row.path.clone();
            if row.expanded {
                self.collapsed.insert(path.clone());
            } else {
                self.collapsed.remove(&path);
            }
            self.rebuild_rows();
            self.select_path(&path);
        } else {
            self.begin_edit();
        }
    }

    // ── editing ───────────────────────────────────────────────────────────────

    pub fn begin_edit(&mut self) {
        let Some(path) = self.selected_path() else {
            return;
        };
        let Some(value) = self.value_at(&path) else {
            return;
        };
        if page::is_container(value) {
            self.status = "can only edit scalar values".to_string();
            return;
        }
        let seed = tree::edit_seed(value);
        self.mode = Mode::Editing { buffer: seed, path };
    }

    pub fn edit_push(&mut self, c: char) {
        if let Mode::Editing { buffer, .. } = &mut self.mode {
            buffer.push(c);
        }
    }

    pub fn edit_backspace(&mut self) {
        if let Mode::Editing { buffer, .. } = &mut self.mode {
            buffer.pop();
        }
    }

    pub fn edit_cancel(&mut self) {
        self.mode = Mode::Normal;
        self.status = "edit cancelled".to_string();
    }

    pub fn edit_commit(&mut self) {
        let Mode::Editing { buffer, path } = &mut self.mode else {
            return;
        };
        let buffer = std::mem::take(buffer);
        let path = std::mem::take(path);
        self.mode = Mode::Normal;

        let value = self.coerce_text(&path, &buffer);
        self.commit(
            EditOp::ReplaceValue {
                path: path.clone(),
                value,
            },
            path,
            "value updated",
        );
    }

    /// Programmatically replace the value at `path` (any depth), refreshing the
    /// view. The non-interactive counterpart to [`edit_commit`](Self::edit_commit)
    /// — for an embedder or FFI that edits by path rather than through the
    /// selection.
    pub fn set_value_at(&mut self, path: &[Seg], value: Value) {
        self.commit(
            EditOp::ReplaceValue {
                path: path.to_vec(),
                value,
            },
            path.to_vec(),
            "value updated",
        );
    }

    /// Set the scalar at `path` from an edit-buffer `text`, coercing by the
    /// schema's expected type when known (a `str` field keeps `"123"` a string)
    /// and otherwise guessing by literal shape — the by-path, schema-aware analog
    /// of [`edit_commit`](Self::edit_commit). Validation (closed-vocabulary
    /// rejection) still happens at the commit funnel.
    pub fn set_scalar_text(&mut self, path: &[Seg], text: &str) {
        let value = self.coerce_text(path, text);
        self.set_value_at(path, value);
    }

    /// Turn edit-buffer `text` into the value that belongs at `path`: the type the
    /// schema declares for that path when it declares one, and otherwise a guess
    /// from the literal's shape.
    ///
    /// The single rule behind [`edit_commit`](Self::edit_commit),
    /// [`set_scalar_text`](Self::set_scalar_text),
    /// [`insert_key_text`](Self::insert_key_text) and
    /// [`append_item_text`](Self::append_item_text). It is keyed on the path of the
    /// value being *written*, not of its container — that is what lets an
    /// each-item rule type a list's items independently of the list.
    fn coerce_text(&self, path: &[Seg], text: &str) -> Value {
        match self.rule_at(path).and_then(|r| r.ty) {
            Some(ty) => ty.coerce(text),
            None => tree::parse_scalar(text),
        }
    }

    /// Rename the mapping entry at `path` to `new_key`, keeping its value and
    /// re-anchoring the selection onto the renamed entry. A no-op (with a status
    /// hint) when `path` doesn't end in a key — a sequence item has no key. The
    /// backend rejects a name that collides with an existing sibling key.
    pub fn rename_key(&mut self, path: &[Seg], new_key: &str) {
        match path.last() {
            Some(Seg::Key(_)) => {
                let mut anchor = path[..path.len() - 1].to_vec();
                anchor.push(Seg::Key(new_key.to_string()));
                self.commit(
                    EditOp::RenameKey {
                        path: path.to_vec(),
                        new_key: new_key.to_string(),
                    },
                    anchor,
                    "renamed",
                );
            }
            _ => self.status = "only mapping keys can be renamed".to_string(),
        }
    }

    /// Insert `key = value` into the mapping at `map_path`, selecting the new
    /// entry. A frontend offers this on a map container; the backend rejects a
    /// duplicate key or a non-mapping target, leaving the document untouched.
    pub fn insert_key(&mut self, map_path: &[Seg], key: &str, value: Value) {
        let mut anchor = map_path.to_vec();
        anchor.push(Seg::Key(key.to_string()));
        self.commit(
            EditOp::InsertKey {
                map_path: map_path.to_vec(),
                key: key.to_string(),
                value,
            },
            anchor,
            "inserted",
        );
    }

    /// Insert `key = text` into the mapping at `map_path`, coercing `text` by the
    /// type the schema declares for the new entry and otherwise guessing by literal
    /// shape — the insert-shaped analog of
    /// [`set_scalar_text`](Self::set_scalar_text).
    ///
    /// Prefer this to [`insert_key`](Self::insert_key) whenever the value comes
    /// from a user's text: a caller that shape-guesses on its own writes `2026` as
    /// an integer into a field the schema declares `str`, and gets no say from the
    /// schema it is otherwise honoring everywhere else.
    pub fn insert_key_text(&mut self, map_path: &[Seg], key: &str, text: &str) {
        let mut target = map_path.to_vec();
        target.push(Seg::Key(key.to_string()));
        let value = self.coerce_text(&target, text);
        self.insert_key(map_path, key, value);
    }

    /// Append `value` to the sequence at `seq_path`, selecting the new item.
    pub fn append_item(&mut self, seq_path: &[Seg], value: Value) {
        let idx = self.seq_len(seq_path);
        let mut anchor = seq_path.to_vec();
        anchor.push(Seg::Index(idx));
        self.commit(
            EditOp::AppendItem {
                seq_path: seq_path.to_vec(),
                value,
            },
            anchor,
            "appended",
        );
    }

    /// Append `text` to the sequence at `seq_path`, coercing it by the type the
    /// schema declares for the sequence's *items* and otherwise guessing by literal
    /// shape — the append-shaped analog of
    /// [`set_scalar_text`](Self::set_scalar_text).
    ///
    /// The item's type comes from the rule matching the item path (an each-item or
    /// subtree rule), not from the rule on the list itself: `tags` is a `seq`, its
    /// items are `str`.
    pub fn append_item_text(&mut self, seq_path: &[Seg], text: &str) {
        let mut target = seq_path.to_vec();
        target.push(Seg::Index(self.seq_len(seq_path)));
        let value = self.coerce_text(&target, text);
        self.append_item(seq_path, value);
    }

    /// Move the selected row one place earlier among its siblings — a sequence
    /// item via fig's array-move, a mapping entry via a one-swap reorder.
    pub fn move_selected_up(&mut self) {
        self.reorder_selected(-1);
    }

    /// Move the selected row one place later among its siblings.
    pub fn move_selected_down(&mut self) {
        self.reorder_selected(1);
    }

    /// The shared body of [`move_selected_up`](Self::move_selected_up) /
    /// [`move_selected_down`](Self::move_selected_down): shift the selected row by
    /// `delta` positions within its parent container.
    fn reorder_selected(&mut self, delta: isize) {
        let Some(path) = self.selected_path() else {
            return;
        };
        let Some(last) = path.last().cloned() else {
            self.status = "cannot move the document root".to_string();
            return;
        };
        let parent = path[..path.len() - 1].to_vec();
        match last {
            Seg::Index(i) => {
                let len = self.seq_len(&parent);
                let to = i as isize + delta;
                if to < 0 || to as usize >= len {
                    self.status = "already at the edge".to_string();
                    return;
                }
                let to = to as usize;
                let mut anchor = parent.clone();
                anchor.push(Seg::Index(to));
                self.commit(
                    EditOp::MoveItem {
                        seq_path: parent,
                        from: i,
                        to,
                    },
                    anchor,
                    "moved",
                );
            }
            Seg::Key(k) => {
                let keys = self.map_keys(&parent);
                let Some(pos) = keys.iter().position(|x| *x == k) else {
                    return;
                };
                let target = pos as isize + delta;
                if target < 0 || target as usize >= keys.len() {
                    self.status = "already at the edge".to_string();
                    return;
                }
                let mut order = keys;
                order.swap(pos, target as usize);
                self.commit(
                    EditOp::ReorderKeys {
                        map_path: parent,
                        keys: order,
                    },
                    path,
                    "moved",
                );
            }
        }
    }

    /// The value the document currently holds at `path` (the whole tree for the
    /// empty path), or `None` when the path doesn't resolve — for a frontend
    /// reading a row's value without reaching for the backend.
    pub fn value_at(&self, path: &[Seg]) -> Option<&Value> {
        tree::value_at(&self.value, path)
    }

    /// The mapping keys at `path`, in document order (empty for a non-mapping).
    fn map_keys(&self, path: &[Seg]) -> Vec<String> {
        tree::map_keys(&self.value, path).unwrap_or_default()
    }

    /// The length of the sequence at `path` (0 for a non-sequence) — the index an
    /// append will land at.
    pub fn seq_len(&self, path: &[Seg]) -> usize {
        tree::seq_len(&self.value, path).unwrap_or(0)
    }

    /// `x`: delete the selected mapping entry or sequence item.
    pub fn delete_selected(&mut self) {
        let Some(path) = self.selected_path() else {
            return;
        };
        let (op, anchor) = match path.last() {
            Some(Seg::Index(i)) => {
                let seq_path = path[..path.len() - 1].to_vec();
                (
                    EditOp::RemoveItem {
                        seq_path: seq_path.clone(),
                        index: *i,
                    },
                    seq_path,
                )
            }
            Some(Seg::Key(_)) => (
                EditOp::DeleteKey { path: path.clone() },
                path[..path.len() - 1].to_vec(),
            ),
            None => {
                self.status = "cannot delete the document root".to_string();
                return;
            }
        };
        self.commit(op, anchor, "deleted");
    }

    /// Apply one edit through the backend, then refresh the view (or report the
    /// rollback). The single path every mutation funnels through — and the choke
    /// point where the schema validates values: a closed vocabulary rejects an
    /// unknown value here, before it reaches the backend; an open one applies but
    /// surfaces a soft warning. fig's reparse stays the last-resort backstop.
    fn commit(&mut self, op: EditOp, anchor: Vec<Seg>, msg: &str) {
        // A workspace-maintained field declines every mutation, not just a value
        // edit: renaming or deleting one would be undone on the next write just
        // as surely as retyping it.
        if let Some(key) = op_root_key(&op)
            && self.derived.contains(key)
        {
            self.status = format!("rejected: `{key}` is maintained by the workspace");
            return;
        }
        let mut warn: Option<Issue> = None;
        if let Some((path, value)) = op_target(&op)
            && let Some(rule) = self.rule_at(&path)
        {
            match rule.validate(value) {
                Validation::Reject(why) => {
                    self.status = format!("rejected: {why}");
                    return;
                }
                Validation::Warn(why) => warn = Some(why),
                Validation::Ok => {}
            }
        }
        match self.backend.apply(op) {
            Ok(()) => {
                self.after_edit(&anchor, msg);
                // A soft-warn overrides the success status so the user sees it.
                if let Some(why) = warn {
                    self.status = why.to_string();
                }
            }
            // The backend rolled back / declined; the document is untouched.
            Err(e) => self.status = format!("rejected: {e}"),
        }
    }

    /// Shared tail of a successful mutation: refresh the view, re-anchor
    /// selection, mark dirty, set the status line.
    fn after_edit(&mut self, anchor: &[Seg], msg: &str) {
        if let Err(e) = self.reload() {
            self.status = format!("view refresh failed: {e}");
            return;
        }
        self.select_path(anchor);
        self.dirty = true;
        self.status = msg.to_string();
    }
}

/// The (target path, value) a value-bearing [`EditOp`] writes — what schema
/// validation checks. An append's item index isn't known here, so a placeholder
/// `Index(0)` stands in; it only serves to match an `EachItem` rule pattern, which
/// is index-agnostic. Structural ops (delete, move, reorder, rename) carry no new
/// value and return `None`.
/// The top-level mapping key an op would change, if any — the unit at which a
/// document's managed fields are declared, so an edit anywhere beneath one
/// (an item of a managed list, a nested key) is caught along with the field
/// itself.
fn op_root_key(op: &EditOp) -> Option<&str> {
    fn first_key(path: &[Seg]) -> Option<&str> {
        match path.first() {
            Some(Seg::Key(k)) => Some(k.as_str()),
            _ => None,
        }
    }
    match op {
        EditOp::ReplaceValue { path, .. }
        | EditOp::DeleteKey { path }
        | EditOp::RenameKey { path, .. } => first_key(path),
        EditOp::RemoveItem { seq_path, .. }
        | EditOp::AppendItem { seq_path, .. }
        | EditOp::MoveItem { seq_path, .. } => first_key(seq_path),
        // An insert *at the root* names the new top-level key itself; deeper, the
        // container it lands in is what matters.
        EditOp::InsertKey { map_path, key, .. } => match map_path.first() {
            None => Some(key.as_str()),
            _ => first_key(map_path),
        },
        // Reordering the root's own keys moves no field's value.
        EditOp::ReorderKeys { map_path, .. } => first_key(map_path),
    }
}

fn op_target(op: &EditOp) -> Option<(Vec<Seg>, &Value)> {
    match op {
        EditOp::ReplaceValue { path, value } => Some((path.clone(), value)),
        EditOp::InsertKey {
            map_path,
            key,
            value,
        } => {
            let mut p = map_path.clone();
            p.push(Seg::Key(key.clone()));
            Some((p, value))
        }
        EditOp::AppendItem { seq_path, value } => {
            let mut p = seq_path.clone();
            p.push(Seg::Index(0));
            Some((p, value))
        }
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backend::FigBackend;
    use fig::Format;

    const SAMPLE: &str = "\
# flower sample config — comments and formatting below should survive edits
title = \"flower\"
version = 1
enabled = true

# the server block
[server]
host = \"localhost\"
port = 8080
tags = [\"alpha\", \"beta\"]

[server.limits]
max_connections = 100
timeout = 30.5
";

    fn sample_model() -> Model<FigBackend> {
        let backend = FigBackend::open(SAMPLE.as_bytes(), Format::Toml).expect("open backend");
        Model::new(backend).expect("build model")
    }

    fn select(model: &mut Model<FigBackend>, path: &[Seg]) {
        model.selected = model
            .rows
            .iter()
            .position(|r| r.path == path)
            .unwrap_or_else(|| panic!("no row for {path:?}"));
    }

    fn type_value(model: &mut Model<FigBackend>, text: &str) {
        if let Mode::Editing { buffer, .. } = &mut model.mode {
            buffer.clear();
        }
        for c in text.chars() {
            model.edit_push(c);
        }
        model.edit_commit();
    }

    #[test]
    fn a_fresh_model_has_nothing_to_report() {
        // The status line carries refusals. A model that has refused nothing
        // has nothing for it, and a frontend reads the empty string as "draw no
        // bar" rather than having to know which openings words are noise.
        assert!(
            sample_model().status.is_empty(),
            "status: {}",
            sample_model().status
        );
    }

    #[test]
    fn edits_a_scalar_losslessly() {
        let mut model = sample_model();

        select(&mut model, &[Seg::Key("version".into())]);
        model.begin_edit();
        type_value(&mut model, "2");

        let src = model.source_snapshot();
        assert!(src.contains("version = 2"), "value changed:\n{src}");
        assert!(
            src.contains("# the server block"),
            "comment preserved:\n{src}"
        );
        assert!(
            src.contains("# flower sample config"),
            "header preserved:\n{src}"
        );
        assert!(model.dirty);
    }

    #[test]
    fn edits_a_nested_string() {
        let mut model = sample_model();

        select(
            &mut model,
            &[Seg::Key("server".into()), Seg::Key("host".into())],
        );
        model.begin_edit();
        type_value(&mut model, "example.com");

        let src = model.source_snapshot();
        assert!(
            src.contains("host = \"example.com\""),
            "nested edit:\n{src}"
        );
        assert!(src.contains("port = 8080"), "sibling untouched:\n{src}");
    }

    #[test]
    fn deletes_a_key() {
        let mut model = sample_model();

        select(&mut model, &[Seg::Key("enabled".into())]);
        model.delete_selected();

        let src = model.source_snapshot();
        assert!(!src.contains("enabled = true"), "key removed:\n{src}");
        assert!(src.contains("title = \"flower\""), "siblings kept:\n{src}");
    }

    #[test]
    fn appends_a_sequence_item() {
        let mut model = sample_model();
        let tags = vec![Seg::Key("server".into()), Seg::Key("tags".into())];
        model.append_item(&tags, Value::Str("gamma".into()));

        let src = model.source_snapshot();
        assert!(src.contains("gamma"), "item appended:\n{src}");
        assert!(
            src.contains("alpha") && src.contains("beta"),
            "siblings kept"
        );
        assert!(model.dirty);
    }

    #[test]
    fn inserts_a_mapping_key() {
        let mut model = sample_model();
        let server = vec![Seg::Key("server".into())];
        model.insert_key(&server, "scheme", Value::Str("https".into()));

        let src = model.source_snapshot();
        // fig may quote the inserted key (`"scheme" = …`); both are valid TOML.
        assert!(
            src.contains("scheme") && src.contains("= \"https\""),
            "key inserted:\n{src}"
        );
        assert!(src.contains("host = \"localhost\""), "siblings kept");
    }

    #[test]
    fn moves_a_sequence_item_and_reorders_keys() {
        let mut model = sample_model();

        // Move the second tag ("beta", index 1) up to index 0.
        select(
            &mut model,
            &[
                Seg::Key("server".into()),
                Seg::Key("tags".into()),
                Seg::Index(1),
            ],
        );
        model.move_selected_up();
        let src = model.source_snapshot();
        let a = src.find("alpha").unwrap();
        let b = src.find("beta").unwrap();
        assert!(b < a, "beta now precedes alpha:\n{src}");

        // Move a top-level mapping entry down: title should follow version.
        select(&mut model, &[Seg::Key("title".into())]);
        model.move_selected_down();
        let src = model.source_snapshot();
        assert!(
            src.find("version").unwrap() < src.find("title").unwrap(),
            "version now precedes title:\n{src}"
        );
    }

    #[test]
    fn hidden_top_level_keys_are_projected_out_but_kept_lossless() {
        let backend = FigBackend::open(SAMPLE.as_bytes(), Format::Toml).expect("open");
        let mut model =
            Model::with_hidden(backend, vec!["title".into(), "enabled".into()]).expect("model");

        // Hidden keys produce no rows…
        assert!(
            !model
                .rows
                .iter()
                .any(|r| r.path == [Seg::Key("title".into())])
        );
        assert!(
            !model
                .rows
                .iter()
                .any(|r| r.path == [Seg::Key("enabled".into())])
        );
        // …but a visible sibling is still there,
        assert!(
            model
                .rows
                .iter()
                .any(|r| r.path == [Seg::Key("version".into())])
        );
        // …and the hidden keys remain in the document bytes.
        assert!(model.source_snapshot().contains("title = \"flower\""));
        assert!(model.source_snapshot().contains("enabled = true"));

        // Editing a visible key doesn't disturb the hidden ones.
        select(&mut model, &[Seg::Key("version".into())]);
        model.begin_edit();
        type_value(&mut model, "9");
        let src = model.source_snapshot();
        assert!(src.contains("version = 9"));
        assert!(src.contains("title = \"flower\"") && src.contains("enabled = true"));
    }

    #[test]
    fn reorder_leaves_hidden_keys_in_place() {
        let backend = FigBackend::open(SAMPLE.as_bytes(), Format::Toml).expect("open");
        let mut model = Model::with_hidden(backend, vec!["title".into()]).expect("model");

        // Move a visible top-level key; the hidden `title` must keep its position.
        select(&mut model, &[Seg::Key("enabled".into())]);
        model.move_selected_up(); // enabled moves above version
        let src = model.source_snapshot();
        // title stays first (it was declared before version/enabled).
        let title = src.find("title").unwrap();
        let version = src.find("version").unwrap();
        let enabled = src.find("enabled").unwrap();
        assert!(
            title < version && title < enabled,
            "title stayed put:\n{src}"
        );
        assert!(enabled < version, "enabled moved above version:\n{src}");
    }

    #[test]
    fn inserts_a_root_level_key() {
        let mut model = sample_model();
        model.insert_key(&[], "root_flag", Value::Bool(true));
        let src = model.source_snapshot();
        assert!(src.contains("root_flag"), "root key inserted:\n{src}");
        assert!(src.contains("title = \"flower\""), "existing kept");
    }

    #[test]
    fn renames_a_key_losslessly() {
        let mut model = sample_model();
        select(&mut model, &[Seg::Key("version".into())]);
        model.rename_key(&[Seg::Key("version".into())], "revision");
        let src = model.source_snapshot();
        // fig may quote the new key (`"revision" = 1`); both are valid TOML.
        assert!(
            src.contains("revision") && src.contains("= 1"),
            "renamed with value kept:\n{src}"
        );
        assert!(!src.contains("version = 1"), "old key gone");
        // Selection re-anchored onto the renamed entry.
        assert_eq!(
            model.rows[model.selected].path,
            [Seg::Key("revision".into())]
        );
    }

    #[test]
    fn rename_rejects_a_sequence_item() {
        let mut model = sample_model();
        model.rename_key(
            &[
                Seg::Key("server".into()),
                Seg::Key("tags".into()),
                Seg::Index(0),
            ],
            "nope",
        );
        assert!(model.status.contains("mapping keys"));
    }

    #[test]
    fn schema_closed_vocabulary_rejects_an_unknown_edit() {
        use crate::schema::{Constraint, FieldRule};
        use fig_schema::{FieldType, PathPat, Term};
        let src = "audience = [\"public\"]\ntitle = \"note\"\n";
        let backend = FigBackend::open(src.as_bytes(), Format::Toml).expect("open");
        let mut model = Model::new(backend).expect("model");
        model.set_schema(crate::schema::Schema::new(vec![
            FieldRule::new(PathPat::each_item_of("audience"))
                .ty(FieldType::Str)
                .constraint(Constraint::Enum {
                    values: vec![Term::value("public"), Term::value("private")],
                    closed: true,
                }),
        ]));

        // An unknown value is rejected at the commit funnel; the document is
        // untouched (fig never sees the edit).
        select(&mut model, &[Seg::Key("audience".into()), Seg::Index(0)]);
        model.begin_edit();
        type_value(&mut model, "familly");
        assert!(
            model.status.contains("rejected"),
            "status: {}",
            model.status
        );
        assert!(
            model.source_snapshot().contains("public"),
            "document unchanged:\n{}",
            model.source_snapshot()
        );

        // A known value commits normally.
        model.begin_edit();
        type_value(&mut model, "private");
        let out = model.source_snapshot();
        assert!(out.contains("private"), "known value applied:\n{out}");
        assert!(!out.contains("public"), "old value replaced:\n{out}");
    }

    /// A declared field the document omits is otherwise unreachable — it has no
    /// row, because rows come from the document. This is what lets a frontend
    /// offer it.
    #[test]
    fn addable_fields_are_the_declared_keys_the_document_lacks() {
        use crate::schema::{Constraint, FieldRule};
        use fig_schema::{FieldType, PathPat, Term};
        let src = "audience = [\"public\"]\ntitle = \"note\"\n";
        let backend = FigBackend::open(src.as_bytes(), Format::Toml).expect("open");
        let mut model =
            Model::with_hidden(backend, vec!["title".into(), "updated".into()]).expect("model");
        model.set_schema(crate::schema::Schema::new(vec![
            // Present in the document — already reachable, so never offered.
            FieldRule::new(PathPat::key("audience")).ty(FieldType::Str),
            // An each-item rule governs *within* a field; it names none.
            FieldRule::new(PathPat::each_item_of("audience"))
                .ty(FieldType::Str)
                .constraint(Constraint::Enum {
                    values: vec![Term::value("public")],
                    closed: true,
                }),
            // Declared, absent, not managed — the one to offer.
            FieldRule::new(PathPat::key("created")).ty(FieldType::Str),
            // Declared and absent, but the embedder manages it.
            FieldRule::new(PathPat::key("updated")).ty(FieldType::Str),
        ]));

        let offered: Vec<_> = model
            .addable_fields()
            .iter()
            .map(|r| match r.at.0.as_slice() {
                [SegPat::Key(k)] => k.clone(),
                _ => unreachable!("only single-key rules are offered"),
            })
            .collect();
        assert_eq!(offered, vec!["created".to_string()]);

        // Once added it is a real row, so it stops being offered.
        model.insert_key(&[], "created", Value::Str("2026-07-24".into()));
        assert!(model.addable_fields().is_empty());
    }

    /// A derived field keeps its row — unlike a hidden one — but declines every
    /// mutation, because the workspace rewrites it on the next save regardless.
    #[test]
    fn a_derived_field_is_visible_but_declines_edits() {
        let src = "title = \"note\"\nupdated = \"2026-07-01\"\ncreated = \"2026-06-01\"\n";
        let backend = FigBackend::open(src.as_bytes(), Format::Toml).expect("open");
        let mut model = Model::with_managed(backend, vec!["title".into()], vec!["updated".into()])
            .expect("model");

        // Hidden means no row; derived means a row that is marked.
        let labels: Vec<&str> = model.rows.iter().map(|r| r.label.as_str()).collect();
        assert_eq!(labels, vec!["updated", "created"]);
        assert!(model.is_derived(&[Seg::Key("updated".into())]));
        assert!(!model.is_derived(&[Seg::Key("created".into())]));

        // Every shape of mutation is declined, and the document is untouched.
        model.set_scalar_text(&[Seg::Key("updated".into())], "2026-01-01");
        assert!(model.status.contains("maintained by the workspace"));
        model.rename_key(&[Seg::Key("updated".into())], "modified");
        assert!(model.status.contains("maintained by the workspace"));
        model.selected = 0;
        model.delete_selected();
        assert!(model.status.contains("maintained by the workspace"));
        let out = model.source_snapshot();
        assert!(
            out.contains("updated = \"2026-07-01\""),
            "unchanged:\n{out}"
        );

        // A neighbouring ordinary field still edits normally.
        model.set_scalar_text(&[Seg::Key("created".into())], "2026-06-15");
        assert!(model.source_snapshot().contains("2026-06-15"));
    }

    /// Without a schema there is nothing to declare, so nothing is offered —
    /// a standalone config keeps the free-text add path.
    #[test]
    fn addable_fields_are_empty_without_a_schema() {
        let src = "title = \"note\"\n";
        let backend = FigBackend::open(src.as_bytes(), Format::Toml).expect("open");
        let model = Model::new(backend).expect("model");
        assert!(model.addable_fields().is_empty());
    }

    #[test]
    fn schema_typed_field_keeps_a_numeric_string_as_text() {
        use crate::schema::FieldRule;
        use fig_schema::{FieldType, PathPat};
        let src = "code = \"x\"\n";
        let backend = FigBackend::open(src.as_bytes(), Format::Toml).expect("open");
        let mut model = Model::new(backend).expect("model");
        model.set_schema(crate::schema::Schema::new(vec![
            FieldRule::new(PathPat::key("code")).ty(FieldType::Str),
        ]));

        select(&mut model, &[Seg::Key("code".into())]);
        model.begin_edit();
        type_value(&mut model, "123");
        // Schema says `str`, so the buffer stays a quoted string rather than being
        // coerced to an integer the way the shape-guessing heuristic would.
        let out = model.source_snapshot();
        assert!(out.contains("code = \"123\""), "kept as string:\n{out}");
    }

    /// The point of a default-collapsed set: the *opening* frame is already
    /// folded, without a toggle pass that walks the selection across the document.
    #[test]
    fn containers_can_arrive_collapsed() {
        let backend = FigBackend::open(SAMPLE.as_bytes(), Format::Toml).expect("open");
        let model = Model::with_collapsed(
            backend,
            Vec::new(),
            Vec::new(),
            vec![
                vec![Seg::Key("server".into())],
                // Naming a scalar is inert, not an error — a caller collapses the
                // keys it means to without first sorting containers from scalars.
                vec![Seg::Key("title".into())],
            ],
        )
        .expect("model");

        let server = model
            .rows
            .iter()
            .find(|r| r.path == [Seg::Key("server".into())])
            .expect("server row");
        assert!(!server.expanded, "collapsed before the first frame");
        assert!(
            !model.rows.iter().any(|r| r.path.len() > 1),
            "no descendant rows: {:?}",
            model.rows.iter().map(|r| &r.label).collect::<Vec<_>>()
        );
        // The inert scalar path didn't cost `title` its row.
        assert!(
            model
                .rows
                .iter()
                .any(|r| r.path == [Seg::Key("title".into())])
        );
        assert_eq!(model.selected, 0, "selection untouched");
    }

    /// Unlike `activate`, folding by path is not a selection move — that is the
    /// whole reason a caller reaches for it.
    #[test]
    fn set_collapsed_folds_by_path_without_moving_the_selection() {
        let mut model = sample_model();
        select(&mut model, &[Seg::Key("title".into())]);

        model.set_collapsed(&[Seg::Key("server".into())], true);
        assert!(model.is_collapsed(&[Seg::Key("server".into())]));
        assert!(
            !model.rows.iter().any(|r| r.path.len() > 1),
            "children hidden"
        );
        assert_eq!(
            model.rows[model.selected].path,
            [Seg::Key("title".into())],
            "selection stayed on title"
        );

        model.set_collapsed(&[Seg::Key("server".into())], false);
        assert!(!model.is_collapsed(&[Seg::Key("server".into())]));
        assert!(
            model
                .rows
                .iter()
                .any(|r| r.path == [Seg::Key("server".into()), Seg::Key("host".into())])
        );
        assert_eq!(model.rows[model.selected].path, [Seg::Key("title".into())]);
    }

    /// The one case where the selection *must* move: it was inside the fold.
    #[test]
    fn set_collapsed_reanchors_a_selection_it_swallowed() {
        let mut model = sample_model();
        select(
            &mut model,
            &[Seg::Key("server".into()), Seg::Key("host".into())],
        );
        model.set_collapsed(&[Seg::Key("server".into())], true);
        assert_eq!(
            model.rows[model.selected].path,
            [Seg::Key("server".into())],
            "landed on the container that swallowed it"
        );
    }

    /// The insert/append counterparts of the type-directed scalar edit: without
    /// them a caller shape-guesses, and `2026` lands in a `str` list as an integer.
    #[test]
    fn insert_and_append_are_type_directed_by_the_schema() {
        use crate::schema::FieldRule;
        use fig_schema::{FieldType, PathPat};
        let src = "tags = [\"alpha\"]\n\n[meta]\nk = \"v\"\n";
        let backend = FigBackend::open(src.as_bytes(), Format::Toml).expect("open");
        let mut model = Model::new(backend).expect("model");
        model.set_schema(crate::schema::Schema::new(vec![
            // The *items* of `tags` are strings — the list itself is a seq.
            FieldRule::new(PathPat::each_item_of("tags")).ty(FieldType::Str),
            FieldRule::new(PathPat::key("year")).ty(FieldType::Str),
            FieldRule::new(PathPat(vec![
                fig_schema::SegPat::Key("meta".into()),
                fig_schema::SegPat::Key("code".into()),
            ]))
            .ty(FieldType::Str),
        ]));

        model.append_item_text(&[Seg::Key("tags".into())], "2026");
        model.insert_key_text(&[], "year", "2026");
        // The nested case flower-ffi and Diaryx both shape-guessed.
        model.insert_key_text(&[Seg::Key("meta".into())], "code", "2026");

        let out = model.source_snapshot();
        assert!(
            !out.contains("2026,") && !out.contains("[2026]") && !out.contains("= 2026"),
            "no bare integers survived the schema:\n{out}"
        );
        assert_eq!(
            model.value_at(&[Seg::Key("tags".into()), Seg::Index(1)]),
            Some(&Value::Str("2026".into())),
            "list item took the each-item type:\n{out}"
        );
        assert_eq!(
            model.value_at(&[Seg::Key("year".into())]),
            Some(&Value::Str("2026".into()))
        );
        assert_eq!(
            model.value_at(&[Seg::Key("meta".into()), Seg::Key("code".into())]),
            Some(&Value::Str("2026".into()))
        );
    }

    /// With no rule to consult they fall back to the same shape-guessing the raw
    /// `insert_key`/`append_item` callers do today, so a standalone config is
    /// unaffected.
    #[test]
    fn insert_and_append_text_shape_guess_without_a_schema() {
        let mut model = sample_model();
        model.append_item_text(&[Seg::Key("server".into()), Seg::Key("tags".into())], "42");
        model.insert_key_text(&[], "count", "7");
        assert_eq!(
            model.value_at(&[
                Seg::Key("server".into()),
                Seg::Key("tags".into()),
                Seg::Index(2)
            ]),
            Some(&Value::Int(42))
        );
        assert_eq!(
            model.value_at(&[Seg::Key("count".into())]),
            Some(&Value::Int(7))
        );
    }

    /// The walkers a backend needs, over a plain `Value` — no `Model` in reach.
    #[test]
    fn tree_walkers_resolve_paths_and_reject_mismatches() {
        let model = sample_model();
        let root = model.value_at(&[]).expect("root");

        assert_eq!(
            tree::value_at(root, &[Seg::Key("server".into()), Seg::Key("port".into())]),
            Some(&Value::Int(8080))
        );
        assert_eq!(
            tree::seq_len(root, &[Seg::Key("server".into()), Seg::Key("tags".into())]),
            Some(2)
        );
        // Not a sequence, versus not there at all — both `None`, and neither is a
        // length of zero a caller could mistake for an empty list.
        assert_eq!(tree::seq_len(root, &[Seg::Key("title".into())]), None);
        assert_eq!(tree::seq_len(root, &[Seg::Key("absent".into())]), None);
        assert_eq!(
            tree::map_keys(root, &[Seg::Key("server".into())]),
            Some(vec![
                "host".to_string(),
                "port".to_string(),
                "tags".to_string(),
                "limits".to_string()
            ])
        );
        assert_eq!(tree::map_keys(root, &[Seg::Key("title".into())]), None);
        // A key step into a sequence resolves to nothing rather than guessing.
        assert_eq!(
            tree::value_at(
                root,
                &[
                    Seg::Key("server".into()),
                    Seg::Key("tags".into()),
                    Seg::Key("0".into())
                ]
            ),
            None
        );
    }

    #[test]
    fn navigation_folds_and_reanchors() {
        let mut model = sample_model();

        select(&mut model, &[Seg::Key("server".into())]);
        model.collapse_or_leave();
        assert!(
            !model
                .rows
                .iter()
                .any(|r| r.path == [Seg::Key("server".into()), Seg::Key("host".into())]),
            "collapsed children hidden"
        );
        assert_eq!(model.rows[model.selected].path, [Seg::Key("server".into())]);
    }

    // ── the page projection ───────────────────────────────────────────────

    fn key(k: &str) -> Seg {
        Seg::Key(k.to_string())
    }

    /// A model in the page view, cursor on the root page.
    fn paged_model() -> Model<FigBackend> {
        let mut model = sample_model();
        model.set_view(ViewMode::Pages);
        model
    }

    fn page_labels(model: &Model<FigBackend>) -> Vec<String> {
        model.page().items.iter().map(|i| i.label.clone()).collect()
    }

    fn selected_label(model: &Model<FigBackend>) -> String {
        model.page_item().expect("a selected item").label.clone()
    }

    #[test]
    fn drilling_opens_a_page_and_backing_out_returns_the_cursor_to_it() {
        let mut model = paged_model();
        assert!(model.focus().is_empty());

        // Down to `server`, then in.
        for _ in 0..3 {
            model.page_move_down();
        }
        assert_eq!(selected_label(&model), "server");
        model.page_enter();

        assert_eq!(model.focus(), &[key("server")]);
        assert_eq!(selected_label(&model), "host");

        model.page_back();
        assert!(model.focus().is_empty());
        assert_eq!(selected_label(&model), "server");
    }

    #[test]
    fn depth_costs_a_page_not_a_column() {
        let mut model = paged_model();
        // Two levels down, and the page is still four items of one rank plus the
        // members of the groups inlined into it — never an indentation ladder.
        model.focus_on(&[key("server"), key("limits")]);
        assert_eq!(model.focus(), &[key("server")]);
        assert!(model.page().items.iter().all(|i| i.inset <= 1));
        assert_eq!(selected_label(&model), "limits");

        // A group header opens nothing — its members are already here — so `l`
        // steps onto the first of them instead.
        model.page_enter();
        assert_eq!(model.focus(), &[key("server")]);
        assert_eq!(selected_label(&model), "max_connections");
    }

    #[test]
    fn raising_the_inline_budget_turns_the_root_page_into_the_document() {
        let mut model = paged_model();
        model.set_inline_budget(InlineBudget::new(99, 8));

        // Everything inlines, so the cursor can stand on the deepest member
        // without ever leaving the root page…
        model.focus_on(&[key("server"), key("limits"), key("timeout")]);
        assert!(model.focus().is_empty());
        assert_eq!(selected_label(&model), "timeout");
        assert!(model.page().items.iter().any(|i| i.inset == 2));

        // …and with nothing left to drill into, a second pane has no job.
        assert!(model.pages_would_degenerate());

        // Back to the default, the same node is reached through its page again.
        model.set_inline_budget(InlineBudget::default());
        model.focus_on(&[key("server"), key("limits"), key("timeout")]);
        assert_eq!(model.focus(), &[key("server")]);
    }

    #[test]
    fn a_group_header_never_opens_a_page_that_repeats_it() {
        let mut model = paged_model();
        model.focus_on(&[key("server")]);
        model.page_enter();
        for header in ["tags", "limits"] {
            let at = model
                .page()
                .items
                .iter()
                .position(|i| i.label == header)
                .expect("the group header");
            assert!(!model.page().items[at].is_drill());
            // Whatever the cursor does, the focused page never becomes the group's.
            model.page_enter();
            assert_eq!(model.focus(), &[key("server")]);
        }
    }

    #[test]
    fn an_edit_made_from_a_page_is_lossless() {
        let mut model = paged_model();
        // An inlined member, two ranks below the page's focus — the case where the
        // page's layout and the document's shape disagree most.
        model.focus_on(&[key("server"), key("limits"), key("timeout")]);
        assert_eq!(model.focus(), &[key("server")]);
        assert_eq!(selected_label(&model), "timeout");

        model.begin_edit();
        type_value(&mut model, "45.5");

        let src = model.source_snapshot();
        assert_eq!(src, SAMPLE.replace("timeout = 30.5", "timeout = 45.5"));
        assert!(model.dirty);
        // The cursor stayed on the field that was edited, in both projections.
        assert_eq!(selected_label(&model), "timeout");
        assert_eq!(
            model.rows[model.selected].path,
            vec![key("server"), key("limits"), key("timeout")]
        );
    }

    #[test]
    fn losing_the_container_you_are_standing_in_pops_you_out() {
        // `b` nests a container, so it is a real drill rather than an inlined
        // group — the only kind of row a page can be opened from.
        let backend =
            FigBackend::open(br#"{"a": {"b": {"c": {"d": 1}}}}"#, Format::Json).expect("open");
        let mut model = Model::new(backend).expect("model");
        model.set_view(ViewMode::Pages);
        model.focus_on(&[key("a"), key("b")]);
        model.page_enter();
        assert_eq!(model.focus(), &[key("a"), key("b")]);

        // Replace the container the page is listing with a scalar: the focus now
        // names something that cannot be listed at all.
        model.set_value_at(&[key("a"), key("b")], Value::Int(1));

        assert_eq!(model.focus(), &[key("a")]);
        assert_eq!(page_labels(&model), vec!["b"]);
    }

    #[test]
    fn switching_views_carries_the_selection_both_ways() {
        let mut model = sample_model();
        select(&mut model, &[key("server"), key("limits"), key("timeout")]);

        model.set_view(ViewMode::Pages);
        // The page that *lists* an inlined member is its grandparent's.
        assert_eq!(model.focus(), &[key("server")]);
        assert_eq!(selected_label(&model), "timeout");

        // Move within the page, and the tree lands where the page left off.
        model.page_move_up();
        assert_eq!(selected_label(&model), "max_connections");
        model.set_view(ViewMode::Tree);
        assert_eq!(
            model.rows[model.selected].path,
            vec![key("server"), key("limits"), key("max_connections")]
        );
    }

    #[test]
    fn switching_to_the_tree_opens_the_lineage_of_a_folded_selection() {
        let mut model = sample_model();
        model.set_collapsed(&[key("server")], true);
        model.set_view(ViewMode::Pages);
        model.focus_on(&[key("server"), key("host")]);

        model.set_view(ViewMode::Tree);
        // `server` was shut, so `host` had no row to land on until it was opened.
        assert!(!model.is_collapsed(&[key("server")]));
        assert_eq!(
            model.rows[model.selected].path,
            vec![key("server"), key("host")]
        );
    }

    /// The `repos.figl` shape: one key, holding a list too long to inline.
    fn list_model() -> Model<FigBackend> {
        let items: Vec<String> = (0..22)
            .map(|i| format!(r#"{{"name": "r{i}", "lang": "rust"}}"#))
            .collect();
        let src = format!(r#"{{"repo": [{}]}}"#, items.join(", "));
        let backend = FigBackend::open(src.as_bytes(), Format::Json).expect("open");
        let mut model = Model::new(backend).expect("model");
        model.set_view(ViewMode::Pages);
        model
    }

    #[test]
    fn a_document_that_is_one_list_opens_on_the_list() {
        let mut model = list_model();
        // Before: a root page whose one row names the file you just opened.
        assert_eq!(page_labels(&model), ["repo"]);

        model.enter_document();
        assert_eq!(model.focus(), &[Seg::Key("repo".into())]);
        assert_eq!(model.page().items.len(), 22);
        assert_eq!(model.page_selected(), 0);
        // The page it skipped is one step out, not gone: `repo` still renames,
        // deletes and takes an append there.
        model.page_back();
        assert_eq!(page_labels(&model), ["repo"]);
    }

    #[test]
    fn a_root_page_with_something_to_say_is_opened_where_it_is() {
        let mut model = paged_model();
        model.enter_document();
        assert!(model.focus().is_empty());
        assert_eq!(selected_label(&model), "title");
    }

    #[test]
    fn the_page_leads_the_split_when_the_one_behind_it_holds_a_single_row() {
        let mut model = list_model();
        model.enter_document();
        // The root page holds one row, so drawing it beside this one would
        // spend half the width on something nobody can choose between. This
        // page leads instead, and the other pane previews what it opens.
        assert!(model.page_leads_the_split());
        assert!(!model.pages_would_degenerate());
        assert_eq!(model.peek_page().expect("the first repo").items.len(), 2);

        // A root page with four rows on it is worth a pane, so it keeps one.
        let mut model = paged_model();
        model.focus_on(&[Seg::Key("server".into())]);
        model.page_enter();
        assert!(!model.page_leads_the_split());
    }

    #[test]
    fn fitting_the_room_puts_a_document_that_fits_on_one_page() {
        let mut model = paged_model();
        assert!(model.page().has_drills());

        // Twelve rows of document, and room for them.
        model.fit_to_room(12);
        assert!(!model.page().has_drills());
        assert!(model.pages_would_degenerate());
        assert_eq!(page_labels(&model).len(), 12);

        // One row short and the founding rule is back.
        model.fit_to_room(11);
        assert!(model.page().has_drills());
        assert_eq!(
            page_labels(&model),
            ["title", "version", "enabled", "server"]
        );
    }

    #[test]
    fn fitting_the_room_leaves_the_cursor_and_the_focus_where_they_were() {
        // A resize is not a navigation. It changes how much of the document a
        // page shows, and nothing about where the reader is in it.
        let mut model = list_model();
        model.enter_document();
        model.page_move_down();
        model.page_move_down();
        let (focus, at) = (model.focus().to_vec(), selected_label(&model));
        model.fit_to_room(80);
        assert_eq!(model.focus(), focus.as_slice());
        assert_eq!(selected_label(&model), at);
    }

    #[test]
    fn a_document_poured_onto_one_page_wastes_a_second_pane_wherever_you_are() {
        // Nothing to navigate to from the root, so there is no lineage to put
        // two panes on — even standing one level in, where a parent page and a
        // page would otherwise be two halves that repeat each other.
        let mut model = list_model();
        model.enter_document();
        model.set_inline_budget(InlineBudget::new(99, 8));
        assert!(!model.focus().is_empty());
        assert!(model.pages_would_degenerate());
    }

    #[test]
    fn a_flat_document_would_waste_a_second_pane() {
        let flat = FigBackend::open(
            b"a = 1
b = 2
",
            Format::Toml,
        )
        .expect("open");
        let flat = Model::new(flat).expect("model");
        assert!(flat.pages_would_degenerate());
        assert!(!sample_model().pages_would_degenerate());
    }

    #[test]
    fn the_root_page_previews_what_the_cursor_would_open() {
        let mut model = paged_model();
        assert_eq!(selected_label(&model), "title");
        assert!(model.peek_page().is_none(), "a scalar has no page");

        for _ in 0..3 {
            model.page_move_down();
        }
        let peek = model.peek_page().expect("server's page");
        assert_eq!(peek.focus, vec![key("server")]);
        assert_eq!(peek.breadcrumb("‹document›"), "server");
    }

    #[test]
    fn opening_a_compressed_row_lands_past_the_pages_that_say_nothing() {
        let backend = FigBackend::open(
            br#"{"exports": {"journal": {"label": "x", "gate": {"f": 1}}}, "z": 1}"#,
            Format::Json,
        )
        .expect("open");
        let mut model = Model::new(backend).expect("model");
        model.set_view(ViewMode::Pages);

        model.page_enter();
        // One step, two levels: the `exports` page held nothing but `journal`.
        assert_eq!(model.focus(), &[key("exports"), key("journal")]);
        assert_eq!(
            model.page().breadcrumb("‹document›"),
            "exports › journal",
            "the trail still shows what was skipped"
        );

        // Backing out retraces the step: one tap in was two levels, so one tap
        // out is two levels, and it lands on the page that listed the row rather
        // than on the page the compression existed to skip.
        model.page_back();
        assert!(model.focus().is_empty());
        // The cursor is on the row that was opened, which still addresses
        // `exports` and still renames it.
        assert_eq!(
            model.page_item().map(|i| i.label.clone()),
            Some("exports".into())
        );
        assert!(model.page_item().unwrap().can_rename());
    }

    #[test]
    fn the_left_pane_is_the_page_that_listed_the_row_not_the_level_above() {
        let backend = FigBackend::open(
            br#"{"exports": {"journal": {"label": "x", "gate": {"f": 1}}}, "z": 1}"#,
            Format::Json,
        )
        .expect("open");
        let mut model = Model::new(backend).expect("model");
        model.set_view(ViewMode::Pages);
        model.page_enter();
        assert_eq!(model.focus(), &[key("exports"), key("journal")]);

        // One level out is `exports`, whose page holds nothing but the row that
        // was tapped — the page the compression exists to skip. The left pane
        // walks past it to the page that actually listed the row.
        assert!(
            model.parent_page().focus.is_empty(),
            "the root, not `exports`"
        );
        // And it can still mark what was opened: the compressed row answers for
        // its whole chain.
        let marked = model
            .parent_page()
            .position_of(model.focus())
            .expect("marked");
        assert_eq!(model.parent_page().items[marked].label, "exports");

        // And backing out agrees with the pane: `exports` is skipped both ways,
        // so the page on the left is the page you land on.
        model.page_back();
        assert!(model.focus().is_empty());
        assert_eq!(model.focus(), model.parent_page().focus);
    }

    #[test]
    fn a_compressed_row_still_answers_ops_as_its_outermost_node() {
        let backend = FigBackend::open(
            br#"{"exports": {"journal": {"label": "x", "gate": {"f": 1}}}, "z": 1}"#,
            Format::Json,
        )
        .expect("open");
        let mut model = Model::new(backend).expect("model");
        model.set_view(ViewMode::Pages);

        // Deleting a row reading `exports › journal` takes the whole chain, so
        // no empty `exports: {}` is left behind to delete separately.
        model.delete_selected();
        assert!(!model.source_snapshot().contains("exports"));
        assert!(!model.source_snapshot().contains("journal"));
        assert!(model.source_snapshot().contains('z'));
    }

    /// A host driving both surfaces — a metadata pane beside a settings page —
    /// hands a *row* index to a model left standing in the page projection. The
    /// index means nothing there, and before `select_row` asserted the tree the
    /// delete that followed read the page cursor and removed a different node.
    #[test]
    fn a_row_index_deletes_the_row_it_names_even_from_the_page_projection() {
        let backend = FigBackend::open(
            br#"{"alpha": 1, "beta": 2, "gamma": {"inner": 3}}"#,
            Format::Json,
        )
        .expect("open");
        let mut model = Model::new(backend).expect("model");

        // Go and stand somewhere in the page projection, with its cursor on a
        // different node than the row index below names.
        model.set_view(ViewMode::Pages);
        model.page_move_down();
        assert_eq!(
            model.page_item().map(|i| i.label.clone()),
            Some("beta".into())
        );

        // Now the other surface speaks, in its own coordinates, without first
        // announcing a switch.
        model.select_row(0);
        model.delete_selected();

        assert!(
            !model.source_snapshot().contains("alpha"),
            "row 0 was `alpha`"
        );
        assert!(
            model.source_snapshot().contains("beta"),
            "the page cursor was not the target"
        );
    }

    /// The mirror: page vocabulary asserts pages, so a page op after tree work
    /// acts on the page cursor rather than on whatever row was last selected.
    #[test]
    fn a_page_op_acts_on_the_page_cursor_even_from_the_tree_projection() {
        // `gamma` holds a container *and* a scalar, so it neither inlines into
        // the root page nor compresses into a chain — it is a plain drill row.
        let backend = FigBackend::open(
            br#"{"alpha": 1, "beta": 2, "gamma": {"inner": {"deep": 3}, "flag": true}}"#,
            Format::Json,
        )
        .expect("open");
        let mut model = Model::new(backend).expect("model");

        model.select_row(0);
        assert_eq!(model.view(), ViewMode::Tree);

        // `page_enter` is page vocabulary; it must not be read against the tree.
        model.page_move_down();
        model.page_move_down();
        model.page_enter();
        assert_eq!(model.view(), ViewMode::Pages);
        assert_eq!(model.focus(), &[key("gamma")]);
    }

    #[test]
    fn backing_out_past_the_root_is_inert() {
        let mut model = paged_model();
        model.page_back();
        assert!(model.focus().is_empty());
        assert_eq!(model.page_selected(), 0);
    }

    /// Arriving and leaving cost the same number of steps.
    ///
    /// `views` holds only `date`, so its row compresses and `page_enter` lands
    /// straight on `views.date`. Popping one raw segment would put you on the
    /// `views` page — one row, named `date`, which is the page compression
    /// exists to skip — and make the way out twice as long as the way in.
    #[test]
    fn backing_out_retraces_what_entering_skipped() {
        let backend = FigBackend::open(
            br#"{"views": {"date": {"icon": "calendar", "group": ["created"], "by": "year"}}, "fixity": "all"}"#,
            Format::Json,
        )
        .expect("open");
        let mut model = Model::new(backend).expect("model");
        model.set_view(ViewMode::Pages);

        // One step in, past `views`, to the first page with more on it than the
        // name that was tapped.
        model.page_enter();
        assert_eq!(model.focus(), &[key("views"), key("date")]);

        // One step out, to the page that listed the row — not to `views`.
        model.page_back();
        assert!(model.focus().is_empty());
        // And the cursor is back on the row that was opened: a compressed row
        // answers for its whole chain, so the child path finds it.
        assert_eq!(model.page_selected(), 0);
    }

    /// The skipped page held nothing but the chain, so skipping it takes no
    /// operation away: the row on the page we land on still addresses `views`.
    #[test]
    fn the_skipped_level_is_still_operable_from_the_row() {
        let backend = FigBackend::open(
            br#"{"views": {"date": {"icon": "calendar", "group": ["created"], "by": "year"}}, "fixity": "all"}"#,
            Format::Json,
        )
        .expect("open");
        let mut model = Model::new(backend).expect("model");
        model.set_view(ViewMode::Pages);

        model.page_enter();
        model.page_back();
        let row = model.page_item().expect("a row under the cursor");
        assert_eq!(row.path, vec![key("views")]);
        assert_eq!(row.descend_to, vec![key("views"), key("date")]);
    }

    #[test]
    fn the_two_panes_are_consecutive_levels_of_one_lineage() {
        // Every level here holds two things, so no row compresses and each
        // `page_enter` moves exactly one level — which is what this is about.
        let backend = FigBackend::open(
            br#"{"jobs": {"plan": {"steps": {"a": 1, "b": {"c": 2}}, "id": 3}, "name": "x"}}"#,
            Format::Json,
        )
        .expect("open");
        let mut model = Model::new(backend).expect("model");
        model.set_view(ViewMode::Pages);

        // At the root there is no parent to show on the left.
        assert!(model.parent_page().is_empty());

        model.page_enter(); // jobs
        assert_eq!(model.parent_page().focus, Vec::<Seg>::new());
        model.page_enter(); // jobs.plan
        assert_eq!(model.parent_page().focus, vec![key("jobs")]);
        model.page_enter(); // jobs.plan.steps
        assert_eq!(model.parent_page().focus, vec![key("jobs"), key("plan")]);

        // The left pane can always mark the row the right one was opened from.
        assert!(model.parent_page().position_of(model.focus()).is_some());
    }
}