firestore-cli 0.3.0

fsq, a command line client for Google Firestore: a SQL REPL with tables, query plans and index statements, and a scripting mode with JSON output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
use super::editor::{FilterEditor, FilterHistory, LineEdit, LineEditor, Recall, ValueEditor};
use super::external::{EditorFile, EditorOutcome, ExternalDraft};
use super::new_field::{NewField, NewFieldStep};
use super::tree::{Expansion, FieldParent, Fold, Listing, MaskPath, NodePath, Row, Tree};
use super::write::{
    Change, DocumentWrite, Draft, Edit, Halt, PartialDelete, RecursiveDelete, RecursiveOutcome,
    Step, WriteOutcome,
};
use super::BrowseTarget;
use crate::describe::CollectionPath;
use crate::errors::{FsqError, FsqResult};
use crate::field_path::FieldPath;
use firestore::gcloud_sdk::google::firestore::v1::value::ValueType;
use firestore::gcloud_sdk::google::firestore::v1::Value;
use firestore::{FirestoreCollectionId, FirestoreDb, FirestoreDocument, FirestoreVector};
use sqlparser::ast::{self, Expr, LimitClause, OrderByKind, Query, Statement, ValueWithSpan};
use sqlparser::dialect::BigQueryDialect;
use sqlparser::parser::Parser;
use std::cmp::Ordering;
use std::collections::HashSet;
use std::fmt::{Display, Formatter};

/// How many documents a level shows when its filter has no `LIMIT` of its own.
pub const BROWSE_DOCUMENT_LIMIT: usize = 100;

/// The end of a `SELECT` after its `FROM`, such as `WHERE …`, `ORDER BY …` and `LIMIT …`, as
/// typed, without the `;` that ends a statement, and what the browser reads from it. An empty one
/// reads the collection as it is.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FilterTail {
    text: String,
    /// The `LIMIT` of the query this filter ends, `None` when it has none.
    limit: Option<Limit>,
    /// The field the documents are ordered by first, when the first key of the `ORDER BY` of the
    /// query is a field path, such as `rating` or `address.city`.
    order_key: Option<NodePath>,
}

/// The `LIMIT` of the query a filter ends.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Limit {
    Count(usize),
    /// A limit that is not a number, such as `LIMIT 2 + 3`.
    Uncounted,
}

impl Limit {
    /// The `LIMIT` of `query`. A field named `limit`, the `LIMIT` of a subquery and an `OFFSET`
    /// alone bound nothing.
    fn of(query: &Query) -> Option<Self> {
        let limit = match query.limit_clause.as_ref()? {
            LimitClause::LimitOffset { limit, .. } => limit.as_ref()?,
            LimitClause::OffsetCommaLimit { limit, .. } => limit,
        };
        Some(match limit {
            Expr::Value(ValueWithSpan {
                value: ast::Value::Number(count, _),
                ..
            }) => count.parse().map_or(Self::Uncounted, Self::Count),
            _ => Self::Uncounted,
        })
    }
}

impl FilterTail {
    pub fn is_empty(&self) -> bool {
        self.text.is_empty()
    }

    /// Whether the query this filter ends has a `LIMIT` of its own.
    pub fn has_limit(&self) -> bool {
        self.limit.is_some()
    }

    /// The most documents the query of this filter reads: its own `LIMIT` when that is a number,
    /// else [`BROWSE_DOCUMENT_LIMIT`] when it has none. `None` for a `LIMIT` that is not a number.
    pub fn effective_limit(&self) -> Option<usize> {
        match self.limit {
            None => Some(BROWSE_DOCUMENT_LIMIT),
            Some(Limit::Count(count)) => Some(count),
            Some(Limit::Uncounted) => None,
        }
    }

    pub fn order_key(&self) -> Option<&NodePath> {
        self.order_key.as_ref()
    }
}

/// The field path of the first key of the `ORDER BY` of `query`.
fn first_order_key(query: &Query) -> Option<NodePath> {
    let OrderByKind::Expressions(keys) = &query.order_by.as_ref()?.kind else {
        return None;
    };
    let names = match &keys.first()?.expr {
        Expr::Identifier(name) => std::slice::from_ref(name),
        Expr::CompoundIdentifier(names) => names.as_slice(),
        _ => return None,
    };
    Some(
        names
            .iter()
            .fold(NodePath::default(), |path, name| path.field(&name.value)),
    )
}

impl From<&str> for FilterTail {
    /// The filter `text`, read as the parser the firestore crate translates with reads it. A
    /// filter that does not parse has no limit and no order key.
    fn from(text: &str) -> Self {
        let text = text.trim();
        let text = text.strip_suffix(';').unwrap_or(text).trim_end();
        let statement = format!("SELECT * FROM t\n{text}");
        let parsed = Parser::parse_sql(&BigQueryDialect {}, &statement);
        let query = match parsed.as_deref() {
            Ok([Statement::Query(query)]) => Some(query.as_ref()),
            _ => None,
        };
        Self {
            text: text.to_string(),
            limit: query.and_then(Limit::of),
            order_key: query.and_then(first_order_key),
        }
    }
}

impl Display for FilterTail {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.text)
    }
}

/// Names one Firestore call of the browser, so that an answer that arrives after the browser
/// stopped waiting for it is told apart from the one it waits for.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RequestId(u64);

impl RequestId {
    fn following(self) -> Self {
        Self(self.0 + 1)
    }
}

/// The query of the documents of one level.
#[derive(Debug, PartialEq, Eq)]
pub struct DocumentsQuery {
    pub request: RequestId,
    pub collection: CollectionPath,
    pub filter: FilterTail,
}

impl DocumentsQuery {
    /// ``SELECT * FROM `<collection>` <filter>``, limited to [`BROWSE_DOCUMENT_LIMIT`] documents
    /// when the filter sets no limit.
    pub fn sql(&self) -> String {
        let collection = self.collection.to_string().replace('`', "``");
        let mut sql = format!("SELECT * FROM `{collection}`");
        // The filter and the limit each start a line: an error in the filter then names the
        // column of the filter as typed, and a comment that ends the filter cannot swallow the
        // limit.
        if !self.filter.is_empty() {
            sql.push('\n');
            sql.push_str(&self.filter.text);
        }
        if !self.filter.has_limit() {
            sql.push_str(&format!("\nLIMIT {BROWSE_DOCUMENT_LIMIT}"));
        }
        sql
    }
}

#[derive(Debug)]
pub enum Load {
    Done,
    Pending {
        request: RequestId,
        filter: FilterTail,
    },
    /// Ctrl-C stopped the query of `filter`, and the documents before it stay.
    Stopped {
        filter: FilterTail,
    },
    /// The query of `filter` failed, and the documents before it stay.
    Failed {
        error: FsqError,
        filter: FilterTail,
    },
}

/// One collection on the way down from the collection the browser opened.
#[derive(Debug)]
pub struct Level {
    path: CollectionPath,
    /// The filter the documents were read with. A filter that is still running or failed is in
    /// [`Load`] instead, so that this one never names documents it did not read.
    filter: FilterTail,
    /// `None` until the first query of the level answers.
    documents: Option<Vec<FirestoreDocument>>,
    /// The position of the selected document, 0 when there are none.
    selected: usize,
    tree: Tree,
    load: Load,
    /// The names of the documents created since the documents were read, which may not match
    /// their filter.
    created: HashSet<String>,
}

impl Level {
    /// A level that has read nothing yet, so that it names the filter it is reading with.
    fn loading(path: CollectionPath, filter: FilterTail, request: RequestId) -> Self {
        let pending = Load::Pending {
            request,
            filter: filter.clone(),
        };
        Self {
            path,
            filter,
            documents: None,
            selected: 0,
            tree: Tree::default(),
            load: pending,
            created: HashSet::new(),
        }
    }

    /// Stops waiting for the pending query, if there is one, and the documents before it stay.
    /// `false` when no query was pending.
    fn stop_waiting(&mut self) -> bool {
        let Load::Pending { filter, .. } = std::mem::replace(&mut self.load, Load::Done) else {
            return false;
        };
        self.load = Load::Stopped { filter };
        true
    }

    /// Puts `document`, as written or read again, in place of the document of the same name, and
    /// keeps the cursor and the open maps of its tree. A document the level does not show stays
    /// out of it.
    fn patch(&mut self, document: FirestoreDocument) {
        let Some(documents) = &mut self.documents else {
            return;
        };
        let Some(position) = documents
            .iter()
            .position(|shown| shown.name == document.name)
        else {
            return;
        };
        let before = std::mem::replace(&mut documents[position], document);
        if position == self.selected {
            self.tree.patch(&before, &documents[position]);
        }
    }

    /// Puts `document`, written where no document of its name was, in the level, marked new until
    /// the documents are read again: in place of a row of the same name the level still shows,
    /// else under the selected document, which it then is. The tree moves to it as the cursor
    /// would.
    fn insert(&mut self, document: FirestoreDocument) {
        self.created.insert(document.name.clone());
        if self.shows(&document.name) {
            self.patch(document);
            return;
        }
        let documents = self.documents.get_or_insert_with(Vec::new);
        if documents.is_empty() {
            documents.push(document);
            self.tree = Tree::default();
            return;
        }
        let position = self.selected + 1;
        documents.insert(position, document);
        self.tree
            .switch_document(&documents[self.selected], &documents[position]);
        self.selected = position;
    }

    fn shows(&self, name: &str) -> bool {
        self.documents
            .iter()
            .flatten()
            .any(|shown| shown.name == name)
    }

    /// Takes the document `name` out of the level, as deleted. The selection stays on its row,
    /// which the next document takes, and the tree moves to that document as the cursor would.
    fn remove(&mut self, name: &str) {
        let Some(documents) = &mut self.documents else {
            return;
        };
        let Some(position) = documents.iter().position(|shown| shown.name == name) else {
            return;
        };
        let removed = documents.remove(position);
        match position.cmp(&self.selected) {
            Ordering::Less => self.selected -= 1,
            Ordering::Equal => {
                self.selected = self.selected.min(documents.len().saturating_sub(1));
                match documents.get(self.selected) {
                    Some(next) => self.tree.switch_document(&removed, next),
                    None => self.tree = Tree::default(),
                }
            }
            Ordering::Greater => {}
        }
    }

    fn query(&self, request: RequestId, filter: FilterTail) -> DocumentsQuery {
        DocumentsQuery {
            request,
            collection: self.path.clone(),
            filter,
        }
    }

    /// The filter the next edit starts from: the one that last ran, whether or not it answered.
    fn filter_to_edit(&self) -> &FilterTail {
        match &self.load {
            Load::Pending { filter, .. }
            | Load::Stopped { filter }
            | Load::Failed { filter, .. } => filter,
            Load::Done => &self.filter,
        }
    }

    pub fn path(&self) -> &CollectionPath {
        &self.path
    }

    pub fn filter(&self) -> &FilterTail {
        &self.filter
    }

    /// The documents of the last query that answered, `None` before the first one has.
    pub fn documents(&self) -> Option<&[FirestoreDocument]> {
        self.documents.as_deref()
    }

    pub fn selected(&self) -> usize {
        self.selected
    }

    pub fn selected_document(&self) -> Option<&FirestoreDocument> {
        self.documents.as_ref()?.get(self.selected)
    }

    pub fn tree(&self) -> &Tree {
        &self.tree
    }

    pub fn load(&self) -> &Load {
        &self.load
    }

    /// Whether `document` was created since the documents were read, so that it may not match
    /// their filter.
    pub fn is_new(&self, document: &FirestoreDocument) -> bool {
        self.created.contains(&document.name)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pane {
    Documents,
    Tree,
}

/// A move of the cursor in the focused pane, or of the text of a popup, by rows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Movement {
    Up(usize),
    Down(usize),
    First,
    Last,
}

impl Movement {
    /// The position this leads to from `position` in a list of `len` rows, never past either end.
    pub fn applied_to(self, position: usize, len: usize) -> usize {
        let last = len.saturating_sub(1);
        match self {
            Self::Up(rows) => position.saturating_sub(rows),
            Self::Down(rows) => position.saturating_add(rows).min(last),
            Self::First => 0,
            Self::Last => last,
        }
    }
}

/// What the keys go to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    Panes,
    FilterEditor,
    /// The one-line editor of a value, over the filter editor when that is open too.
    ValueEditor,
    /// A change shown before it is written, waiting for `y`, `e` or `n`.
    Confirmation,
    /// The external editor, open on a value, or with a text it saved that did not read as one,
    /// waiting for `e` to open it again or `n`.
    ExternalEditor,
    /// The prompt for the name of a field being added.
    FieldName,
    /// The list of types of a field being added.
    FieldType,
    /// A popup, over the panes and over an editor when one is open too.
    Popup,
}

/// A box over the panes that takes every key until Esc or Ctrl-C closes it.
#[derive(Debug)]
pub enum Popup {
    /// The value at `path` in the selected document, whole, as it was when the popup opened.
    Value { path: NodePath, value: Value },
    /// The whole error of a failed query or listing.
    Error(Failure),
    /// Every key of the browser.
    Help,
}

/// What failed on the current level.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Failure {
    Query,
    Listing,
}

/// Which editor `e` and `E` open on a value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditorChoice {
    /// `e`: the one-line editor where it takes the value, else the external editor.
    Fitting,
    /// `E`: the external editor, on the value as tagged JSON.
    External,
}

/// What `e` or `E` edits.
enum EditTarget<'a> {
    Line(ValueEditor),
    /// The field at `path`, in the external editor.
    Field {
        path: MaskPath,
        value: &'a Value,
    },
    Document(&'a FirestoreDocument),
}

/// What `y` and `Y` put on the clipboard.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Copied {
    Value,
    /// The path of the value, as the bottom border of the tree shows it.
    Path,
}

#[derive(Debug)]
pub enum Message {
    Move(Movement),
    /// Expands the row under the cursor, opens a subcollection, or in the documents pane moves
    /// to the tree.
    Expand,
    /// Shows the value under the cursor whole, a leaf or an expanded map or array, and else
    /// does what [`Message::Expand`] does.
    Open,
    /// Expands the row under the cursor, or collapses it when it is expanded.
    Toggle,
    /// Collapses the row under the cursor or moves to the row it is in, and from a top-level row
    /// back to the documents. In the documents pane it goes back up as [`Message::Back`] does.
    Collapse,
    SwitchPane,
    /// Goes back up to the collection the current one was opened from.
    Back,
    /// Reads the documents of the current level again, with the filter they were read with.
    Reload,
    /// Shows the whole error of what failed, as [`Browser::failure`] names it.
    ShowError,
    ShowHelp,
    ClosePopup,
    EditFilter,
    Edit(LineEdit),
    /// Text pasted at once, which goes into the line being typed as one line. With no line being
    /// typed it is dropped.
    Paste(String),
    RunFilter,
    CancelFilter,
    /// Copies the value under the tree cursor, or in the value popup, or its path.
    Copy(Copied),
    /// Opens the filter editor with the filter of the documents whose field at the tree cursor
    /// holds the same value, when the value has a literal in SQL.
    FilterOnValue,
    /// Shows an earlier filter that ran, or a later one, in the filter editor.
    Recall(Recall),
    /// Opens an editor on the value under the tree cursor, from the tree or from the popup that
    /// shows the value whole: the one-line editor on a string on one line, a number, a boolean, a
    /// timestamp, a reference or a geopoint, and the external editor on any other value but a
    /// null, and on the whole array a value is inside. In the documents pane it opens the
    /// external editor on the selected document.
    EditValue,
    /// Opens the external editor on the value under the tree cursor as tagged JSON, which can
    /// change its type, also from its popup, or in the documents pane on the selected document.
    EditExternally,
    /// How the external editor ended, or why it did not run.
    EditorClosed(FsqResult<EditorOutcome>),
    /// Shows the change the value editor gives, to be confirmed. A text that does not read as a
    /// value of the type of its field stays in the editor, with its error, and one that reads as
    /// the value the field holds closes the editor.
    SubmitValue,
    /// Closes the value editor and changes nothing.
    CancelValue,
    /// Asks to delete the field under the tree cursor, also from the popup that shows its value,
    /// or in the documents pane the document. An element of an array is not deleted alone, since
    /// arrays are written whole.
    Delete,
    /// Opens the prompt for the name of a field to add where [`Browser::new_field_parent`] says.
    AddField,
    /// Goes on from the name of the field being added to the list of types, unless the name is
    /// refused.
    SubmitFieldName,
    /// Goes on from the type of the field being added to its value.
    PickFieldType,
    /// Drops the field being added before its value, and writes nothing.
    CancelNewField,
    /// Opens the external editor on a new document of the current collection, from the
    /// documents pane.
    NewDocument,
    /// Opens the external editor on a copy of the selected document under a new ID, from the
    /// documents pane.
    DuplicateDocument,
    /// Writes the change being confirmed.
    Confirm,
    /// Deletes the document being confirmed and every document under it, while
    /// [`Browser::offers_recursive_delete`].
    ConfirmRecursive,
    /// Goes back from the confirmation to the editor the change came from, with its text, and
    /// opens the external editor again on a text it saved that did not read.
    EditAgain,
    /// Drops the change being confirmed, unless it is being written.
    Discard,
    /// Ctrl-C, which ends the innermost thing going on: stops waiting for Firestore, else closes
    /// the popup, else the edit, else the filter editor, else quits.
    Interrupt,
    Quit,
    DocumentsLoaded {
        request: RequestId,
        outcome: FsqResult<Vec<FirestoreDocument>>,
    },
    SubcollectionsListed {
        request: RequestId,
        outcome: FsqResult<Vec<FirestoreCollectionId>>,
    },
    Written {
        request: RequestId,
        outcome: FsqResult<WriteOutcome>,
    },
    /// The count of documents the recursive delete `request` has deleted so far.
    RecursiveProgress {
        request: RequestId,
        deleted: usize,
    },
    /// How the recursive delete `request` ended. A failure is of the call, which ended without
    /// an answer.
    RecursivelyDeleted {
        request: RequestId,
        outcome: FsqResult<RecursiveOutcome>,
    },
    /// The document read again, `None` when it no longer exists.
    DocumentRead {
        request: RequestId,
        outcome: FsqResult<Option<FirestoreDocument>>,
    },
}

/// What the browser asks its caller to do.
#[derive(Debug, PartialEq)]
pub enum Effect {
    Query(DocumentsQuery),
    Write(DocumentWrite),
    DeleteRecursively(RecursiveDelete),
    /// Hands the terminal to the external editor on `file`, until it exits.
    OpenEditor(EditorFile),
    /// Reads `document`, a full resource name, again.
    ReadDocument {
        request: RequestId,
        document: String,
    },
    /// Lists the collections under `document`, a full resource name.
    ListSubcollections {
        request: RequestId,
        document: String,
    },
    /// Puts `text`, the value or the path `copied` names, on the terminal's clipboard.
    Copy {
        copied: Copied,
        text: String,
    },
    /// Stops every call still pending. A recursive delete stops once its request in flight
    /// answers, and still answers how it ended.
    Cancel,
    /// Drops the recursive delete at once, with its request in flight, and its answer with it.
    AbandonRecursiveDelete,
    Quit,
}

/// The state of a browser, changed only by [`Browser::update`] so that it can be tested without a
/// terminal or a database.
#[derive(Debug)]
pub struct Browser {
    current: Level,
    /// The levels the current one was opened from, the first one the browser opened first.
    parents: Vec<Level>,
    focus: Pane,
    filter_editor: Option<FilterEditor>,
    /// The change to a document that is being edited or confirmed.
    edit: Option<Edit>,
    /// The field being added, until its type is picked and the edit of its value starts.
    new_field: Option<NewField>,
    popup: Option<Popup>,
    history: FilterHistory,
    documents_path: String,
    last_request: RequestId,
}

impl Browser {
    /// A browser of `target`, which recalls the filters of `history`, and the query that reads
    /// its first documents.
    pub fn open(
        target: BrowseTarget,
        documents_path: &str,
        history: FilterHistory,
    ) -> (Self, Effect) {
        let request = RequestId::default().following();
        let current = Level::loading(target.collection, target.filter, request);
        let query = current.query(request, current.filter.clone());
        let browser = Self {
            current,
            parents: Vec::new(),
            focus: Pane::Documents,
            filter_editor: None,
            edit: None,
            new_field: None,
            popup: None,
            history,
            documents_path: documents_path.to_string(),
            last_request: request,
        };
        (browser, Effect::Query(query))
    }

    pub fn update(&mut self, message: Message) -> Option<Effect> {
        match message {
            Message::Move(movement) => self.move_cursor(movement),
            Message::Expand => return self.expand(),
            Message::Open => return self.open_at_cursor(),
            Message::Toggle => return self.toggle(),
            Message::Collapse => return self.collapse(),
            Message::SwitchPane => {
                self.focus = match self.focus {
                    Pane::Documents => Pane::Tree,
                    Pane::Tree => Pane::Documents,
                }
            }
            Message::Back => return self.back(),
            Message::Reload => {
                let filter = self.current.filter.clone();
                return Some(self.read(filter));
            }
            Message::ShowError => {
                if let Some(failure) = self.failure() {
                    self.popup = Some(Popup::Error(failure));
                }
            }
            Message::ShowHelp => self.popup = Some(Popup::Help),
            Message::ClosePopup => self.popup = None,
            Message::EditFilter => {
                self.filter_editor = Some(FilterEditor::from(self.current.filter_to_edit()))
            }
            Message::Edit(edit) => {
                if let Some(line) = self.line_mut() {
                    line.apply(edit);
                }
            }
            Message::Paste(pasted) => {
                let typing = matches!(
                    self.mode(),
                    Mode::FilterEditor | Mode::ValueEditor | Mode::FieldName
                );
                if let (true, Some(line)) = (typing, self.line_mut()) {
                    line.paste(&pasted);
                }
            }
            Message::RunFilter => return self.run_filter(),
            Message::CancelFilter => self.filter_editor = None,
            Message::Copy(copied) => {
                return self
                    .copy_text(copied)
                    .map(|text| Effect::Copy { copied, text })
            }
            Message::FilterOnValue => {
                if let Some(filter) = self.filter_on_cursor() {
                    self.filter_editor = Some(FilterEditor::from(&filter));
                }
            }
            Message::Recall(recall) => {
                if let Some(editor) = &mut self.filter_editor {
                    editor.recall(recall, &self.history);
                }
            }
            Message::EditValue => return self.edit_value(EditorChoice::Fitting),
            Message::EditExternally => return self.edit_value(EditorChoice::External),
            Message::EditorClosed(outcome) => self.editor_closed(outcome),
            Message::SubmitValue => self.edit = self.edit.take().and_then(Edit::submitted),
            Message::CancelValue => self.edit = None,
            Message::Delete => return self.delete(),
            Message::AddField => self.add_field(),
            Message::SubmitFieldName => {
                if let Some(new_field) = &mut self.new_field {
                    new_field.submit_name();
                }
            }
            Message::PickFieldType => return self.pick_field_type(),
            Message::CancelNewField => self.new_field = None,
            Message::NewDocument => return self.create_document(None),
            Message::DuplicateDocument => {
                let copied = self.current.selected_document().cloned()?;
                return self.create_document(Some(&copied));
            }
            Message::Confirm => return self.confirm(),
            Message::ConfirmRecursive => return self.confirm_recursive(),
            Message::EditAgain => {
                self.edit = self.edit.take().map(Edit::reopened);
                return self.external_editor();
            }
            Message::Discard => {
                if !self.edit.as_ref().is_some_and(Edit::is_waiting) {
                    self.edit = None;
                }
            }
            Message::Written { request, outcome } => return self.written(request, outcome),
            Message::RecursiveProgress { request, deleted } => {
                self.recursive_progress(request, deleted)
            }
            Message::RecursivelyDeleted { request, outcome } => {
                return self.recursively_deleted(request, outcome)
            }
            Message::DocumentRead { request, outcome } => self.document_read(request, outcome),
            Message::Interrupt => return self.interrupt(),
            Message::Quit => return Some(Effect::Quit),
            Message::DocumentsLoaded { request, outcome } => self.loaded(request, outcome),
            Message::SubcollectionsListed { request, outcome } => {
                self.current.tree.listed(request, outcome)
            }
        }
        None
    }

    fn next_request(&mut self) -> RequestId {
        self.last_request = self.last_request.following();
        self.last_request
    }

    fn move_cursor(&mut self, movement: Movement) {
        if let Some(new_field) = &mut self.new_field {
            new_field.move_type(movement);
            return;
        }
        let level = &mut self.current;
        match self.focus {
            Pane::Documents => {
                let Some(documents) = level.documents.as_deref() else {
                    return;
                };
                let selected = movement.applied_to(level.selected, documents.len());
                if selected != level.selected {
                    level
                        .tree
                        .switch_document(&documents[level.selected], &documents[selected]);
                    level.selected = selected;
                }
            }
            Pane::Tree => {
                if let Some(document) = level.selected_document() {
                    let rows = level.tree.rows(document).len();
                    let row = movement.applied_to(level.tree.cursor(), rows);
                    level.tree.select(row);
                }
            }
        }
    }

    fn expand(&mut self) -> Option<Effect> {
        let level = &mut self.current;
        let document = level.documents.as_ref()?.get(level.selected)?;
        if self.focus == Pane::Documents {
            self.focus = Pane::Tree;
            return None;
        }
        let expansion = level.tree.expand(document)?;
        let document = document.name.clone();
        Some(self.expanded(expansion, document))
    }

    fn open_at_cursor(&mut self) -> Option<Effect> {
        let level = &self.current;
        let document = level.selected_document()?;
        if self.focus == Pane::Tree {
            if let Some(Row::Field {
                path,
                value,
                fold: Fold::Leaf | Fold::Expanded,
            }) = level.tree.cursor_row(document)
            {
                let value = value.clone();
                self.popup = Some(Popup::Value { path, value });
                return None;
            }
        }
        self.expand()
    }

    fn toggle(&mut self) -> Option<Effect> {
        let level = &mut self.current;
        let document = level.documents.as_ref()?.get(level.selected)?;
        if self.focus == Pane::Documents {
            return None;
        }
        let expansion = level.tree.toggle(document)?;
        let document = document.name.clone();
        Some(self.expanded(expansion, document))
    }

    /// What `expansion` of the tree of `document`, a full resource name, asks of Firestore.
    fn expanded(&mut self, expansion: Expansion, document: String) -> Effect {
        match expansion {
            Expansion::ListSubcollections => {
                let request = self.next_request();
                self.current.tree.listing_started(request);
                Effect::ListSubcollections { request, document }
            }
            Expansion::OpenSubcollection(collection_id) => {
                let parent = FirestoreDb::relative_document_name(&self.documents_path, &document);
                let path = CollectionPath::in_document(parent, collection_id);
                self.go_down(path)
            }
        }
    }

    /// Goes down into the collection at `path`. The query of the level it leaves, if one is
    /// pending, gives way to the query of the new level.
    fn go_down(&mut self, path: CollectionPath) -> Effect {
        let request = self.next_request();
        let level = Level::loading(path, FilterTail::default(), request);
        let query = level.query(request, FilterTail::default());
        self.current.stop_waiting();
        self.parents
            .push(std::mem::replace(&mut self.current, level));
        self.focus = Pane::Documents;
        Effect::Query(query)
    }

    fn collapse(&mut self) -> Option<Effect> {
        if self.focus == Pane::Documents {
            return self.back();
        }
        let level = &mut self.current;
        let document = level.documents.as_ref()?.get(level.selected)?;
        if !level.tree.collapse(document) {
            self.focus = Pane::Documents;
        }
        None
    }

    /// Returns to the level the current one was opened from, as it was left. Whatever the
    /// current level still waits for is of no use any more.
    fn back(&mut self) -> Option<Effect> {
        self.current = self.parents.pop()?;
        self.focus = Pane::Tree;
        Some(Effect::Cancel)
    }

    fn run_filter(&mut self) -> Option<Effect> {
        let editor = self.filter_editor.take()?;
        Some(self.read(FilterTail::from(editor.line().text())))
    }

    /// The line the keys edit: of the value editor, else of the name of a field being added, else
    /// of the filter editor.
    fn line_mut(&mut self) -> Option<&mut LineEditor> {
        if let Some(editor) = self.edit.as_mut().and_then(Edit::value_editor_mut) {
            return Some(editor.line_mut());
        }
        if let Some(name) = self.new_field.as_mut().and_then(NewField::name_line_mut) {
            return Some(name);
        }
        self.filter_editor.as_mut().map(FilterEditor::line_mut)
    }

    /// Reads the documents of the current level with `filter`.
    fn read(&mut self, filter: FilterTail) -> Effect {
        let request = self.next_request();
        let level = &mut self.current;
        let query = level.query(request, filter.clone());
        level.load = Load::Pending { request, filter };
        Effect::Query(query)
    }

    /// A recursive delete stops between two requests, and a second Ctrl-C abandons it with its
    /// request in flight, which a dead connection can hold for minutes.
    fn interrupt(&mut self) -> Option<Effect> {
        if self.edit.as_mut().is_some_and(Edit::abandon) {
            self.current.tree.forget_listing();
            return Some(Effect::AbandonRecursiveDelete);
        }
        let level = &mut self.current;
        let query_stopped = level.stop_waiting();
        let listing_stopped = level.tree.cancel_listing();
        let edit_stopped = self.edit.as_mut().is_some_and(Edit::stop_waiting);
        if query_stopped || listing_stopped || edit_stopped {
            return Some(Effect::Cancel);
        }
        if self.popup.take().is_some()
            || self.edit.take().is_some()
            || self.new_field.take().is_some()
            || self.filter_editor.take().is_some()
        {
            return None;
        }
        Some(Effect::Quit)
    }

    /// Opens the editor `choice` asks for at the cursor: the one-line editor, or the external
    /// editor, which the effect runs.
    fn edit_value(&mut self, choice: EditorChoice) -> Option<Effect> {
        let view = self.value_view();
        let draft = match self.edit_target(choice)? {
            EditTarget::Line(editor) => Draft::Value(editor),
            EditTarget::Field { path, value } => {
                Draft::External(ExternalDraft::field(path, value, choice, &view))
            }
            EditTarget::Document(document) => {
                Draft::External(ExternalDraft::document(document, &view))
            }
        };
        let document = self.current.selected_document()?;
        self.edit = Some(Edit::editing(document, draft));
        self.popup = None;
        self.external_editor()
    }

    /// The effect that opens the external editor, while the edit is in it.
    fn external_editor(&self) -> Option<Effect> {
        let draft = self.edit.as_ref()?.external_draft()?;
        Some(Effect::OpenEditor(draft.file()))
    }

    /// Takes how the external editor ended. A text that changes the value goes to its
    /// confirmation, and one that does not read stays with its error. A text that reads as the
    /// value the document holds, the template of a new document saved as it opened, and an
    /// editor that failed end the edit with nothing written.
    fn editor_closed(&mut self, outcome: FsqResult<EditorOutcome>) {
        let Some(draft) = self.edit.as_mut().and_then(Edit::external_draft_mut) else {
            return;
        };
        match outcome {
            Ok(EditorOutcome::Saved(text)) => {
                draft.keep(text);
                self.edit = if draft.is_untouched_template() {
                    None
                } else {
                    self.edit.take().and_then(Edit::submitted)
                };
            }
            Ok(EditorOutcome::Failed) => self.edit = None,
            Err(error) => draft.fail(error),
        }
    }

    /// Asks to confirm the delete `d` stands for. The delete of a document lists its
    /// subcollections first, unless its tree has them, so that the confirmation can name what
    /// stays.
    fn delete(&mut self) -> Option<Effect> {
        let change = self.deletion_at_cursor()?;
        let level = &self.current;
        let document = level.selected_document()?;
        let deletes_document = matches!(change, Change::Document(None));
        let listed = !matches!(
            level.tree.listing(),
            Listing::NotListed | Listing::Failed(_)
        );
        let name = document.name.clone();
        self.edit = Some(Edit::confirming(document, change));
        self.popup = None;
        if !deletes_document || listed {
            return None;
        }
        let request = self.next_request();
        self.current.tree.listing_started(request);
        Some(Effect::ListSubcollections {
            request,
            document: name,
        })
    }

    /// Opens the external editor on a new document of the current collection, with no fields or
    /// with those of `copied`, from the documents pane.
    fn create_document(&mut self, copied: Option<&FirestoreDocument>) -> Option<Effect> {
        if self.focus != Pane::Documents {
            return None;
        }
        let draft = ExternalDraft::new_document(&self.current.path, copied, &self.value_view());
        self.edit = Some(Edit::creating(draft));
        self.external_editor()
    }

    /// Opens the prompt for the name of a field to add, where `a` adds one.
    fn add_field(&mut self) {
        let Some(parent) = self.new_field_parent() else {
            return;
        };
        if let Some(document) = self.current.selected_document() {
            self.new_field = Some(NewField::new(document, parent));
            self.popup = None;
        }
    }

    /// Starts the edit of the value of the field being added, once its type is picked: in the
    /// value editor, in the external editor, which the effect opens, or at the confirmation.
    fn pick_field_type(&mut self) -> Option<Effect> {
        let edit = self.new_field.as_ref()?.edit(&self.value_view())?;
        self.new_field = None;
        self.edit = Some(edit);
        self.external_editor()
    }

    fn confirm(&mut self) -> Option<Effect> {
        if self.waits_for_listing() {
            return None;
        }
        let request = self.next_request();
        self.edit.as_mut()?.write(request).map(Effect::Write)
    }

    fn confirm_recursive(&mut self) -> Option<Effect> {
        if !self.offers_recursive_delete() {
            return None;
        }
        let request = self.next_request();
        self.edit
            .as_mut()?
            .delete_recursively(request)
            .map(Effect::DeleteRecursively)
    }

    /// Whether `R` deletes the document being confirmed with every document under it: the change
    /// is the delete of the document, `y` would write it now, and its listing found
    /// subcollections.
    pub fn offers_recursive_delete(&self) -> bool {
        let has_subcollections = matches!(
            self.current.tree.listing(),
            Listing::Listed(collection_ids) if !collection_ids.is_empty()
        );
        has_subcollections
            && self
                .edit
                .as_ref()
                .is_some_and(|edit| edit.deletes_document() && edit.can_write())
    }

    fn recursive_progress(&mut self, request: RequestId, deleted: usize) {
        if let Some(edit) = self.edit.as_mut().filter(|edit| edit.waits_for(request)) {
            edit.count_deleted(deleted);
        }
    }

    /// Takes how the recursive delete `request` ended, unless the edit stopped waiting for it. A
    /// document that went leaves the level as a deleted one does. One found changed before
    /// anything was deleted is read again, as after a stale write. One that stays otherwise keeps
    /// the confirmation open on how far the delete got, and its subcollections are listed again
    /// when next asked for, since the delete changed them.
    fn recursively_deleted(
        &mut self,
        request: RequestId,
        outcome: FsqResult<RecursiveOutcome>,
    ) -> Option<Effect> {
        if !self
            .edit
            .as_ref()
            .is_some_and(|edit| edit.waits_for(request))
        {
            return None;
        }
        let partial = match outcome {
            Ok(RecursiveOutcome::Deleted) => {
                let edit = self.edit.take()?;
                self.current.remove(edit.document()?);
                return None;
            }
            Ok(RecursiveOutcome::Partial(PartialDelete {
                deleted: 0,
                halt: Halt::Stale,
            })) => return self.read_edited_again(),
            Ok(RecursiveOutcome::Partial(partial)) => Ok(partial),
            Err(error) => Err(error),
        };
        self.edit.as_mut()?.end_partly(partial);
        self.current.tree.forget_listing();
        None
    }

    /// Reads the document of the edit again, after a write found it other than it was read.
    fn read_edited_again(&mut self) -> Option<Effect> {
        let request = self.next_request();
        let edit = self.edit.as_mut()?;
        let document = edit.document()?.to_string();
        edit.wait_for_read(request);
        Some(Effect::ReadDocument { request, document })
    }

    /// Whether the delete of a document being confirmed waits for the listing of its
    /// subcollections, which its confirmation names before `y` can write it.
    pub fn waits_for_listing(&self) -> bool {
        self.edit.as_ref().is_some_and(Edit::deletes_document) && self.current.tree.is_listing()
    }

    /// Takes the answer to the write `request`, unless the edit stopped waiting for it. A
    /// document written or deleted ends the edit, and the level shows it as Firestore returned
    /// it, without reading the documents again: in place, or as a new document under the cursor
    /// when it was written where none was. A stale write reads the document again.
    fn written(&mut self, request: RequestId, outcome: FsqResult<WriteOutcome>) -> Option<Effect> {
        if !self
            .edit
            .as_ref()
            .is_some_and(|edit| edit.waits_for(request))
        {
            return None;
        }
        match outcome {
            Ok(WriteOutcome::Written(document)) => match self.edit.take()?.last_read() {
                Some(_) => self.current.patch(document),
                None => self.current.insert(document),
            },
            Ok(WriteOutcome::Deleted) => {
                let edit = self.edit.take()?;
                self.current.remove(edit.document()?);
            }
            Ok(WriteOutcome::Stale) => return self.read_edited_again(),
            Err(error) => {
                if let Some(edit) = &mut self.edit {
                    edit.fail(error);
                }
            }
        }
        None
    }

    /// Takes the document as read again, unless the edit stopped waiting for it: the level shows
    /// it, as a new document when the level no longer did, or leaves it out when it no longer
    /// exists, and the edit shows its change over it. For a new document found under its name,
    /// one that holds the fields of the create is the create written, and any other waits for
    /// `e` to give the new one another name.
    fn document_read(&mut self, request: RequestId, outcome: FsqResult<Option<FirestoreDocument>>) {
        let Some(edit) = self.edit.as_mut().filter(|edit| edit.waits_for(request)) else {
            return;
        };
        match outcome {
            Ok(Some(stored)) if edit.created(&stored) => {
                self.edit = None;
                self.current.insert(stored);
            }
            Ok(Some(_)) if edit.creates() => edit.refuse_existing(),
            Ok(read) => {
                match (&read, edit.document()) {
                    (Some(document), _) if self.current.shows(&document.name) => {
                        self.current.patch(document.clone())
                    }
                    (Some(document), _) => self.current.insert(document.clone()),
                    (None, Some(name)) => self.current.remove(name),
                    (None, None) => {}
                }
                edit.read_again(read);
            }
            Err(error) => edit.fail(error),
        }
    }

    /// Keeps the answer to the query `request`, unless the browser stopped waiting for it. A
    /// filter that fails opens in the editor to be fixed, unless the editor is open already with
    /// what the user is typing. The first read without a filter, and a read again with the
    /// filter of the documents on show, such as a reload, fail for a reason the filter cannot
    /// fix, so the keys stay with the panes. Documents read again with the filter they were read
    /// with keep the selected document and its tree, while it is among them. The popup of a value
    /// closes, since its keys act on the row under the cursor, which the documents read may have
    /// moved or changed.
    fn loaded(&mut self, request: RequestId, outcome: FsqResult<Vec<FirestoreDocument>>) {
        let level = &mut self.current;
        if !matches!(&level.load, Load::Pending { request: pending, .. } if *pending == request) {
            return;
        }
        let Load::Pending { filter, .. } = std::mem::replace(&mut level.load, Load::Done) else {
            return;
        };
        match outcome {
            Ok(documents) => {
                let kept = level
                    .selected_document()
                    .filter(|_| level.filter == filter)
                    .and_then(|selected| {
                        documents
                            .iter()
                            .position(|document| document.name == selected.name)
                    });
                if let Some(Popup::Value { .. }) = self.popup {
                    self.popup = None;
                }
                self.history.add(&filter);
                level.documents = Some(documents);
                level.created.clear();
                level.filter = filter;
                match kept {
                    Some(position) => level.selected = position,
                    None => {
                        level.selected = 0;
                        level.tree = Tree::default();
                    }
                }
                let selected = level
                    .documents
                    .as_ref()
                    .and_then(|documents| documents.get(level.selected));
                if let Some(document) = selected {
                    level.tree.keep_cursor_in(document);
                }
            }
            Err(error) => {
                let fixable =
                    filter != level.filter || (level.documents.is_none() && !filter.is_empty());
                if fixable {
                    self.filter_editor
                        .get_or_insert_with(|| FilterEditor::from(&filter));
                }
                level.load = Load::Failed { error, filter };
            }
        }
    }

    /// What Ctrl-G shows the whole error of: while the filter is in the editor, its failed query;
    /// else a failed listing, else a failed query.
    pub fn failure(&self) -> Option<Failure> {
        let level = &self.current;
        let query_failed = matches!(level.load, Load::Failed { .. });
        let listing_failed = matches!(level.tree.listing(), Listing::Failed(_));
        match (self.filter_editor.is_some(), query_failed, listing_failed) {
            (true, true, _) | (false, true, false) => Some(Failure::Query),
            (false, _, true) => Some(Failure::Listing),
            (true, false, _) | (false, false, false) => None,
        }
    }

    /// The error of `failure`, while the current level still has it.
    pub fn error(&self, failure: Failure) -> Option<&FsqError> {
        let level = &self.current;
        match (failure, &level.load, level.tree.listing()) {
            (Failure::Query, Load::Failed { error, .. }, _)
            | (Failure::Listing, _, Listing::Failed(error)) => Some(error),
            _ => None,
        }
    }

    pub fn mode(&self) -> Mode {
        match (
            &self.popup,
            self.edit.as_ref().map(Edit::step),
            self.new_field.as_ref().map(NewField::step),
            &self.filter_editor,
        ) {
            (Some(_), _, _, _) => Mode::Popup,
            (None, Some(Step::Editing(Draft::Value(_))), _, _) => Mode::ValueEditor,
            (None, Some(Step::Editing(Draft::External(_))), _, _) => Mode::ExternalEditor,
            (None, Some(Step::Confirming(_)), _, _) => Mode::Confirmation,
            (None, None, Some(NewFieldStep::Naming { .. }), _) => Mode::FieldName,
            (None, None, Some(NewFieldStep::Typing { .. }), _) => Mode::FieldType,
            (None, None, None, Some(_)) => Mode::FilterEditor,
            (None, None, None, None) => Mode::Panes,
        }
    }

    /// The change to a document being edited or confirmed.
    pub fn edit(&self) -> Option<&Edit> {
        self.edit.as_ref()
    }

    pub fn new_field(&self) -> Option<&NewField> {
        self.new_field.as_ref()
    }

    pub fn popup(&self) -> Option<&Popup> {
        self.popup.as_ref()
    }

    pub fn level(&self) -> &Level {
        &self.current
    }

    /// Whether the current level waits for its documents or its subcollections, or a change
    /// waits for its write.
    pub fn is_waiting(&self) -> bool {
        matches!(self.current.load, Load::Pending { .. })
            || self.current.tree.is_listing()
            || self.edit.as_ref().is_some_and(Edit::is_waiting)
    }

    pub fn focus(&self) -> Pane {
        self.focus
    }

    pub fn filter_editor(&self) -> Option<&FilterEditor> {
        self.filter_editor.as_ref()
    }

    pub fn has_parent(&self) -> bool {
        !self.parents.is_empty()
    }

    pub fn documents_path(&self) -> &str {
        &self.documents_path
    }

    /// The filters this browser and the ones before it ran, for the next browser.
    pub fn into_history(self) -> FilterHistory {
        self.history
    }

    /// The row under the tree cursor and its document, while the tree has the focus.
    pub fn tree_cursor(&self) -> Option<(&FirestoreDocument, Row<'_>)> {
        let level = &self.current;
        let document = level
            .selected_document()
            .filter(|_| self.focus == Pane::Tree)?;
        Some((document, level.tree.cursor_row(document)?))
    }

    /// Whether `e`, or `E` for [`EditorChoice::External`], edits something at the cursor.
    pub fn edits_at_cursor(&self, choice: EditorChoice) -> bool {
        self.edit_target(choice).is_some()
    }

    /// What `e`, or `E` for [`EditorChoice::External`], edits at the cursor, also from the popup
    /// that shows the value whole: the field under the tree cursor, or the array it is inside,
    /// since arrays are written whole, and in the documents pane the selected document. `None`
    /// where the key does nothing, as `e` does on a null.
    fn edit_target(&self, choice: EditorChoice) -> Option<EditTarget<'_>> {
        if let Some(Popup::Error(_) | Popup::Help) = &self.popup {
            return None;
        }
        if self.focus == Pane::Documents {
            return self.current.selected_document().map(EditTarget::Document);
        }
        let (document, Row::Field { path, value, .. }) = self.tree_cursor()? else {
            return None;
        };
        let field = path.written_field()?;
        let written = NodePath::from(&field);
        if written != path {
            let array = written.value_in(document)?;
            return Some(EditTarget::Field {
                path: field,
                value: array,
            });
        }
        match choice {
            EditorChoice::External => Some(EditTarget::Field { path: field, value }),
            EditorChoice::Fitting => match ValueEditor::new(&path, value, &self.value_view()) {
                Some(editor) => Some(EditTarget::Line(editor)),
                None if matches!(value.value_type, None | Some(ValueType::NullValue(_))) => None,
                None => Some(EditTarget::Field { path: field, value }),
            },
        }
    }

    /// The change `d` asks to confirm: the delete of the field under the tree cursor, also from
    /// the popup that shows its value, or in the documents pane of the selected document. `None`
    /// on an element of an array, which is not deleted alone.
    pub fn deletion_at_cursor(&self) -> Option<Change> {
        if let Some(Popup::Error(_) | Popup::Help) = &self.popup {
            return None;
        }
        match self.focus {
            Pane::Documents => self
                .current
                .selected_document()
                .map(|_| Change::Document(None)),
            Pane::Tree => match self.tree_cursor()? {
                (_, Row::Field { path, .. }) => Some(Change::Field {
                    path: path.mask()?,
                    value: None,
                }),
                _ => None,
            },
        }
    }

    /// The fields `a` adds a field among: those of the map the value popup shows, of the open map
    /// under the tree cursor, else those the row under the cursor, or in the popup of its value,
    /// is one of, which for the group of subcollections are the document's own. `None` on an
    /// open array and inside one, since an array is written whole, and on a subcollection.
    pub fn new_field_parent(&self) -> Option<FieldParent> {
        match &self.popup {
            Some(Popup::Value { path, value }) if is_map(value) => {
                return path.mask().map(FieldParent::Map)
            }
            Some(Popup::Error(_) | Popup::Help) => return None,
            Some(Popup::Value { .. }) | None => {}
        }
        match self.tree_cursor()?.1 {
            Row::Field {
                path,
                value,
                fold: Fold::Expanded,
            } if is_map(value) => path.mask().map(FieldParent::Map),
            Row::Field {
                fold: Fold::Expanded,
                ..
            } => None,
            Row::Field { path, .. } => Some(path.mask()?.parent()),
            Row::Subcollections { .. } => Some(FieldParent::Document),
            Row::Subcollection(_) => None,
        }
    }

    /// The filter `f` opens the editor with: the documents whose field at the tree cursor holds
    /// the same leaf value.
    pub fn filter_on_cursor(&self) -> Option<FilterTail> {
        match self.tree_cursor()? {
            (
                _,
                Row::Field {
                    path,
                    value,
                    fold: Fold::Leaf,
                },
            ) => FilterTail::matching(&path, value),
            _ => None,
        }
    }

    /// What `y` or `Y` puts on the clipboard: the value under the tree cursor or in the value
    /// popup, or its path as the bottom border of the tree shows it.
    fn copy_text(&self, copied: Copied) -> Option<String> {
        if let Some(popup) = &self.popup {
            return match (popup, copied) {
                (Popup::Value { value, .. }, Copied::Value) => Some(self.clipboard_value(value)),
                (Popup::Value { path, .. }, Copied::Path) => {
                    Some(FieldPath::from(path).to_string())
                }
                (Popup::Error(_) | Popup::Help, _) => None,
            };
        }
        match (copied, self.tree_cursor()?) {
            (Copied::Value, (_, Row::Field { value, .. })) => Some(self.clipboard_value(value)),
            (Copied::Value, _) => None,
            (Copied::Path, (document, row)) => Some(self.row_path(&row, document)),
        }
    }

    /// `value` as it pastes: a string as its text, and any other value as compact JSON in the
    /// tagged encoding `fsq export` writes, which reads back to the same Firestore type.
    fn clipboard_value(&self, value: &Value) -> String {
        if let Some(ValueType::StringValue(text)) = &value.value_type {
            return text.clone();
        }
        self.value_view().tagged_json(value).to_string()
    }

    /// Where `row` of the tree of `document` points: a field path as SQL reads it, a collection
    /// path, and for the group of subcollections, the path of the document they are under.
    pub fn row_path(&self, row: &Row<'_>, document: &FirestoreDocument) -> String {
        let document_path =
            FirestoreDb::relative_document_name(self.documents_path(), &document.name);
        match row {
            Row::Field { path, .. } => FieldPath::from(path).to_string(),
            Row::Subcollections { .. } => document_path.to_string(),
            Row::Subcollection(collection_id) => {
                CollectionPath::in_document(document_path, (*collection_id).clone()).to_string()
            }
        }
    }
}

/// Whether `value` is a map, which a vector, stored as a map with a type marker, is not.
fn is_map(value: &Value) -> bool {
    matches!(value.value_type, Some(ValueType::MapValue(_))) && !FirestoreVector::is_vector(value)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::browse::fixtures::{
        browser_of, field_path, opened, point_at, save, stored, unchanged_since, READ_AT,
        WRITTEN_AT,
    };
    use crate::browse::new_field::FieldType;
    use crate::browse::write::{Confirmation, Note, Stage, ValueChange, WriteOperation};
    use crate::errors::{
        GeoPointProblem, InvalidEditedText, InvalidFieldName, InvalidValueText, ValueTextProblem,
    };
    use crate::render::fixtures::{document, draft, dune, string, value, DOCUMENTS_PATH};
    use firestore::gcloud_sdk::google::firestore::v1::value::ValueType;
    use firestore::gcloud_sdk::google::firestore::v1::{ArrayValue, MapValue};
    use firestore::gcloud_sdk::prost_types::Timestamp;
    use firestore::FirestoreWritePrecondition;
    use std::collections::HashMap;

    fn books(filter: &str) -> DocumentsQuery {
        DocumentsQuery {
            request: RequestId::default(),
            collection: "books".parse().expect("a collection path"),
            filter: FilterTail::from(filter),
        }
    }

    fn orders() -> FirestoreCollectionId {
        "orders".parse().expect("a collection ID")
    }

    fn query_of(effect: Option<Effect>) -> DocumentsQuery {
        match effect {
            Some(Effect::Query(query)) => query,
            other => panic!("no query: {other:?}"),
        }
    }

    /// A browser of `books` that has read `draft` and `dune`, in that order.
    fn browser() -> Browser {
        browser_of("books", "", vec![draft(), dune()])
    }

    /// Opens the filter editor, types `text` into it and runs it.
    fn run_filter(browser: &mut Browser, text: &str) -> DocumentsQuery {
        browser.update(Message::EditFilter);
        for typed in text.chars() {
            browser.update(Message::Edit(LineEdit::Insert(typed)));
        }
        query_of(browser.update(Message::RunFilter))
    }

    fn edited_text(browser: &Browser) -> Option<&str> {
        browser.filter_editor().map(|editor| editor.line().text())
    }

    fn selected_id(browser: &Browser) -> Option<&str> {
        browser
            .level()
            .selected_document()
            .and_then(|document| document.name.rsplit('/').next())
    }

    /// Selects `dune`, lists its subcollections as `orders`, and opens `orders`.
    fn open_orders(browser: &mut Browser) -> Option<Effect> {
        browser.update(Message::Move(Movement::Down(1)));
        browser.update(Message::Expand);
        browser.update(Message::Move(Movement::Last));
        let Some(Effect::ListSubcollections { request, .. }) = browser.update(Message::Expand)
        else {
            panic!("no listing")
        };
        browser.update(Message::SubcollectionsListed {
            request,
            outcome: Ok(vec![orders()]),
        });
        browser.update(Message::Move(Movement::Last));
        browser.update(Message::Expand)
    }

    #[test]
    fn a_filter_without_a_limit_reads_the_first_hundred_documents() {
        assert_eq!(books("").sql(), "SELECT * FROM `books`\nLIMIT 100");
        assert_eq!(
            books("WHERE note = 'no limit' -- or offset").sql(),
            "SELECT * FROM `books`\nWHERE note = 'no limit' -- or offset\nLIMIT 100"
        );
        assert_eq!(
            books("WHERE genre = 'sf' ORDER BY title limit 5").sql(),
            "SELECT * FROM `books`\nWHERE genre = 'sf' ORDER BY title limit 5"
        );
        assert_eq!(
            books("ORDER BY title OFFSET 10").sql(),
            "SELECT * FROM `books`\nORDER BY title OFFSET 10\nLIMIT 100"
        );
    }

    #[test]
    fn a_field_named_limit_is_not_a_limit_of_the_query() {
        for filter in ["WHERE quota.limit > 5", "WHERE limit > 5", "ORDER BY limit"] {
            assert_eq!(
                books(filter).sql(),
                format!("SELECT * FROM `books`\n{filter}\nLIMIT 100")
            );
        }
    }

    #[test]
    fn a_filter_ends_without_the_semicolon_that_ends_the_statement() {
        assert_eq!(
            books("WHERE genre = 'sf';").sql(),
            "SELECT * FROM `books`\nWHERE genre = 'sf'\nLIMIT 100"
        );
        assert_eq!(
            books("WHERE genre = 'sf' LIMIT 5 ;").sql(),
            "SELECT * FROM `books`\nWHERE genre = 'sf' LIMIT 5"
        );
    }

    #[test]
    fn a_limit_inside_parentheses_is_not_the_limit_of_the_query() {
        let filter = "WHERE EXISTS(SELECT * FROM subcollection('orders') LIMIT 1)";

        assert_eq!(
            books(filter).sql(),
            format!("SELECT * FROM `books`\n{filter}\nLIMIT 100")
        );
    }

    #[test]
    fn a_subcollection_is_read_by_its_full_quoted_path() {
        let mut browser = browser();

        let query = query_of(open_orders(&mut browser));

        assert_eq!(query.sql(), "SELECT * FROM `books/dune/orders`\nLIMIT 100");
        assert_eq!(browser.level().path(), &query.collection);
        assert_eq!(browser.focus(), Pane::Documents);
    }

    #[test]
    fn going_back_from_a_subcollection_returns_to_the_document_it_was_opened_from() {
        let mut browser = browser();
        open_orders(&mut browser);

        let back = browser.update(Message::Back);

        assert_eq!(back, Some(Effect::Cancel));
        assert_eq!(browser.level().path().to_string(), "books");
        assert_eq!(selected_id(&browser), Some("dune"));
        assert!(!browser.has_parent());
        assert_eq!(browser.update(Message::Back), None);
    }

    #[test]
    fn the_effective_limit_is_the_count_of_the_filter_else_the_default() {
        assert_eq!(FilterTail::default().effective_limit(), Some(100));
        assert_eq!(
            FilterTail::from("WHERE quota.limit > 5").effective_limit(),
            Some(100)
        );
        assert_eq!(
            FilterTail::from("ORDER BY title LIMIT 5").effective_limit(),
            Some(5)
        );
        assert_eq!(
            FilterTail::from("ORDER BY title LIMIT 2 + 3").effective_limit(),
            None
        );
    }

    #[test]
    fn a_failed_filter_keeps_the_documents_and_reopens_in_the_editor_until_it_answers() {
        let mut browser = browser();

        let failing = run_filter(&mut browser, "WHERE pagez > 100");
        browser.update(Message::DocumentsLoaded {
            request: failing.request,
            outcome: Err(FsqError::NoProject),
        });

        assert!(matches!(
            browser.level().load(),
            Load::Failed {
                error: FsqError::NoProject,
                ..
            }
        ));
        assert_eq!(browser.level().documents().map(<[_]>::len), Some(2));
        assert_eq!(browser.level().filter(), &FilterTail::default());
        assert_eq!(edited_text(&browser), Some("WHERE pagez > 100"));
        browser.update(Message::CancelFilter);
        browser.update(Message::EditFilter);
        assert_eq!(edited_text(&browser), Some("WHERE pagez > 100"));
        let query = query_of(browser.update(Message::RunFilter));
        browser.update(Message::DocumentsLoaded {
            request: query.request,
            outcome: Ok(vec![dune()]),
        });
        assert_eq!(
            browser.level().filter(),
            &FilterTail::from("WHERE pagez > 100")
        );
    }

    #[test]
    fn a_first_read_with_a_filter_that_fails_opens_it_in_the_editor_and_one_without_does_not() {
        let (mut filtered, first) = opened("books", "WHERE pagez > 100");
        filtered.update(Message::DocumentsLoaded {
            request: first.request,
            outcome: Err(FsqError::NoProject),
        });
        assert_eq!(edited_text(&filtered), Some("WHERE pagez > 100"));
        let again = query_of(filtered.update(Message::RunFilter));
        filtered.update(Message::DocumentsLoaded {
            request: again.request,
            outcome: Err(FsqError::NoProject),
        });
        assert_eq!(edited_text(&filtered), Some("WHERE pagez > 100"));

        let (mut unfiltered, first) = opened("books", "");
        unfiltered.update(Message::DocumentsLoaded {
            request: first.request,
            outcome: Err(FsqError::NoProject),
        });
        assert_eq!(unfiltered.mode(), Mode::Panes);
    }

    #[test]
    fn a_failure_leaves_a_filter_being_typed_as_it_is() {
        let mut browser = browser();
        let query = run_filter(&mut browser, "WHERE pagez > 100");
        browser.update(Message::EditFilter);
        browser.update(Message::Edit(LineEdit::DeleteWordBefore));

        browser.update(Message::DocumentsLoaded {
            request: query.request,
            outcome: Err(FsqError::NoProject),
        });

        assert_eq!(edited_text(&browser), Some("WHERE pagez > "));
    }

    #[test]
    fn a_stopped_query_drops_its_late_answer_and_reopens_with_slash() {
        let mut browser = browser();
        let query = run_filter(&mut browser, "WHERE pages > 100");

        assert_eq!(browser.update(Message::Interrupt), Some(Effect::Cancel));
        browser.update(Message::DocumentsLoaded {
            request: query.request,
            outcome: Ok(Vec::new()),
        });

        assert!(matches!(browser.level().load(), Load::Stopped { .. }));
        assert_eq!(browser.level().documents().map(<[_]>::len), Some(2));
        assert!(browser.filter_editor().is_none());
        browser.update(Message::EditFilter);
        assert_eq!(edited_text(&browser), Some("WHERE pages > 100"));
    }

    #[test]
    fn ctrl_c_stops_a_load_then_closes_the_popup_then_the_filter_editor_then_quits() {
        let mut browser = browser();
        run_filter(&mut browser, "WHERE pages > 100");
        browser.update(Message::EditFilter);
        browser.update(Message::ShowHelp);

        assert_eq!(browser.update(Message::Interrupt), Some(Effect::Cancel));
        assert_eq!(browser.mode(), Mode::Popup);
        assert_eq!(browser.update(Message::Interrupt), None);
        assert_eq!(browser.mode(), Mode::FilterEditor);
        assert_eq!(browser.update(Message::Interrupt), None);
        assert_eq!(browser.mode(), Mode::Panes);
        assert_eq!(browser.update(Message::Interrupt), Some(Effect::Quit));
    }

    #[test]
    fn a_paste_goes_only_into_a_filter_editor_without_a_popup_over_it() {
        let mut browser = browser();
        browser.update(Message::Paste("q".to_string()));
        assert!(browser.filter_editor().is_none());

        browser.update(Message::EditFilter);
        browser.update(Message::ShowHelp);
        browser.update(Message::Paste(" AND".to_string()));
        browser.update(Message::ClosePopup);
        browser.update(Message::Paste("WHERE".to_string()));

        assert_eq!(edited_text(&browser), Some("WHERE"));
    }

    #[test]
    fn the_cursor_stops_at_the_first_and_the_last_document() {
        let mut browser = browser();

        browser.update(Message::Move(Movement::Up(1)));
        assert_eq!(selected_id(&browser), Some("draft"));
        browser.update(Message::Move(Movement::Down(10)));
        assert_eq!(selected_id(&browser), Some("dune"));
        browser.update(Message::Move(Movement::Down(1)));
        assert_eq!(selected_id(&browser), Some("dune"));
        browser.update(Message::Move(Movement::First));
        assert_eq!(selected_id(&browser), Some("draft"));
    }

    /// The path of the field under the tree cursor of the selected document.
    fn cursor_path(browser: &Browser) -> Option<NodePath> {
        let level = browser.level();
        match level.tree().cursor_row(level.selected_document()?)? {
            Row::Field { path, .. } => Some(path),
            _ => None,
        }
    }

    fn has_open_map(browser: &Browser) -> bool {
        let level = browser.level();
        let document = level.selected_document().expect("a document");
        level
            .tree()
            .rows(document)
            .iter()
            .any(|row| row.depth() > 0 && matches!(row, Row::Field { .. }))
    }

    /// `dune` under another ID.
    fn dune_messiah() -> FirestoreDocument {
        let mut sequel = dune();
        sequel.name = sequel.name.replace("dune", "dune-messiah");
        sequel
    }

    /// Opens `address` in the tree of the first document, puts the cursor on its city, and gives
    /// the focus back to the documents.
    fn on_city(browser: &mut Browser) {
        browser.update(Message::Expand);
        browser.update(Message::Expand);
        browser.update(Message::Move(Movement::Down(1)));
        browser.update(Message::SwitchPane);
    }

    #[test]
    fn another_document_keeps_the_open_maps_and_the_cursor_on_the_same_path() {
        let mut browser = browser_of("books", "", vec![dune(), dune_messiah()]);
        on_city(&mut browser);
        assert_eq!(
            cursor_path(&browser),
            Some(field_path(&["address", "city"]))
        );

        browser.update(Message::Move(Movement::Down(1)));

        assert_eq!(selected_id(&browser), Some("dune-messiah"));
        assert!(has_open_map(&browser));
        assert_eq!(
            cursor_path(&browser),
            Some(field_path(&["address", "city"]))
        );
    }

    #[test]
    fn the_cursor_falls_back_to_the_nearest_path_the_next_document_has() {
        let mut one_tag = dune();
        one_tag.name = one_tag.name.replace("dune", "one-tag");
        let tags = Value {
            value_type: Some(ValueType::ArrayValue(ArrayValue {
                values: vec![string("sf")],
            })),
        };
        one_tag.fields.insert("tags".to_string(), tags);
        let mut browser = browser_of("books", "", vec![dune(), one_tag]);
        browser.update(Message::Expand);
        browser.update(Message::Move(Movement::Down(10)));
        browser.update(Message::Expand);
        browser.update(Message::Move(Movement::Down(2)));
        assert_eq!(cursor_path(&browser).map(|at| at.depth()), Some(1));
        browser.update(Message::SwitchPane);

        browser.update(Message::Move(Movement::Down(1)));

        assert_eq!(cursor_path(&browser), Some(field_path(&["tags"])));
        assert_eq!(browser.level().tree().cursor(), 10);
    }

    #[test]
    fn a_new_query_starts_with_the_tree_collapsed() {
        let mut browser = browser_of("books", "", vec![dune(), dune_messiah()]);
        on_city(&mut browser);

        let query = run_filter(&mut browser, "WHERE pages > 100");
        browser.update(Message::DocumentsLoaded {
            request: query.request,
            outcome: Ok(vec![dune(), dune_messiah()]),
        });

        assert!(!has_open_map(&browser));
        assert_eq!(browser.level().tree().cursor(), 0);
    }

    /// Runs `filter` in place of the one in the editor, and answers it with `outcome`.
    fn answered(browser: &mut Browser, filter: &str, outcome: FsqResult<Vec<FirestoreDocument>>) {
        browser.update(Message::EditFilter);
        browser.update(Message::Edit(LineEdit::DeleteToStart));
        browser.update(Message::Paste(filter.to_string()));
        let query = query_of(browser.update(Message::RunFilter));
        browser.update(Message::DocumentsLoaded {
            request: query.request,
            outcome,
        });
    }

    /// The text of the editor after each of `recalls`.
    fn recalled(browser: &mut Browser, recalls: &[Recall]) -> Vec<String> {
        recalls
            .iter()
            .map(|recall| {
                browser.update(Message::Recall(*recall));
                edited_text(browser).unwrap_or_default().to_string()
            })
            .collect()
    }

    #[test]
    fn up_and_down_recall_the_filters_that_ran_most_recent_first_and_keep_the_draft() {
        let mut browser = browser();
        for filter in [
            "WHERE pages > 100",
            "WHERE genre = 'sf'",
            "WHERE pages > 100",
        ] {
            answered(&mut browser, filter, Ok(vec![dune()]));
        }
        browser.update(Message::EditFilter);
        browser.update(Message::Edit(LineEdit::DeleteToStart));
        browser.update(Message::Paste("ORDER BY".to_string()));

        let texts = recalled(
            &mut browser,
            &[
                Recall::Older,
                Recall::Older,
                Recall::Older,
                Recall::Newer,
                Recall::Newer,
                Recall::Newer,
            ],
        );

        assert_eq!(
            texts,
            [
                "WHERE pages > 100",
                "WHERE genre = 'sf'",
                "WHERE genre = 'sf'",
                "WHERE pages > 100",
                "ORDER BY",
                "ORDER BY",
            ]
        );
    }

    #[test]
    fn a_filter_that_failed_is_not_recalled() {
        let mut browser = browser();
        answered(&mut browser, "WHERE pages > 100", Ok(vec![dune()]));
        answered(&mut browser, "WHERE pagez > 100", Err(FsqError::NoProject));

        let texts = recalled(&mut browser, &[Recall::Older, Recall::Older, Recall::Newer]);

        assert_eq!(
            texts,
            [
                "WHERE pages > 100",
                "WHERE pages > 100",
                "WHERE pagez > 100"
            ]
        );
    }

    #[test]
    fn the_next_browser_recalls_the_filters_of_the_one_before() {
        let mut first = browser();
        answered(&mut first, "WHERE pages > 100", Ok(vec![dune()]));
        let target = BrowseTarget {
            collection: "books".parse().expect("a collection path"),
            filter: FilterTail::default(),
        };

        let (mut next, _) = Browser::open(target, DOCUMENTS_PATH, first.into_history());
        next.update(Message::EditFilter);

        assert_eq!(recalled(&mut next, &[Recall::Older]), ["WHERE pages > 100"]);
    }

    #[test]
    fn the_order_key_is_the_first_field_path_the_documents_are_ordered_by() {
        let order_key = |filter: &str| FilterTail::from(filter).order_key().cloned();

        assert_eq!(
            order_key("WHERE pages > 100 ORDER BY rating DESC, title LIMIT 5"),
            Some(field_path(&["rating"]))
        );
        assert_eq!(
            order_key("ORDER BY address.city"),
            Some(field_path(&["address", "city"]))
        );
        assert_eq!(
            order_key("ORDER BY `unit-price`"),
            Some(field_path(&["unit-price"]))
        );
        for unordered in [
            "",
            "WHERE note = 'ORDER BY rating'",
            "ORDER BY LENGTH(title)",
            "ORDER BY",
        ] {
            assert_eq!(order_key(unordered), None, "{unordered}");
        }
    }

    #[test]
    fn a_query_answer_closes_the_popup_of_a_value() {
        let mut browser = on_field(&["pages"]);
        let query = run_filter(&mut browser, "WHERE pages > 100");
        browser.update(Message::Open);
        let opened = browser.mode();

        browser.update(Message::DocumentsLoaded {
            request: query.request,
            outcome: Ok(vec![stored(draft(), READ_AT), stored(dune(), READ_AT)]),
        });

        assert_eq!(opened, Mode::Popup);
        assert_eq!(browser.mode(), Mode::Panes);
    }

    /// A browser of `books` that has read `dune` and then `draft`, both as stored at [`READ_AT`],
    /// with the cursor in the tree of `dune` on the field `path` leads to.
    fn on_field(path: &[&str]) -> Browser {
        let mut browser = browser_of(
            "books",
            "",
            vec![stored(dune(), READ_AT), stored(draft(), READ_AT)],
        );
        browser.update(Message::Expand);
        point_at(&mut browser, &field_path(path));
        browser
    }

    fn edit_value(browser: &mut Browser, text: &str) {
        browser.update(Message::EditValue);
        browser.update(Message::Edit(LineEdit::DeleteToStart));
        browser.update(Message::Paste(text.to_string()));
        browser.update(Message::SubmitValue);
    }

    fn write_of(effect: Option<Effect>) -> DocumentWrite {
        match effect {
            Some(Effect::Write(write)) => write,
            other => panic!("no write: {other:?}"),
        }
    }

    fn value_editor_text(browser: &Browser) -> Option<&str> {
        let editor = browser.edit()?.value_editor()?;
        Some(editor.line().text())
    }

    fn rejection(browser: &Browser) -> Option<&ValueTextProblem> {
        match browser.edit()?.value_editor()?.error()? {
            FsqError::InvalidValueText(InvalidValueText { problem, .. }) => Some(problem),
            _ => None,
        }
    }

    fn confirmed_change(browser: &Browser) -> Option<&Change> {
        browser.edit()?.confirmation().map(Confirmation::change)
    }

    fn map(fields: Vec<(&str, Value)>) -> Value {
        let fields = fields
            .into_iter()
            .map(|(name, value)| (name.to_string(), value))
            .collect();
        value(ValueType::MapValue(MapValue { fields }))
    }

    #[test]
    fn y_writes_the_confirmed_value_with_the_update_time_the_document_was_read_with() {
        let mut browser = on_field(&["title"]);

        edit_value(&mut browser, "Dune Messiah");
        assert_eq!(browser.mode(), Mode::Confirmation);
        let write = write_of(browser.update(Message::Confirm));

        assert_eq!(write.document, dune().name);
        assert_eq!(write.precondition, unchanged_since(READ_AT));
        assert_eq!(
            write.operation,
            WriteOperation::Update {
                fields: HashMap::from([("title".to_string(), string("Dune Messiah"))]),
                mask: field_path(&["title"]).mask(),
            }
        );
        assert!(browser.is_waiting());
    }

    #[test]
    fn discarding_the_confirmation_writes_nothing() {
        let mut browser = on_field(&["title"]);
        edit_value(&mut browser, "Dune Messiah");
        assert_eq!(browser.mode(), Mode::Confirmation);

        assert_eq!(browser.update(Message::Discard), None);

        assert!(browser.edit().is_none());
        assert_eq!(browser.mode(), Mode::Panes);
        assert_eq!(browser.update(Message::Confirm), None);
        assert_eq!(
            browser.level().selected_document(),
            Some(&stored(dune(), READ_AT))
        );
    }

    #[test]
    fn e_at_the_confirmation_returns_to_the_editor_with_the_text_it_was_left_with() {
        let mut browser = on_field(&["title"]);
        edit_value(&mut browser, "Dune Messiah");

        browser.update(Message::EditAgain);
        assert_eq!(browser.mode(), Mode::ValueEditor);
        assert_eq!(value_editor_text(&browser), Some("Dune Messiah"));
        browser.update(Message::Edit(LineEdit::Insert('!')));
        browser.update(Message::SubmitValue);
        let write = write_of(browser.update(Message::Confirm));

        assert_eq!(
            write.operation,
            WriteOperation::Update {
                fields: HashMap::from([("title".to_string(), string("Dune Messiah!"))]),
                mask: field_path(&["title"]).mask(),
            }
        );
    }

    #[test]
    fn a_stale_write_reads_the_document_again_and_shows_the_kept_text_against_it() {
        let mut browser = on_field(&["title"]);
        edit_value(&mut browser, "Dune Messiah");
        let stale = write_of(browser.update(Message::Confirm));
        let mut retitled = stored(dune(), WRITTEN_AT);
        retitled
            .fields
            .insert("title".to_string(), string("Dune: Book One"));

        let reread = browser.update(Message::Written {
            request: stale.request,
            outcome: Ok(WriteOutcome::Stale),
        });
        let Some(Effect::ReadDocument { request, document }) = reread else {
            panic!("no read: {reread:?}")
        };
        browser.update(Message::DocumentRead {
            request,
            outcome: Ok(Some(retitled.clone())),
        });

        assert_eq!(document, dune().name);
        let edit = browser.edit().expect("the edit");
        assert_eq!(
            edit.value_change(),
            Some(ValueChange {
                before: Some(string("Dune: Book One")),
                after: Some(string("Dune Messiah")),
            })
        );
        assert!(matches!(
            edit.confirmation().map(Confirmation::stage),
            Some(Stage::Asking(Some(Note::Changed)))
        ));
        assert_eq!(browser.level().selected_document(), Some(&retitled));
        let again = write_of(browser.update(Message::Confirm));
        assert_eq!(again.precondition, unchanged_since(WRITTEN_AT));
        assert_eq!(again.operation, stale.operation);
    }

    #[test]
    fn a_written_value_patches_the_document_in_place_and_keeps_the_cursor_and_the_open_maps() {
        let mut browser = on_field(&["address"]);
        browser.update(Message::Expand);
        browser.update(Message::Move(Movement::Down(1)));
        edit_value(&mut browser, "Paris");
        let write = write_of(browser.update(Message::Confirm));
        let mut written = stored(dune(), WRITTEN_AT);
        let address = map(vec![("city", string("Paris")), ("zip", string("N1 9GU"))]);
        written.fields.insert("address".to_string(), address);

        let effect = browser.update(Message::Written {
            request: write.request,
            outcome: Ok(WriteOutcome::Written(written.clone())),
        });

        assert_eq!(
            write.operation,
            WriteOperation::Update {
                fields: HashMap::from([(
                    "address".to_string(),
                    map(vec![("city", string("Paris"))])
                )]),
                mask: field_path(&["address", "city"]).mask(),
            }
        );
        assert_eq!(effect, None);
        assert_eq!(browser.mode(), Mode::Panes);
        assert_eq!(browser.level().selected_document(), Some(&written));
        assert_eq!(
            cursor_path(&browser),
            Some(field_path(&["address", "city"]))
        );
        assert!(has_open_map(&browser));
    }

    #[test]
    fn d_on_a_field_deletes_that_field_alone_and_the_next_row_takes_the_cursor() {
        let mut browser = on_field(&["pages"]);
        let row = browser.level().tree().cursor();

        browser.update(Message::Delete);
        assert_eq!(browser.mode(), Mode::Confirmation);
        let write = write_of(browser.update(Message::Confirm));
        let mut written = stored(dune(), WRITTEN_AT);
        written.fields.remove("pages");
        browser.update(Message::Written {
            request: write.request,
            outcome: Ok(WriteOutcome::Written(written.clone())),
        });

        assert_eq!(
            write.operation,
            WriteOperation::Update {
                fields: HashMap::new(),
                mask: field_path(&["pages"]).mask(),
            }
        );
        assert_eq!(write.precondition, unchanged_since(READ_AT));
        assert_eq!(browser.level().selected_document(), Some(&written));
        assert_eq!(browser.level().tree().cursor(), row);
        assert_eq!(cursor_path(&browser), Some(field_path(&["published"])));
    }

    #[test]
    fn an_element_of_an_array_is_not_deleted_alone() {
        let mut browser = on_field(&["tags"]);
        browser.update(Message::Delete);
        assert_eq!(browser.mode(), Mode::Confirmation);
        browser.update(Message::Discard);
        browser.update(Message::Expand);
        browser.update(Message::Move(Movement::Down(1)));

        assert_eq!(browser.update(Message::Delete), None);

        assert!(browser.edit().is_none());
        assert_eq!(browser.mode(), Mode::Panes);
    }

    #[test]
    fn a_text_that_does_not_read_as_the_type_of_its_field_stays_in_the_editor_with_its_error() {
        let rejected = [
            ("pages", "412.5"),
            ("published", "14 November 2023"),
            ("location", "51.5"),
        ]
        .map(|(name, text)| {
            let mut browser = on_field(&[name]);
            edit_value(&mut browser, text);
            assert_eq!(browser.mode(), Mode::ValueEditor, "{name}");
            assert_eq!(value_editor_text(&browser), Some(text), "{name}");
            browser
        });

        let problems = rejected.each_ref().map(rejection);

        assert!(
            matches!(
                problems,
                [
                    Some(ValueTextProblem::Integer(_)),
                    Some(ValueTextProblem::Timestamp(_)),
                    Some(ValueTextProblem::GeoPoint(GeoPointProblem::NotAPair)),
                ]
            ),
            "{problems:?}"
        );
    }

    #[test]
    fn a_timestamp_with_an_offset_is_written_as_the_same_instant_in_utc() {
        let mut browser = on_field(&["published"]);

        edit_value(&mut browser, "2023-11-15T02:13:20+02:00");

        assert_eq!(
            confirmed_change(&browser),
            Some(&Change::Field {
                path: field_path(&["published"])
                    .mask()
                    .expect("a top-level field"),
                value: Some(value(ValueType::TimestampValue(Timestamp {
                    seconds: 1_700_007_200,
                    nanos: 0,
                }))),
            })
        );
    }

    #[test]
    fn a_text_that_reads_as_the_value_the_field_holds_closes_the_editor_and_writes_nothing() {
        let mut browser = on_field(&["published"]);

        edit_value(&mut browser, "2023-11-15T00:13:20+02:00");

        assert!(browser.edit().is_none(), "{:?}", browser.edit());
        assert_eq!(browser.mode(), Mode::Panes);
    }

    /// A browser of `dune` and `draft` that deletes `dune` with everything under it, once its
    /// listing found `orders`, and the delete.
    fn deleting_dune_recursively() -> (Browser, RecursiveDelete) {
        let mut browser = browser_of(
            "books",
            "",
            vec![stored(dune(), READ_AT), stored(draft(), READ_AT)],
        );
        let Some(Effect::ListSubcollections { request, .. }) = browser.update(Message::Delete)
        else {
            panic!("no listing")
        };
        browser.update(Message::SubcollectionsListed {
            request,
            outcome: Ok(vec![orders()]),
        });
        match browser.update(Message::ConfirmRecursive) {
            Some(Effect::DeleteRecursively(delete)) => (browser, delete),
            other => panic!("no recursive delete: {other:?}"),
        }
    }

    #[test]
    fn a_recursive_delete_that_ends_removes_the_row_as_a_delete_does() {
        let (mut browser, delete) = deleting_dune_recursively();

        let ended = browser.update(Message::RecursivelyDeleted {
            request: delete.request,
            outcome: Ok(RecursiveOutcome::Deleted),
        });

        assert_eq!(ended, None);
        assert_eq!(delete.update_time, READ_AT);
        assert_eq!(browser.level().documents().map(<[_]>::len), Some(1));
        assert_eq!(selected_id(&browser), Some("draft"));
        assert_eq!(browser.mode(), Mode::Panes);
    }

    #[test]
    fn a_recursive_delete_that_ctrl_c_stops_keeps_its_count_and_the_documents_on_show() {
        let (mut browser, delete) = deleting_dune_recursively();
        browser.update(Message::RecursiveProgress {
            request: delete.request,
            deleted: 500,
        });

        let interrupted = browser.update(Message::Interrupt);
        let stopping = browser.is_waiting();
        let ended = browser.update(Message::RecursivelyDeleted {
            request: delete.request,
            outcome: Ok(RecursiveOutcome::Partial(PartialDelete {
                deleted: 500,
                halt: Halt::Stopped,
            })),
        });

        assert_eq!(interrupted, Some(Effect::Cancel));
        assert!(stopping);
        assert_eq!(ended, None);
        assert!(matches!(
            browser
                .edit()
                .and_then(Edit::confirmation)
                .map(Confirmation::stage),
            Some(Stage::DeletedPartly(PartialDelete {
                deleted: 500,
                halt: Halt::Stopped
            }))
        ));
        assert_eq!(browser.level().documents().map(<[_]>::len), Some(2));
        assert_eq!(browser.update(Message::Confirm), None);
        browser.update(Message::Discard);
        assert_eq!(browser.mode(), Mode::Panes);
    }

    #[test]
    fn a_second_ctrl_c_stops_waiting_for_a_recursive_delete_with_its_request_in_flight() {
        let (mut browser, delete) = deleting_dune_recursively();
        browser.update(Message::RecursiveProgress {
            request: delete.request,
            deleted: 500,
        });
        browser.update(Message::Interrupt);

        let abandoned = browser.update(Message::Interrupt);

        assert_eq!(abandoned, Some(Effect::AbandonRecursiveDelete));
        assert!(!browser.is_waiting());
        assert!(matches!(
            browser
                .edit()
                .and_then(Edit::confirmation)
                .map(Confirmation::stage),
            Some(Stage::DeletedPartly(PartialDelete {
                deleted: 500,
                halt: Halt::Abandoned
            }))
        ));
        assert_eq!(browser.level().documents().map(<[_]>::len), Some(2));
        browser.update(Message::Discard);
        assert_eq!(browser.mode(), Mode::Panes);
    }

    #[test]
    fn a_recursive_delete_of_a_document_changed_since_it_was_read_reads_it_again_and_offers_r() {
        let (mut browser, delete) = deleting_dune_recursively();

        let reread = browser.update(Message::RecursivelyDeleted {
            request: delete.request,
            outcome: Ok(RecursiveOutcome::Partial(PartialDelete {
                deleted: 0,
                halt: Halt::Stale,
            })),
        });
        let Some(Effect::ReadDocument { request, document }) = reread else {
            panic!("no read: {reread:?}")
        };
        browser.update(Message::DocumentRead {
            request,
            outcome: Ok(Some(stored(dune(), WRITTEN_AT))),
        });
        let noted = matches!(
            browser
                .edit()
                .and_then(Edit::confirmation)
                .map(Confirmation::stage),
            Some(Stage::Asking(Some(Note::Changed)))
        );
        let offered = browser.offers_recursive_delete();
        let again = browser.update(Message::ConfirmRecursive);

        assert_eq!(document, dune().name);
        assert!(noted);
        assert!(offered);
        assert!(
            matches!(
                &again,
                Some(Effect::DeleteRecursively(delete)) if delete.update_time == WRITTEN_AT
            ),
            "{again:?}"
        );
    }

    #[test]
    fn d_in_the_documents_deletes_the_document_once_its_subcollections_are_listed() {
        let mut browser = browser_of(
            "books",
            "",
            vec![stored(dune(), READ_AT), stored(draft(), READ_AT)],
        );

        let listing = browser.update(Message::Delete);
        let Some(Effect::ListSubcollections { request, document }) = listing else {
            panic!("no listing: {listing:?}")
        };
        assert_eq!(browser.update(Message::Confirm), None);
        browser.update(Message::SubcollectionsListed {
            request,
            outcome: Ok(vec![orders()]),
        });
        let write = write_of(browser.update(Message::Confirm));
        browser.update(Message::Written {
            request: write.request,
            outcome: Ok(WriteOutcome::Deleted),
        });

        assert_eq!(document, dune().name);
        assert_eq!(write.operation, WriteOperation::Delete);
        assert_eq!(write.precondition, unchanged_since(READ_AT));
        assert_eq!(browser.level().documents().map(<[_]>::len), Some(1));
        assert_eq!(selected_id(&browser), Some("draft"));
        assert_eq!(browser.focus(), Pane::Documents);
        assert_eq!(browser.mode(), Mode::Panes);
    }

    fn editor_file(effect: Option<Effect>) -> EditorFile {
        match effect {
            Some(Effect::OpenEditor(file)) => file,
            other => panic!("no editor: {other:?}"),
        }
    }

    fn rejected_text(browser: &Browser) -> Option<&FsqError> {
        browser.edit()?.external_draft()?.error()
    }

    fn array(values: Vec<Value>) -> Value {
        value(ValueType::ArrayValue(ArrayValue { values }))
    }

    #[test]
    fn e_on_an_element_of_an_array_edits_the_whole_array_in_the_external_editor() {
        let mut browser = on_field(&["tags"]);
        browser.update(Message::Expand);
        browser.update(Message::Move(Movement::Down(1)));

        let file = editor_file(browser.update(Message::EditValue));
        save(&mut browser, r#"["sf", "classic", "space opera"]"#);

        assert_eq!(file.text, "[\n  \"sf\",\n  \"classic\"\n]\n");
        assert_eq!(
            confirmed_change(&browser),
            Some(&Change::Field {
                path: field_path(&["tags"]).mask().expect("a top-level field"),
                value: Some(array(vec![
                    string("sf"),
                    string("classic"),
                    string("space opera")
                ])),
            })
        );
    }

    #[test]
    fn shift_e_on_a_null_writes_the_type_its_tagged_json_names() {
        let mut browser = on_field(&["subtitle"]);
        assert_eq!(browser.update(Message::EditValue), None);

        let file = editor_file(browser.update(Message::EditExternally));
        save(&mut browser, r#""The desert planet""#);

        assert_eq!(file.text, "null\n");
        assert_eq!(
            confirmed_change(&browser),
            Some(&Change::Field {
                path: field_path(&["subtitle"]).mask().expect("a top-level field"),
                value: Some(string("The desert planet")),
            })
        );
    }

    #[test]
    fn e_opens_a_string_as_its_text_and_bytes_as_a_hex_dump_and_shift_e_both_as_tagged_json() {
        let opened = [
            ("blurb", Message::EditValue),
            ("blurb", Message::EditExternally),
            ("cover", Message::EditValue),
            ("cover", Message::EditExternally),
        ]
        .map(|(name, key)| editor_file(on_field(&[name]).update(key)));

        assert_eq!(
            opened,
            [
                (
                    "A desert planet, a spice that extends life,\nand a duke's son\n",
                    "txt"
                ),
                (
                    "\"A desert planet, a spice that extends life,\\nand a duke's son\"\n",
                    "json"
                ),
                ("00000000  01 02 03 ff\n", "txt"),
                ("{\n  \"$bytes\": \"AQID/w==\"\n}\n", "json"),
            ]
            .map(|(text, extension)| EditorFile {
                text: text.to_string(),
                extension,
            })
        );
    }

    #[test]
    fn e_in_the_documents_replaces_the_whole_document_under_the_update_time_it_was_read_with() {
        let mut browser = browser_of("books", "", vec![stored(dune(), READ_AT)]);

        let file = editor_file(browser.update(Message::EditValue));
        let without_tags = file
            .text
            .replace("\"tags\": [\n    \"sf\",\n    \"classic\"\n  ],\n  ", "");
        save(
            &mut browser,
            &without_tags.replace("\"Dune\"", "\"Dune Messiah\""),
        );
        let change = confirmed_change(&browser).cloned();
        let write = write_of(browser.update(Message::Confirm));

        assert!(file
            .text
            .starts_with("{\n  \"__name__\": \"books/dune\",\n"));
        let mut fields = dune().fields;
        fields.remove("tags");
        fields.insert("title".to_string(), string("Dune Messiah"));
        assert_eq!(change, Some(Change::Document(Some(fields.clone()))));
        assert_eq!(
            write.operation,
            WriteOperation::Update { fields, mask: None }
        );
        assert_eq!(write.precondition, unchanged_since(READ_AT));
    }

    #[test]
    fn a_save_that_reads_as_the_value_it_opened_with_or_a_failed_editor_writes_nothing() {
        let replies: [fn(EditorFile) -> EditorOutcome; 3] = [
            |opened| EditorOutcome::Saved(opened.text),
            |_| EditorOutcome::Saved(r#"{"zip": "N1 9GU", "city": "London"}"#.to_string()),
            |_| EditorOutcome::Failed,
        ];
        for reply in replies {
            let mut browser = on_field(&["address"]);
            let file = editor_file(browser.update(Message::EditValue));

            let closed = browser.update(Message::EditorClosed(Ok(reply(file))));

            assert_eq!(closed, None);
            assert!(browser.edit().is_none());
            assert_eq!(browser.mode(), Mode::Panes);
        }
    }

    #[test]
    fn after_a_stale_write_a_text_saved_as_it_first_opened_shows_over_the_document_read_again() {
        let mut browser = on_field(&["address"]);
        let opened = editor_file(browser.update(Message::EditValue));
        save(&mut browser, &opened.text.replace("London", "Paris"));
        let stale = write_of(browser.update(Message::Confirm));
        let reread = browser.update(Message::Written {
            request: stale.request,
            outcome: Ok(WriteOutcome::Stale),
        });
        let Some(Effect::ReadDocument { request, .. }) = reread else {
            panic!("no read: {reread:?}")
        };
        let mut moved = stored(dune(), WRITTEN_AT);
        let address = map(vec![("city", string("London")), ("zip", string("E1 6AN"))]);
        moved.fields.insert("address".to_string(), address.clone());
        browser.update(Message::DocumentRead {
            request,
            outcome: Ok(Some(moved)),
        });

        browser.update(Message::EditAgain);
        save(&mut browser, &opened.text);

        assert_eq!(
            browser.edit().and_then(Edit::value_change),
            Some(ValueChange {
                before: Some(address),
                after: Some(map(vec![
                    ("city", string("London")),
                    ("zip", string("N1 9GU"))
                ])),
            })
        );
    }

    /// A browser of `dune` and `draft` that has written a whole-document edit of `dune` and
    /// found `dune` gone when it read it again, and the write that would recreate it.
    fn editing_dune_deleted_meanwhile() -> (Browser, DocumentWrite) {
        let mut browser = browser_of(
            "books",
            "",
            vec![stored(dune(), READ_AT), stored(draft(), READ_AT)],
        );
        let file = editor_file(browser.update(Message::EditValue));
        save(
            &mut browser,
            &file.text.replace("\"Dune\"", "\"Dune Messiah\""),
        );
        let stale = write_of(browser.update(Message::Confirm));
        let reread = browser.update(Message::Written {
            request: stale.request,
            outcome: Ok(WriteOutcome::Stale),
        });
        let Some(Effect::ReadDocument { request, .. }) = reread else {
            panic!("no read: {reread:?}")
        };
        browser.update(Message::DocumentRead {
            request,
            outcome: Ok(None),
        });
        assert_eq!(selected_id(&browser), Some("draft"));
        let recreate = write_of(browser.update(Message::Confirm));
        (browser, recreate)
    }

    #[test]
    fn a_whole_document_edit_of_a_document_deleted_meanwhile_creates_it_again_and_shows_it() {
        let (mut browser, recreate) = editing_dune_deleted_meanwhile();
        let mut recreated = stored(dune(), WRITTEN_AT);
        recreated
            .fields
            .insert("title".to_string(), string("Dune Messiah"));

        browser.update(Message::Written {
            request: recreate.request,
            outcome: Ok(WriteOutcome::Written(recreated.clone())),
        });

        assert_eq!(
            recreate.precondition,
            FirestoreWritePrecondition::Exists(false)
        );
        assert_eq!(browser.level().selected_document(), Some(&recreated));
        assert!(browser.level().is_new(&recreated));
    }

    #[test]
    fn a_whole_document_edit_of_a_document_created_again_meanwhile_reads_it_and_writes_over_it() {
        let (mut browser, recreate) = editing_dune_deleted_meanwhile();
        let reread = browser.update(Message::Written {
            request: recreate.request,
            outcome: Ok(WriteOutcome::Stale),
        });
        let Some(Effect::ReadDocument { request, .. }) = reread else {
            panic!("no read: {reread:?}")
        };
        let created_again = stored(dune(), WRITTEN_AT);

        browser.update(Message::DocumentRead {
            request,
            outcome: Ok(Some(created_again.clone())),
        });
        let over = write_of(browser.update(Message::Confirm));

        assert_eq!(over.precondition, unchanged_since(WRITTEN_AT));
        assert_eq!(browser.level().selected_document(), Some(&created_again));
    }

    #[test]
    fn a_text_that_does_not_read_shows_its_error_and_e_opens_the_editor_on_it_again() {
        let mut browser = on_field(&["address"]);
        editor_file(browser.update(Message::EditValue));
        let broken = "{\n  \"city\": \"Paris\",\n}\n";

        save(&mut browser, broken);
        let reopened = editor_file(browser.update(Message::EditAgain));

        assert_eq!(browser.mode(), Mode::ExternalEditor);
        assert!(
            matches!(
                rejected_text(&browser),
                Some(FsqError::InvalidEditedText(InvalidEditedText::NotJson(error))) if error.line() == 3
            ),
            "{:?}",
            rejected_text(&browser)
        );
        assert_eq!(reopened.text, broken);
    }

    #[test]
    fn a_document_edit_that_changes_its_name_is_refused() {
        let mut browser = browser_of("books", "", vec![stored(draft(), READ_AT)]);
        let file = editor_file(browser.update(Message::EditValue));

        save(
            &mut browser,
            &file.text.replace("books/draft", "books/draft-2"),
        );

        assert_eq!(browser.mode(), Mode::ExternalEditor);
        assert!(
            matches!(
                rejected_text(&browser),
                Some(FsqError::InvalidEditedText(
                    InvalidEditedText::Renamed { .. }
                ))
            ),
            "{:?}",
            rejected_text(&browser)
        );
        assert_eq!(browser.update(Message::Confirm), None);
    }

    fn mask(names: &[&str]) -> MaskPath {
        field_path(names)
            .mask()
            .expect("a field outside every array")
    }

    fn null() -> Value {
        value(ValueType::NullValue(0))
    }

    fn add_field(browser: &mut Browser, name: &str, field_type: FieldType) -> Option<Effect> {
        browser.update(Message::AddField);
        browser.update(Message::Paste(name.to_string()));
        browser.update(Message::SubmitFieldName);
        let position = FieldType::ALL
            .iter()
            .position(|listed| *listed == field_type)
            .expect("a listed type");
        browser.update(Message::Move(Movement::Down(position)));
        browser.update(Message::PickFieldType)
    }

    fn refused_name(browser: &Browser) -> Option<&InvalidFieldName> {
        match browser.new_field()?.error()? {
            FsqError::InvalidFieldName(problem) => Some(problem),
            _ => None,
        }
    }

    #[test]
    fn a_adds_a_field_beside_the_row_under_the_cursor_or_inside_an_open_map_or_a_map_popup() {
        let mut browser = on_field(&["address"]);
        let mut added = Vec::new();

        add_field(&mut browser, "country", FieldType::Null);
        added.push(confirmed_change(&browser).cloned());
        browser.update(Message::Discard);
        browser.update(Message::Expand);
        add_field(&mut browser, "country", FieldType::Null);
        added.push(confirmed_change(&browser).cloned());
        browser.update(Message::Discard);
        point_at(&mut browser, &field_path(&["address", "zip"]));
        add_field(&mut browser, "country", FieldType::Null);
        added.push(confirmed_change(&browser).cloned());
        browser.update(Message::Discard);
        point_at(&mut browser, &field_path(&["address"]));
        browser.update(Message::Open);
        add_field(&mut browser, "country", FieldType::Null);
        added.push(confirmed_change(&browser).cloned());
        browser.update(Message::Discard);
        browser.update(Message::Move(Movement::Last));
        add_field(&mut browser, "country", FieldType::Null);
        added.push(confirmed_change(&browser).cloned());
        browser.update(Message::Discard);
        point_at(&mut browser, &field_path(&["title"]));
        browser.update(Message::Open);
        add_field(&mut browser, "country", FieldType::Null);
        added.push(confirmed_change(&browser).cloned());

        let null_at = |names: &[&str]| {
            Some(Change::Field {
                path: mask(names),
                value: Some(null()),
            })
        };
        assert_eq!(
            added,
            [
                null_at(&["country"]),
                null_at(&["address", "country"]),
                null_at(&["address", "country"]),
                null_at(&["address", "country"]),
                null_at(&["country"]),
                null_at(&["country"]),
            ]
        );
    }

    #[test]
    fn a_new_bytes_field_saved_empty_or_as_eight_digits_reaches_its_confirmation() {
        let mut browser = on_field(&["title"]);

        let file = editor_file(add_field(&mut browser, "scan", FieldType::Bytes));
        save(&mut browser, "");
        let empty = confirmed_change(&browser).cloned();
        editor_file(browser.update(Message::EditAgain));
        save(&mut browser, "deadbeef\n");
        let packed = confirmed_change(&browser).cloned();

        let bytes_at = |bytes: Vec<u8>| {
            Some(Change::Field {
                path: mask(&["scan"]),
                value: Some(value(ValueType::BytesValue(bytes))),
            })
        };
        assert_eq!(file.text, "");
        assert_eq!(empty, bytes_at(Vec::new()));
        assert_eq!(packed, bytes_at(vec![0xde, 0xad, 0xbe, 0xef]));
    }

    #[test]
    fn a_new_field_without_a_name_or_with_the_name_of_a_field_beside_it_is_refused() {
        let mut browser = on_field(&["title"]);
        browser.update(Message::AddField);

        browser.update(Message::SubmitFieldName);
        let unnamed = browser.mode();
        let unnamed_problem =
            refused_name(&browser).map(|problem| matches!(problem, InvalidFieldName::Empty));
        browser.update(Message::Paste("pages".to_string()));
        browser.update(Message::SubmitFieldName);
        let taken = browser.mode();
        let taken_problem =
            refused_name(&browser).map(|problem| matches!(problem, InvalidFieldName::Taken { .. }));
        browser.update(Message::Edit(LineEdit::DeleteToStart));
        browser.update(Message::Paste("city".to_string()));
        browser.update(Message::SubmitFieldName);

        assert_eq!([unnamed, taken], [Mode::FieldName, Mode::FieldName]);
        assert_eq!([unnamed_problem, taken_problem], [Some(true), Some(true)]);
        assert_eq!(browser.mode(), Mode::FieldType);
    }

    #[test]
    fn a_new_integer_field_is_written_as_an_integer_under_the_update_time_it_was_read_with() {
        let mut browser = on_field(&["title"]);

        add_field(&mut browser, "copies", FieldType::Integer);
        let opened_with = value_editor_text(&browser).map(str::to_string);
        browser.update(Message::Paste("12000".to_string()));
        browser.update(Message::SubmitValue);
        let shown = browser.edit().and_then(Edit::value_change);
        let write = write_of(browser.update(Message::Confirm));

        let copies = value(ValueType::IntegerValue(12000));
        assert_eq!(opened_with.as_deref(), Some(""));
        assert_eq!(
            shown,
            Some(ValueChange {
                before: None,
                after: Some(copies.clone()),
            })
        );
        assert_eq!(
            write.operation,
            WriteOperation::Update {
                fields: HashMap::from([("copies".to_string(), copies)]),
                mask: Some(mask(&["copies"])),
            }
        );
        assert_eq!(write.precondition, unchanged_since(READ_AT));
    }

    #[test]
    fn a_new_map_goes_straight_to_its_confirmation_and_is_written_empty() {
        let mut browser = on_field(&["title"]);

        add_field(&mut browser, "shelf", FieldType::Map);
        let mode = browser.mode();
        let write = write_of(browser.update(Message::Confirm));

        assert_eq!(mode, Mode::Confirmation);
        assert_eq!(
            write.operation,
            WriteOperation::Update {
                fields: HashMap::from([("shelf".to_string(), map(Vec::new()))]),
                mask: Some(mask(&["shelf"])),
            }
        );
    }

    #[test]
    fn a_does_nothing_on_an_open_array_inside_one_or_in_its_popup() {
        let mut browser = on_field(&["tags"]);
        browser.update(Message::AddField);
        let beside_closed_array = browser.mode();
        browser.update(Message::CancelNewField);
        browser.update(Message::Expand);

        browser.update(Message::AddField);
        let on_open_array = browser.mode();
        browser.update(Message::Open);
        browser.update(Message::AddField);
        let in_popup = browser.mode();
        browser.update(Message::ClosePopup);
        browser.update(Message::Move(Movement::Down(1)));
        browser.update(Message::AddField);

        assert_eq!(beside_closed_array, Mode::FieldName);
        assert_eq!(
            [on_open_array, in_popup, browser.mode()],
            [Mode::Panes, Mode::Popup, Mode::Panes]
        );
        assert!(browser.new_field().is_none());
    }

    fn create(browser: &mut Browser, text: &str) {
        editor_file(browser.update(Message::NewDocument));
        save(browser, text);
    }

    #[test]
    fn n_opens_an_empty_document_of_the_collection_on_show_and_an_unchanged_save_writes_nothing() {
        let mut browser = browser_of("authors/herbert/books", "", Vec::new());
        browser.update(Message::SwitchPane);
        let in_tree = browser.update(Message::NewDocument);
        browser.update(Message::SwitchPane);

        let file = editor_file(browser.update(Message::NewDocument));
        let closed = save(&mut browser, &file.text);

        assert_eq!(in_tree, None);
        assert_eq!(
            file,
            EditorFile {
                text: "{\n  \"__name__\": \"authors/herbert/books/\"\n}\n".to_string(),
                extension: "json",
            }
        );
        assert_eq!(closed, None);
        assert!(browser.edit().is_none());
    }

    #[test]
    fn an_id_after_the_collection_path_is_kept_and_written_only_while_no_document_has_it() {
        let mut browser = browser_of("books", "", vec![stored(dune(), READ_AT)]);
        create(
            &mut browser,
            r#"{"__name__": "books/dune-2", "title": "Dune"}"#,
        );

        let write = write_of(browser.update(Message::Confirm));

        assert_eq!(write.document, format!("{DOCUMENTS_PATH}/books/dune-2"));
        assert_eq!(
            write.precondition,
            FirestoreWritePrecondition::Exists(false)
        );
        assert_eq!(
            write.operation,
            WriteOperation::Update {
                fields: HashMap::from([("title".to_string(), string("Dune"))]),
                mask: None,
            }
        );
    }

    #[test]
    fn a_new_document_named_outside_the_collection_or_deeper_down_is_refused() {
        for name in ["books", "booksellers/dune", "books/dune/editions/first"] {
            let mut browser = browser_of("books", "", Vec::new());

            create(&mut browser, &format!(r#"{{"__name__": "{name}"}}"#));

            assert_eq!(browser.mode(), Mode::ExternalEditor, "{name}");
            assert!(
                matches!(
                    rejected_text(&browser),
                    Some(FsqError::InvalidEditedText(
                        InvalidEditedText::OutsideCollection { .. }
                    ))
                ),
                "{name}: {:?}",
                rejected_text(&browser)
            );
        }
    }

    #[test]
    fn a_new_document_whose_id_exists_goes_back_to_the_editor_with_its_text_and_is_not_written() {
        let mut browser = browser_of("books", "", vec![stored(dune(), READ_AT)]);
        let text = r#"{"__name__": "books/dune", "title": "Dune Messiah"}"#;
        create(&mut browser, text);
        let write = write_of(browser.update(Message::Confirm));

        let reread = browser.update(Message::Written {
            request: write.request,
            outcome: Ok(WriteOutcome::Stale),
        });
        let Some(Effect::ReadDocument { request, .. }) = reread else {
            panic!("no read: {reread:?}")
        };
        browser.update(Message::DocumentRead {
            request,
            outcome: Ok(Some(stored(dune(), READ_AT))),
        });
        let noted = matches!(
            browser
                .edit()
                .and_then(Edit::confirmation)
                .map(Confirmation::stage),
            Some(Stage::Asking(Some(Note::Exists)))
        );
        let again = browser.update(Message::Confirm);
        let reopened = editor_file(browser.update(Message::EditAgain));

        assert!(noted);
        assert_eq!(again, None);
        assert_eq!(reopened.text, text);
        assert_eq!(
            browser.level().documents(),
            Some(&[stored(dune(), READ_AT)][..])
        );
    }

    #[test]
    fn a_new_document_found_existing_with_the_fields_it_writes_is_taken_as_written() {
        let mut browser = browser_of("books", "", vec![stored(dune(), READ_AT)]);
        create(
            &mut browser,
            r#"{"__name__": "books/dune-2", "title": "Dune"}"#,
        );
        let write = write_of(browser.update(Message::Confirm));

        let reread = browser.update(Message::Written {
            request: write.request,
            outcome: Ok(WriteOutcome::Stale),
        });
        let Some(Effect::ReadDocument {
            request,
            document: read,
        }) = reread
        else {
            panic!("no read: {reread:?}")
        };
        let created = stored(
            document("dune-2", vec![("title", string("Dune"))]),
            WRITTEN_AT,
        );
        browser.update(Message::DocumentRead {
            request,
            outcome: Ok(Some(created.clone())),
        });

        assert_eq!(read, created.name);
        assert!(browser.edit().is_none());
        assert_eq!(browser.level().selected_document(), Some(&created));
        assert!(browser.level().is_new(&created));
    }

    #[test]
    fn shift_d_copies_the_fields_of_the_selected_document_under_a_new_id() {
        let mut browser = browser_of(
            "books",
            "",
            vec![stored(draft(), READ_AT), stored(dune(), READ_AT)],
        );
        browser.update(Message::Move(Movement::Down(1)));

        let file = editor_file(browser.update(Message::DuplicateDocument));
        save(&mut browser, &file.text);

        assert!(
            file.text.starts_with("{\n  \"__name__\": \"books/\",\n"),
            "{}",
            file.text
        );
        let Some(Change::NewDocument { name, fields }) = confirmed_change(&browser) else {
            panic!("no new document: {:?}", confirmed_change(&browser))
        };
        let id = name
            .strip_prefix(&format!("{DOCUMENTS_PATH}/books/"))
            .expect("a document of books");
        assert!(!id.is_empty() && id != "dune", "{id}");
        assert_eq!(fields, &dune().fields);
    }

    #[test]
    fn a_new_document_once_written_goes_under_the_cursor_and_takes_the_selection() {
        let mut browser = browser_of(
            "books",
            "",
            vec![stored(draft(), READ_AT), stored(dune(), READ_AT)],
        );
        create(
            &mut browser,
            r#"{"__name__": "books/dune-2", "title": "Dune"}"#,
        );
        let write = write_of(browser.update(Message::Confirm));
        let created = stored(
            document("dune-2", vec![("title", string("Dune"))]),
            WRITTEN_AT,
        );

        browser.update(Message::Written {
            request: write.request,
            outcome: Ok(WriteOutcome::Written(created.clone())),
        });
        let ids: Vec<String> = browser
            .level()
            .documents()
            .unwrap_or_default()
            .iter()
            .filter_map(|document| document.name.rsplit('/').next())
            .map(str::to_string)
            .collect();

        assert_eq!(ids, ["draft", "dune-2", "dune"]);
        assert_eq!(browser.level().selected_document(), Some(&created));
    }

    #[test]
    fn a_new_document_named_as_a_row_on_show_takes_the_place_of_that_row() {
        let mut browser = browser_of(
            "books",
            "",
            vec![stored(draft(), READ_AT), stored(dune(), READ_AT)],
        );
        create(
            &mut browser,
            r#"{"__name__": "books/dune", "title": "Dune Messiah"}"#,
        );
        let write = write_of(browser.update(Message::Confirm));
        let created = stored(
            document("dune", vec![("title", string("Dune Messiah"))]),
            WRITTEN_AT,
        );

        browser.update(Message::Written {
            request: write.request,
            outcome: Ok(WriteOutcome::Written(created.clone())),
        });

        assert_eq!(
            browser.level().documents(),
            Some(&[stored(draft(), READ_AT), created.clone()][..])
        );
        assert!(browser.level().is_new(&created));
    }
}