rs-rich-interact 0.0.2

Interactive terminal components for rs-rich: event loop, viewport, item model, headless testing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
//! Fuzzy selection (#287), single and multiple, with a preview pane
//! (#454).
//!
//! Typing filters the items with the [fuzzy](crate::fuzzy) matcher and
//! highlights what matched; the arrows move; Enter picks. A multi-select
//! marks items with Tab. When the focused item has a
//! [`Preview`](crate::Preview), a pane shows it beside the list on a wide
//! terminal and below it on a narrow one. An item's
//! [`Action`](crate::Action) keys pick it and record which action was asked
//! for; Ctrl+K opens a menu of every action for the focused item, its own
//! and the view's ([`Actions`], #491).
//!
//! With the mouse on (#476), a click focuses a row and a second click on it
//! picks it, the wheel moves, and the border between the list and a preview
//! beside it can be dragged to resize the panes.
//!
//! Since 0.0.14 a select is made of the public [kit](crate::kit): a
//! [`FilterState`] ranks the items against the query, a [`ListState`] holds
//! the cursor, the scroll and the marks, a [`Divider`] is the preview's
//! border and an [`ActionMenu`] is the Ctrl+K menu. Its keys are declared in
//! a [`Keymap`] (context `select`), so they can be rebound and listed.

use std::cell::Cell;
use std::sync::mpsc::{Receiver, TryRecvError};
use std::time::Duration;

use rich::Segment;

use crate::component::{Component, Context, Flow, View};
use crate::components::{fit, highlight, pad, plain, question, text, Theme};
use crate::event::{Button, Event, Key, KeyCode, Modifiers, Mouse, MouseKind};
use crate::fuzzy::rank;
use crate::item::{Action, ActionTarget, Actions, Item, TargetKind};
use crate::keymap::{keys, Keymap};
use crate::kit::{ActionMenu, Divider, FilterState, ListState, MenuReply};
use crate::policy::{LineIo, NotInteractive};

/// Where the preview pane goes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PreviewLayout {
    /// Beside the list from 72 columns, below it when narrower.
    #[default]
    Auto,
    Right,
    Below,
    Hidden,
}

/// Works out an item's [`ActionTarget::value`] from its index.
pub(crate) type ValueOf = std::sync::Arc<dyn Fn(usize) -> String + Send + Sync>;

/// The narrowest a pane gets when the border between them is dragged.
const MIN_PANE: usize = 12;

/// The keys of a [`Select`] (and of the views built on one), in context
/// `select`. The `mark` actions apply to a [`MultiSelect`].
pub fn select_keymap() -> Keymap {
    Keymap::new("select")
        .bind("pick", keys("enter"), "pick")
        .bind("cancel", keys("escape"), "cancel")
        .bind("up", keys("up ctrl+p"), "move up")
        .bind("down", keys("down ctrl+n"), "move down")
        .bind("page-up", keys("pageup"), "page up")
        .bind("page-down", keys("pagedown"), "page down")
        .bind("first", keys("home"), "first")
        .bind("last", keys("end"), "last")
        .bind("mark", keys("tab"), "mark and move down")
        .bind("mark-up", keys("shift+tab"), "mark and move up")
        .bind("mark-all", keys("ctrl+a"), "mark every match")
        .bind("clear", keys("ctrl+u"), "clear the filter")
        .bind("delete", keys("backspace"), "delete a character")
        .bind("actions", keys("ctrl+k"), "actions")
        .bind("reload", Vec::new(), "reload the items")
}

/// How often a select fed from a channel looks for new items.
const FEED_POLL: Duration = Duration::from_millis(100);

/// Where reloaded items come from (#485).
type Source<T> = Box<dyn FnMut() -> Vec<Item<T>> + Send>;

/// Actions only a multi-select has.
const MARKING: [&str; 3] = ["mark", "mark-up", "mark-all"];

/// A fuzzy single choice among items. Enter returns the focused item's
/// value; Escape cancels.
pub struct Select<T> {
    prompt: String,
    items: Vec<Item<T>>,
    /// The query, and the item indices that match it, best first, with the
    /// label characters to highlight.
    filter: FilterState,
    /// The cursor over the matches, the first shown, and the marked items
    /// (by item index).
    list: ListState,
    height: usize,
    multi: bool,
    preview: PreviewLayout,
    preview_height: usize,
    theme: Theme,
    action: Option<String>,
    default: Option<usize>,
    /// Repaint at least this often, for previews that change by themselves.
    repaint: Option<Duration>,
    /// Once finished: the answer shown in place of the list (`None` inside
    /// means cancelled).
    answer: Option<Option<String>>,
    /// What an action is done to here, and the actions offered on every
    /// item (#491).
    kind: TargetKind,
    actions: Actions,
    menu_key: Key,
    menu: Option<ActionMenu>,
    keymap: Keymap,
    /// Each item's identity for an action ([`ActionTarget::value`]); the
    /// label when empty.
    values: Vec<String>,
    /// Each item's identity where `values` has none, worked out when asked
    /// (a tree node's path), so a large list keeps no string per item.
    pub(crate) value_of: Option<ValueOf>,
    /// A tree's guides, drawn for the rows on screen only (in place of
    /// `prefixes`).
    pub(crate) guides: Option<crate::components::views::Guides>,
    /// A line above the list, under the question: a table's headings.
    pub(crate) heading: Option<Vec<Segment>>,
    /// Text before each label, not searched: a tree's guides, an emoji.
    pub(crate) prefixes: Vec<String>,
    /// Prefixes drawn as they are rather than dimmed.
    pub(crate) prefix_plain: bool,
    /// An icon after each prefix, by index: cells drawn as they are, style
    /// metadata kept (a micro asset's placeholder, which the painter's
    /// graphics draw over).
    pub(crate) icons: Vec<Option<Vec<Segment>>>,
    /// Items left out while nothing is typed: a collapsed node's children.
    pub(crate) hidden: Vec<bool>,
    /// A line of extra key hints for the footer.
    pub(crate) hints: Option<String>,
    /// Always take `height` rows, however few items there are: for lists
    /// that change under the user, such as a directory's entries.
    pub(crate) steady: bool,
    mouse: bool,
    /// The list position the last click focused, until a key: a click on
    /// it again picks it.
    clicked: Option<usize>,
    /// Rows on screen, from the last context: the list is cut to fit.
    space: Cell<usize>,
    /// The border between the list and a preview beside it.
    divider: Divider,
    /// A line shown in place of the footer until the next key: what an
    /// action just did ("copied path").
    status: Option<Vec<Segment>>,
    /// What the `reload` key reloads the items from (#485).
    source: Option<Source<T>>,
    /// New items sent from elsewhere, taken on every event and tick.
    feed: Option<Receiver<Vec<Item<T>>>>,
}

impl<T> Select<T> {
    pub fn new<I, V>(prompt: impl Into<String>, items: I) -> Select<T>
    where
        I: IntoIterator<Item = V>,
        V: Into<Item<T>>,
    {
        let items: Vec<Item<T>> = items.into_iter().map(Into::into).collect();
        let mut list = ListState::new();
        list.clear_selection(items.len());
        let mut select = Select {
            prompt: prompt.into(),
            items,
            filter: FilterState::default(),
            list,
            height: 10,
            multi: false,
            preview: PreviewLayout::Auto,
            preview_height: 10,
            theme: Theme::default(),
            action: None,
            default: None,
            repaint: None,
            answer: None,
            kind: TargetKind::Item,
            actions: Actions::new(),
            menu_key: Key::ctrl('k'),
            menu: None,
            keymap: select_keymap(),
            values: Vec::new(),
            value_of: None,
            guides: None,
            heading: None,
            prefixes: Vec::new(),
            prefix_plain: false,
            icons: Vec::new(),
            hidden: Vec::new(),
            hints: None,
            steady: false,
            mouse: false,
            clicked: None,
            space: Cell::new(usize::MAX),
            divider: Divider::new(3).min(MIN_PANE),
            status: None,
            source: None,
            feed: None,
        };
        select.refilter();
        select
    }

    /// Show at most `rows` items at once (default 10).
    pub fn height(mut self, rows: usize) -> Self {
        self.height = rows.max(1);
        self
    }

    pub fn preview(mut self, layout: PreviewLayout) -> Self {
        self.preview = layout;
        self
    }

    /// Rows the preview takes when it is below the list (default 10).
    pub fn preview_height(mut self, rows: usize) -> Self {
        self.preview_height = rows.max(1);
        self
    }

    pub fn theme(mut self, theme: Theme) -> Self {
        self.theme = theme;
        self
    }

    /// Start with this filter text.
    pub fn query(mut self, query: impl Into<String>) -> Self {
        *self.filter.query_mut() = query.into();
        self.refilter();
        self
    }

    /// Render again at least every `interval`, even with no key pressed:
    /// for previews that fill in by themselves, such as a command's output
    /// computed on another thread. An unchanged view still writes nothing.
    pub fn repaint_every(mut self, interval: Duration) -> Self {
        self.repaint = Some(interval);
        self
    }

    /// The item returned without a terminal when the policy asks for
    /// defaults, and focused first.
    pub fn default(mut self, index: usize) -> Self {
        if index < self.items.len() {
            self.default = Some(index);
            if let Some(position) = self.filter.position_of(index) {
                self.list.set_cursor(position);
            }
        }
        self
    }

    /// Actions offered on every item, beside each item's own (#491): in
    /// the action menu, and on their keys.
    pub fn actions(mut self, actions: Actions) -> Self {
        self.actions = actions;
        self
    }

    /// The key that opens the action menu (default Ctrl+K).
    pub fn menu_key(mut self, key: Key) -> Self {
        self.menu_key = key;
        self.keymap.rebind("actions", [key]);
        self
    }

    /// Make `keys` do `action` (see [`select_keymap`]) on this select only;
    /// no keys unbinds it.
    pub fn rebind(mut self, action: &str, keys: impl IntoIterator<Item = Key>) -> Self {
        self.keymap.rebind(action, keys);
        self
    }

    /// Report the mouse (#476): a click focuses a row, a second click picks
    /// it, and the border beside a preview drags.
    pub fn with_mouse(mut self, on: bool) -> Self {
        self.mouse = on;
        self
    }

    /// Reload the items from `source` when `key` is pressed (#485), as
    /// [`reload`](Self::reload) does: the query, the focused item and the
    /// marks stay.
    pub fn reload_on(
        mut self,
        key: Key,
        source: impl FnMut() -> Vec<Item<T>> + Send + 'static,
    ) -> Self {
        self.keymap.rebind("reload", [key]);
        self.source = Some(Box::new(source));
        self
    }

    /// Take new items from `feed` whenever they arrive (#485): a watcher or
    /// a command on another thread sends the whole list again, and the
    /// select [reloads](Self::reload) it, keeping the query, the focused
    /// item and the marks. The select looks every 100 ms.
    pub fn reload_from(mut self, feed: Receiver<Vec<Item<T>>>) -> Self {
        self.feed = Some(feed);
        self
    }

    /// The list's width beside a preview, in columns: where the border is
    /// until it is dragged.
    pub fn split(mut self, columns: usize) -> Self {
        self.divider.set_position(Some(columns));
        self
    }

    /// The id of the [`Action`] that picked the item, from its key or the
    /// action menu, if one did.
    pub fn action(&self) -> Option<&str> {
        self.action.as_deref()
    }

    pub fn items(&self) -> &[Item<T>] {
        &self.items
    }

    /// The focused item's index, if any item matches.
    pub fn focused(&self) -> Option<usize> {
        self.filter.index(self.list.cursor())
    }

    /// The list's width beside a preview, once dragged.
    pub fn split_width(&self) -> Option<usize> {
        self.divider.position()
    }

    /// The query and what matches it.
    pub fn filter(&self) -> &FilterState {
        &self.filter
    }

    /// The cursor, the scroll and the marks.
    pub fn list(&self) -> &ListState {
        &self.list
    }

    /// The border beside the preview.
    pub fn divider(&self) -> &Divider {
        &self.divider
    }

    /// The action menu, while it is open.
    pub fn menu(&self) -> Option<&ActionMenu> {
        self.menu.as_ref()
    }

    /// The keys, with any rebinding.
    pub fn select_keymap(&self) -> &Keymap {
        &self.keymap
    }

    /// Whether this is the list of a [`MultiSelect`].
    pub fn is_multi(&self) -> bool {
        self.multi
    }

    /// What an action is done to: an item, a row, a node, a file.
    pub fn set_kind(&mut self, kind: TargetKind) {
        self.kind = kind;
    }

    /// Each item's identity for an action ([`ActionTarget::value`]), by
    /// index; the label where missing.
    pub fn set_values(&mut self, values: Vec<String>) {
        self.values = values;
    }

    /// A line above the list, under the question: a table's headings.
    pub fn set_heading(&mut self, heading: Option<Vec<Segment>>) {
        self.heading = heading;
    }

    /// Text before each label, by index, not searched: a tree's guides, an
    /// emoji. Dimmed, unless `plain`. Call [`refilter`](Self::refilter)
    /// after.
    pub fn set_prefixes(&mut self, prefixes: Vec<String>, plain: bool) {
        self.prefixes = prefixes;
        self.prefix_plain = plain;
    }

    /// An icon before each label, by index, after its prefix: one line of
    /// text (see [`kit::icon`](crate::kit::icon)), its styles and metadata
    /// kept, so a micro asset's placeholder cells stay tagged for the
    /// painter's graphics. `None` leaves an item without one.
    pub fn set_icons(&mut self, icons: Vec<Option<rich::Text>>) {
        self.icons = icons
            .iter()
            .map(|icon| icon.as_ref().map(crate::kit::icon))
            .collect();
    }

    /// Items left out while nothing is typed, by index: a collapsed node's
    /// children. Call [`refilter`](Self::refilter) after.
    pub fn set_hidden(&mut self, hidden: Vec<bool>) {
        self.hidden = hidden;
    }

    /// A line of extra key hints for the footer.
    pub fn set_hints(&mut self, hints: Option<String>) {
        self.hints = hints;
    }

    /// Always take the full height, however few items there are: for lists
    /// that change under the user, such as a directory's entries.
    pub fn set_steady(&mut self, steady: bool) {
        self.steady = steady;
    }

    /// Replace the items and keep the user's place (#485): the query stays
    /// and is matched against the new items, the focused item stays
    /// focused if it is still there (matched by label), and so do the
    /// marks. Per-item settings (values, prefixes, what is hidden) are
    /// cleared, as with [`replace_items`](Self::replace_items); a view that
    /// sets them sets them again.
    pub fn reload(&mut self, items: Vec<Item<T>>) {
        let focused = self.focused().map(|index| self.items[index].label.clone());
        let marked: std::collections::HashSet<String> = self
            .list
            .selected()
            .into_iter()
            .map(|index| self.items[index].label.clone())
            .collect();
        let offset = self.list.offset();
        self.list.clear_selection(items.len());
        for (index, item) in items.iter().enumerate() {
            if marked.contains(&item.label) {
                self.list.set_selected(index, true);
            }
        }
        self.items = items;
        self.values.clear();
        self.value_of = None;
        self.guides = None;
        self.prefixes.clear();
        self.icons.clear();
        self.hidden.clear();
        if self.default.is_some_and(|index| index >= self.items.len()) {
            self.default = None;
        }
        self.menu = None;
        self.clicked = None;
        self.refilter();
        let target = focused
            .and_then(|label| self.items.iter().position(|item| item.label == label))
            .and_then(|index| self.filter.position_of(index));
        if let Some(position) = target {
            // Where it was on screen, if that still works.
            self.list.set_offset(offset.min(position));
            self.list.set_cursor(position);
            self.scroll();
        }
    }

    /// Take the newest list sent through [`reload_from`](Self::reload_from).
    fn poll_feed(&mut self) {
        let Some(feed) = &self.feed else { return };
        let mut latest = None;
        loop {
            match feed.try_recv() {
                Ok(items) => latest = Some(items),
                Err(TryRecvError::Empty) => break,
                Err(TryRecvError::Disconnected) => {
                    self.feed = None;
                    break;
                }
            }
        }
        if let Some(items) = latest {
            self.reload(items);
        }
    }

    /// Show `status` in place of the footer until the next key: what an
    /// action just did.
    pub fn set_status(&mut self, status: Option<String>) {
        self.status = status.map(|status| vec![text(format!("  {status}"), &self.theme.hint)]);
    }

    /// The status line, if one is showing.
    pub fn status(&self) -> Option<&[Segment]> {
        self.status.as_deref()
    }

    /// Filter as a tree (#428; see [`FilterState::set_tree`]): matches keep
    /// their ancestors, dimmed, and the cursor goes to the best match.
    pub fn set_tree(&mut self, parents: Option<Vec<Option<usize>>>) {
        self.filter.set_tree(parents);
        self.refilter();
    }

    /// How often to tick: the repaint interval, and often enough to take
    /// fed items.
    pub fn tick_interval(&self) -> Option<Duration> {
        match (self.repaint, self.feed.is_some()) {
            (Some(repaint), true) => Some(repaint.min(FEED_POLL)),
            (None, true) => Some(FEED_POLL),
            (repaint, false) => repaint,
        }
    }

    /// Replace the items, keeping the settings; the query is cleared.
    pub fn replace_items(&mut self, items: Vec<Item<T>>) {
        self.list.clear_selection(items.len());
        self.items = items;
        self.values.clear();
        self.value_of = None;
        self.guides = None;
        self.prefixes.clear();
        self.icons.clear();
        self.hidden.clear();
        self.filter.query_mut().clear();
        self.default = None;
        self.menu = None;
        self.list.set_cursor(0);
        // A click on the old items is not the first of a pair on the new
        // ones, which may have another item at the same position.
        self.clicked = None;
        self.refilter();
    }

    /// Whether the action menu is open.
    pub fn menu_open(&self) -> bool {
        self.menu.is_some()
    }

    /// What is typed.
    pub fn query_text(&self) -> &str {
        self.filter.query()
    }

    /// Show `answer` in place of the list (`None`: cancelled), as a
    /// finished select does.
    pub fn set_answer(&mut self, answer: Option<String>) {
        self.answer = Some(answer);
    }

    /// Carry on after an Enter that did not finish (a directory opened).
    pub fn reopen(&mut self) {
        self.answer = None;
        self.action = None;
    }

    /// Focus item `index` if it is listed.
    pub fn focus_item(&mut self, index: usize) {
        if let Some(position) = self.filter.position_of(index) {
            self.list.set_cursor(position);
            self.scroll();
        }
    }

    /// The target an action on item `index` is done to.
    pub fn target(&self, index: usize) -> ActionTarget {
        let label = self.items[index].label.clone();
        ActionTarget {
            kind: self.kind,
            index,
            value: self
                .values
                .get(index)
                .cloned()
                .or_else(|| self.value_of.as_ref().map(|value| value(index)))
                .or_else(|| {
                    let guides = self.guides.as_ref()?;
                    Some(guides.path(index, |node| self.items[node].label.as_str()))
                })
                .unwrap_or_else(|| label.clone()),
            label,
        }
    }

    /// Every action for item `index`: its own, then the view's that apply.
    pub fn actions_for(&self, index: usize) -> Vec<Action> {
        self.actions
            .for_target(&self.target(index), &self.items[index].actions)
    }

    /// Match the items against the query again, after the items, their
    /// prefixes or what is hidden changed.
    pub fn refilter(&mut self) {
        let focused = self.focused();
        self.filter.set_hidden(self.hidden.clone());
        self.filter.set_highlight_limits(
            self.items
                .iter()
                .map(|item| item.label.chars().count())
                .collect(),
        );
        self.filter
            .set_candidates(self.items.iter().map(Item::search_text));
        // Keep the focused item when it still matches, else the best match.
        let cursor = focused
            .and_then(|index| self.filter.position_of(index))
            .filter(|_| !self.filter.is_filtering())
            .or_else(|| self.filter.best())
            .unwrap_or(0);
        self.list.set_len(self.filter.len());
        self.list.reset(cursor, self.shown());
    }

    fn scroll(&mut self) {
        self.list.follow(self.shown());
    }

    fn step(&mut self, delta: isize) {
        self.list.step(delta, self.shown());
    }

    /// Handle an event as the select does, for a component built round
    /// one: `Some(Flow::Done)` finishes with item indices (the view then
    /// collapses to the answer), `Some(Flow::Cancel)` cancels,
    /// `Some(Flow::Ignored)` means the event was not the select's, and
    /// `None` carries on.
    pub fn event(&mut self, event: &Event, context: &Context<'_>) -> Option<Flow<Vec<usize>>> {
        self.space.set(context.height);
        self.poll_feed();
        if matches!(event, Event::Key(_) | Event::Paste(_) | Event::Mouse(_)) {
            self.status = None;
        }
        let flow = self.event_inner(event, context.width);
        match &flow {
            Some(Flow::Done(indices)) => {
                let labels: Vec<&str> = indices
                    .iter()
                    .map(|&index| self.items[index].label.as_str())
                    .collect();
                self.answer = Some(Some(labels.join(", ")));
            }
            Some(Flow::Cancel) => self.answer = Some(None),
            _ => {}
        }
        flow
    }

    /// Pick `index` with `action`.
    fn run_action(&mut self, index: usize, action: &Action) -> Option<Flow<Vec<usize>>> {
        self.menu = None;
        self.action = Some(action.id.clone());
        Some(Flow::Done(vec![index]))
    }

    fn pick_focused(&mut self) -> Option<Flow<Vec<usize>>> {
        let index = self.focused()?;
        let marked = self.list.selected();
        Some(Flow::Done(if self.multi && !marked.is_empty() {
            marked
        } else {
            vec![index]
        }))
    }

    fn menu_event(&mut self, event: &Event, width: usize) -> Option<Flow<Vec<usize>>> {
        let index = self.focused()?;
        // The menu is a modal over the list: see `menu_box`.
        let (x, y, outer_width, outer_height) = self.menu_box(width)?;
        if let Some(mouse) = event.mouse() {
            let (column, row) = (mouse.column as usize, mouse.row as usize);
            let inside = (x..x + outer_width).contains(&column)
                && (y + 1..y + outer_height - 1).contains(&row);
            if mouse.is_click() && !inside {
                self.menu = None;
                return None;
            }
        }
        match self.menu.as_mut()?.handle(event, y + 1) {
            MenuReply::Stay => None,
            MenuReply::Close => {
                self.menu = None;
                None
            }
            MenuReply::Run(action) => self.run_action(index, &action),
        }
    }

    /// The action `key` triggers here. A key with modifiers that is not
    /// bound as it is does what it does without them, unless it types.
    fn key_action(&self, key: Key) -> Option<&str> {
        let action = self.keymap.action(key).or_else(|| {
            let typing = matches!(key.code, KeyCode::Char(_));
            (!typing && key.modifiers != Modifiers::NONE)
                .then(|| self.keymap.action(Key::new(key.code)))
                .flatten()
        })?;
        (self.multi || !MARKING.contains(&action)).then_some(action)
    }

    fn event_inner(&mut self, event: &Event, width: usize) -> Option<Flow<Vec<usize>>> {
        if self.menu.is_some() {
            return self.menu_event(event, width);
        }
        if let Event::Mouse(mouse) = event {
            return self.mouse_event(*mouse, width);
        }
        if let Event::Paste(text) = event {
            self.clicked = None;
            self.filter
                .query_mut()
                .push_str(&crate::components::pasted(text, " "));
            self.refilter();
            return None;
        }
        let key = event.key()?;
        // A click after a key is a first click again.
        self.clicked = None;
        if let Some(index) = self.focused() {
            let actions = self.actions_for(index);
            if self.keymap.is(key, "actions") && !actions.is_empty() {
                self.menu = Some(ActionMenu::new(actions, key));
                return None;
            }
            if let Some(action) = actions.iter().find(|action| action.key == Some(key)) {
                let action = action.clone();
                return self.run_action(index, &action);
            }
        }
        match self.key_action(key) {
            Some("reload") if self.source.is_some() => {
                if let Some(source) = self.source.as_mut() {
                    let items = source();
                    self.reload(items);
                }
            }
            Some("pick") => return self.pick_focused(),
            Some("cancel") => return Some(Flow::Cancel),
            Some("up") => self.step(-1),
            Some("down") => self.step(1),
            Some("page-up") => self.step(-(self.shown() as isize)),
            Some("page-down") => self.step(self.shown() as isize),
            Some("first") => self.step(isize::MIN / 2),
            Some("last") => self.step(isize::MAX / 2),
            Some(mark @ ("mark" | "mark-up")) => {
                let down = mark == "mark";
                if let Some(index) = self.focused() {
                    self.list.toggle(index);
                    self.step(if down { 1 } else { -1 });
                }
            }
            Some("mark-all") => {
                let matches: Vec<usize> = self.filter.matches().iter().map(|(i, _)| *i).collect();
                let all = matches.iter().all(|&index| self.list.is_selected(index));
                for index in matches {
                    self.list.set_selected(index, !all);
                }
            }
            Some("clear") => {
                self.filter.query_mut().clear();
                self.refilter();
            }
            Some("delete") => {
                if self.filter.query_mut().pop().is_some() {
                    self.refilter();
                }
            }
            _ => match key.code {
                KeyCode::Char(c) if !key.modifiers.ctrl && !key.modifiers.alt => {
                    self.filter.query_mut().push(c);
                    self.refilter();
                }
                _ => return Some(Flow::Ignored),
            },
        }
        None
    }

    /// Rows above the list: the question, and the heading if any.
    fn top(&self) -> usize {
        1 + usize::from(self.heading.is_some())
    }

    /// The most rows the list takes: the height asked for, cut to what
    /// fits on screen beside the question, the heading and the footer.
    fn shown(&self) -> usize {
        self.height
            .min(self.space.get().saturating_sub(self.top() + 1))
            .max(1)
    }

    /// Rows the list takes.
    fn rows(&self) -> usize {
        if self.steady {
            return self.shown();
        }
        self.shown().min(self.items.len()).max(1)
    }

    /// Where the action menu's modal goes at `width`, border included:
    /// `(x, y, width, height)`, centred over the list, from its first row.
    fn menu_box(&self, width: usize) -> Option<(usize, usize, usize, usize)> {
        let menu = self.menu.as_ref()?;
        let (inner, rows) = menu.size();
        let outer = (inner + 2).min(width.max(2));
        Some(((width - outer) / 2, self.top(), outer, rows + 2))
    }

    /// The preview's layout at `width` for the focused item, and the
    /// list's width when the preview is beside it.
    fn layout(&self, width: usize) -> (PreviewLayout, usize) {
        let preview = self
            .focused()
            .is_some_and(|index| self.items[index].preview.is_some())
            && self.preview != PreviewLayout::Hidden;
        if !preview {
            return (PreviewLayout::Hidden, width);
        }
        let layout = match self.preview {
            PreviewLayout::Auto if width >= 72 => PreviewLayout::Right,
            PreviewLayout::Auto => PreviewLayout::Below,
            layout => layout,
        };
        let left = self
            .divider
            .resolve(width, (width * 45 / 100).max(20).min(width));
        (layout, left)
    }

    fn mouse_event(&mut self, mouse: Mouse, width: usize) -> Option<Flow<Vec<usize>>> {
        let (layout, left) = self.layout(width);
        let (row, column) = (mouse.row as usize, mouse.column as usize);
        let top = self.top();
        let in_list = row >= top && row < top + self.rows();
        match mouse.kind {
            MouseKind::ScrollUp => self.step(-1),
            MouseKind::ScrollDown => self.step(1),
            MouseKind::Down(Button::Left) => {
                let border = layout == PreviewLayout::Right && self.divider.hit(column, left);
                if border && in_list {
                    self.divider.press(column, left);
                } else if in_list && (layout != PreviewLayout::Right || column < left) {
                    let position = self.list.offset() + row - top;
                    if position < self.filter.len() {
                        if self.clicked == Some(position) && position == self.list.cursor() {
                            return self.pick_focused();
                        }
                        self.list.set_cursor(position);
                        self.clicked = Some(position);
                    }
                }
            }
            MouseKind::Drag(Button::Left) if self.divider.dragging() => {
                self.divider.drag(column, width);
            }
            MouseKind::Up(_) => self.divider.release(),
            _ => {}
        }
        None
    }

    fn row(&self, position: usize, width: usize) -> Vec<Segment> {
        let (index, positions) = &self.filter.matches()[position];
        let item = &self.items[*index];
        let theme = &self.theme;
        let focused = position == self.list.cursor();
        let mut line = if focused {
            vec![text(format!("{} ", theme.pointer), &theme.pointer_style)]
        } else {
            vec![plain("  ")]
        };
        if self.multi {
            line.push(if self.list.is_selected(*index) {
                text(format!("{} ", theme.checked), &theme.checked_style)
            } else {
                text(format!("{} ", theme.unchecked), &theme.hint)
            });
        }
        let prefix = match &self.guides {
            Some(guides) => Some(guides.prefix(*index)),
            None => self.prefixes.get(*index).cloned(),
        };
        if let Some(prefix) = prefix.filter(|p| !p.is_empty()) {
            line.push(if self.prefix_plain {
                plain(prefix)
            } else {
                text(prefix, &theme.hint)
            });
        }
        if let Some(Some(icon)) = self.icons.get(*index) {
            line.extend(icon.iter().cloned());
            line.push(plain(" "));
        }
        // An ancestor kept only to place a match (a tree's filter) is dim.
        let base = if self.filter.is_context(position) {
            Some(&theme.hint)
        } else {
            focused.then_some(&theme.focused)
        };
        line.extend(highlight(&item.label, positions, base, &theme.matched));
        if let Some(description) = &item.description {
            line.push(text(format!("  {description}"), &theme.hint));
        }
        fit(line, width)
    }

    /// The list's rows at `width`: the matches shown, or "no matches", kept
    /// at a steady height.
    pub fn list_lines(&self, width: usize) -> Vec<Vec<Segment>> {
        let rows = self.rows();
        let mut lines: Vec<Vec<Segment>> = (self.list.offset()..self.filter.len())
            .take(rows)
            .map(|position| self.row(position, width))
            .collect();
        if self.filter.is_empty() {
            lines.push(vec![text("  no matches", &self.theme.hint)]);
        }
        // A steady height, so the footer does not jump as the list filters.
        lines.resize_with(rows, Vec::new);
        lines
    }

    /// The footer: counts and key hints.
    pub fn footer(&self, width: usize) -> Vec<Segment> {
        let mut hint = format!("{}/{}", self.filter.len(), self.items.len());
        if self.multi {
            let marked = self.list.selected_count();
            hint.push_str(&format!(" · {marked} marked · tab mark"));
        }
        hint.push_str(" · ↑↓ move · enter pick");
        if let Some(extra) = &self.hints {
            hint.push_str(&format!(" · {extra}"));
        }
        if self
            .focused()
            .is_some_and(|index| !self.actions_for(index).is_empty())
        {
            hint.push_str(&format!(" · {} actions", self.menu_key));
        }
        hint.push_str(" · esc cancel");
        fit(vec![text(format!("  {hint}"), &self.theme.hint)], width)
    }

    fn render_view(&self, context: &Context<'_>) -> View {
        self.space.set(context.height);
        let width = context.width;
        let theme = &self.theme;
        let mut header = question(theme, &self.prompt);
        if let Some(answer) = &self.answer {
            header.push(match answer {
                Some(answer) => text(answer.clone(), &theme.answer),
                None => text("cancelled", &theme.hint),
            });
            return View::new(vec![fit(header, width)]);
        }
        let query = self.filter.query();
        let column = crate::components::width(&header) + rich::cells::cell_len(query);
        header.push(plain(query.to_string()));
        let mut lines = vec![fit(header, width)];
        if let Some(heading) = &self.heading {
            let mut line = vec![plain(if self.multi { "    " } else { "  " })];
            line.extend(heading.iter().cloned());
            lines.push(fit(line, width));
        }
        let footer = |this: &Self| match &this.status {
            Some(status) => vec![fit(status.clone(), width)],
            None => vec![this.footer(width)],
        };
        let preview = self
            .focused()
            .and_then(|index| self.items[index].preview.as_ref());
        match (preview, self.layout(width)) {
            (Some(preview), (PreviewLayout::Right, left)) => {
                let right = width.saturating_sub(left + 3).max(1);
                let list = self.list_lines(left);
                let shown = context.lines_at(&*preview.renderable(), right);
                for (row, line) in list.into_iter().enumerate() {
                    let mut line = pad(line, left);
                    line.push(text(" │ ", &theme.border));
                    if let Some(preview) = shown.get(row) {
                        line.extend(fit(preview.clone(), right));
                    }
                    lines.push(line);
                }
                lines.extend(footer(self));
            }
            (Some(preview), (PreviewLayout::Below, _)) => {
                lines.extend(self.list_lines(width));
                lines.extend(footer(self));
                lines.push(vec![text("─".repeat(width), &theme.border)]);
                let shown = context.lines_at(&*preview.renderable(), width);
                lines.extend(
                    shown
                        .into_iter()
                        .take(self.preview_height)
                        .map(|line| fit(line, width)),
                );
            }
            _ => {
                lines.extend(self.list_lines(width));
                lines.extend(footer(self));
            }
        }
        // The action menu (#474): a modal over the view, titled with its
        // target, dimming what is under it.
        if let (Some(menu), Some((x, y, outer, _))) = (&self.menu, self.menu_box(width)) {
            let inner = outer.saturating_sub(2);
            let title = self
                .focused()
                .map(|index| format!("Actions · {}", self.items[index].label));
            let boxed = crate::kit::frame(
                menu.render(theme, inner),
                inner,
                title.as_deref(),
                &theme.border,
            );
            let dim = rich::Style::parse("dim").expect("a built-in style");
            crate::kit::place(&mut lines, x, y, &boxed, Some(&dim));
            return View::new(lines);
        }
        View::new(lines).with_cursor(0, column.min(width.saturating_sub(1)))
    }

    /// The keys that apply now: no marking for a single choice, and the
    /// action menu's while it is open.
    pub fn visible_keymap(&self) -> Keymap {
        if self.menu.is_some() {
            return Keymap::new("menu")
                .bind("up", keys("up"), "move up")
                .bind("down", keys("down tab"), "move down")
                .bind("run", keys("enter"), "run")
                .bind("close", keys("escape"), "close");
        }
        let mut keymap = Keymap::new("select");
        for binding in self.keymap.bindings() {
            let action = binding.action.as_str();
            let shown = (self.multi || !MARKING.contains(&action))
                && (action != "reload" || self.source.is_some());
            if shown {
                keymap.add(binding);
            }
        }
        keymap
    }

    /// Ask without a terminal: list the items, read a number or text.
    fn ask(&mut self, io: &mut dyn LineIo) -> Result<Option<Vec<usize>>, NotInteractive> {
        io.write(&format!("{}\n", self.prompt));
        for (index, item) in self.items.iter().enumerate() {
            let mut row = format!("  {}) {}", index + 1, item.label);
            if let Some(description) = &item.description {
                row.push_str(&format!(" — {description}"));
            }
            io.write(&format!("{row}\n"));
        }
        io.write(if self.multi {
            "Numbers or names, separated by commas: "
        } else {
            "Number or name: "
        });
        // At the end of input, or on an empty line, the default answers:
        // the default item, or with `multi` the marked ones.
        let default: Vec<usize> = if self.multi {
            self.list.selected()
        } else {
            self.default.into_iter().collect()
        };
        let Some(line) = io.read_line() else {
            if default.is_empty() {
                return Err(NotInteractive::Ended);
            }
            return Ok(Some(default));
        };
        if line.trim().is_empty() && !default.is_empty() {
            return Ok(Some(default));
        }
        let answers: Vec<&str> = if self.multi {
            line.split(',')
                .map(str::trim)
                .filter(|a| !a.is_empty())
                .collect()
        } else {
            vec![line.trim()]
        };
        let texts: Vec<String> = self.items.iter().map(Item::search_text).collect();
        let mut chosen = Vec::new();
        for answer in answers {
            let index = match answer.parse::<usize>() {
                Ok(number) if (1..=self.items.len()).contains(&number) => number - 1,
                _ => rank(answer, texts.iter().map(String::as_str))
                    .first()
                    .map(|(index, _)| *index)
                    .filter(|_| !answer.is_empty())
                    .ok_or_else(|| {
                        NotInteractive::Invalid(format!("no item matches {answer:?}"))
                    })?,
            };
            if !chosen.contains(&index) {
                chosen.push(index);
            }
        }
        if chosen.is_empty() {
            return Err(NotInteractive::Invalid("nothing chosen".into()));
        }
        Ok(Some(chosen))
    }
}

/// The list's width beside a preview when the border is at `column`: both
/// panes at least [`MIN_PANE`] wide when there is room for that.
#[cfg(test)]
fn clamp_split(column: usize, width: usize) -> usize {
    Divider::new(3).min(MIN_PANE).clamp(column, width)
}

impl<T: Clone> Component for Select<T> {
    type Output = T;

    fn handle(&mut self, event: &Event, context: &Context<'_>) -> Flow<T> {
        match self.event(event, context) {
            Some(Flow::Done(indices)) => Flow::Done(self.items[indices[0]].value.clone()),
            Some(Flow::Cancel) => Flow::Cancel,
            Some(Flow::Ignored) => Flow::Ignored,
            _ => Flow::Continue,
        }
    }

    fn render(&self, context: &Context<'_>) -> View {
        self.render_view(context)
    }

    fn tick(&self) -> Option<Duration> {
        self.tick_interval()
    }

    fn mouse(&self) -> bool {
        self.mouse
    }

    fn keymap(&self) -> Keymap {
        self.visible_keymap()
    }

    fn default_value(&self) -> Option<T> {
        self.default.map(|index| self.items[index].value.clone())
    }

    fn prompt(&mut self, io: &mut dyn LineIo) -> Result<Option<T>, NotInteractive> {
        Ok(self
            .ask(io)?
            .map(|indices| self.items[indices[0]].value.clone()))
    }
}

/// A fuzzy multiple choice: Tab marks items (Shift+Tab marks and moves up,
/// Ctrl+A marks every match), Enter returns the marked items in list
/// order, or the focused one when none is marked.
pub struct MultiSelect<T>(Select<T>);

impl<T> MultiSelect<T> {
    pub fn new<I, V>(prompt: impl Into<String>, items: I) -> MultiSelect<T>
    where
        I: IntoIterator<Item = V>,
        V: Into<Item<T>>,
    {
        let mut select = Select::new(prompt, items);
        select.multi = true;
        MultiSelect(select)
    }

    pub fn height(self, rows: usize) -> Self {
        MultiSelect(self.0.height(rows))
    }

    pub fn preview(self, layout: PreviewLayout) -> Self {
        MultiSelect(self.0.preview(layout))
    }

    pub fn theme(self, theme: Theme) -> Self {
        MultiSelect(self.0.theme(theme))
    }

    pub fn query(self, query: impl Into<String>) -> Self {
        MultiSelect(self.0.query(query))
    }

    /// See [`Select::repaint_every`].
    pub fn repaint_every(self, interval: Duration) -> Self {
        MultiSelect(self.0.repaint_every(interval))
    }

    /// See [`Select::actions`].
    pub fn actions(self, actions: Actions) -> Self {
        MultiSelect(self.0.actions(actions))
    }

    /// See [`Select::with_mouse`].
    pub fn with_mouse(self, on: bool) -> Self {
        MultiSelect(self.0.with_mouse(on))
    }

    /// See [`Select::reload_on`]: marks stay with their items.
    pub fn reload_on(
        self,
        key: Key,
        source: impl FnMut() -> Vec<Item<T>> + Send + 'static,
    ) -> Self {
        MultiSelect(self.0.reload_on(key, source))
    }

    /// See [`Select::reload_from`].
    pub fn reload_from(self, feed: Receiver<Vec<Item<T>>>) -> Self {
        MultiSelect(self.0.reload_from(feed))
    }

    /// Replace the items, keeping the query, the focus and the marks: see
    /// [`Select::reload`].
    pub fn reload(&mut self, items: Vec<Item<T>>) {
        self.0.reload(items);
    }

    /// Mark these items to begin with; they are also the default without a
    /// terminal.
    pub fn marked(mut self, indices: impl IntoIterator<Item = usize>) -> Self {
        for index in indices {
            if index < self.0.items.len() {
                self.0.list.set_selected(index, true);
            }
        }
        self
    }

    pub fn action(&self) -> Option<&str> {
        self.0.action()
    }

    pub fn items(&self) -> &[Item<T>] {
        self.0.items()
    }
}

impl<T: Clone> Component for MultiSelect<T> {
    type Output = Vec<T>;

    fn handle(&mut self, event: &Event, context: &Context<'_>) -> Flow<Vec<T>> {
        match self.0.event(event, context) {
            Some(Flow::Done(indices)) => Flow::Done(
                indices
                    .into_iter()
                    .map(|index| self.0.items[index].value.clone())
                    .collect(),
            ),
            Some(Flow::Cancel) => Flow::Cancel,
            Some(Flow::Ignored) => Flow::Ignored,
            _ => Flow::Continue,
        }
    }

    fn render(&self, context: &Context<'_>) -> View {
        self.0.render_view(context)
    }

    fn keymap(&self) -> Keymap {
        self.0.visible_keymap()
    }

    fn tick(&self) -> Option<Duration> {
        self.0.tick_interval()
    }

    fn mouse(&self) -> bool {
        self.0.mouse
    }

    fn default_value(&self) -> Option<Vec<T>> {
        Some(
            self.0
                .list
                .selected()
                .into_iter()
                .map(|index| self.0.items[index].value.clone())
                .collect(),
        )
    }

    fn prompt(&mut self, io: &mut dyn LineIo) -> Result<Option<Vec<T>>, NotInteractive> {
        Ok(self.0.ask(io)?.map(|indices| {
            indices
                .into_iter()
                .map(|index| self.0.items[index].value.clone())
                .collect()
        }))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_dragged_split_keeps_both_panes_usable() {
        assert_eq!(clamp_split(5, 80), MIN_PANE);
        assert_eq!(clamp_split(40, 80), 40);
        assert_eq!(clamp_split(79, 80), 80 - MIN_PANE - 3);
        // Too narrow for both minimums: the list keeps what it can.
        assert!(clamp_split(3, 20) <= 20);
    }
}