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
//! The full-screen browser of `\browse` and `fsq browse`: the documents of a collection on the
//! left, the values of the selected one as a tree on the right, and the subcollections of each
//! document one level further down.

mod draw;
mod editor;
mod external;
#[cfg(test)]
mod fixtures;
mod hex;
mod matching;
mod new_field;
mod recursive;
mod state;
mod tree;
mod write;

use crate::connection::Connection;
use crate::describe::CollectionPath;
use crate::errors::{is_existing_document, is_failed_precondition, FsqError, FsqResult};
use crate::render::ANIMATION_TICK;
use crate::walk::Walk;
use crossterm::clipboard::CopyToClipboard;
use crossterm::event::{
    DisableBracketedPaste, EnableBracketedPaste, Event, EventStream, KeyCode, KeyEvent,
    KeyEventKind, KeyModifiers,
};
use crossterm::execute;
use crossterm::terminal::{enable_raw_mode, EnterAlternateScreen};
use draw::Viewport;
pub use editor::FilterHistory;
use editor::{LineEdit, Recall};
use external::{EditorCommand, EditorFile, EditorOutcome};
use firestore::{FirestoreCollectionId, FirestoreDb, FirestoreDocument, FirestoreSqlOptions};
use futures::channel::mpsc::{self, UnboundedReceiver};
use futures::StreamExt;
use ratatui::backend::CrosstermBackend;
use ratatui::{DefaultTerminal, Terminal};
pub use state::FilterTail;
use state::{
    Browser, Copied, DocumentsQuery, Effect, Message, Mode, Movement, RequestId,
    BROWSE_DOCUMENT_LIMIT,
};
use std::future::Future;
use std::io::IsTerminal;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Once};
use std::time::{Duration, Instant};
use tokio::task::JoinHandle;
use write::{DocumentWrite, RecursiveDelete, RecursiveOutcome, WriteOperation, WriteOutcome};

#[derive(Debug, Clone, PartialEq, Eq, clap::Args)]
pub struct BrowseTarget {
    #[arg(help = "Collection path, such as `books` or `users/alice/orders`")]
    pub collection: CollectionPath,

    #[arg(
        long,
        default_value_t,
        hide_default_value = true,
        help = "The end of a SELECT after its FROM, such as \"WHERE genre = 'sf' ORDER BY title LIMIT 20\"; without a LIMIT, the first 100 documents"
    )]
    pub filter: FilterTail,
}

/// Browses `target` until the user quits, with the filters of `history` to recall, and adds the
/// filters that ran to it. Fails before it draws anything when stdin or stdout is not a terminal.
pub async fn run(
    connection: &Connection,
    target: BrowseTarget,
    history: &mut FilterHistory,
) -> FsqResult<()> {
    if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() {
        return Err(FsqError::BrowseNeedsTerminal);
    }
    let db = &connection.db;
    let (mut browser, first_query) =
        Browser::open(target, db.get_documents_path(), std::mem::take(history));
    let browsed = BROWSER_TASK
        .scope((), browse(db, &mut browser, first_query))
        .await;
    *history = browser.into_history();
    browsed
}

/// Draws after every key, message and resize, and every [`ANIMATION_TICK`] while the browser waits
/// for Firestore. In between it sleeps.
async fn browse(db: &FirestoreDb, browser: &mut Browser, first_query: Effect) -> FsqResult<()> {
    let mut calls = Calls::default();
    let mut screen = Screen::enter()?;
    let mut viewport = Viewport::default();
    let mut effect = Some(first_query);
    loop {
        match effect {
            Some(Effect::Query(query)) => calls.query(db, query),
            Some(Effect::ListSubcollections { request, document }) => {
                calls.list_subcollections(db, request, document)
            }
            Some(Effect::Write(write)) => calls.write(db, write),
            Some(Effect::DeleteRecursively(delete)) => calls.delete_recursively(db, delete),
            Some(Effect::ReadDocument { request, document }) => {
                calls.read_document(db, request, document)
            }
            Some(Effect::OpenEditor(file)) => {
                let outcome;
                (screen, outcome) = screen.hand_over(&file)?;
                effect = browser.update(Message::EditorClosed(outcome));
                continue;
            }
            Some(Effect::Copy { text, .. }) => screen.copy(&text)?,
            Some(Effect::Cancel) => calls.cancel(),
            Some(Effect::AbandonRecursiveDelete) => calls.recursive = None,
            Some(Effect::Quit) => return Ok(()),
            None => {}
        }
        screen.draw(browser, &mut viewport)?;
        effect = loop {
            tokio::select! {
                answer = calls.answer() => break browser.update(answer),
                event = screen.next_event() => {
                    match event? {
                        Event::Key(key) if key.kind == KeyEventKind::Press => {
                            break pressed(browser, &mut viewport, key);
                        }
                        Event::Paste(text) => break browser.update(Message::Paste(text)),
                        Event::Resize(..) => break None,
                        _ => {}
                    }
                }
                () = tokio::time::sleep(ANIMATION_TICK), if browser.is_waiting() => break None,
            }
        };
    }
}

/// Takes `key`: while a box is open over the panes, a move scrolls its text, and any other key
/// goes to the browser as the message it stands for. The note of a copy shows until the next key.
fn pressed(browser: &mut Browser, viewport: &mut Viewport, key: KeyEvent) -> Option<Effect> {
    viewport.copied = None;
    let mode = browser.mode();
    let page_rows = viewport.page_rows();
    if let (Mode::Popup | Mode::Confirmation | Mode::ExternalEditor, Some(movement)) =
        (mode, movement_for(key, page_rows))
    {
        viewport.scroll_popup(movement);
        return None;
    }
    let effect = browser.update(message_for(key, mode, page_rows)?);
    if let Some(Effect::Copy { copied, .. }) = &effect {
        viewport.copied = Some(*copied);
    }
    effect
}

/// What `key` asks of the browser in `mode`. A letter with Ctrl is a key of its own, which does
/// nothing unless it is bound, as Ctrl-C is. Raw mode delivers Ctrl-C as a key rather than a
/// signal.
fn message_for(key: KeyEvent, mode: Mode, page_rows: usize) -> Option<Message> {
    let control = key.modifiers.contains(KeyModifiers::CONTROL);
    let boxed = matches!(
        mode,
        Mode::Popup | Mode::Confirmation | Mode::ExternalEditor | Mode::FieldType
    );
    match key.code {
        KeyCode::Char('c') if control => return Some(Message::Interrupt),
        // Ctrl-G rather than a letter, which the filter editor would take as text. less and vim
        // show what they know about the file on Ctrl-G. A box shows its own error.
        KeyCode::Char('g') if control && !boxed => return Some(Message::ShowError),
        _ => {}
    }
    match mode {
        Mode::Popup => match key.code {
            KeyCode::Esc => Some(Message::ClosePopup),
            KeyCode::Char('y') if !control => Some(Message::Copy(Copied::Value)),
            KeyCode::Char('Y') if !control => Some(Message::Copy(Copied::Path)),
            KeyCode::Char('e') if !control => Some(Message::EditValue),
            KeyCode::Char('E') if !control => Some(Message::EditExternally),
            KeyCode::Char('a') if !control => Some(Message::AddField),
            KeyCode::Char('d') if !control => Some(Message::Delete),
            _ => None,
        },
        Mode::Confirmation | Mode::ExternalEditor => confirmation_message_for(key, control),
        Mode::FilterEditor => filter_message_for(key, control),
        Mode::ValueEditor => value_message_for(key, control),
        Mode::FieldName => field_name_message_for(key, control),
        Mode::FieldType => field_type_message_for(key, page_rows),
        Mode::Panes => pane_message_for(key, control, page_rows),
    }
}

fn field_name_message_for(key: KeyEvent, control: bool) -> Option<Message> {
    match key.code {
        KeyCode::Enter => Some(Message::SubmitFieldName),
        KeyCode::Esc => Some(Message::CancelNewField),
        _ => line_edit_for(key, control).map(Message::Edit),
    }
}

fn field_type_message_for(key: KeyEvent, page_rows: usize) -> Option<Message> {
    match key.code {
        KeyCode::Enter => Some(Message::PickFieldType),
        KeyCode::Esc => Some(Message::CancelNewField),
        _ => movement_for(key, page_rows).map(Message::Move),
    }
}

fn filter_message_for(key: KeyEvent, control: bool) -> Option<Message> {
    match key.code {
        KeyCode::Enter => Some(Message::RunFilter),
        KeyCode::Esc => Some(Message::CancelFilter),
        KeyCode::Up => Some(Message::Recall(Recall::Older)),
        KeyCode::Down => Some(Message::Recall(Recall::Newer)),
        _ => line_edit_for(key, control).map(Message::Edit),
    }
}

fn value_message_for(key: KeyEvent, control: bool) -> Option<Message> {
    match key.code {
        KeyCode::Enter => Some(Message::SubmitValue),
        KeyCode::Esc => Some(Message::CancelValue),
        _ => line_edit_for(key, control).map(Message::Edit),
    }
}

/// The edit of the line being typed that `key` asks for, in either editor.
fn line_edit_for(key: KeyEvent, control: bool) -> Option<LineEdit> {
    let edit = match key.code {
        KeyCode::Char('w') if control => LineEdit::DeleteWordBefore,
        KeyCode::Char('u') if control => LineEdit::DeleteToStart,
        KeyCode::Char(typed) if !control => LineEdit::Insert(typed),
        KeyCode::Backspace => LineEdit::DeleteBefore,
        KeyCode::Delete => LineEdit::DeleteAfter,
        KeyCode::Left => LineEdit::Left,
        KeyCode::Right => LineEdit::Right,
        KeyCode::Home => LineEdit::Start,
        KeyCode::End => LineEdit::End,
        _ => return None,
    };
    Some(edit)
}

/// What `key` asks of a confirmation: `y` writes, `R` deletes a document with everything under
/// it, `e` edits again, and `n` or Esc discards. A text the external editor saved that did not
/// read takes the same keys, and has nothing for `y` and `R` to write.
fn confirmation_message_for(key: KeyEvent, control: bool) -> Option<Message> {
    match key.code {
        KeyCode::Esc => Some(Message::Discard),
        KeyCode::Char(_) if control => None,
        KeyCode::Char('y') => Some(Message::Confirm),
        KeyCode::Char('R') => Some(Message::ConfirmRecursive),
        KeyCode::Char('e') => Some(Message::EditAgain),
        KeyCode::Char('n') => Some(Message::Discard),
        _ => None,
    }
}

fn pane_message_for(key: KeyEvent, control: bool, page_rows: usize) -> Option<Message> {
    if let Some(movement) = movement_for(key, page_rows) {
        return Some(Message::Move(movement));
    }
    let message = match key.code {
        KeyCode::Char(_) if control => return None,
        KeyCode::Right | KeyCode::Char('l') => Message::Expand,
        KeyCode::Enter => Message::Open,
        KeyCode::Char(' ') => Message::Toggle,
        KeyCode::Left | KeyCode::Char('h') => Message::Collapse,
        KeyCode::Tab | KeyCode::BackTab => Message::SwitchPane,
        KeyCode::Char('/') => Message::EditFilter,
        KeyCode::Char('f') => Message::FilterOnValue,
        KeyCode::Char('e') => Message::EditValue,
        KeyCode::Char('E') => Message::EditExternally,
        KeyCode::Char('d') => Message::Delete,
        KeyCode::Char('a') => Message::AddField,
        KeyCode::Char('n') => Message::NewDocument,
        KeyCode::Char('D') => Message::DuplicateDocument,
        KeyCode::Char('y') => Message::Copy(Copied::Value),
        KeyCode::Char('Y') => Message::Copy(Copied::Path),
        KeyCode::Char('r') => Message::Reload,
        KeyCode::Char('?') => Message::ShowHelp,
        KeyCode::Esc | KeyCode::Backspace => Message::Back,
        KeyCode::Char('q') => Message::Quit,
        _ => return None,
    };
    Some(message)
}

/// The move of the cursor, or of the text of a popup, that `key` asks for, where a page is
/// `page_rows` rows.
fn movement_for(key: KeyEvent, page_rows: usize) -> Option<Movement> {
    let control = key.modifiers.contains(KeyModifiers::CONTROL);
    let half_page = (page_rows / 2).max(1);
    let movement = match key.code {
        KeyCode::Up => Movement::Up(1),
        KeyCode::Down => Movement::Down(1),
        KeyCode::PageUp => Movement::Up(page_rows),
        KeyCode::PageDown => Movement::Down(page_rows),
        KeyCode::Home => Movement::First,
        KeyCode::End => Movement::Last,
        KeyCode::Char('u') if control => Movement::Up(half_page),
        KeyCode::Char('d') if control => Movement::Down(half_page),
        _ if control => return None,
        KeyCode::Char('k') => Movement::Up(1),
        KeyCode::Char('j') => Movement::Down(1),
        KeyCode::Char('g') => Movement::First,
        KeyCode::Char('G') => Movement::Last,
        _ => return None,
    };
    Some(movement)
}

tokio::task_local! {
    /// Set while the browser's own task runs. A panic there ends the browser, so the panic hook
    /// restores the terminal for it, and a panic in a call the browser waits for does not.
    static BROWSER_TASK: ();
}

/// Whether a [`Screen`] holds the terminal, which is what tells the panic hook that there is
/// something to restore.
static SCREEN_ACTIVE: AtomicBool = AtomicBool::new(false);

/// Whether a panic outside the browser's task printed its message over the screen, which the
/// next frame then draws whole.
static SCREEN_OVERWRITTEN: AtomicBool = AtomicBool::new(false);

/// The terminal in raw mode on the alternate screen, with bracketed paste on, and its events,
/// until this is dropped. On a panic in the browser's own task, a panic hook restores the
/// terminal before the message prints.
struct Screen {
    terminal: DefaultTerminal,
    /// `None` only while the screen is dropped.
    events: Option<EventStream>,
    /// Whether colour is on, as for the rest of fsq: off with `NO_COLOR` set, for one.
    colour: bool,
}

impl Screen {
    fn enter() -> FsqResult<Self> {
        static PANIC_HOOK: Once = Once::new();
        // One hook for the life of the process: a hook added per `\browse` would stack up, and
        // every later panic would restore the terminal once for each of them.
        PANIC_HOOK.call_once(|| {
            let previous = std::panic::take_hook();
            std::panic::set_hook(Box::new(move |info| {
                let in_browser_task = BROWSER_TASK.try_with(|_| ()).is_ok();
                if in_browser_task && SCREEN_ACTIVE.swap(false, Ordering::SeqCst) {
                    Self::restore();
                }
                previous(info);
                // Only once the message is out, so that a frame drawn while it prints does not
                // take the flag.
                if !in_browser_task && SCREEN_ACTIVE.load(Ordering::SeqCst) {
                    SCREEN_OVERWRITTEN.store(true, Ordering::SeqCst);
                }
            }));
        });
        SCREEN_ACTIVE.store(true, Ordering::SeqCst);
        match Self::init_terminal() {
            Ok(terminal) => Ok(Self {
                terminal,
                events: Some(EventStream::new()),
                colour: console::colors_enabled(),
            }),
            Err(error) => {
                SCREEN_ACTIVE.store(false, Ordering::SeqCst);
                Self::restore();
                Err(error.into())
            }
        }
    }

    fn init_terminal() -> std::io::Result<DefaultTerminal> {
        enable_raw_mode()?;
        execute!(
            std::io::stdout(),
            EnterAlternateScreen,
            EnableBracketedPaste
        )?;
        Terminal::new(CrosstermBackend::new(std::io::stdout()))
    }

    /// The next key, paste or resize. A terminal that ends its input is an error.
    async fn next_event(&mut self) -> std::io::Result<Event> {
        let events = self
            .events
            .as_mut()
            .expect("the events end only when the screen is dropped");
        events
            .next()
            .await
            .unwrap_or_else(|| Err(std::io::ErrorKind::UnexpectedEof.into()))
    }

    fn draw(&mut self, browser: &Browser, viewport: &mut Viewport) -> std::io::Result<()> {
        if SCREEN_OVERWRITTEN.swap(false, Ordering::SeqCst) {
            self.terminal.clear()?;
        }
        let now = Instant::now();
        self.terminal.draw(|frame| {
            browser.draw(frame, viewport, now);
            if !self.colour {
                draw::drop_hues(frame.buffer_mut());
            }
        })?;
        Ok(())
    }

    /// Puts `text` on the terminal's clipboard, between two frames, with OSC 52, the escape
    /// sequence that asks the terminal to set the system clipboard. It reaches the clipboard of
    /// the machine the terminal runs on, also over SSH, where the terminal allows it.
    fn copy(&mut self, text: &str) -> std::io::Result<()> {
        execute!(
            self.terminal.backend_mut(),
            CopyToClipboard::to_clipboard_from(text)
        )
    }

    /// Runs the editor the environment names on `file`, which has the terminal until it exits,
    /// then takes the terminal back. A variable that does not split into words is the outcome,
    /// before the terminal is handed over.
    fn hand_over(self, file: &EditorFile) -> FsqResult<(Self, FsqResult<EditorOutcome>)> {
        let command = match EditorCommand::from_environment(|name| std::env::var(name).ok()) {
            Ok(command) => command,
            Err(error) => return Ok((self, Err(error))),
        };
        // A listener of SIGINT takes the place of its default action, ending the process, for the
        // rest of the process, so that a Ctrl-C an editor leaves to the terminal does not end
        // fsq. It has to listen before the screen leaves raw mode, where Ctrl-C becomes the
        // signal.
        #[cfg(unix)]
        let _interrupts =
            tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt())?;
        #[cfg(windows)]
        let _interrupts = tokio::signal::windows::ctrl_c()?;
        // The editor takes the terminal as a shell hands it over: off the alternate screen, out
        // of raw mode, and with no reader of crossterm's left to take its keys.
        drop(self);
        let outcome = tokio::task::block_in_place(|| command.edit(file));
        Ok((Self::enter()?, outcome))
    }

    fn restore() {
        // ratatui's restore leaves bracketed paste on. A terminal that cannot take this fails
        // that restore too, which reports the error.
        let _ = execute!(std::io::stdout(), DisableBracketedPaste);
        ratatui::restore();
    }
}

impl Drop for Screen {
    fn drop(&mut self) {
        // Dropping the stream wakes crossterm's reader, which reedline shares. When the browser
        // read a key last, nothing waits on the reader, so the wake stays queued, and reedline's
        // next prompt takes it for a timeout when it asks where the cursor is, and fails.
        // Reading until nothing is left takes the wake, and with it the keys pressed while the
        // browser was still on screen.
        self.events = None;
        while let Ok(true) = crossterm::event::poll(Duration::ZERO) {
            if crossterm::event::read().is_err() {
                break;
            }
        }
        if SCREEN_ACTIVE.swap(false, Ordering::SeqCst) {
            Self::restore();
        }
    }
}

/// The Firestore calls the browser waits for. A call replaces the call of its kind before it,
/// since the browser only waits for the latest of each.
#[derive(Default)]
struct Calls {
    query: Option<Call<Vec<FirestoreDocument>>>,
    listing: Option<Call<Vec<FirestoreCollectionId>>>,
    write: Option<Call<WriteOutcome>>,
    recursive: Option<RecursiveCall>,
    read: Option<Call<Option<FirestoreDocument>>>,
}

impl Calls {
    fn query(&mut self, db: &FirestoreDb, query: DocumentsQuery) {
        let db = db.clone();
        self.query = Some(Call::spawn(query.request, async move {
            query.documents(&db).await
        }));
    }

    fn list_subcollections(&mut self, db: &FirestoreDb, request: RequestId, document: String) {
        let db = db.clone();
        self.listing = Some(Call::spawn(request, async move {
            Walk::new(&db).collection_ids(Some(&document)).await
        }));
    }

    fn write(&mut self, db: &FirestoreDb, write: DocumentWrite) {
        let db = db.clone();
        self.write = Some(Call::spawn(
            write.request,
            async move { write.send(&db).await },
        ));
    }

    fn delete_recursively(&mut self, db: &FirestoreDb, delete: RecursiveDelete) {
        let db = db.clone();
        let stop = Arc::new(AtomicBool::new(false));
        let (counts, progress) = mpsc::unbounded();
        let stopped = Arc::clone(&stop);
        let call = Call::spawn(delete.request, async move {
            let count = |deleted| {
                // Fails only once the browser dropped the receiver, and with it the call.
                let _ = counts.unbounded_send(deleted);
            };
            Ok(delete.run(&db, &stopped, count).await)
        });
        self.recursive = Some(RecursiveCall {
            call,
            progress,
            stop,
        });
    }

    fn read_document(&mut self, db: &FirestoreDb, request: RequestId, document: String) {
        let db = db.clone();
        self.read = Some(Call::spawn(request, async move {
            read_document(&db, &document).await
        }));
    }

    fn cancel(&mut self) {
        self.query = None;
        self.listing = None;
        self.write = None;
        self.read = None;
        if let Some(recursive) = &self.recursive {
            recursive.stop.store(true, Ordering::Relaxed);
        }
    }

    /// The answer of the first pending call to end, which never comes while none is pending.
    async fn answer(&mut self) -> Message {
        tokio::select! {
            (request, outcome) = Call::ended(&mut self.query) => {
                Message::DocumentsLoaded { request, outcome }
            }
            (request, outcome) = Call::ended(&mut self.listing) => {
                Message::SubcollectionsListed { request, outcome }
            }
            (request, outcome) = Call::ended(&mut self.write) => {
                Message::Written { request, outcome }
            }
            message = RecursiveCall::answer(&mut self.recursive) => message,
            (request, outcome) = Call::ended(&mut self.read) => {
                Message::DocumentRead { request, outcome }
            }
        }
    }
}

/// A Firestore call the browser waits for, stopped when it is dropped.
struct Call<T> {
    request: RequestId,
    task: JoinHandle<FsqResult<T>>,
}

impl<T: Send + 'static> Call<T> {
    fn spawn(
        request: RequestId,
        call: impl Future<Output = FsqResult<T>> + Send + 'static,
    ) -> Self {
        Self {
            request,
            task: tokio::spawn(call),
        }
    }
}

impl<T> Call<T> {
    /// Waits for the call in `slot` to end and empties the slot. Never ends while the slot is
    /// empty.
    async fn ended(slot: &mut Option<Self>) -> (RequestId, FsqResult<T>) {
        let Some(call) = slot else {
            return std::future::pending().await;
        };
        let outcome = call.outcome().await;
        let request = call.request;
        *slot = None;
        (request, outcome)
    }

    /// Waits for the call to end. A call that panicked fails with [`FsqError::CallPanicked`].
    async fn outcome(&mut self) -> FsqResult<T> {
        (&mut self.task)
            .await
            .unwrap_or_else(|error| Err(FsqError::CallPanicked(error)))
    }
}

/// A recursive delete the browser waits for, with the counts of documents it reports as it goes
/// and the flag that stops it between two requests. Dropping it aborts the delete at once, even
/// with a request in flight, whose deletes may still reach Firestore.
struct RecursiveCall {
    call: Call<RecursiveOutcome>,
    progress: UnboundedReceiver<usize>,
    stop: Arc<AtomicBool>,
}

impl RecursiveCall {
    /// The next count the delete in `slot` reports, and once they are all taken, how it ended,
    /// which empties the slot. Never ends while the slot is empty.
    async fn answer(slot: &mut Option<Self>) -> Message {
        let Some(recursive) = slot else {
            return std::future::pending().await;
        };
        let request = recursive.call.request;
        // The delete holds the sender until it ends, so the counts run out only then.
        if let Some(deleted) = recursive.progress.next().await {
            return Message::RecursiveProgress { request, deleted };
        }
        let outcome = recursive.call.outcome().await;
        *slot = None;
        Message::RecursivelyDeleted { request, outcome }
    }
}

impl<T> Drop for Call<T> {
    fn drop(&mut self) {
        self.task.abort();
    }
}

impl DocumentsQuery {
    /// Runs the query. Without a filter, a database that refuses pipelines, as a Standard edition
    /// one does, gets the first documents by ID from a listing instead.
    async fn documents(&self, db: &FirestoreDb) -> FsqResult<Vec<FirestoreDocument>> {
        let outcome = db
            .fluent()
            .sql(self.sql())
            .options(FirestoreSqlOptions::read_only())
            .query()
            .await;
        match outcome {
            Err(error) if self.filter.is_empty() && is_failed_precondition(&error) => {
                Walk::new(db)
                    .first_documents(&self.collection, BROWSE_DOCUMENT_LIMIT)
                    .await
            }
            outcome => Ok(outcome?),
        }
    }
}

impl DocumentWrite {
    /// Sends the write. A precondition that does not hold is the outcome [`WriteOutcome::Stale`],
    /// not a failure.
    async fn send(self, db: &FirestoreDb) -> FsqResult<WriteOutcome> {
        let name = DocumentName::split(&self.document);
        let precondition = self.precondition;
        let sent = match self.operation {
            WriteOperation::Update { fields, mask } => {
                let update = db.fluent().update();
                let update = match mask {
                    Some(mask) => update.fields([mask.to_string()]),
                    None => update,
                };
                let document = FirestoreDocument {
                    name: self.document.clone(),
                    fields,
                    create_time: None,
                    update_time: None,
                };
                update
                    .in_col(name.collection_id)
                    .precondition(precondition)
                    .document(document)
                    .execute()
                    .await
                    .map(WriteOutcome::Written)
            }
            WriteOperation::Delete => db
                .fluent()
                .delete()
                .from(name.collection_id)
                .parent(name.parent)
                .precondition(precondition)
                .document_id(name.document_id)
                .execute()
                .await
                .map(|()| WriteOutcome::Deleted),
        };
        match sent {
            Err(error) if is_failed_precondition(&error) || is_existing_document(&error) => {
                Ok(WriteOutcome::Stale)
            }
            sent => Ok(sent?),
        }
    }
}

/// The document named `document`, a full resource name, as stored now, `None` when it does not
/// exist.
async fn read_document(db: &FirestoreDb, document: &str) -> FsqResult<Option<FirestoreDocument>> {
    let name = DocumentName::split(document);
    Ok(db
        .fluent()
        .select()
        .by_id_in(name.collection_id)
        .parent(name.parent)
        .one(name.document_id)
        .await?)
}

/// The full resource name of a document, in the parts the firestore crate's calls take it in.
struct DocumentName<'a> {
    /// The documents path of the database, or the full resource name of the document the
    /// collection is under.
    parent: &'a str,
    collection_id: &'a str,
    document_id: &'a str,
}

impl<'a> DocumentName<'a> {
    fn split(name: &'a str) -> Self {
        let (collection, document_id) = name
            .rsplit_once('/')
            .expect("Firestore names a document <parent>/<collection ID>/<document ID>");
        let (parent, collection_id) = collection
            .rsplit_once('/')
            .expect("Firestore names a document <parent>/<collection ID>/<document ID>");
        Self {
            parent,
            collection_id,
            document_id,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::browse::fixtures::{books, browser_of, field_path, opened, save, stored, READ_AT};
    #[cfg(feature = "ci-live")]
    use crate::browse::fixtures::{live_collection, point_at};
    use crate::browse::state::{Load, Pane};
    use crate::browse::write::{Change, Confirmation, Edit};
    use crate::render::fixtures::{document, draft, dune, value};
    use firestore::gcloud_sdk::google::firestore::v1::value::ValueType;
    use ratatui::backend::TestBackend;
    use std::time::Duration;

    /// A browser of `books` that has read `documents`, and the viewport of a frame of it at
    /// 80 by 24, which sizes its pages.
    fn on_screen(documents: Vec<FirestoreDocument>) -> (Browser, Viewport) {
        let browser = browser_of("books", "", documents);
        let mut viewport = Viewport::default();
        drawn(&browser, &mut viewport);
        (browser, viewport)
    }

    fn drawn(browser: &Browser, viewport: &mut Viewport) {
        Terminal::new(TestBackend::new(80, 24))
            .expect("a test terminal")
            .draw(|frame| browser.draw(frame, viewport, Instant::now()))
            .expect("a frame");
    }

    fn press(browser: &mut Browser, viewport: &mut Viewport, code: KeyCode) -> Option<Effect> {
        press_with(browser, viewport, code, KeyModifiers::NONE)
    }

    fn press_with(
        browser: &mut Browser,
        viewport: &mut Viewport,
        code: KeyCode,
        modifiers: KeyModifiers,
    ) -> Option<Effect> {
        let effect = pressed(browser, viewport, KeyEvent::new(code, modifiers));
        drawn(browser, viewport);
        effect
    }

    fn selected(browser: &Browser) -> usize {
        browser.level().selected()
    }

    /// How many rows the tree of the selected document shows.
    fn tree_rows(browser: &Browser) -> usize {
        let level = browser.level();
        let document = level.selected_document().expect("a document");
        level.tree().rows(document).len()
    }

    #[test]
    fn g_and_shift_g_go_to_the_first_and_the_last_row() {
        let (mut browser, mut viewport) = on_screen(books(30));

        press(&mut browser, &mut viewport, KeyCode::Char('G'));
        assert_eq!(selected(&browser), 29);
        press(&mut browser, &mut viewport, KeyCode::Char('g'));
        assert_eq!(selected(&browser), 0);
    }

    #[test]
    fn ctrl_d_and_ctrl_u_move_half_a_page() {
        let (mut browser, mut viewport) = on_screen(books(30));
        let half_page = viewport.page_rows() / 2;
        assert!(half_page > 1);

        press_with(
            &mut browser,
            &mut viewport,
            KeyCode::Char('d'),
            KeyModifiers::CONTROL,
        );
        assert_eq!(selected(&browser), half_page);
        press_with(
            &mut browser,
            &mut viewport,
            KeyCode::Char('d'),
            KeyModifiers::CONTROL,
        );
        press_with(
            &mut browser,
            &mut viewport,
            KeyCode::Char('u'),
            KeyModifiers::CONTROL,
        );
        assert_eq!(selected(&browser), half_page);
    }

    #[test]
    fn space_opens_and_closes_the_map_under_the_cursor() {
        let (mut browser, mut viewport) = on_screen(vec![dune()]);
        press(&mut browser, &mut viewport, KeyCode::Tab);
        let collapsed = tree_rows(&browser);

        press(&mut browser, &mut viewport, KeyCode::Char(' '));
        let expanded = tree_rows(&browser);
        press(&mut browser, &mut viewport, KeyCode::Char(' '));

        assert_eq!(expanded, collapsed + 2);
        assert_eq!(tree_rows(&browser), collapsed);
    }

    #[test]
    fn left_in_the_documents_goes_up_a_level() {
        let (mut browser, mut viewport) = on_screen(vec![draft(), dune()]);
        press(&mut browser, &mut viewport, KeyCode::Down);
        press(&mut browser, &mut viewport, KeyCode::Right);
        press(&mut browser, &mut viewport, KeyCode::Char('G'));
        let Some(Effect::ListSubcollections { request, .. }) =
            press(&mut browser, &mut viewport, KeyCode::Right)
        else {
            panic!("no listing")
        };
        browser.update(Message::SubcollectionsListed {
            request,
            outcome: Ok(vec!["reviews".parse().expect("a collection ID")]),
        });
        press(&mut browser, &mut viewport, KeyCode::Char('G'));
        press(&mut browser, &mut viewport, KeyCode::Right);
        assert!(browser.has_parent());
        assert_eq!(browser.focus(), Pane::Documents);

        let up = press(&mut browser, &mut viewport, KeyCode::Left);

        assert_eq!(up, Some(Effect::Cancel));
        assert!(!browser.has_parent());
        assert_eq!(selected(&browser), 1);
        assert_eq!(press(&mut browser, &mut viewport, KeyCode::Left), None);
    }

    #[test]
    fn r_reads_the_documents_again_with_their_filter_and_keeps_the_selected_one() {
        let (mut browser, mut viewport) = on_screen(vec![draft(), dune()]);
        press(&mut browser, &mut viewport, KeyCode::Down);
        press(&mut browser, &mut viewport, KeyCode::Right);
        press(&mut browser, &mut viewport, KeyCode::Right);
        let expanded = tree_rows(&browser);

        let Some(Effect::Query(query)) = press(&mut browser, &mut viewport, KeyCode::Char('r'))
        else {
            panic!("no query")
        };
        browser.update(Message::DocumentsLoaded {
            request: query.request,
            outcome: Ok(vec![document("prologue", Vec::new()), draft(), dune()]),
        });

        assert_eq!(query.filter, FilterTail::default());
        assert_eq!(selected(&browser), 2);
        assert_eq!(tree_rows(&browser), expanded);
    }

    #[test]
    fn the_keys_of_the_panes_type_into_the_filter_editor() {
        let (mut browser, mut viewport) = on_screen(vec![draft(), dune()]);
        press(&mut browser, &mut viewport, KeyCode::Char('/'));

        for typed in ['g', 'G', ' ', 'r', '?', 'q', 'j', 'l', 'y', 'Y', 'f'] {
            assert_eq!(
                press(&mut browser, &mut viewport, KeyCode::Char(typed)),
                None
            );
        }

        assert_eq!(
            browser.filter_editor().map(|editor| editor.line().text()),
            Some("gG r?qjlyYf")
        );
        assert_eq!(selected(&browser), 0);
        assert!(browser.popup().is_none());
    }

    #[test]
    fn a_letter_with_ctrl_is_not_the_letter_in_the_panes_and_the_popup() {
        let (mut browser, mut viewport) = on_screen(vec![dune()]);
        press(&mut browser, &mut viewport, KeyCode::Tab);

        for letter in ['q', 'r', 'y', 'f', 'l', '/'] {
            assert_eq!(
                press_with(
                    &mut browser,
                    &mut viewport,
                    KeyCode::Char(letter),
                    KeyModifiers::CONTROL
                ),
                None,
                "Ctrl-{letter}"
            );
        }
        assert!(browser.filter_editor().is_none());
        assert_eq!(tree_rows(&browser), dune().fields.len() + 1);
        press(&mut browser, &mut viewport, KeyCode::Enter);
        press(&mut browser, &mut viewport, KeyCode::Enter);
        assert!(browser.popup().is_some());
        assert_eq!(
            press_with(
                &mut browser,
                &mut viewport,
                KeyCode::Char('y'),
                KeyModifiers::CONTROL
            ),
            None
        );
    }

    /// The text `effect` puts on the clipboard.
    fn copied_text(effect: Option<Effect>) -> String {
        let Some(Effect::Copy { text, .. }) = effect else {
            panic!("no copy: {effect:?}")
        };
        text
    }

    #[test]
    fn y_copies_a_map_as_tagged_json_and_a_string_as_its_text() {
        let (mut browser, mut viewport) = on_screen(vec![dune()]);
        assert_eq!(press(&mut browser, &mut viewport, KeyCode::Char('y')), None);
        press(&mut browser, &mut viewport, KeyCode::Tab);

        let address = press(&mut browser, &mut viewport, KeyCode::Char('y'));
        press(&mut browser, &mut viewport, KeyCode::Right);
        press(&mut browser, &mut viewport, KeyCode::Down);
        let city = press(&mut browser, &mut viewport, KeyCode::Char('y'));

        assert_eq!(copied_text(address), r#"{"city":"London","zip":"N1 9GU"}"#);
        assert_eq!(copied_text(city), "London");
    }

    #[test]
    fn shift_y_copies_the_path_the_tree_border_shows_and_the_popup_copies_too() {
        let (mut browser, mut viewport) = on_screen(vec![dune()]);
        press(&mut browser, &mut viewport, KeyCode::Tab);
        press(&mut browser, &mut viewport, KeyCode::Right);
        press(&mut browser, &mut viewport, KeyCode::Down);
        let city = press(&mut browser, &mut viewport, KeyCode::Char('Y'));
        press(&mut browser, &mut viewport, KeyCode::Up);
        press(&mut browser, &mut viewport, KeyCode::Left);
        press(&mut browser, &mut viewport, KeyCode::Down);
        press(&mut browser, &mut viewport, KeyCode::Down);
        press(&mut browser, &mut viewport, KeyCode::Enter);
        let popup_path = press(&mut browser, &mut viewport, KeyCode::Char('Y'));
        let popup_value = press(&mut browser, &mut viewport, KeyCode::Char('y'));

        assert_eq!(copied_text(city), "address.city");
        assert_eq!(copied_text(popup_path), "blurb");
        assert_eq!(
            copied_text(popup_value),
            "A desert planet, a spice that extends life,\nand a duke's son"
        );
    }

    #[test]
    fn f_opens_the_editor_with_a_where_on_a_leaf_and_does_nothing_on_a_map() {
        let (mut browser, mut viewport) = on_screen(vec![dune()]);
        press(&mut browser, &mut viewport, KeyCode::Tab);

        press(&mut browser, &mut viewport, KeyCode::Char('f'));
        assert!(browser.filter_editor().is_none());
        for _ in 0..6 {
            press(&mut browser, &mut viewport, KeyCode::Down);
        }
        press(&mut browser, &mut viewport, KeyCode::Char('f'));

        assert_eq!(
            browser.filter_editor().map(|editor| editor.line().text()),
            Some("WHERE pages = 412")
        );
    }

    async fn panicking_query() -> FsqResult<Vec<FirestoreDocument>> {
        panic!("a bug in the query")
    }

    #[tokio::test]
    async fn a_call_that_panics_fails_its_load() {
        let (mut browser, query) = opened("books", "");
        let mut calls = Calls {
            query: Some(Call::spawn(query.request, panicking_query())),
            ..Calls::default()
        };

        let answer = tokio::time::timeout(Duration::from_secs(5), calls.answer())
            .await
            .expect("an answer from the call");
        browser.update(answer);

        assert!(matches!(
            browser.level().load(),
            Load::Failed {
                error: FsqError::CallPanicked(_),
                ..
            }
        ));
    }

    #[test]
    fn e_d_y_n_and_esc_edit_delete_write_and_discard() {
        let (mut browser, mut viewport) = on_screen(vec![stored(dune(), READ_AT)]);
        press(&mut browser, &mut viewport, KeyCode::Tab);
        press(&mut browser, &mut viewport, KeyCode::Char('G'));
        press(&mut browser, &mut viewport, KeyCode::Up);
        press(&mut browser, &mut viewport, KeyCode::Char('e'));
        assert_eq!(browser.mode(), Mode::ValueEditor);
        press(&mut browser, &mut viewport, KeyCode::Char('!'));
        press(&mut browser, &mut viewport, KeyCode::Enter);
        assert_eq!(browser.mode(), Mode::Confirmation);
        press(&mut browser, &mut viewport, KeyCode::Char('e'));
        assert_eq!(browser.mode(), Mode::ValueEditor);
        press(&mut browser, &mut viewport, KeyCode::Esc);
        assert_eq!(browser.mode(), Mode::Panes);

        for discard in [KeyCode::Char('n'), KeyCode::Esc] {
            press(&mut browser, &mut viewport, KeyCode::Char('d'));
            assert_eq!(browser.mode(), Mode::Confirmation);
            assert_eq!(press(&mut browser, &mut viewport, discard), None);
            assert_eq!(browser.mode(), Mode::Panes);
        }
        press(&mut browser, &mut viewport, KeyCode::Char('d'));
        let written = press(&mut browser, &mut viewport, KeyCode::Char('y'));

        assert!(matches!(written, Some(Effect::Write(_))), "{written:?}");
    }

    #[test]
    fn e_on_a_number_edits_it_as_a_number_of_the_type_of_its_field() {
        let (mut browser, mut viewport) = on_screen(vec![stored(dune(), READ_AT)]);
        press(&mut browser, &mut viewport, KeyCode::Tab);
        let mut changes = Vec::new();
        for (row, typed) in [(6, "500"), (8, "4")] {
            press(&mut browser, &mut viewport, KeyCode::Char('g'));
            for _ in 0..row {
                press(&mut browser, &mut viewport, KeyCode::Down);
            }
            press(&mut browser, &mut viewport, KeyCode::Char('e'));
            press_with(
                &mut browser,
                &mut viewport,
                KeyCode::Char('u'),
                KeyModifiers::CONTROL,
            );
            for typed in typed.chars() {
                press(&mut browser, &mut viewport, KeyCode::Char(typed));
            }
            press(&mut browser, &mut viewport, KeyCode::Enter);
            changes.push(
                browser
                    .edit()
                    .and_then(Edit::confirmation)
                    .map(Confirmation::change)
                    .cloned(),
            );
            press(&mut browser, &mut viewport, KeyCode::Char('n'));
        }

        assert_eq!(
            changes,
            [
                Some(Change::Field {
                    path: field_path(&["pages"]).mask().expect("a top-level field"),
                    value: Some(value(ValueType::IntegerValue(500))),
                }),
                Some(Change::Field {
                    path: field_path(&["rating"]).mask().expect("a top-level field"),
                    value: Some(value(ValueType::DoubleValue(4.0))),
                }),
            ]
        );
    }

    #[test]
    fn e_in_the_popup_of_a_value_opens_the_editor_on_it() {
        let (mut browser, mut viewport) = on_screen(vec![stored(dune(), READ_AT)]);
        press(&mut browser, &mut viewport, KeyCode::Tab);
        for _ in 0..6 {
            press(&mut browser, &mut viewport, KeyCode::Down);
        }
        press(&mut browser, &mut viewport, KeyCode::Enter);
        assert_eq!(browser.mode(), Mode::Popup);

        press(&mut browser, &mut viewport, KeyCode::Char('e'));

        assert_eq!(browser.mode(), Mode::ValueEditor);
        assert!(browser.popup().is_none());
        assert_eq!(
            browser
                .edit()
                .and_then(Edit::value_editor)
                .map(|editor| editor.line().text()),
            Some("412")
        );
    }

    #[test]
    fn d_in_the_popup_of_a_value_asks_to_delete_its_field() {
        let (mut browser, mut viewport) = on_screen(vec![stored(dune(), READ_AT)]);
        press(&mut browser, &mut viewport, KeyCode::Tab);
        for _ in 0..6 {
            press(&mut browser, &mut viewport, KeyCode::Down);
        }
        press(&mut browser, &mut viewport, KeyCode::Enter);

        press(&mut browser, &mut viewport, KeyCode::Char('d'));

        assert_eq!(browser.mode(), Mode::Confirmation);
        assert!(browser.popup().is_none());
        assert_eq!(
            browser
                .edit()
                .and_then(Edit::confirmation)
                .map(Confirmation::change),
            Some(&Change::Field {
                path: field_path(&["pages"]).mask().expect("a top-level field"),
                value: None,
            })
        );
    }

    fn opens_the_editor(effect: Option<Effect>) -> bool {
        matches!(effect, Some(Effect::OpenEditor(_)))
    }

    #[test]
    fn shift_e_opens_the_external_editor_from_the_tree_and_the_popup_and_e_and_n_answer_its_error()
    {
        let (mut browser, mut viewport) = on_screen(vec![stored(dune(), READ_AT)]);
        press(&mut browser, &mut viewport, KeyCode::Tab);

        assert!(opens_the_editor(press(
            &mut browser,
            &mut viewport,
            KeyCode::Char('E')
        )));
        save(&mut browser, "{");
        assert_eq!(browser.mode(), Mode::ExternalEditor);
        assert!(opens_the_editor(press(
            &mut browser,
            &mut viewport,
            KeyCode::Char('e')
        )));
        save(&mut browser, "{");
        press(&mut browser, &mut viewport, KeyCode::Char('n'));
        assert_eq!(browser.mode(), Mode::Panes);
        press(&mut browser, &mut viewport, KeyCode::Enter);
        press(&mut browser, &mut viewport, KeyCode::Enter);
        assert_eq!(browser.mode(), Mode::Popup);

        let from_popup = press(&mut browser, &mut viewport, KeyCode::Char('E'));

        assert!(opens_the_editor(from_popup));
        assert!(browser.popup().is_none());
    }

    #[test]
    fn esc_at_each_step_of_a_new_field_writes_nothing() {
        let name = [KeyCode::Char('a')];
        let field_type = [KeyCode::Char('a'), KeyCode::Char('n'), KeyCode::Enter];
        let integer = [&field_type[..], &[KeyCode::Down, KeyCode::Enter]].concat();
        let confirmation = [&integer[..], &[KeyCode::Char('7'), KeyCode::Enter]].concat();
        let steps = [
            (&name[..], Mode::FieldName),
            (&field_type[..], Mode::FieldType),
            (&integer[..], Mode::ValueEditor),
            (&confirmation[..], Mode::Confirmation),
        ];

        for (keys, step) in steps {
            let (mut browser, mut viewport) = on_screen(vec![stored(dune(), READ_AT)]);
            press(&mut browser, &mut viewport, KeyCode::Tab);
            let effects: Vec<_> = keys
                .iter()
                .map(|key| press(&mut browser, &mut viewport, *key))
                .collect();
            let reached = browser.mode();

            let escaped = press(&mut browser, &mut viewport, KeyCode::Esc);

            assert_eq!(reached, step);
            assert!(effects.iter().all(Option::is_none), "{step:?}: {effects:?}");
            assert_eq!(escaped, None, "{step:?}");
            assert_eq!(browser.mode(), Mode::Panes, "{step:?}");
            assert!(browser.edit().is_none() && browser.new_field().is_none());
        }
    }

    #[test]
    fn shift_r_at_the_delete_of_a_document_deletes_it_recursively_only_with_subcollections() {
        for (collection_ids, recursive) in [(Vec::new(), false), (vec!["orders"], true)] {
            let (mut browser, mut viewport) = on_screen(vec![stored(dune(), READ_AT)]);
            let Some(Effect::ListSubcollections { request, .. }) =
                press(&mut browser, &mut viewport, KeyCode::Char('d'))
            else {
                panic!("no listing")
            };
            browser.update(Message::SubcollectionsListed {
                request,
                outcome: Ok(collection_ids
                    .iter()
                    .map(|id| id.parse().expect("a collection ID"))
                    .collect()),
            });

            let effect = press_with(
                &mut browser,
                &mut viewport,
                KeyCode::Char('R'),
                KeyModifiers::SHIFT,
            );

            assert_eq!(
                matches!(effect, Some(Effect::DeleteRecursively(_))),
                recursive,
                "{collection_ids:?}: {effect:?}"
            );
            assert_eq!(browser.mode(), Mode::Confirmation);
        }
    }

    #[cfg(feature = "ci-live")]
    #[tokio::test]
    async fn a_write_over_a_document_changed_since_it_was_read_is_stale_and_writes_nothing() {
        use crate::browse::fixtures::field_path;
        use crate::browse::write::{Change, Edit};
        use crate::render::fixtures::string;

        let (db, collection) = live_collection("stale").await;
        let name = format!("{}/{collection}/dune", db.get_documents_path());
        let dune = |title: &str| FirestoreDocument {
            name: name.clone(),
            fields: [
                ("title".to_string(), string(title)),
                ("pages".to_string(), string("412")),
            ]
            .into(),
            create_time: None,
            update_time: None,
        };
        db.fluent()
            .update()
            .in_col(&collection)
            .document(dune("Dune"))
            .execute()
            .await
            .expect("the document is written");
        let browsed = DocumentsQuery {
            request: RequestId::default(),
            collection: collection.parse().expect("a collection path"),
            filter: FilterTail::default(),
        };
        let read = browsed.documents(&db).await.expect("the browser's read");
        db.fluent()
            .update()
            .fields(["title"])
            .in_col(&collection)
            .document(dune("Dune Messiah"))
            .execute()
            .await
            .expect("the document changes after the read");
        let delete_pages = Change::Field {
            path: field_path(&["pages"]).mask().expect("a top-level field"),
            value: None,
        };

        let mut edit = Edit::confirming(&read[0], delete_pages);
        let stale = edit.write(RequestId::default()).expect("a write");
        let stale = stale.send(&db).await;
        let unchanged = read_document(&db, &name).await;
        db.fluent()
            .delete()
            .from(&collection)
            .document_id("dune")
            .execute()
            .await
            .expect("the document is deleted");

        assert!(matches!(stale, Ok(WriteOutcome::Stale)), "{stale:?}");
        let unchanged = unchanged.expect("a read").expect("the document");
        assert!(unchanged.fields.contains_key("pages"));
        assert_eq!(unchanged.fields.get("title"), Some(&string("Dune Messiah")));
    }

    #[cfg(feature = "ci-live")]
    #[tokio::test]
    async fn a_new_document_with_the_id_of_one_that_exists_writes_nothing() {
        use crate::render::fixtures::string;

        let (db, collection) = live_collection("exists").await;
        let target = BrowseTarget {
            collection: collection.parse().expect("a collection path"),
            filter: FilterTail::default(),
        };
        let (mut browser, Effect::Query(query)) =
            Browser::open(target, db.get_documents_path(), FilterHistory::default())
        else {
            panic!("no query")
        };
        let name = format!("{}/{collection}/dune", db.get_documents_path());
        let stored = FirestoreDocument {
            name: name.clone(),
            fields: [("title".to_string(), string("Dune"))].into(),
            create_time: None,
            update_time: None,
        };
        db.fluent()
            .update()
            .in_col(&collection)
            .document(stored)
            .execute()
            .await
            .expect("the document is written");
        let read = query.documents(&db).await;
        browser.update(Message::DocumentsLoaded {
            request: query.request,
            outcome: read,
        });
        browser.update(Message::NewDocument);
        let text = format!(r#"{{"__name__": "{collection}/dune", "title": "Dune Messiah"}}"#);
        browser.update(Message::EditorClosed(Ok(EditorOutcome::Saved(text))));
        let write = match browser.update(Message::Confirm) {
            Some(Effect::Write(write)) => Some(write),
            _ => None,
        };

        let outcome = match write {
            Some(write) => Some(write.send(&db).await),
            None => None,
        };
        let unchanged = read_document(&db, &name).await;
        db.fluent()
            .delete()
            .from(&collection)
            .document_id("dune")
            .execute()
            .await
            .expect("the document is deleted");

        assert!(
            matches!(outcome, Some(Ok(WriteOutcome::Stale))),
            "{outcome:?}"
        );
        let unchanged = unchanged.expect("a read").expect("the document");
        assert_eq!(unchanged.fields.get("title"), Some(&string("Dune")));
    }

    #[cfg(feature = "ci-live")]
    #[tokio::test]
    async fn a_write_over_a_document_deleted_since_it_was_read_is_stale_and_writes_nothing() {
        use crate::render::fixtures::string;

        let (db, collection) = live_collection("deleted").await;
        let name = format!("{}/{collection}/dune", db.get_documents_path());
        let read = db
            .fluent()
            .update()
            .in_col(&collection)
            .document(FirestoreDocument {
                name: name.clone(),
                fields: [("title".to_string(), string("Dune"))].into(),
                create_time: None,
                update_time: None,
            })
            .execute()
            .await
            .expect("the document is written");
        db.fluent()
            .delete()
            .from(&collection)
            .document_id("dune")
            .execute()
            .await
            .expect("the document is deleted");
        let retitle = Change::Field {
            path: field_path(&["title"]).mask().expect("a top-level field"),
            value: Some(string("Dune Messiah")),
        };

        let mut changes =
            [retitle, Change::Document(None)].map(|change| Edit::confirming(&read, change));
        let mut outcomes = Vec::new();
        for edit in &mut changes {
            let write = edit.write(RequestId::default()).expect("a write");
            outcomes.push(write.send(&db).await);
        }
        let after = read_document(&db, &name).await;
        db.fluent()
            .delete()
            .from(&collection)
            .document_id("dune")
            .execute()
            .await
            .expect("the document is deleted");

        assert!(
            outcomes
                .iter()
                .all(|outcome| matches!(outcome, Ok(WriteOutcome::Stale))),
            "{outcomes:?}"
        );
        assert!(matches!(after, Ok(None)), "{after:?}");
    }

    #[cfg(feature = "ci-live")]
    #[tokio::test]
    async fn a_stale_field_delete_read_again_and_confirmed_deletes_that_field_alone() {
        use crate::render::fixtures::string;

        let (db, collection) = live_collection("stale-then-written").await;
        let name = format!("{}/{collection}/dune", db.get_documents_path());
        let dune = |title: &str| FirestoreDocument {
            name: name.clone(),
            fields: [
                ("title".to_string(), string(title)),
                ("pages".to_string(), string("412")),
            ]
            .into(),
            create_time: None,
            update_time: None,
        };
        db.fluent()
            .update()
            .in_col(&collection)
            .document(dune("Dune"))
            .execute()
            .await
            .expect("the document is written");
        let target = BrowseTarget {
            collection: collection.parse().expect("a collection path"),
            filter: FilterTail::default(),
        };
        let (mut browser, Effect::Query(query)) =
            Browser::open(target, db.get_documents_path(), FilterHistory::default())
        else {
            panic!("no query")
        };
        let read = query.documents(&db).await;
        browser.update(Message::DocumentsLoaded {
            request: query.request,
            outcome: read,
        });
        db.fluent()
            .update()
            .fields(["title"])
            .in_col(&collection)
            .document(dune("Dune Messiah"))
            .execute()
            .await
            .expect("the document changes after the read");
        browser.update(Message::Expand);
        point_at(&mut browser, &field_path(&["pages"]));

        browser.update(Message::Delete);
        let Some(Effect::Write(stale)) = browser.update(Message::Confirm) else {
            panic!("no write")
        };
        let request = stale.request;
        let outcome = stale.send(&db).await;
        let Some(Effect::ReadDocument { request, document }) =
            browser.update(Message::Written { request, outcome })
        else {
            panic!("no read")
        };
        let outcome = read_document(&db, &document).await;
        browser.update(Message::DocumentRead { request, outcome });
        let Some(Effect::Write(write)) = browser.update(Message::Confirm) else {
            panic!("no write over the document read again")
        };
        let request = write.request;
        let outcome = write.send(&db).await;
        browser.update(Message::Written { request, outcome });
        let stored = read_document(&db, &name).await;
        db.fluent()
            .delete()
            .from(&collection)
            .document_id("dune")
            .execute()
            .await
            .expect("the document is deleted");

        let stored = stored.expect("a read").expect("the document");
        assert_eq!(
            stored.fields,
            [("title".to_string(), string("Dune Messiah"))].into()
        );
        assert_eq!(browser.level().selected_document(), Some(&stored));
    }

    /// Sends the write `y` asks for at the confirmation on show, and gives the browser its answer.
    #[cfg(feature = "ci-live")]
    async fn confirm_live(browser: &mut Browser, db: &FirestoreDb) {
        let Some(Effect::Write(write)) = browser.update(Message::Confirm) else {
            panic!("no write")
        };
        let request = write.request;
        let outcome = write.send(db).await;
        browser.update(Message::Written { request, outcome });
    }

    #[cfg(feature = "ci-live")]
    #[tokio::test]
    async fn a_create_a_replace_and_a_delete_write_what_their_confirmations_show() {
        use crate::render::fixtures::string;

        let (db, collection) = live_collection("written").await;
        let name = format!("{}/{collection}/dune", db.get_documents_path());
        let target = BrowseTarget {
            collection: collection.parse().expect("a collection path"),
            filter: FilterTail::default(),
        };
        let (mut browser, Effect::Query(query)) =
            Browser::open(target, db.get_documents_path(), FilterHistory::default())
        else {
            panic!("no query")
        };
        let read = query.documents(&db).await;
        browser.update(Message::DocumentsLoaded {
            request: query.request,
            outcome: read,
        });

        browser.update(Message::NewDocument);
        let text =
            format!(r#"{{"__name__": "{collection}/dune", "title": "Dune", "author": "Herbert"}}"#);
        save(&mut browser, &text);
        confirm_live(&mut browser, &db).await;
        let created = read_document(&db, &name).await;
        let created_on_show = browser.level().selected_document().cloned();
        browser.update(Message::EditValue);
        save(
            &mut browser,
            &format!(r#"{{"__name__": "{collection}/dune", "title": "Dune Messiah"}}"#),
        );
        confirm_live(&mut browser, &db).await;
        let replaced = read_document(&db, &name).await;
        let replaced_on_show = browser.level().selected_document().cloned();
        let Some(Effect::ListSubcollections { request, document }) =
            browser.update(Message::Delete)
        else {
            panic!("no listing")
        };
        let outcome = Walk::new(&db).collection_ids(Some(&document)).await;
        browser.update(Message::SubcollectionsListed { request, outcome });
        confirm_live(&mut browser, &db).await;
        let deleted = read_document(&db, &name).await;
        db.fluent()
            .delete()
            .from(&collection)
            .document_id("dune")
            .execute()
            .await
            .expect("nothing is left");

        let created = created.expect("a read").expect("the document created");
        assert_eq!(
            created.fields,
            [
                ("title".to_string(), string("Dune")),
                ("author".to_string(), string("Herbert"))
            ]
            .into()
        );
        assert_eq!(created_on_show, Some(created));
        let replaced = replaced.expect("a read").expect("the document replaced");
        assert_eq!(
            replaced.fields,
            [("title".to_string(), string("Dune Messiah"))].into()
        );
        assert_eq!(replaced_on_show, Some(replaced));
        assert!(matches!(deleted, Ok(None)), "{deleted:?}");
        assert_eq!(browser.level().documents().map(<[_]>::len), Some(0));
        assert!(browser.edit().is_none());
    }
}