runemark 0.5.1

Opinionated terminal presentation for Rust command-line tools
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
//! Interactive selection from a grouped list.
//!
//! This is the one place where Runemark reads from the terminal instead of only
//! writing to it. Everything else in the crate hands back a string or writes to
//! a writer the application owns; a menu cannot, because a cursor has to react
//! to keys.
//!
//! The boundary still holds in the direction that matters: a [`Menu`] carries
//! labels, descriptions and hints, and nothing about what the entries mean.
//! Grouping, ordering and wording stay with the application.
//!
//! Rendering is available without the `select` feature — [`Menu::render`] is
//! plain formatting. Only `Menu::run` needs the feature.
//!
//! The interactive path talks to the terminal directly: termios for raw mode,
//! four escape sequences for drawing, and a small parser for the handful of
//! keys a menu needs. That keeps the dependency to `libc` and makes the
//! feature Unix-only — on other platforms `Menu::run` reports
//! [`Outcome::Unavailable`] and the caller renders the list instead.

use std::fmt;

use unicode_width::UnicodeWidthStr;

use crate::color::{Console, Tone};

/// Controls whether a menu takes over the terminal.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SelectMode {
    /// Interactive for a terminal, plain listing otherwise.
    #[default]
    Auto,
    /// Interactive even when the stream is not detected as a terminal.
    Always,
    /// Never interactive.
    Never,
}

impl SelectMode {
    /// Whether this mode should take over the terminal.
    pub const fn is_interactive(self, is_terminal: bool) -> bool {
        match self {
            Self::Auto => is_terminal,
            Self::Always => true,
            Self::Never => false,
        }
    }
}

/// One selectable entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Item {
    /// Returned on selection. The application's own identifier.
    pub id: String,
    /// The text shown in the list.
    pub label: String,
    /// Optional second column.
    pub description: Option<String>,
}

impl Item {
    pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            description: None,
        }
    }

    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }
}

/// A titled section of entries.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Group {
    pub label: String,
    pub items: Vec<Item>,
}

impl Group {
    pub fn new(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            items: Vec::new(),
        }
    }

    pub fn add_item(mut self, item: Item) -> Self {
        self.items.push(item);
        self
    }
}

/// A key shown in the footer, reported back when pressed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Hint {
    pub key: char,
    pub label: String,
}

impl Hint {
    pub fn new(key: char, label: impl Into<String>) -> Self {
        Self {
            key,
            label: label.into(),
        }
    }
}

/// What the user did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
    /// An entry was chosen, carrying its [`Item::id`].
    Selected(String),
    /// A footer key was pressed.
    Hotkey(char),
    /// Escape, `q`, or `Ctrl-C`.
    Cancelled,
    /// The menu did not run, because the mode or the stream ruled it out.
    /// The caller decides what to show instead — often [`Menu::render`].
    Unavailable,
}

/// Columns the cursor marker and its trailing space occupy.
const MARKER_WIDTH: usize = 2;
/// Columns between the label column and the description.
const GAP_WIDTH: usize = 2;
/// Below this, a description says nothing and is left out instead.
const MIN_DESCRIPTION: usize = 12;

/// Shortens `text` to `max` columns, marking the cut with an ellipsis.
///
/// Entries are shortened rather than wrapped. A wrapped line would change the
/// number of lines the frame occupies, which the redraw counts on, and a
/// description spilling to column zero is what makes a long list unreadable in
/// the first place.
fn shorten(text: &str, max: usize) -> std::borrow::Cow<'_, str> {
    if text.width() <= max {
        return std::borrow::Cow::Borrowed(text);
    }
    if max <= 1 {
        return std::borrow::Cow::Borrowed("");
    }

    let mut out = String::new();
    let mut used = 0;
    for character in text.chars() {
        let next = character.to_string().width();
        if used + next > max - 1 {
            break;
        }
        out.push(character);
        used += next;
    }
    out.push('…');
    std::borrow::Cow::Owned(out)
}

/// How well an item answers a search, lower being better.
///
/// The tiers matter more than the numbers: a name the user is typing beats a
/// description that happens to contain the same letters, and a run of adjacent
/// characters beats the same letters scattered through the name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct Score(u32);

impl Score {
    const LABEL_SUBSTRING: u32 = 0;
    const LABEL_SUBSEQUENCE: u32 = 1_000;
    const DESCRIPTION: u32 = 10_000;
}

/// Scores `item` against a lowercased, non-empty `query`, or `None` if it does
/// not match.
fn score(item: &Item, query: &str) -> Option<Score> {
    let label = item.label.to_lowercase();
    if let Some(at) = label.find(query) {
        return Some(Score(
            Score::LABEL_SUBSTRING + u32::try_from(at).unwrap_or(u32::MAX),
        ));
    }
    // Typing "bl" for "build:landings" should still find it.
    if let Some(span) = subsequence_span(&label, query) {
        return Some(Score(
            Score::LABEL_SUBSEQUENCE + u32::try_from(span).unwrap_or(u32::MAX),
        ));
    }
    let description = item.description.as_ref()?.to_lowercase();
    let at = description.find(query)?;
    Some(Score(
        Score::DESCRIPTION + u32::try_from(at).unwrap_or(u32::MAX),
    ))
}

/// The span `query` occupies in `text` as a subsequence, if it occurs at all.
///
/// The span is what separates a tight match from a lucky one: `dl` spans two
/// characters in `dl-report` and fourteen in `deploy:landings`.
fn subsequence_span(text: &str, query: &str) -> Option<usize> {
    let mut chars = text.char_indices();
    let mut first = None;
    let mut last = 0;

    for wanted in query.chars() {
        let (at, _) = chars.find(|(_, character)| *character == wanted)?;
        first.get_or_insert(at);
        last = at;
    }

    Some(last - first.unwrap_or(last) + 1)
}

/// One drawn line of the menu body.
enum Row<'a> {
    Group(&'a str),
    /// An entry, with its position among selectable items.
    Item(&'a Item, usize),
}

/// The visible area, for a terminal that cannot show the whole menu.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Viewport {
    /// First body row to draw.
    start: usize,
    /// Body rows available, before any scroll indicator is subtracted.
    height: usize,
    /// Columns available. Entries are shortened to fit rather than wrapped:
    /// a wrapped line would change the frame height and break the redraw.
    width: Option<usize>,
}

impl Viewport {
    pub(crate) const fn new(start: usize, height: usize) -> Self {
        Self {
            start,
            height,
            width: None,
        }
    }

    pub(crate) const fn with_width(mut self, width: Option<usize>) -> Self {
        self.width = width;
        self
    }

    /// Whether `row` lands inside what this viewport draws of `rows` rows.
    #[cfg(any(all(feature = "select", unix), test))]
    pub(crate) fn shows(self, rows: usize, row: usize) -> bool {
        self.window(rows).contains(&row)
    }

    /// The rows to draw, leaving room for whichever indicators are needed.
    ///
    /// An indicator costs a body line, and showing one can be what pushes the
    /// other into existence, so the two are resolved together rather than in
    /// sequence.
    fn window(self, rows: usize) -> std::ops::Range<usize> {
        if rows <= self.height {
            return 0..rows;
        }

        let start = self.start.min(rows.saturating_sub(1));
        let above = usize::from(start > 0);
        // Assume a trailing indicator, then confirm: with one line spent above
        // and one below, anything that still does not fit needs both.
        let visible = self.height.saturating_sub(above + 1).max(1);
        let end = (start + visible).min(rows);

        if end == rows {
            // Nothing below after all; that line goes back to the body.
            let visible = self.height.saturating_sub(above).max(1);
            let start = rows.saturating_sub(visible).max(start);
            return start..rows;
        }

        start..end
    }
}

/// A grouped list the user picks from.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Menu {
    heading: Option<String>,
    /// Shown at the end of the heading line, for context such as a detected tool.
    note: Option<String>,
    groups: Vec<Group>,
    hints: Vec<Hint>,
}

impl Menu {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_heading(mut self, heading: impl Into<String>) -> Self {
        self.heading = Some(heading.into());
        self
    }

    pub fn with_note(mut self, note: impl Into<String>) -> Self {
        self.note = Some(note.into());
        self
    }

    pub fn add_group(mut self, group: Group) -> Self {
        self.groups.push(group);
        self
    }

    pub fn add_hint(mut self, hint: Hint) -> Self {
        self.hints.push(hint);
        self
    }

    /// Every item, in display order.
    pub fn items(&self) -> impl Iterator<Item = &Item> {
        self.groups.iter().flat_map(|group| group.items.iter())
    }

    /// The number of selectable entries.
    pub fn len(&self) -> usize {
        self.items().count()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// The label column width, so descriptions line up across all groups.
    fn label_width(&self) -> usize {
        self.items()
            .map(|item| item.label.width())
            .max()
            .unwrap_or(0)
    }

    /// Renders the menu as plain text, with no cursor and no terminal control.
    ///
    /// This is what a non-interactive caller shows, and what tests assert on.
    pub fn render(&self, console: Console) -> String {
        crate::internal::collect_to_string(|buf| self.write_frame(buf, console, None, None, None))
    }

    /// The body as a flat list of lines, so a viewport can window over it.
    ///
    /// With a `query`, only matching items appear, best first, and a group with
    /// nothing left disappears with them. Item indices are positions in that
    /// filtered order, which is what the cursor counts.
    fn body_rows(&self, query: Option<&str>) -> Vec<Row<'_>> {
        // An empty query is not a search result: ranking it would sort the menu
        // alphabetically, which is the arrangement the grouping exists to avoid.
        let query = query.filter(|query| !query.is_empty());

        let Some(query) = query else {
            let mut rows = Vec::with_capacity(self.groups.len() + self.len());
            let mut index = 0;
            for group in &self.groups {
                rows.push(Row::Group(&group.label));
                for item in &group.items {
                    rows.push(Row::Item(item, index));
                    index += 1;
                }
            }
            return rows;
        };

        // Ranking across the whole menu, not within each group: the best answer
        // to what was typed should be the first thing the cursor sits on.
        let mut ranked: Vec<(Score, &str, &Item)> =
            self.groups
                .iter()
                .flat_map(|group| {
                    group.items.iter().filter_map(move |item| {
                        Some((score(item, query)?, group.label.as_str(), item))
                    })
                })
                .collect();
        ranked.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.2.label.cmp(&b.2.label)));

        let mut rows = Vec::with_capacity(ranked.len() + 1);
        let mut last_group = None;
        for (index, (_, group, item)) in ranked.iter().enumerate() {
            if last_group != Some(*group) {
                rows.push(Row::Group(group));
                last_group = Some(*group);
            }
            rows.push(Row::Item(item, index));
        }
        rows
    }

    /// The items a `query` matches, in the order they are drawn.
    fn matching_items(&self, query: Option<&str>) -> Vec<&Item> {
        self.body_rows(query)
            .into_iter()
            .filter_map(|row| match row {
                Row::Item(item, _) => Some(item),
                Row::Group(_) => None,
            })
            .collect()
    }

    /// Writes the menu, marking `cursor` when one is given.
    ///
    /// `viewport` limits the body to a window, for a terminal that cannot show
    /// every entry. Without it the whole menu is written — which is what a
    /// pipe or a file wants, neither having a height to run out of.
    fn write_frame(
        &self,
        writer: &mut (impl std::io::Write + ?Sized),
        console: Console,
        cursor: Option<usize>,
        viewport: Option<Viewport>,
        query: Option<&str>,
    ) -> std::io::Result<()> {
        let columns = viewport.and_then(|viewport| viewport.width);

        if let Some(heading) = &self.heading {
            let note_room = self
                .note
                .as_ref()
                .map_or(0, |note| note.width() + GAP_WIDTH);
            let room = columns.map_or(usize::MAX, |columns| columns.saturating_sub(note_room));
            console.write_paint(Tone::Title, shorten(heading, room), writer)?;
            if let Some(note) = &self.note {
                write!(writer, "  ")?;
                console.write_paint(Tone::Muted, note, writer)?;
            }
            writeln!(writer)?;
            writeln!(writer)?;
        }

        let width = self.label_width().min(
            // A label column wider than the terminal leaves nothing for the
            // description and pushes it off screen entirely.
            columns.map_or(usize::MAX, |columns| columns.saturating_sub(MARKER_WIDTH)),
        );
        let rows = self.body_rows(query);
        let window = viewport.map_or(0..rows.len(), |viewport| viewport.window(rows.len()));

        if window.start > 0 {
            console.write_paint(Tone::Muted, format!("  ↑ {} more", window.start), writer)?;
            writeln!(writer)?;
        }

        for row in &rows[window.clone()] {
            match row {
                Row::Group(label) => {
                    let room = columns.unwrap_or(usize::MAX);
                    console.write_paint(Tone::Info, shorten(label, room), writer)?;
                }
                Row::Item(item, index) => {
                    let selected = cursor == Some(*index);
                    let marker = if selected { "›" } else { " " };
                    let label = shorten(&item.label, width);
                    let padding = width.saturating_sub(label.width());

                    write!(writer, "{marker} ")?;
                    console.write_paint(
                        if selected { Tone::Success } else { Tone::Info },
                        &label,
                        writer,
                    )?;

                    if let Some(description) = &item.description {
                        // What is left after the marker, the label column and
                        // the gap. Below a readable minimum the description is
                        // dropped rather than cut to a stub.
                        let room = columns.map_or(usize::MAX, |columns| {
                            columns.saturating_sub(MARKER_WIDTH + width + GAP_WIDTH)
                        });
                        if room >= MIN_DESCRIPTION {
                            write!(writer, "{:padding$}  ", "")?;
                            console.write_paint(Tone::Muted, shorten(description, room), writer)?;
                        }
                    }
                }
            }
            writeln!(writer)?;
        }

        if rows.is_empty() && query.is_some() {
            console.write_paint(Tone::Muted, "  no matches", writer)?;
            writeln!(writer)?;
        }

        let remaining = rows.len() - window.end;
        if remaining > 0 {
            console.write_paint(Tone::Muted, format!("  ↓ {remaining} more"), writer)?;
            writeln!(writer)?;
        }

        if let Some(query) = query {
            writeln!(writer)?;
            console.write_paint(Tone::Success, "/", writer)?;
            write!(writer, " ")?;
            if query.is_empty() {
                console.write_paint(Tone::Muted, "type to filter", writer)?;
            } else {
                console.write_paint(Tone::Title, query, writer)?;
            }
            writeln!(writer)?;
        } else if !self.hints.is_empty() || self.offers_search(cursor) {
            writeln!(writer)?;
            let mut written = 0;
            // `/` is reserved for the filter and cannot be bound as a hint, so
            // nothing else can advertise it. A key the menu answers to but
            // never mentions is a key nobody presses.
            if self.offers_search(cursor) {
                console.write_paint(Tone::Success, '/', writer)?;
                write!(writer, " ")?;
                console.write_paint(Tone::Muted, "search", writer)?;
                written += 1;
            }
            for hint in &self.hints {
                if written > 0 {
                    write!(writer, "   ")?;
                }
                console.write_paint(Tone::Success, hint.key, writer)?;
                write!(writer, " ")?;
                console.write_paint(Tone::Muted, &hint.label, writer)?;
                written += 1;
            }
            writeln!(writer)?;
        }

        Ok(())
    }

    /// Whether this frame should advertise the filter.
    ///
    /// A cursor means the menu is being driven from a keyboard; `render` passes
    /// none, and offering a key to a pipe would be a lie.
    fn offers_search(&self, cursor: Option<usize>) -> bool {
        cursor.is_some() && !self.is_empty()
    }

    /// The body row showing item `index`, for keeping the cursor in view.
    #[cfg(any(all(feature = "select", unix), test))]
    fn row_of_item(&self, index: usize, query: Option<&str>) -> usize {
        self.body_rows(query)
            .iter()
            .position(|row| matches!(row, Row::Item(_, item) if *item == index))
            .unwrap_or(0)
    }

    /// Body rows in total, for sizing a viewport.
    #[cfg(any(all(feature = "select", unix), test))]
    fn body_height(&self, query: Option<&str>) -> usize {
        // The "no matches" line occupies the body when nothing is left.
        self.body_rows(query)
            .len()
            .max(usize::from(query.is_some()))
    }

    /// Lines the menu spends on anything but the body.
    #[cfg(any(all(feature = "select", unix), test))]
    fn chrome_height(&self, searching: bool) -> usize {
        let heading = if self.heading.is_some() { 2 } else { 0 };
        // Interactive frames always carry a footer: the query line while
        // searching, otherwise at least the filter affordance.
        let footer = if searching || !self.hints.is_empty() || !self.is_empty() {
            2
        } else {
            0
        };
        heading + footer
    }
}

impl fmt::Display for Menu {
    /// Plain, uncoloured rendering.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.render(Console::new(crate::ColorMode::Never, false)))
    }
}

#[cfg(all(feature = "select", unix))]
mod interactive;
#[cfg(all(feature = "select", unix))]
mod terminal;

/// Without a terminal backend the menu still exists; it just never takes over.
///
/// The interactive path is Unix-only, so a caller can write one code path and
/// fall back to [`Menu::render`] on [`Outcome::Unavailable`] everywhere else.
#[cfg(all(feature = "select", not(unix)))]
impl Menu {
    pub fn run(
        &self,
        _console: Console,
        _mode: SelectMode,
        _is_terminal: bool,
    ) -> std::io::Result<Outcome> {
        Ok(Outcome::Unavailable)
    }
}

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

    fn plain() -> Console {
        Console::new(ColorMode::Never, false)
    }

    fn menu() -> Menu {
        Menu::new()
            .with_heading("casoon.dev")
            .with_note("pnpm")
            .add_group(
                Group::new("Development")
                    .add_item(Item::new("dev", "dev").with_description("Start the site"))
                    .add_item(Item::new("dev:landings", "dev:landings")),
            )
            .add_group(Group::new("Build").add_item(Item::new("build", "build")))
            .add_hint(Hint::new('U', "Updates"))
    }

    #[test]
    fn renders_groups_headings_and_hints() {
        let output = menu().render(plain());
        assert!(output.starts_with("casoon.dev  pnpm\n\n"));
        assert!(output.contains("Development\n"));
        assert!(output.contains("  dev "));
        assert!(output.contains("Build\n"));
        assert!(output.trim_end().ends_with("U Updates"));
    }

    #[test]
    fn a_keyboard_frame_advertises_the_filter() {
        // `/` cannot be bound as a hint, so if the menu does not mention it,
        // nothing will.
        let menu = menu();
        let interactive = crate::internal::collect_to_string(|buf| {
            menu.write_frame(buf, plain(), Some(0), None, None)
        });
        assert!(interactive.contains("/ search"));
        assert!(
            interactive.contains("U Updates"),
            "and the menu's own hints"
        );
    }

    #[test]
    fn a_rendered_frame_offers_no_keys() {
        // Printed to a pipe there is no keyboard, so offering one would lie.
        assert!(!menu().render(plain()).contains("/ search"));
    }

    #[test]
    fn an_empty_menu_advertises_nothing() {
        let empty = Menu::new().with_heading("nothing");
        let shown = crate::internal::collect_to_string(|buf| {
            empty.write_frame(buf, plain(), Some(0), None, None)
        });
        assert!(!shown.contains("search"));
    }

    #[test]
    fn plain_rendering_has_no_cursor_marker() {
        assert!(!menu().render(plain()).contains('›'));
    }

    #[test]
    fn descriptions_line_up_across_groups() {
        let output = menu().render(plain());
        let line = output
            .lines()
            .find(|line| line.contains("Start the site"))
            .expect("description line");
        // The label column is as wide as the longest label anywhere in the menu.
        assert_eq!(
            line.find("Start the site"),
            Some(2 + "dev:landings".width() + 2)
        );
    }

    #[test]
    fn an_item_without_a_description_ends_at_its_label() {
        let output = menu().render(plain());
        let line = output
            .lines()
            .find(|line| line.trim_start().starts_with("build"))
            .expect("build line");
        assert_eq!(line, "  build");
    }

    #[test]
    fn items_are_yielded_in_display_order() {
        let menu = menu();
        let ids: Vec<&str> = menu.items().map(|item| item.id.as_str()).collect();
        assert_eq!(ids, ["dev", "dev:landings", "build"]);
    }

    #[test]
    fn length_counts_items_not_groups() {
        assert_eq!(menu().len(), 3);
        assert!(!menu().is_empty());
        assert!(Menu::new().is_empty());
    }

    fn windowed(menu: &Menu, start: usize, height: usize) -> String {
        crate::internal::collect_to_string(|buf| {
            menu.write_frame(
                buf,
                plain(),
                Some(0),
                Some(Viewport::new(start, height)),
                None,
            )
        })
    }

    fn at_width(menu: &Menu, columns: usize) -> String {
        crate::internal::collect_to_string(|buf| {
            menu.write_frame(
                buf,
                plain(),
                Some(0),
                Some(Viewport::new(0, 999).with_width(Some(columns))),
                None,
            )
        })
    }

    fn long_menu(items: usize) -> Menu {
        let mut group = Group::new("Scripts");
        for n in 0..items {
            group = group.add_item(Item::new(format!("t{n}"), format!("t{n}")));
        }
        Menu::new().with_heading("many").add_group(group)
    }

    #[test]
    fn a_body_that_fits_is_shown_whole() {
        let menu = long_menu(3);
        let output = windowed(&menu, 0, 50);
        assert!(!output.contains("more"));
        assert!(output.contains("t2"));
    }

    #[test]
    fn a_body_that_does_not_fit_says_how_much_is_below() {
        let menu = long_menu(40);
        let output = windowed(&menu, 0, 10);
        assert!(output.contains("↓ "));
        assert!(!output.contains("↑ "), "nothing is above the top");
    }

    #[test]
    fn scrolling_into_the_middle_shows_both_directions() {
        let menu = long_menu(40);
        let output = windowed(&menu, 15, 10);
        assert!(output.contains("↑ 15 more"));
        assert!(output.contains("↓ "));
    }

    #[test]
    fn the_end_of_the_list_drops_the_trailing_indicator() {
        let menu = long_menu(40);
        let output = windowed(&menu, 60, 10);
        assert!(output.contains("↑ "));
        assert!(
            !output.contains("↓ "),
            "there is nothing below the last row"
        );
        assert!(output.contains("t39"), "the last entry is visible");
    }

    #[test]
    fn a_window_never_draws_more_body_lines_than_it_was_given() {
        // The whole point: the frame must not outgrow the terminal, or the
        // redraw moves the cursor further up than there are lines.
        let menu = long_menu(40);
        let chrome = menu.chrome_height(false);
        for start in [0, 1, 7, 20, 39] {
            for height in [3, 5, 10, 25] {
                let body = windowed(&menu, start, height).lines().count() - chrome;
                assert!(
                    body <= height,
                    "start {start}, height {height}: drew {body} body lines"
                );
            }
        }
    }

    #[test]
    fn a_window_always_draws_something() {
        let menu = long_menu(40);
        let chrome = menu.chrome_height(false);
        for height in [1, 2, 3] {
            let body = windowed(&menu, 0, height).lines().count() - chrome;
            assert!(body >= 1, "height {height} drew nothing");
        }
    }

    #[test]
    fn row_lookup_accounts_for_group_labels() {
        let menu = menu();
        // Rows: Development, dev, dev:landings, Build, build
        assert_eq!(menu.row_of_item(0, None), 1);
        assert_eq!(menu.row_of_item(2, None), 4);
        assert_eq!(menu.body_height(None), 5);
    }

    #[test]
    fn chrome_height_counts_heading_and_hints() {
        assert_eq!(menu().chrome_height(false), 4);
        assert_eq!(Menu::new().chrome_height(false), 0);
        assert_eq!(
            Menu::new().with_heading("h").chrome_height(false),
            2,
            "heading plus its blank line"
        );
        assert_eq!(
            Menu::new().chrome_height(true),
            2,
            "the query line needs room even without hints"
        );
    }

    #[test]
    fn scrolling_keeps_every_cursor_position_in_view() {
        // The bug this pins: stepping to the last entry left the cursor one
        // row below the window, because the scroll maths and the window maths
        // disagreed about how many lines the indicators cost.
        let menu = long_menu(40);
        let rows = menu.body_height(None);

        for height in [4, 6, 11, 21, 30] {
            let mut start = 0usize;
            for index in 0..menu.len() {
                let cursor = menu.row_of_item(index, None);
                if cursor < start {
                    start = cursor;
                }
                while start < rows - 1 && !Viewport::new(start, height).shows(rows, cursor) {
                    start += 1;
                }
                assert!(
                    Viewport::new(start, height).shows(rows, cursor),
                    "height {height}, item {index} (row {cursor}) not visible from {start}"
                );
            }
        }
    }

    #[test]
    fn nothing_exceeds_the_given_width() {
        // The defect this pins: without a width, a long description wrapped to
        // column zero and destroyed the two-column layout.
        let menu = Menu::new()
            .with_heading("a-rather-long-project-name")
            .with_note("pnpm")
            .add_group(Group::new("Quality").add_item(
                Item::new("type-check", "type-check").with_description(
                    "Führt den TypeScript-Check in allen Packages des Workspace aus",
                ),
            ));

        for columns in [20, 40, 60, 80, 100] {
            for line in at_width(&menu, columns).lines() {
                assert!(
                    line.width() <= columns,
                    "width {columns}: line of {} columns: {line:?}",
                    line.width()
                );
            }
        }
    }

    #[test]
    fn a_shortened_entry_is_marked_as_cut() {
        let menu = Menu::new().add_group(Group::new("G").add_item(
            Item::new("x", "x").with_description("eine sehr lange Beschreibung, die nicht passt"),
        ));
        assert!(at_width(&menu, 30).contains('…'));
    }

    #[test]
    fn a_description_with_no_room_is_dropped_rather_than_stubbed() {
        let menu = Menu::new().add_group(Group::new("G").add_item(
            Item::new("a-long-script-name", "a-long-script-name").with_description("beschreibung"),
        ));
        let narrow = at_width(&menu, 24);
        assert!(!narrow.contains("besch"), "no room left, so no description");
        assert!(
            narrow.contains("a-long-script-name"),
            "the name still shows"
        );
    }

    #[test]
    fn shortening_counts_display_columns_not_bytes() {
        // German descriptions are the normal case here; multi-byte characters
        // must not be counted twice.
        assert_eq!(shorten("äöüß", 10), "äöüß");
        assert_eq!(shorten("äöüß", 3).width(), 3);
        assert!(shorten("äöüß", 3).ends_with('…'));
        assert_eq!(shorten("abc", 1), "");
    }

    fn searched(menu: &Menu, query: &str) -> Vec<String> {
        menu.matching_items(Some(query))
            .into_iter()
            .map(|item| item.label.clone())
            .collect()
    }

    fn script_menu() -> Menu {
        Menu::new()
            .add_group(
                Group::new("Development")
                    .add_item(Item::new("dev", "dev").with_description("Start the site"))
                    .add_item(Item::new("dev:landings", "dev:landings")),
            )
            .add_group(
                Group::new("Deploy")
                    .add_item(Item::new("deploy", "deploy").with_description("Ship everything"))
                    .add_item(Item::new("deploy:landings", "deploy:landings")),
            )
            .add_group(
                Group::new("Quality")
                    .add_item(Item::new("check", "check").with_description("Lint and format")),
            )
    }

    #[test]
    fn an_empty_query_keeps_the_menu_as_it_was() {
        // Backspacing a query away must restore the meaning-first order, not
        // leave the menu sorted alphabetically by a rank everything ties on.
        let menu = script_menu();
        let unsearched: Vec<String> = menu.items().map(|item| item.label.clone()).collect();
        assert_eq!(searched(&menu, ""), unsearched);
    }

    #[test]
    fn a_substring_in_the_name_wins_over_one_in_a_description() {
        // "s" appears in "Start the site" and in "deploy:landings"; the name
        // is what the user is typing towards.
        let hits = searched(&script_menu(), "landings");
        assert_eq!(hits, ["dev:landings", "deploy:landings"]);
    }

    #[test]
    fn scattered_letters_still_find_a_name() {
        assert!(searched(&script_menu(), "dpl").contains(&"deploy".to_owned()));
    }

    #[test]
    fn a_tight_match_ranks_before_a_scattered_one() {
        let hits = searched(&script_menu(), "dep");
        assert_eq!(hits.first().map(String::as_str), Some("deploy"));
    }

    #[test]
    fn a_description_match_is_found_when_no_name_matches() {
        let hits = searched(&script_menu(), "lint");
        assert_eq!(hits, ["check"]);
    }

    #[test]
    fn a_query_that_matches_nothing_yields_nothing() {
        assert!(searched(&script_menu(), "qqqq").is_empty());
    }

    #[test]
    fn a_query_that_matches_nothing_says_so() {
        // An empty area under a query reads as a broken menu rather than an
        // answer.
        let menu = script_menu();
        let shown = crate::internal::collect_to_string(|buf| {
            menu.write_frame(buf, plain(), Some(0), None, Some("qqqq"))
        });
        assert!(shown.contains("no matches"));
        assert_eq!(menu.body_height(Some("qqqq")), 1, "the notice needs a line");
    }

    #[test]
    fn searching_is_case_insensitive() {
        assert_eq!(
            searched(&script_menu(), "dev"),
            searched(&script_menu(), "dev")
        );
        assert!(
            !searched(&script_menu(), "start").is_empty(),
            "matches a capitalised description"
        );
    }

    #[test]
    fn a_group_with_no_matches_is_not_drawn() {
        let menu = script_menu();
        let rows = menu.body_rows(Some("check"));
        let groups: Vec<&str> = rows
            .iter()
            .filter_map(|row| match row {
                Row::Group(label) => Some(*label),
                Row::Item(..) => None,
            })
            .collect();
        assert_eq!(groups, ["Quality"]);
    }

    #[test]
    fn filtered_item_indices_are_positions_in_the_result() {
        let menu = script_menu();
        let rows = menu.body_rows(Some("landings"));
        let indices: Vec<usize> = rows
            .iter()
            .filter_map(|row| match row {
                Row::Item(_, index) => Some(*index),
                Row::Group(_) => None,
            })
            .collect();
        assert_eq!(indices, [0, 1], "the cursor counts matches, not all items");
    }

    #[test]
    fn a_subsequence_span_measures_tightness() {
        assert_eq!(subsequence_span("deploy", "dep"), Some(3));
        assert_eq!(subsequence_span("deploy", "dy"), Some(6));
        assert_eq!(subsequence_span("deploy", "dz"), None);
    }

    #[test]
    fn the_query_line_is_drawn_while_searching() {
        let menu = script_menu();
        let shown = crate::internal::collect_to_string(|buf| {
            menu.write_frame(buf, plain(), Some(0), None, Some("dep"))
        });
        assert!(shown.contains("/ dep"));
    }

    #[test]
    fn an_opened_search_prompts_before_anything_is_typed() {
        let menu = script_menu();
        let shown = crate::internal::collect_to_string(|buf| {
            menu.write_frame(buf, plain(), Some(0), None, Some(""))
        });
        assert!(shown.contains("type to filter"));
    }

    #[test]
    fn rendering_is_never_windowed() {
        // A pipe or a file has no height to run out of, so truncating there
        // would lose entries for no reason.
        let output = long_menu(40).render(plain());
        assert!(output.contains("t0") && output.contains("t39"));
        assert!(!output.contains("more"));
    }

    #[test]
    fn auto_mode_is_interactive_only_for_terminals() {
        assert!(SelectMode::Auto.is_interactive(true));
        assert!(!SelectMode::Auto.is_interactive(false));
        assert!(SelectMode::Always.is_interactive(false));
        assert!(!SelectMode::Never.is_interactive(true));
    }

    #[test]
    fn display_renders_without_colour() {
        let shown = menu().to_string();
        assert!(!shown.contains('\u{1b}'));
        assert_eq!(shown, menu().render(plain()));
    }

    #[cfg(feature = "select")]
    #[test]
    fn a_non_interactive_stream_returns_without_reading() {
        // The guarantee that matters in CI and in a pipeline: no blocking read.
        assert_eq!(
            menu().run(plain(), SelectMode::Auto, false).expect("run"),
            Outcome::Unavailable
        );
        assert_eq!(
            menu().run(plain(), SelectMode::Never, true).expect("run"),
            Outcome::Unavailable
        );
    }

    #[cfg(feature = "select")]
    #[test]
    fn an_empty_menu_never_takes_over_the_terminal() {
        assert_eq!(
            Menu::new()
                .run(plain(), SelectMode::Always, true)
                .expect("run"),
            Outcome::Unavailable
        );
    }
}