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
use super::footer::{Hint, Hints};
use super::{PopupScroll, Viewport, CURSOR_BAR, SELECTION_MARKER};
use crate::browse::external::ExternalDraft;
use crate::browse::hex::{hex_lines, HEX_BYTES_PER_LINE, HEX_OFFSET_WIDTH};
use crate::browse::new_field::FieldType;
use crate::browse::state::{Browser, EditorChoice, Popup};
use crate::browse::tree::{Listing, MaskPath};
use crate::browse::write::{
    Change, Confirmation, Edit, Halt, Note, PartialDelete, Stage, ValueChange,
};
use crate::errors::FsqError;
use crate::field_path::FieldPath;
use crate::render::{counted, cut_middle, type_name, View};
use firestore::gcloud_sdk::google::firestore::v1::value::ValueType;
use firestore::gcloud_sdk::google::firestore::v1::Value;
use firestore::{FirestoreDb, FirestoreVector};
use ratatui::layout::{Constraint, Rect};
use ratatui::style::{Style, Stylize};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Clear, HighlightSpacing, List, ListState, Paragraph};
use ratatui::Frame;
use similar::{ChangeTag, TextDiff};
use std::borrow::Cow;
use std::time::Duration;

/// How long the diff of a confirmation may take, past which it settles for one with more lines
/// removed and added than needed. The diff is drawn again every frame.
const CONFIRMATION_DIFF_TIMEOUT: Duration = Duration::from_millis(50);

/// The columns a popup leaves free of the panes on either side of it.
const POPUP_MARGIN: usize = 2;

/// The columns a tab in a value takes in a popup.
const POPUP_TAB: &str = "    ";

/// The most columns a note, a line without a marker, widens a popup to. A longer one wraps.
const POPUP_NOTE_WIDTH: usize = 60;

impl Browser {
    /// Draws `popup` over `body`, the area of the panes.
    pub(super) fn draw_popup(
        &self,
        frame: &mut Frame,
        popup: &Popup,
        body: Rect,
        viewport: &mut Viewport,
    ) {
        let view = self.value_view();
        let (title, text) = match popup {
            Popup::Value { path, value } => {
                let details = [Some(type_name(value).to_string()), size_detail(value)];
                let title = PopupTitle {
                    name: FieldPath::from(path).to_string(),
                    details: details.into_iter().flatten().collect(),
                };
                (title, PopupText::of(value, &view))
            }
            Popup::Error(failure) => {
                let error = self.error(*failure).map(ToString::to_string);
                (
                    PopupTitle::named("error"),
                    PopupText::Text(error.unwrap_or_default()),
                )
            }
            Popup::Help => (PopupTitle::named("keys"), PopupText::Help),
        };
        let mut hints = Vec::new();
        if let Popup::Value { .. } = popup {
            hints.push(Hint::new("y", "copy", 2));
        }
        if self.edits_at_cursor(EditorChoice::Fitting) {
            hints.push(Hint::new("e", "edit", 1));
        }
        if self.new_field_parent().is_some() {
            hints.push(Hint::new("a", "add", 1));
        }
        hints.push(Hint::new("Esc", "close", 3));
        draw_box(frame, body, viewport, title, text, hints);
    }

    /// Draws the change `edit` waits to confirm over `body`: the path of the document in the
    /// title, after it the field and what the change does to it, then the value before and after
    /// as a line diff, the subcollections a deleted document leaves or `R` deletes too, and
    /// where the write stands.
    pub(super) fn draw_confirmation(
        &self,
        frame: &mut Frame,
        edit: &Edit,
        confirmation: &Confirmation,
        body: Rect,
        viewport: &mut Viewport,
    ) {
        let change = confirmation.change();
        let mut details = Vec::new();
        let action = match change {
            Change::Field { path, value } => {
                details.push(FieldPath::from(path).to_string());
                value.as_ref().map_or("delete", type_name)
            }
            Change::Document(None) => "delete",
            Change::Document(Some(_)) if edit.last_read().is_some() => "replace",
            Change::Document(Some(_)) | Change::NewDocument { .. } => "new",
        };
        details.push(action.to_string());
        let title = PopupTitle {
            name: self.edited_document_path(edit),
            details,
        };

        let view = self.value_view();
        let mut lines = edit
            .value_change()
            .map(|values| values.lines(&view))
            .unwrap_or_default();
        let deletes_document = matches!(change, Change::Document(None));
        let recursive_delete_started = matches!(
            confirmation.stage(),
            Stage::DeletingRecursively(_) | Stage::DeletedPartly(_)
        );
        if deletes_document && !recursive_delete_started {
            let listing = self.level().tree().listing();
            lines.push(MarkedLine::blank());
            lines.extend(listing.confirmation_lines(self.offers_recursive_delete()));
        }
        let stage_lines = match confirmation.stage() {
            _ if edit.is_gone() => vec![MarkedLine::note(
                "the document no longer exists",
                Style::new().red(),
            )],
            Stage::Asking(None) => Vec::new(),
            Stage::Asking(Some(Note::Changed)) => vec![MarkedLine::note(
                "nothing was written: the document changed since it was read, and the diff is \
                 against what it holds now",
                Style::new().yellow(),
            )],
            Stage::Asking(Some(Note::WriteStopped)) => vec![MarkedLine::note(
                "stopped waiting: the write may have reached Firestore, and y tries again",
                Style::new().yellow(),
            )],
            Stage::Asking(Some(Note::ReadStopped)) => vec![MarkedLine::note(
                "stopped reading the document again, and y tries the write again",
                Style::new().yellow(),
            )],
            Stage::Asking(Some(Note::Exists)) => vec![MarkedLine::note(
                "nothing was written: a document of this name exists, and e gives the new one \
                 another",
                Style::new().red(),
            )],
            Stage::Writing(_) => vec![MarkedLine::note("writing…", Style::new().yellow())],
            Stage::DeletingRecursively(progress) => {
                let deleted = counted(progress.deleted, "document", "documents");
                let text = if progress.stopping {
                    format!("stopping after the request in flight… {deleted} deleted so far")
                } else {
                    format!("deleting… {deleted} deleted so far")
                };
                vec![MarkedLine::note(&text, Style::new().yellow())]
            }
            Stage::DeletedPartly(partial) => partial.lines(),
            Stage::Reading(_) => vec![MarkedLine::note(
                "reading the document again…",
                Style::new().yellow(),
            )],
            Stage::Failed(error) => vec![
                MarkedLine::note(&format!("error: {error}"), Style::new().red()),
                MarkedLine::note("y tries again", Style::new().dim()),
            ],
        };
        if !stage_lines.is_empty() {
            lines.push(MarkedLine::blank());
            lines.extend(stage_lines);
        }

        let mut hints = Vec::new();
        if edit.is_waiting() {
            let stopping = matches!(
                confirmation.stage(),
                Stage::DeletingRecursively(progress) if progress.stopping
            );
            let action = if stopping { "stop waiting" } else { "stop" };
            hints.push(Hint::new("Ctrl-C", action, 4));
        } else if edit.is_gone() || recursive_delete_started {
            if confirmation.has_draft() {
                hints.push(Hint::new("e", "edit", 2));
            }
            hints.push(Hint::new("n", "close", 4));
        } else {
            let deletes = matches!(
                change,
                Change::Field { value: None, .. } | Change::Document(None)
            );
            if !self.waits_for_listing() && !edit.exists_already() {
                hints.push(Hint::new("y", if deletes { "delete" } else { "write" }, 4));
            }
            if self.offers_recursive_delete() {
                hints.push(Hint::new("R", "delete all", 3));
            }
            if confirmation.has_draft() {
                hints.push(Hint::new("e", "edit", 2));
            }
            hints.push(Hint::new("n", "discard", 3));
        }
        draw_box(
            frame,
            body,
            viewport,
            title,
            PopupText::Marked(lines),
            hints,
        );
    }

    /// Draws `error`, of the text the external editor saved for `edit`, over `body`: the path of
    /// the document in the title, after it the field the edit changes, and the keys that open
    /// the editor again on the text or discard it.
    pub(super) fn draw_rejected_text(
        &self,
        frame: &mut Frame,
        edit: &Edit,
        draft: &ExternalDraft,
        error: &FsqError,
        body: Rect,
        viewport: &mut Viewport,
    ) {
        let title = PopupTitle {
            name: self.edited_document_path(edit),
            details: draft
                .path()
                .map(|path| FieldPath::from(path).to_string())
                .into_iter()
                .collect(),
        };
        let lines = vec![
            MarkedLine::note(&format!("error: {error}"), Style::new().red()),
            MarkedLine::blank(),
            MarkedLine::note("nothing was written", Style::new().dim()),
        ];
        let hints = vec![Hint::new("e", "edit", 2), Hint::new("n", "discard", 3)];
        draw_box(
            frame,
            body,
            viewport,
            title,
            PopupText::Marked(lines),
            hints,
        );
    }

    /// Draws the list of types of the new field at `path` over `body`, with the cursor on
    /// `selected`, scrolled to keep it in view.
    pub(super) fn draw_type_list(
        &self,
        frame: &mut Frame,
        path: &MaskPath,
        selected: FieldType,
        body: Rect,
        viewport: &mut Viewport,
    ) {
        let title = PopupTitle {
            name: FieldPath::from(path).to_string(),
            details: vec!["type".to_string()],
        };
        let hints = vec![
            Hint::new("↑↓", "move", 1),
            Hint::new("Enter", "pick", 3),
            Hint::new("Esc", "cancel", 2),
        ];
        let names: Vec<String> = FieldType::ALL.iter().map(ToString::to_string).collect();
        let marker = Span::from(SELECTION_MARKER).width();
        let widest = names
            .iter()
            .map(|name| marker + Span::from(name.as_str()).width())
            .max()
            .unwrap_or_default();
        let inner_width = box_width(body, widest, &title, &hints);
        let (area, rows) = box_area(body, inner_width, names.len());
        viewport.page_rows = rows;
        let position = FieldType::ALL.iter().position(|listed| *listed == selected);
        let list = List::new(names)
            .block(box_block(&title, hints, inner_width))
            .highlight_style(CURSOR_BAR)
            .highlight_symbol(SELECTION_MARKER)
            .highlight_spacing(HighlightSpacing::Always);
        frame.render_widget(Clear, area);
        frame.render_stateful_widget(
            list,
            area,
            &mut ListState::default().with_selected(position),
        );
    }

    /// The path of the document `edit` changes, from the root of the database, or of the
    /// collection on show for a new document its text does not name yet.
    fn edited_document_path(&self, edit: &Edit) -> String {
        match edit.document() {
            Some(name) => {
                FirestoreDb::relative_document_name(self.documents_path(), name).to_string()
            }
            None => self.level().path().to_string(),
        }
    }
}

/// Draws a box over `body`, the area of the panes, as wide as its text, its title and its
/// `hints`, inside the panes, with its text wrapped to the box and scrolled to where `viewport`
/// keeps it, and the hints on its bottom border.
fn draw_box(
    frame: &mut Frame,
    body: Rect,
    viewport: &mut Viewport,
    title: PopupTitle,
    text: PopupText,
    mut hints: Vec<Hint>,
) {
    let mut inner_width = box_width(body, text.natural_width(), &title, &hints);
    let mut lines = text.lines(inner_width);
    let mut rows = box_area(body, inner_width, lines.len()).1;
    if rows < lines.len() {
        hints.insert(0, Hint::new("↑↓", "scroll", 1));
        inner_width = box_width(body, text.natural_width(), &title, &hints);
        lines = text.lines(inner_width);
    }
    let area;
    (area, rows) = box_area(body, inner_width, lines.len());
    let last_top = lines.len() - rows;
    let scroll = viewport.popup.get_or_insert_with(PopupScroll::default);
    scroll.top = scroll.top.min(last_top);
    scroll.last_top = last_top;
    let top = scroll.top;
    viewport.page_rows = rows;

    let block = box_block(&title, hints, inner_width);
    let shown: Vec<Line> = lines.into_iter().skip(top).take(rows).collect();
    frame.render_widget(Clear, area);
    frame.render_widget(Paragraph::new(shown).block(block), area);
}

/// The columns inside a box over `body` that holds text `natural_width` columns wide, `title`
/// and `hints`: as wide as the widest of them, inside the panes.
fn box_width(body: Rect, natural_width: usize, title: &PopupTitle, hints: &[Hint]) -> usize {
    let most = usize::from(body.width).saturating_sub(2 * POPUP_MARGIN + 2);
    let hints_width = usize::from(Hints(hints.to_vec()).columns()) + 2;
    natural_width.max(title.width()).max(hints_width).min(most)
}

/// The area of a box in the middle of `body`, `inner_width` columns inside, for `lines` lines of
/// text, and how many of them show inside the panes.
fn box_area(body: Rect, inner_width: usize, lines: usize) -> (Rect, usize) {
    let rows = lines.min(usize::from(body.height).saturating_sub(2));
    let area = body.centered(
        Constraint::Length(u16::try_from(inner_width + 2).unwrap_or(u16::MAX)),
        Constraint::Length(u16::try_from(rows + 2).unwrap_or(u16::MAX)),
    );
    (area, rows)
}

/// The border of a box `inner_width` columns inside, with `title` on top and as many of `hints`
/// as fit at the bottom.
fn box_block(title: &PopupTitle, hints: Vec<Hint>, inner_width: usize) -> Block<'static> {
    let mut hints = Hints(hints).fitted(inner_width.saturating_sub(2)).line();
    hints.spans.insert(0, Span::from(" "));
    hints.spans.push(Span::from(" "));
    Block::bordered()
        .title(title.line(inner_width))
        .title_bottom(hints)
        .border_style(Style::new().cyan())
}

impl ValueChange {
    /// The value before and after the change as a line diff: the lines both share dim, the
    /// others after a `-` or a `+`.
    fn lines(&self, view: &View<'_>) -> Vec<MarkedLine> {
        if self.changes_nothing() {
            return vec![MarkedLine::note("no change", Style::new().dim())];
        }
        let [before, after] = self.texts(view);
        TextDiff::configure()
            .timeout(CONFIRMATION_DIFF_TIMEOUT)
            .diff_lines(&before, &after)
            .iter_all_changes()
            .map(|line| {
                let (marker, style) = match line.tag() {
                    ChangeTag::Equal => ("  ", Style::new().dim()),
                    ChangeTag::Delete => ("- ", Style::new().red()),
                    ChangeTag::Insert => ("+ ", Style::new().green()),
                };
                MarkedLine {
                    marker,
                    text: line.value().trim_end_matches(['\r', '\n']).to_string(),
                    style,
                }
            })
            .collect()
    }

    /// The texts the diff compares: those the value popup shows, so that it compares what was
    /// seen, unless they do not tell the two values apart or show nothing of one: values of two
    /// types, text that differs only in whitespace, which a wrapped line does not show, and an
    /// empty string or empty bytes. Then the tagged JSON, which names each type and quotes a
    /// string.
    fn texts(&self, view: &View<'_>) -> [String; 2] {
        let values = [&self.before, &self.after];
        let shown = values.map(|value| value.as_ref().map(|value| value_text(value, view)));
        let retyped = matches!(
            (&self.before, &self.after),
            (Some(before), Some(after)) if type_name(before) != type_name(after)
        );
        let blank = shown.iter().flatten().any(String::is_empty);
        let [before, after] = shown.map(Option::unwrap_or_default);
        if retyped || blank || before.split_whitespace().eq(after.split_whitespace()) {
            return values.map(|value| {
                value
                    .as_ref()
                    .map(|value| format!("{:#}", view.tagged_json(value)))
                    .unwrap_or_default()
            });
        }
        [before, after]
    }
}

/// `value` as the value popup shows it, with bytes as lines of [`HEX_BYTES_PER_LINE`].
fn value_text(value: &Value, view: &View<'_>) -> String {
    match &value.value_type {
        Some(ValueType::BytesValue(bytes)) => hex_lines(bytes, HEX_BYTES_PER_LINE).join("\n"),
        _ => view.pretty_value(value),
    }
}

impl Listing {
    /// What deleting a document leaves under it, as this listing of its subcollections found
    /// it, and with `offers_recursive`, what `R` deletes besides.
    fn confirmation_lines(&self, offers_recursive: bool) -> Vec<MarkedLine> {
        match self {
            Self::Listed(collection_ids) if collection_ids.is_empty() => {
                vec![MarkedLine::note("no subcollections", Style::new().dim())]
            }
            Self::Listed(collection_ids) => {
                let names: Vec<String> = collection_ids.iter().map(ToString::to_string).collect();
                let names = names.join(", ");
                if offers_recursive {
                    vec![
                        MarkedLine::note(
                            &format!("y leaves the subcollections: {names}"),
                            Style::new().yellow(),
                        ),
                        MarkedLine::note(
                            "R deletes them too, with every document under them",
                            Style::new().yellow(),
                        ),
                    ]
                } else {
                    vec![MarkedLine::note(
                        &format!("the subcollections stay: {names}"),
                        Style::new().yellow(),
                    )]
                }
            }
            Self::Pending(_) => vec![MarkedLine::note(
                "listing the subcollections…",
                Style::new().dim(),
            )],
            Self::Failed(error) => vec![MarkedLine::note(
                &format!("the subcollections could not be listed: {error}"),
                Style::new().red(),
            )],
            Self::NotListed => vec![MarkedLine::note(
                "the subcollections were not listed",
                Style::new().dim(),
            )],
        }
    }
}

impl PartialDelete {
    /// How far the recursive delete got, and why it ended before the document went.
    fn lines(&self) -> Vec<MarkedLine> {
        let deleted = counted(self.deleted, "document", "documents");
        let stopped = format!(
            "stopped after deleting {deleted} under it; the document stays, with the rest under it"
        );
        match &self.halt {
            Halt::Stopped => vec![MarkedLine::note(&stopped, Style::new().yellow())],
            Halt::Stale => vec![MarkedLine::note(
                &format!(
                    "deleted {deleted} under it; the document stays, since it changed after it \
                     was read"
                ),
                Style::new().yellow(),
            )],
            Halt::Failed(error) => vec![
                MarkedLine::note(&format!("error: {error}"), Style::new().red()),
                MarkedLine::note(
                    &format!("deleted {deleted} under it; the document stays"),
                    Style::new().dim(),
                ),
            ],
            Halt::Abandoned => vec![MarkedLine::note(
                &format!(
                    "stopped waiting after deleting {deleted} under it; the request in flight may \
                     still delete more, the document among them, and r shows what stays"
                ),
                Style::new().yellow(),
            )],
        }
    }
}

/// The title of a popup: its name, cut in the middle when the title is wider than the popup, and
/// the details after it, a `·` before each, with a space at either end.
struct PopupTitle {
    name: String,
    details: Vec<String>,
}

impl PopupTitle {
    fn named(name: &str) -> Self {
        Self {
            name: name.to_string(),
            details: Vec::new(),
        }
    }

    fn tail(&self) -> String {
        self.details
            .iter()
            .map(|detail| format!(" · {detail}"))
            .collect::<String>()
            + " "
    }

    fn width(&self) -> usize {
        1 + Span::from(self.name.as_str()).width() + Span::from(self.tail()).width()
    }

    /// This title in `width` columns.
    fn line(&self, width: usize) -> Line<'static> {
        let tail = self.tail();
        let room = width.saturating_sub(1 + Span::from(tail.as_str()).width());
        Line::from(format!(" {}{tail}", cut_middle(&self.name, room)))
    }
}

/// How much `value` holds, for the types whose value does not say it at a glance.
fn size_detail(value: &Value) -> Option<String> {
    match &value.value_type {
        Some(ValueType::StringValue(text)) => Some(counted(text.chars().count(), "char", "chars")),
        Some(ValueType::BytesValue(bytes)) => Some(counted(bytes.len(), "byte", "bytes")),
        Some(ValueType::ArrayValue(array)) => Some(counted(array.values.len(), "item", "items")),
        Some(ValueType::MapValue(map)) => Some(match FirestoreVector::from_value(value) {
            Ok(vector) => counted(vector.as_vec().len(), "dimension", "dimensions"),
            Err(_) => counted(map.fields.len(), "field", "fields"),
        }),
        _ => None,
    }
}

/// The text of a popup, which it lays out to the width of the popup.
enum PopupText<'a> {
    /// Text wrapped at words, each of its lines on a line of its own.
    Text(String),
    /// Bytes in hexadecimal, after the offset of the first byte of each line.
    Hex(&'a [u8]),
    /// Every key of the browser, by where it works.
    Help,
    Marked(Vec<MarkedLine>),
}

/// A line of a popup after a marker of its own, such as the `-` and `+` of a diff, in a style of
/// its own. It wraps at words, and its wrapped lines start under its text.
struct MarkedLine {
    marker: &'static str,
    text: String,
    style: Style,
}

impl MarkedLine {
    fn note(text: &str, style: Style) -> Self {
        Self {
            marker: "",
            text: text.to_string(),
            style,
        }
    }

    fn blank() -> Self {
        Self::note("", Style::new())
    }
}

impl<'a> PopupText<'a> {
    /// A value whole: bytes in hexadecimal, and any other value as [`View::pretty_value`] writes
    /// it, a map or an array as indented JSON-like text.
    fn of(value: &'a Value, view: &View<'_>) -> Self {
        match &value.value_type {
            Some(ValueType::BytesValue(bytes)) => Self::Hex(bytes),
            _ => Self::Text(view.pretty_value(value)),
        }
    }

    /// The columns the widest line takes, unwrapped.
    fn natural_width(&self) -> usize {
        match self {
            Self::Text(text) => text_lines(text)
                .map(|line| Span::from(line.as_ref()).width())
                .max()
                .unwrap_or_default(),
            Self::Hex(bytes) => hex_line_width(bytes.len().min(HEX_BYTES_PER_LINE)),
            Self::Help => {
                let action_column = help_action_column();
                help_keys()
                    .map(|key| action_column + Span::from(key.action).width())
                    .max()
                    .unwrap_or_default()
                    .min(HELP_MAX_WIDTH)
            }
            Self::Marked(lines) => lines
                .iter()
                .flat_map(|line| {
                    let marker = Span::from(line.marker).width();
                    let most = if line.marker.is_empty() {
                        POPUP_NOTE_WIDTH
                    } else {
                        usize::MAX
                    };
                    text_lines(&line.text)
                        .map(move |text| (marker + Span::from(text.as_ref()).width()).min(most))
                })
                .max()
                .unwrap_or_default(),
        }
    }

    /// The lines of the text in `width` columns.
    fn lines(&self, width: usize) -> Vec<Line<'static>> {
        let width = width.max(1);
        match self {
            Self::Text(text) => text_lines(text)
                .flat_map(|line| {
                    textwrap::wrap(&line, width)
                        .into_iter()
                        .map(|wrapped| Line::from(wrapped.into_owned()))
                        .collect::<Vec<_>>()
                })
                .collect(),
            Self::Hex(bytes) => {
                let per_line = [HEX_BYTES_PER_LINE, 8, 4]
                    .into_iter()
                    .find(|&count| hex_line_width(count) <= width)
                    .unwrap_or(4);
                hex_lines(bytes, per_line)
                    .into_iter()
                    .map(Line::from)
                    .collect()
            }
            Self::Marked(lines) => lines
                .iter()
                .flat_map(|line| {
                    let indent = " ".repeat(Span::from(line.marker).width());
                    let room = width.saturating_sub(indent.len()).max(1);
                    let mut wrapped: Vec<Line<'static>> = text_lines(&line.text)
                        .flat_map(|text| {
                            textwrap::wrap(&text, room)
                                .into_iter()
                                .map(Cow::into_owned)
                                .collect::<Vec<_>>()
                        })
                        .enumerate()
                        .map(|(position, text)| {
                            let lead = if position == 0 { line.marker } else { &indent };
                            Line::from(format!("{lead}{text}")).style(line.style)
                        })
                        .collect();
                    if wrapped.is_empty() {
                        wrapped.push(Line::from(line.marker).style(line.style));
                    }
                    wrapped
                })
                .collect(),
            Self::Help => {
                let action_column = help_action_column();
                let indent = " ".repeat(action_column);
                let options = textwrap::Options::new(width).subsequent_indent(&indent);
                let mut lines = Vec::new();
                for (position, section) in HELP_SECTIONS.iter().enumerate() {
                    if position > 0 {
                        lines.push(Line::default());
                    }
                    lines.push(Line::from(section.title).bold());
                    for key in section.keys {
                        let padding = action_column - HELP_INDENT - Span::from(key.keys).width();
                        let line = format!(
                            "{}{}{}{}",
                            " ".repeat(HELP_INDENT),
                            key.keys,
                            " ".repeat(padding),
                            key.action
                        );
                        lines.extend(
                            textwrap::wrap(&line, &options)
                                .into_iter()
                                .map(|wrapped| Line::from(wrapped.into_owned())),
                        );
                    }
                }
                lines
            }
        }
    }
}

/// The lines of `text` as a popup shows them: a tab as spaces and any other control character
/// as one space, since the terminal would act on it.
fn text_lines(text: &str) -> impl Iterator<Item = Cow<'_, str>> {
    text.lines().map(|line| {
        if line.contains(char::is_control) {
            Cow::Owned(line.replace('\t', POPUP_TAB).replace(char::is_control, " "))
        } else {
            Cow::Borrowed(line)
        }
    })
}

/// The columns of a line of `count` bytes in hexadecimal, after its offset.
fn hex_line_width(count: usize) -> usize {
    HEX_OFFSET_WIDTH + 2 + (3 * count).saturating_sub(1)
}

/// The keys of one place of the browser, and what each does there.
struct HelpSection {
    title: &'static str,
    keys: &'static [HelpKey],
}

struct HelpKey {
    keys: &'static str,
    action: &'static str,
}

const HELP_INDENT: usize = 2;

/// The widest the help gets, so that its longer lines wrap rather than run across a wide
/// terminal.
const HELP_MAX_WIDTH: usize = 80;

const HELP_SECTIONS: &[HelpSection] = &[
    HelpSection {
        title: "Documents and tree",
        keys: &[
            HelpKey {
                keys: "↑ ↓  k j",
                action: "move the cursor",
            },
            HelpKey {
                keys: "PgUp PgDn",
                action: "move a page",
            },
            HelpKey {
                keys: "Ctrl-U Ctrl-D",
                action: "move half a page",
            },
            HelpKey {
                keys: "g G  Home End",
                action: "go to the first or the last row",
            },
            HelpKey {
                keys: "→ l",
                action: "open the map, array or subcollection; from the documents, go to the tree",
            },
            HelpKey {
                keys: "Enter",
                action: "show the value whole, or open what → opens",
            },
            HelpKey {
                keys: "Space",
                action: "open or close the map, array or subcollections",
            },
            HelpKey {
                keys: "← h",
                action: "close the map or array, or go to the one it is in; from the top of the tree, go to the documents; from the documents, go up a level",
            },
            HelpKey {
                keys: "Tab",
                action: "switch between the documents and the tree",
            },
            HelpKey {
                keys: "/",
                action: "edit the filter",
            },
            HelpKey {
                keys: "f",
                action: "open the editor with a filter on the value under the cursor, WHERE <path> = <value>",
            },
            HelpKey {
                keys: "y Y",
                action: "copy the value under the cursor, or its path, to the clipboard",
            },
            HelpKey {
                keys: "e",
                action: "edit the value under the cursor on one line, or in $VISUAL or $EDITOR when it does not fit, then confirm the change; from the documents, the document",
            },
            HelpKey {
                keys: "E",
                action: "edit the value in $VISUAL or $EDITOR as tagged JSON",
            },
            HelpKey {
                keys: "d",
                action: "delete the field under the cursor, or from the documents, the document, once confirmed, and with R every document under it too; an element of an array is not deleted alone",
            },
            HelpKey {
                keys: "a",
                action: "add a field beside the one under the cursor, or inside the open map under it: its name, its type, then its value; not in an array",
            },
            HelpKey {
                keys: "n",
                action: "from the documents, create a document in $VISUAL or $EDITOR",
            },
            HelpKey {
                keys: "D",
                action: "from the documents, copy the document under a new ID",
            },
            HelpKey {
                keys: "r",
                action: "read the documents again with their filter",
            },
            HelpKey {
                keys: "Esc Backspace",
                action: "go back up from a subcollection",
            },
            HelpKey {
                keys: "Ctrl-G",
                action: "show the whole error of a failed filter or listing",
            },
            HelpKey {
                keys: "?",
                action: "show these keys",
            },
            HelpKey {
                keys: "Ctrl-C",
                action: "stop waiting for Firestore, else close the popup, the change or the editor, else quit",
            },
            HelpKey {
                keys: "q",
                action: "quit",
            },
        ],
    },
    HelpSection {
        title: "Filter editor",
        keys: &[
            HelpKey {
                keys: "← →  Home End",
                action: "move the cursor",
            },
            HelpKey {
                keys: "↑ ↓",
                action: "recall an earlier filter that ran, or a later one",
            },
            HelpKey {
                keys: "Backspace Delete",
                action: "delete the character before or after the cursor",
            },
            HelpKey {
                keys: "Ctrl-W Ctrl-U",
                action: "delete the word before the cursor, or everything before it",
            },
            HelpKey {
                keys: "Enter",
                action: "run the filter",
            },
            HelpKey {
                keys: "Esc",
                action: "close the editor and keep the filter before",
            },
            HelpKey {
                keys: "Ctrl-G",
                action: "show the whole error of the filter",
            },
        ],
    },
    HelpSection {
        title: "Value editor",
        keys: &[
            HelpKey {
                keys: "Enter",
                action: "show the change, to confirm it, or the error of a text that does not read as a value of the field's type",
            },
            HelpKey {
                keys: "Esc",
                action: "close the editor and change nothing",
            },
            HelpKey {
                keys: "other keys",
                action: "edit the line as in the filter editor",
            },
        ],
    },
    HelpSection {
        title: "New field",
        keys: &[
            HelpKey {
                keys: "Enter",
                action: "go on from the name to the list of types, and from the type to the value",
            },
            HelpKey {
                keys: "↑ ↓  k j",
                action: "choose the type",
            },
            HelpKey {
                keys: "Esc",
                action: "drop the field and write nothing",
            },
            HelpKey {
                keys: "other keys",
                action: "edit the name as in the filter editor",
            },
        ],
    },
    HelpSection {
        title: "Confirmation",
        keys: &[
            HelpKey {
                keys: "y",
                action: "write the change, if the document is still as it was read; else read it again and show the change over it; a new document, if none has its name",
            },
            HelpKey {
                keys: "R",
                action: "delete the document and every document under it, at any depth: in batches of 500, each after the documents under it, and the document last; only for a document with subcollections",
            },
            HelpKey {
                keys: "e",
                action: "go back to the editor with the text as it was left",
            },
            HelpKey {
                keys: "n Esc",
                action: "discard the change",
            },
            HelpKey {
                keys: "Ctrl-C",
                action: "stop waiting for the write, or stop a delete with R once its batch in flight is answered and, a second time, stop waiting for that batch, else discard the change",
            },
        ],
    },
    HelpSection {
        title: "Text from $VISUAL or $EDITOR that does not read",
        keys: &[
            HelpKey {
                keys: "e",
                action: "open the editor again on the text as it was saved",
            },
            HelpKey {
                keys: "n Esc",
                action: "discard the change",
            },
        ],
    },
    HelpSection {
        title: "Popup",
        keys: &[
            HelpKey {
                keys: "↑ ↓  k j",
                action: "scroll a line",
            },
            HelpKey {
                keys: "PgUp PgDn",
                action: "scroll a page",
            },
            HelpKey {
                keys: "Ctrl-U Ctrl-D",
                action: "scroll half a page",
            },
            HelpKey {
                keys: "g G  Home End",
                action: "go to the start or the end",
            },
            HelpKey {
                keys: "y Y",
                action: "copy the value, or its path, to the clipboard",
            },
            HelpKey {
                keys: "e E",
                action: "edit the value, as e and E do in the tree",
            },
            HelpKey {
                keys: "d",
                action: "delete the field",
            },
            HelpKey {
                keys: "a",
                action: "add a field to the map, or beside any other value",
            },
            HelpKey {
                keys: "Esc",
                action: "close the popup",
            },
        ],
    },
];

fn help_keys() -> impl Iterator<Item = &'static HelpKey> {
    HELP_SECTIONS.iter().flat_map(|section| section.keys)
}

/// The column the actions of the help start at, two after the longest keys.
fn help_action_column() -> usize {
    let keys = help_keys()
        .map(|key| Span::from(key.keys).width())
        .max()
        .unwrap_or_default();
    HELP_INDENT + keys + 2
}