Skip to main content

vcon_server/tui/
view.rs

1//! Drawing: a state and a theme give a frame. It reads nothing but its
2//! arguments, so every screen is tested on ratatui's `TestBackend` at the
3//! size the test chooses.
4//!
5//! Nothing is said by color alone: the connection is a word, the selected
6//! row has a marker, and without color the frame uses no color at all.
7
8use ratatui::Frame;
9use ratatui::layout::Rect;
10use ratatui::style::{Color, Modifier, Style};
11use ratatui::text::{Line, Span};
12use ratatui::widgets::{Paragraph, Wrap};
13use time::format_description::well_known::Rfc3339;
14use time::{OffsetDateTime, UtcOffset};
15
16use crate::tui::keys::{BINDINGS, binding};
17use crate::tui::state::{Action, Connection, Listing, Row, State, View};
18
19/// The smallest terminal a view is drawn in.
20const MIN_COLUMNS: u16 = 40;
21const MIN_LINES: u16 = 8;
22/// The offset every time on screen is in, as it is written beside them.
23const ZONE: &str = "UTC+00:00";
24/// The columns of a list row: the marker and the uuid, then each time, then
25/// the version.
26const UUID_COLUMNS: u16 = 38;
27const TIME_COLUMNS: u16 = 21;
28const VERSION_COLUMNS: u16 = 34;
29
30/// Whether color may be used.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct Theme {
33    /// False for a monochrome terminal or a user who asked for none.
34    pub color: bool,
35}
36
37/// The theme for an environment: no color when `NO_COLOR` is set to
38/// anything but the empty string (<https://no-color.org>), when `TERM` is
39/// `dumb`, or when there is no `TERM`.
40#[must_use]
41pub fn theme(no_color: Option<&str>, term: Option<&str>) -> Theme {
42    let refused = no_color.is_some_and(|value| !value.is_empty());
43    let capable = term.is_some_and(|term| term != "dumb");
44    Theme {
45        color: capable && !refused,
46    }
47}
48
49/// An RFC 3339 time as `YYYY-MM-DD HH:MM:SS` in UTC; text that is not one
50/// is returned as it is.
51#[must_use]
52pub fn utc(text: &str) -> String {
53    OffsetDateTime::parse(text, &Rfc3339).map_or_else(|_| text.to_owned(), stamp)
54}
55
56/// `at` as `YYYY-MM-DD HH:MM:SS` in UTC.
57fn stamp(at: OffsetDateTime) -> String {
58    let at = at.to_offset(UtcOffset::UTC);
59    format!(
60        "{:04}-{:02}-{:02} {:02}:{:02}:{:02}",
61        at.year(),
62        u8::from(at.month()),
63        at.day(),
64        at.hour(),
65        at.minute(),
66        at.second()
67    )
68}
69
70/// Draws `state` on the whole frame.
71pub fn draw(frame: &mut Frame<'_>, state: &State, theme: Theme) {
72    let area = frame.area();
73    if area.width < MIN_COLUMNS || area.height < MIN_LINES {
74        let message = format!(
75            "Terminal too small: {MIN_COLUMNS}x{MIN_LINES} is needed. Enlarge it, or press q to quit."
76        );
77        frame.render_widget(Paragraph::new(message).wrap(Wrap { trim: true }), area);
78        return;
79    }
80    let line = |y: u16| Rect {
81        y: area.y.saturating_add(y),
82        height: 1,
83        ..area
84    };
85    // The notice takes the lines it needs, up to half of what is left
86    // after the status line and the key hints, and one line when empty.
87    let most = usize::from(area.height.saturating_sub(2) / 2).max(1);
88    let said = fitted(&notice(state), usize::from(area.width), most);
89    let notice_lines = u16::try_from(said.len()).unwrap_or(1).max(1);
90    let body = Rect {
91        y: area.y.saturating_add(1),
92        height: area.height.saturating_sub(notice_lines.saturating_add(2)),
93        ..area
94    };
95    frame.render_widget(Paragraph::new(status(state, area.width, theme)), line(0));
96    match state.view {
97        View::List => list(frame, state, body),
98        View::Detail => detail(frame, state, body),
99        View::Help => help(frame, body),
100    }
101    let said: Vec<Line<'_>> = said.into_iter().map(Line::from).collect();
102    frame.render_widget(
103        Paragraph::new(said),
104        Rect {
105            y: area.y.saturating_add(body.height).saturating_add(1),
106            height: notice_lines,
107            ..area
108        },
109    );
110    frame.render_widget(
111        Paragraph::new(hints(state.view, usize::from(area.width))),
112        line(area.height.saturating_sub(1)),
113    );
114}
115
116/// `text` as lines of at most `columns` characters, broken between words;
117/// a word longer than a line is broken where the line ends.
118fn wrapped(text: &str, columns: usize) -> Vec<String> {
119    let columns = columns.max(1);
120    let mut lines: Vec<String> = Vec::new();
121    let mut line = String::new();
122    let mut used = 0_usize;
123    for word in text.split(' ').filter(|word| !word.is_empty()) {
124        let mut rest: Vec<char> = word.chars().collect();
125        if used > 0 && used.saturating_add(1).saturating_add(rest.len()) > columns {
126            lines.push(std::mem::take(&mut line));
127            used = 0;
128        }
129        while rest.len() > columns {
130            lines.push(rest.drain(..columns).collect());
131        }
132        if used > 0 {
133            line.push(' ');
134            used = used.saturating_add(1);
135        }
136        used = used.saturating_add(rest.len());
137        line.extend(rest);
138    }
139    if !line.is_empty() {
140        lines.push(line);
141    }
142    lines
143}
144
145/// The parts of the notice as the lines drawn: on one line, joined by
146/// [`BETWEEN`], when that fits `columns`; otherwise each part on lines of
147/// its own, wrapped. At most `most` lines: when there are more, the last
148/// one drawn ends with [`CUT`].
149fn fitted(parts: &[String], columns: usize, most: usize) -> Vec<String> {
150    let whole = parts.join(BETWEEN);
151    if whole.chars().count() <= columns {
152        return vec![whole];
153    }
154    let mut lines: Vec<String> = parts
155        .iter()
156        .flat_map(|part| wrapped(part, columns))
157        .collect();
158    if lines.len() > most {
159        lines.truncate(most);
160        if let Some(last) = lines.last_mut() {
161            let kept = columns.saturating_sub(CUT.chars().count());
162            *last = last.chars().take(kept).collect();
163            last.push_str(CUT);
164        }
165    }
166    lines
167}
168
169/// Whose key the server answered for, as the status line names it.
170enum Owner<'a> {
171    /// The server has not answered for the key.
172    Unknown,
173    /// An operator key, which has no tenant.
174    Operator,
175    /// A tenant key, with the tenant's id.
176    Tenant(&'a str),
177}
178
179/// The scheme every server address has, and so the first thing left out.
180const SCHEME: &str = "https://";
181/// Between the parts of the status line.
182const BETWEEN: &str = " | ";
183/// Ends a part that was shortened.
184const CUT: &str = "...";
185/// The fewest characters of a tenant id worth showing.
186const ID_MIN: usize = 4;
187
188/// The status line before the connection word, which the caller appends:
189/// the server's address and whose key it is, each followed by [`BETWEEN`].
190///
191/// THE RULE for a line longer than `columns`. An operator needs the
192/// connection first, then the server, then the tenant, so the parts give
193/// way in the other order, and nothing that carries information goes
194/// before something that carries none:
195///
196/// 1. The connection word is never shortened or left out.
197/// 2. The address loses `https://`, which every address has.
198/// 3. A tenant id is shortened to what fits, with `...`, down to
199///    [`ID_MIN`] characters. A phrase (`tenant unknown`, `no tenant
200///    (operator key)`) is never cut.
201/// 4. The tenant part is left out.
202/// 5. Only then is the address shortened, at its end, with `...`.
203fn status_lead(server: &str, owner: &Owner<'_>, word: &str, columns: usize) -> String {
204    let length = |text: &str| text.chars().count();
205    let owner_whole = match owner {
206        Owner::Unknown => "tenant unknown".to_owned(),
207        Owner::Operator => "no tenant (operator key)".to_owned(),
208        Owner::Tenant(id) => format!("tenant {id}"),
209    };
210    // What the address and the tenant part may take together.
211    let room = columns.saturating_sub(length(word));
212    let with_owner = |address: &str, owner: &str| format!("{address}{BETWEEN}{owner}{BETWEEN}");
213    let whole = with_owner(server, &owner_whole);
214    if length(&whole) <= room {
215        return whole;
216    }
217    let bare = server.strip_prefix(SCHEME).unwrap_or(server);
218    let unschemed = with_owner(bare, &owner_whole);
219    if length(&unschemed) <= room {
220        return unschemed;
221    }
222    if let Owner::Tenant(id) = owner {
223        let around = length(&with_owner(bare, "tenant ")).saturating_add(length(CUT));
224        let kept = room.saturating_sub(around);
225        if kept >= ID_MIN {
226            let id: String = id.chars().take(kept).collect();
227            return with_owner(bare, &format!("tenant {id}{CUT}"));
228        }
229    }
230    let alone = format!("{bare}{BETWEEN}");
231    if length(&alone) <= room {
232        return alone;
233    }
234    let kept = room.saturating_sub(length(BETWEEN).saturating_add(length(CUT)));
235    let address: String = bare.chars().take(kept).collect();
236    format!("{address}{CUT}{BETWEEN}")
237}
238
239/// The status line: the server, the tenant and the connection, shortened
240/// by [`status_lead`]'s rule when the terminal is narrower than the line.
241fn status(state: &State, columns: u16, theme: Theme) -> Line<'static> {
242    let (owner, word, color) = match &state.connection {
243        Connection::Connecting => (Owner::Unknown, "connecting", Color::Yellow),
244        Connection::Failed(_) => (Owner::Unknown, "not connected", Color::Red),
245        Connection::Connected(info) => (
246            info.tenant
247                .as_deref()
248                .map_or(Owner::Operator, Owner::Tenant),
249            "connected",
250            Color::Green,
251        ),
252    };
253    let lead = status_lead(&state.server, &owner, word, usize::from(columns));
254    let mut style = Style::new().add_modifier(Modifier::BOLD);
255    if theme.color {
256        style = style.fg(color);
257    }
258    Line::from(vec![Span::raw(lead), Span::styled(word, style)])
259}
260
261/// A message in place of a view's content, wrapped to the body.
262fn message(frame: &mut Frame<'_>, body: Rect, lines: Vec<String>) {
263    let lines: Vec<Line<'_>> = lines.into_iter().map(Line::from).collect();
264    frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), body);
265}
266
267/// What a view shows instead of its content while there is no list: the
268/// connecting, loading and error states. `None` when the list is ready.
269fn waiting(state: &State, loading: &str) -> Option<Vec<String>> {
270    if state.connection == Connection::Connecting {
271        return Some(vec![
272            "Connecting to the server...".to_owned(),
273            String::new(),
274            "Press q to quit.".to_owned(),
275        ]);
276    }
277    match &state.listing {
278        Listing::Ready => None,
279        Listing::Loading => Some(vec![
280            loading.to_owned(),
281            String::new(),
282            "Press q to quit.".to_owned(),
283        ]),
284        Listing::Failed(why) => {
285            let mut lines = vec![format!("Could not list vCons: {why}."), String::new()];
286            if why.contains("(401)") {
287                lines
288                    .push("Check that key_file holds a key the server has not revoked.".to_owned());
289            }
290            lines.push("Press r to try again, or q to quit.".to_owned());
291            // The client file, the token and the CA are read once, before
292            // the first screen, so r cannot pick up a corrected file.
293            lines.push(
294                "A change to the client file or the key file takes effect at the next start."
295                    .to_owned(),
296            );
297            Some(lines)
298        }
299    }
300}
301
302/// The list view.
303fn list(frame: &mut Frame<'_>, state: &State, body: Rect) {
304    if let Some(lines) = waiting(state, "Loading vCons...") {
305        return message(frame, body, lines);
306    }
307    if state.rows.is_empty() {
308        let lines = vec![
309            "This tenant has no vCons.".to_owned(),
310            String::new(),
311            "Press r to read again, or q to quit.".to_owned(),
312        ];
313        return message(frame, body, lines);
314    }
315    let times = u16::from(body.width >= UUID_COLUMNS.saturating_add(TIME_COLUMNS)).saturating_add(
316        u16::from(body.width >= UUID_COLUMNS.saturating_add(TIME_COLUMNS.saturating_mul(2))),
317    );
318    let version = body.width
319        >= UUID_COLUMNS
320            .saturating_add(TIME_COLUMNS.saturating_mul(2))
321            .saturating_add(VERSION_COLUMNS);
322    let columns = |marker: &str, uuid: &str, stored: &str, updated: &str, tag: &str| {
323        let mut text = format!("{marker}{uuid:<36}");
324        if times >= 1 {
325            text.push_str(&format!("  {stored:<19}"));
326        }
327        if times >= 2 {
328            text.push_str(&format!("  {updated:<19}"));
329        }
330        if version {
331            text.push_str(&format!("  {tag}"));
332        }
333        text
334    };
335    let visible = usize::from(body.height.saturating_sub(1));
336    let first = state.selected.saturating_add(1).saturating_sub(visible);
337    let mut lines = vec![Line::styled(
338        columns(
339            "  ",
340            "UUID",
341            &format!("STORED ({ZONE})"),
342            &format!("UPDATED ({ZONE})"),
343            "VERSION",
344        ),
345        Style::new().add_modifier(Modifier::BOLD),
346    )];
347    for (index, row) in state.rows.iter().enumerate().skip(first).take(visible) {
348        let selected = index == state.selected;
349        let text = columns(
350            if selected { "> " } else { "  " },
351            &row.uuid,
352            &utc(&row.stored_at),
353            &utc(&row.updated_at),
354            &row.version,
355        );
356        let style = if selected {
357            Style::new().add_modifier(Modifier::REVERSED)
358        } else {
359            Style::new()
360        };
361        lines.push(Line::styled(text, style));
362    }
363    frame.render_widget(Paragraph::new(lines), body);
364}
365
366/// The detail view: the metadata of one vCon, from its row of the list.
367fn detail(frame: &mut Frame<'_>, state: &State, body: Rect) {
368    if let Some(lines) = waiting(state, "Reading the list again...") {
369        return message(frame, body, lines);
370    }
371    let lines = match state.detail_row() {
372        Some(row) => metadata(row),
373        None => vec![
374            "This vCon is no longer in the list: it was deleted, or it is past the pages read."
375                .to_owned(),
376            String::new(),
377            "Press Esc to go back.".to_owned(),
378        ],
379    };
380    message(frame, body, lines);
381}
382
383/// The lines of one vCon's metadata.
384fn metadata(row: &Row) -> Vec<String> {
385    vec![
386        format!("vCon {}", row.uuid),
387        String::new(),
388        format!("Version       {}", row.version),
389        format!("First stored  {} {ZONE}", utc(&row.stored_at)),
390        format!("Last updated  {} {ZONE}", utc(&row.updated_at)),
391        String::new(),
392        "Content is not shown: this view lists metadata only.".to_owned(),
393    ]
394}
395
396/// The help view: every binding, from the table the key reader uses.
397fn help(frame: &mut Frame<'_>, body: Rect) {
398    let mut lines = vec!["Keys".to_owned()];
399    for binding in &BINDINGS {
400        lines.push(format!("  {:<7}{}", binding.label, binding.does));
401    }
402    lines.push(String::new());
403    lines.push(format!("Every time shown is in UTC ({ZONE})."));
404    message(frame, body, lines);
405}
406
407/// The notice above the key hints, as its parts: what went wrong with the
408/// last request, or where the selection is and when the list was read.
409/// [`fitted`] makes lines of them.
410fn notice(state: &State) -> Vec<String> {
411    if let Some(notice) = &state.notice {
412        return vec![notice.clone()];
413    }
414    if state.more {
415        return vec!["Reading the next page...".to_owned()];
416    }
417    let (Listing::Ready, Some(as_of)) = (&state.listing, state.as_of) else {
418        return Vec::new();
419    };
420    let as_of = format!("as of {} {ZONE}", stamp(as_of));
421    if state.rows.is_empty() {
422        return vec![as_of];
423    }
424    let more = if state.next.is_some() {
425        ", more on the server"
426    } else {
427        ""
428    };
429    vec![
430        format!(
431            "{} of {} read{more}",
432            state.selected.saturating_add(1),
433            state.rows.len()
434        ),
435        as_of,
436    ]
437}
438
439/// The key hints of a view, from the bindings, in `columns` columns. Help
440/// and quit end every line. When the line is longer than the terminal is
441/// wide, the hint before those two is left out, then the one before it,
442/// until the line fits: a hint is whole or absent, and `?` lists every key.
443fn hints(view: View, columns: usize) -> String {
444    /// The hints never left out: the last two of a view.
445    const KEPT: usize = 2;
446    let mut shown = view_hints(view);
447    let length = |shown: &[String]| {
448        shown
449            .iter()
450            .map(|hint| hint.chars().count())
451            .sum::<usize>()
452            .saturating_add(shown.len().saturating_sub(1).saturating_mul(2))
453    };
454    while shown.len() > KEPT && length(&shown) > columns {
455        shown.remove(shown.len().saturating_sub(KEPT).saturating_sub(1));
456    }
457    shown.join("  ")
458}
459
460/// Every key hint of a view, each a key and a word.
461fn view_hints(view: View) -> Vec<String> {
462    let actions: &[Action] = match view {
463        View::List => &[
464            Action::Down,
465            Action::Up,
466            Action::Open,
467            Action::Refresh,
468            Action::More,
469            Action::Help,
470            Action::Quit,
471        ],
472        View::Detail => &[
473            Action::Back,
474            Action::Down,
475            Action::Up,
476            Action::Refresh,
477            Action::Help,
478            Action::Quit,
479        ],
480        View::Help => &[Action::Back, Action::Quit],
481    };
482    actions
483        .iter()
484        .filter_map(|action| binding(*action))
485        .map(|binding| format!("{} {}", binding.label, binding.hint))
486        .collect()
487}
488
489#[cfg(test)]
490mod tests {
491    use ratatui::Terminal;
492    use ratatui::backend::TestBackend;
493    use ratatui::buffer::Cell;
494    use ratatui::style::{Color, Modifier};
495    use time::format_description::well_known::Rfc3339;
496    use time::macros::datetime;
497    use time::{Duration, OffsetDateTime};
498
499    use super::{Theme, draw, theme, utc};
500    use crate::tui::client;
501    use crate::tui::keys::BINDINGS;
502    use crate::tui::state::{Action, ApiError, Event, KeyInfo, Page, Row, State};
503
504    const NOW: OffsetDateTime = datetime!(2026-11-10 01:20:00 UTC);
505    const MONO: Theme = Theme { color: false };
506    const COLOR: Theme = Theme { color: true };
507
508    fn row(n: u8) -> Row {
509        Row {
510            uuid: format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc{n:02}"),
511            stored_at: "2026-10-25T12:00:00.123456789Z".to_owned(),
512            updated_at: "2026-10-25T12:30:00Z".to_owned(),
513            version: format!("4f0c4b0a1d2e3f405162738495a6b7{n:02}"),
514        }
515    }
516
517    fn connecting() -> State {
518        State::new("https://vcon.example.com:8443", (80, 24)).0
519    }
520
521    fn connected() -> State {
522        let mut state = connecting();
523        state.step(
524            Event::KeyInfo(Ok(KeyInfo {
525                id: "0123456789abcdef".to_owned(),
526                tenant: Some("t_example".to_owned()),
527                scopes: vec!["read".to_owned()],
528            })),
529            NOW,
530        );
531        state
532    }
533
534    fn listed(rows: u8, next: Option<&str>) -> State {
535        let mut state = connected();
536        state.step(
537            Event::Page(Ok(Page {
538                vcons: (0..rows).map(row).collect(),
539                next: next.map(str::to_owned),
540            })),
541            NOW,
542        );
543        state
544    }
545
546    fn press(mut state: State, actions: &[Action]) -> State {
547        for action in actions {
548            state.step(Event::Action(*action), NOW);
549        }
550        state
551    }
552
553    fn terminal(state: &State, columns: u16, lines: u16, theme: Theme) -> Terminal<TestBackend> {
554        let mut terminal = Terminal::new(TestBackend::new(columns, lines)).expect("a terminal");
555        terminal
556            .draw(|frame| draw(frame, state, theme))
557            .expect("a frame");
558        terminal
559    }
560
561    /// The screen's lines as text.
562    fn screen(state: &State, columns: u16, lines: u16) -> Vec<String> {
563        let terminal = terminal(state, columns, lines, MONO);
564        let buffer = terminal.backend().buffer();
565        (0..lines)
566            .map(|y| (0..columns).map(|x| buffer[(x, y)].symbol()).collect())
567            .collect()
568    }
569
570    fn text(state: &State) -> String {
571        screen(state, 80, 24).join("\n")
572    }
573
574    // Success.
575
576    #[test]
577    fn the_status_line_names_the_server_the_tenant_and_the_connection() {
578        let lines = screen(&listed(1, None), 80, 24);
579        assert!(
580            lines[0].contains("https://vcon.example.com:8443"),
581            "the server: {}",
582            lines[0]
583        );
584        assert!(
585            lines[0].contains("tenant t_example"),
586            "the tenant: {}",
587            lines[0]
588        );
589        assert!(
590            lines[0].contains("connected"),
591            "the connection, in words: {}",
592            lines[0]
593        );
594    }
595
596    #[test]
597    fn the_list_shows_each_vcon_with_its_times_in_utc() {
598        let lines = screen(&listed(2, None), 80, 24);
599        assert!(
600            lines[1].contains("STORED (UTC+00:00)"),
601            "the header states the offset: {}",
602            lines[1]
603        );
604        assert!(
605            lines[2].contains(&row(0).uuid),
606            "the first row's uuid: {}",
607            lines[2]
608        );
609        assert!(
610            lines[2].contains("2026-10-25 12:00:00"),
611            "its stored time: {}",
612            lines[2]
613        );
614        assert!(
615            lines[2].contains("2026-10-25 12:30:00"),
616            "its updated time: {}",
617            lines[2]
618        );
619        assert!(
620            lines[3].contains(&row(1).uuid),
621            "the second row: {}",
622            lines[3]
623        );
624    }
625
626    #[test]
627    fn the_selected_row_is_marked_with_a_character() {
628        let lines = screen(&press(listed(3, None), &[Action::Down]), 80, 24);
629        assert!(
630            lines[3].starts_with("> "),
631            "the selected row has a marker: {}",
632            lines[3]
633        );
634        assert!(
635            lines[2].starts_with("  "),
636            "the others do not: {}",
637            lines[2]
638        );
639    }
640
641    #[test]
642    fn the_list_footer_hints_are_real_bindings() {
643        let lines = screen(&listed(1, None), 80, 24);
644        let footer = &lines[23];
645        for wanted in [Action::Open, Action::Refresh, Action::Help, Action::Quit] {
646            let binding = BINDINGS
647                .iter()
648                .find(|b| b.action == wanted)
649                .expect("a binding");
650            assert!(
651                footer.contains(&format!("{} {}", binding.label, binding.hint)),
652                "the footer shows {wanted:?} as bound: {footer}"
653            );
654        }
655    }
656
657    #[test]
658    fn the_notice_line_says_how_many_are_loaded_and_as_of_when() {
659        let lines = screen(&listed(2, Some("cursor-1")), 80, 24);
660        assert!(lines[22].contains("1 of 2"), "the position: {}", lines[22]);
661        assert!(
662            lines[22].contains("more on the server"),
663            "that more exist: {}",
664            lines[22]
665        );
666        assert!(
667            lines[22].contains("as of 2026-11-10 01:20:00 UTC+00:00"),
668            "when it was read, with the offset: {}",
669            lines[22]
670        );
671    }
672
673    #[test]
674    fn the_detail_view_shows_the_metadata_and_says_content_is_not_shown() {
675        let shown = text(&press(listed(2, None), &[Action::Open]));
676        assert!(shown.contains(&row(0).uuid), "the uuid: {shown}");
677        assert!(shown.contains(&row(0).version), "the version: {shown}");
678        assert!(
679            shown.contains("2026-10-25 12:00:00 UTC+00:00"),
680            "first stored: {shown}"
681        );
682        assert!(
683            shown.contains("2026-10-25 12:30:00 UTC+00:00"),
684            "last updated: {shown}"
685        );
686        assert!(
687            shown.contains("Content is not shown"),
688            "what is left out: {shown}"
689        );
690        assert!(shown.contains("Esc back"), "how to leave: {shown}");
691    }
692
693    #[test]
694    fn the_help_view_lists_every_binding() {
695        let shown = text(&press(listed(1, None), &[Action::Help]));
696        for binding in &BINDINGS {
697            assert!(
698                shown.contains(binding.label),
699                "{} is listed: {shown}",
700                binding.label
701            );
702            assert!(
703                shown.contains(binding.does),
704                "{} is described: {shown}",
705                binding.does
706            );
707        }
708    }
709
710    #[test]
711    fn the_list_scrolls_to_keep_the_selection_on_screen() {
712        let state = press(listed(60, None), &[Action::Bottom]);
713        let shown = text(&state);
714        assert!(
715            shown.contains(&format!("> {}", row(59).uuid)),
716            "the last row is drawn selected"
717        );
718        assert!(
719            !shown.contains(&row(0).uuid),
720            "the first row has scrolled off"
721        );
722    }
723
724    #[test]
725    fn with_color_the_connection_is_colored_and_still_in_words() {
726        let state = listed(1, None);
727        let terminal = terminal(&state, 80, 24, COLOR);
728        let buffer = terminal.backend().buffer();
729        let colored = (0..80).any(|x| buffer[(x, 0)].fg != Color::Reset);
730        assert!(colored, "a color terminal gets color");
731        assert!(
732            screen(&state, 80, 24)[0].contains("connected"),
733            "and the word is still there"
734        );
735    }
736
737    #[test]
738    fn rfc_3339_times_are_shown_to_the_second_in_utc() {
739        assert_eq!(
740            utc("2026-10-25T12:00:00.123456789Z"),
741            "2026-10-25 12:00:00",
742            "fractions dropped"
743        );
744        assert_eq!(
745            utc("2026-10-25T14:30:00+02:00"),
746            "2026-10-25 12:30:00",
747            "an offset is converted"
748        );
749    }
750
751    #[test]
752    fn a_color_terminal_gets_color() {
753        assert_eq!(
754            theme(None, Some("xterm-256color")),
755            COLOR,
756            "nothing asks for none"
757        );
758    }
759
760    #[test]
761    fn a_wider_terminal_shows_the_version_column() {
762        let lines = screen(&listed(1, None), 132, 43);
763        assert!(lines[1].contains("VERSION"), "the header: {}", lines[1]);
764        assert!(
765            lines[2].contains(&row(0).version),
766            "the version: {}",
767            lines[2]
768        );
769    }
770
771    // Failure.
772
773    #[test]
774    fn a_failed_connection_is_said_in_the_status_line_and_the_list() {
775        let mut state = connecting();
776        state.step(
777            Event::KeyInfo(Err(ApiError::Unreachable("connection refused".to_owned()))),
778            NOW,
779        );
780        let lines = screen(&state, 80, 24);
781        assert!(
782            lines[0].contains("not connected"),
783            "the status line: {}",
784            lines[0]
785        );
786        let shown = lines.join("\n");
787        assert!(shown.contains("connection refused"), "why: {shown}");
788        assert!(
789            shown.contains("Press r to try again"),
790            "what to press: {shown}"
791        );
792    }
793
794    #[test]
795    fn a_long_error_wraps_instead_of_being_cut() {
796        let mut state = connected();
797        let long = format!("{} the-end", "word ".repeat(30));
798        state.step(Event::Page(Err(ApiError::Malformed(long))), NOW);
799        assert!(
800            text(&state).contains("the-end"),
801            "the whole reason is on screen"
802        );
803    }
804
805    #[test]
806    fn an_operator_key_is_named_in_the_status_line() {
807        let mut state = connecting();
808        state.step(
809            Event::KeyInfo(Ok(KeyInfo {
810                id: "0123456789abcdef".to_owned(),
811                tenant: None,
812                scopes: vec!["admin".to_owned()],
813            })),
814            NOW,
815        );
816        let lines = screen(&state, 80, 24);
817        assert!(
818            lines[0].contains("no tenant (operator key)"),
819            "the status line: {}",
820            lines[0]
821        );
822        assert!(
823            lines
824                .join("\n")
825                .contains("this is an operator key, which reaches no vCon"),
826            "and the list says why it is empty"
827        );
828    }
829
830    #[test]
831    fn a_failed_next_page_shows_its_notice_over_the_rows() {
832        let mut state = press(listed(2, Some("cursor-1")), &[Action::More]);
833        state.step(
834            Event::Page(Err(ApiError::Unreachable("timed out".to_owned()))),
835            NOW,
836        );
837        let lines = screen(&state, 80, 24);
838        assert!(
839            lines[22].contains("The next page was not read"),
840            "the notice: {}",
841            lines[22]
842        );
843        assert!(
844            lines[2].contains(&row(0).uuid),
845            "the rows stay: {}",
846            lines[2]
847        );
848    }
849
850    #[test]
851    fn the_detail_of_a_vcon_no_longer_listed_says_so() {
852        let mut state = press(listed(2, None), &[Action::Open, Action::Refresh]);
853        state.step(
854            Event::Page(Ok(Page {
855                vcons: vec![row(1)],
856                next: None,
857            })),
858            NOW,
859        );
860        let shown = text(&state);
861        assert!(
862            shown.contains("no longer in the list"),
863            "what happened: {shown}"
864        );
865        assert!(
866            shown.contains("Press Esc to go back"),
867            "what to press: {shown}"
868        );
869    }
870
871    #[test]
872    fn the_detail_view_shows_a_failed_refresh() {
873        let mut state = press(listed(2, None), &[Action::Open, Action::Refresh]);
874        state.step(Event::Page(Err(ApiError::Status(503, None))), NOW);
875        let shown = text(&state);
876        assert!(shown.contains("the server answered 503"), "why: {shown}");
877        assert!(
878            shown.contains("Press r to try again"),
879            "what to press: {shown}"
880        );
881    }
882
883    #[test]
884    fn a_terminal_too_small_says_so_and_how_to_quit() {
885        let lines = screen(&listed(3, None), 30, 5);
886        let shown = lines.join("\n");
887        assert!(shown.contains("too small"), "what is wrong: {shown}");
888        assert!(shown.contains("q"), "the way out: {shown}");
889        assert!(!shown.contains("01a07da8"), "no half-drawn list");
890    }
891
892    #[test]
893    fn a_time_that_does_not_parse_is_shown_as_sent() {
894        assert_eq!(utc("yesterday"), "yesterday", "nothing is invented for it");
895    }
896
897    #[test]
898    fn a_refused_key_says_to_check_the_key_file() {
899        let mut state = connecting();
900        state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
901        let shown = text(&state);
902        assert!(shown.contains("refused the key (401)"), "why: {shown}");
903        assert!(shown.contains("key_file"), "where to look: {shown}");
904    }
905
906    // Edge.
907
908    #[test]
909    fn the_loading_state_says_so_and_how_to_quit() {
910        let shown = text(&connected());
911        assert!(
912            shown.contains("Loading vCons"),
913            "what is happening: {shown}"
914        );
915        assert!(shown.contains("q quit"), "the way out: {shown}");
916    }
917
918    #[test]
919    fn the_connecting_state_is_in_the_status_line() {
920        let lines = screen(&connecting(), 80, 24);
921        assert!(
922            lines[0].contains("connecting"),
923            "the status line: {}",
924            lines[0]
925        );
926        assert!(
927            lines.join("\n").contains("Connecting to the server"),
928            "and the body"
929        );
930    }
931
932    #[test]
933    fn an_empty_tenant_says_so_and_what_to_press() {
934        let shown = text(&listed(0, None));
935        assert!(
936            shown.contains("This tenant has no vCons"),
937            "what happened: {shown}"
938        );
939        assert!(
940            shown.contains("Press r to read again"),
941            "what to press: {shown}"
942        );
943    }
944
945    #[test]
946    fn the_detail_view_says_refreshing_while_a_refresh_is_in_flight() {
947        let shown = text(&press(listed(2, None), &[Action::Open, Action::Refresh]));
948        assert!(
949            shown.contains("Reading the list again"),
950            "what is happening: {shown}"
951        );
952    }
953
954    #[test]
955    fn at_80_columns_every_list_column_fits() {
956        let lines = screen(&listed(1, None), 80, 24);
957        assert!(
958            lines[2].trim_end().ends_with("2026-10-25 12:30:00"),
959            "the last column is whole: {}",
960            lines[2]
961        );
962    }
963
964    #[test]
965    fn below_80_columns_the_updated_column_is_dropped_not_cut() {
966        let lines = screen(&listed(1, None), 60, 24);
967        assert!(
968            lines[2].contains("2026-10-25 12:00:00"),
969            "stored stays: {}",
970            lines[2]
971        );
972        assert!(
973            !lines[2].contains("2026-10-25 12:3"),
974            "no part of updated: {}",
975            lines[2]
976        );
977        assert!(
978            !lines[1].contains("UPDATED"),
979            "nor its header: {}",
980            lines[1]
981        );
982    }
983
984    #[test]
985    fn every_size_from_1x1_up_draws_without_a_panic() {
986        let states = [
987            connecting(),
988            listed(0, None),
989            listed(60, Some("cursor-1")),
990            press(listed(3, None), &[Action::Open]),
991            press(listed(3, None), &[Action::Help]),
992        ];
993        for state in &states {
994            for columns in [1, 2, 10, 39, 40, 79, 80, 200] {
995                for lines in [1, 2, 7, 8, 24, 60] {
996                    let drawn = screen(state, columns, lines);
997                    assert_eq!(
998                        drawn.len(),
999                        usize::from(lines),
1000                        "{columns}x{lines} drew a frame"
1001                    );
1002                }
1003            }
1004        }
1005    }
1006
1007    #[test]
1008    fn no_color_and_a_dumb_terminal_turn_color_off() {
1009        assert_eq!(
1010            theme(Some("1"), Some("xterm-256color")),
1011            MONO,
1012            "NO_COLOR set"
1013        );
1014        assert_eq!(theme(None, Some("dumb")), MONO, "a terminal with no color");
1015        assert_eq!(theme(None, None), MONO, "no TERM at all");
1016        assert_eq!(
1017            theme(Some(""), Some("xterm")),
1018            COLOR,
1019            "an empty NO_COLOR is not set"
1020        );
1021    }
1022
1023    #[test]
1024    fn without_color_no_cell_has_a_color() {
1025        for state in [
1026            listed(3, None),
1027            press(listed(3, None), &[Action::Help]),
1028            connecting(),
1029        ] {
1030            let terminal = terminal(&state, 80, 24, MONO);
1031            let buffer = terminal.backend().buffer();
1032            for cell in buffer.content() {
1033                assert_eq!(cell.fg, Color::Reset, "no foreground color");
1034                assert_eq!(cell.bg, Color::Reset, "no background color");
1035            }
1036        }
1037    }
1038
1039    #[test]
1040    fn the_status_line_keeps_the_connection_when_the_address_is_long() {
1041        let mut state = State::new(
1042            &format!("https://{}.example.com:8443", "a".repeat(90)),
1043            (80, 24),
1044        )
1045        .0;
1046        state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
1047        let lines = screen(&state, 80, 24);
1048        assert!(
1049            lines[0].contains("not connected"),
1050            "the state is never pushed off: {}",
1051            lines[0]
1052        );
1053    }
1054
1055    // The status line at each width. The rule: the connection is never
1056    // shortened; then the server's address; then the tenant.
1057
1058    const SERVER: &str = "https://vcon.example.com:8443";
1059    const LONG_ID: &str = "658a6d102142fea77f47ee8a332323d8";
1060
1061    /// A state for the server at `server` whose key answered with `tenant`.
1062    fn keyed(server: &str, tenant: Option<&str>) -> State {
1063        let mut state = State::new(server, (80, 24)).0;
1064        state.step(
1065            Event::KeyInfo(Ok(KeyInfo {
1066                id: "0123456789abcdef".to_owned(),
1067                tenant: tenant.map(str::to_owned),
1068                scopes: vec!["read".to_owned()],
1069            })),
1070            NOW,
1071        );
1072        state
1073    }
1074
1075    /// A state whose server refused the key.
1076    fn refused(server: &str) -> State {
1077        let mut state = State::new(server, (80, 24)).0;
1078        state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
1079        state
1080    }
1081
1082    /// The status line of `state` in a terminal of `columns`.
1083    fn status_at(state: &State, columns: u16) -> String {
1084        screen(state, columns, 24)[0].trim_end().to_owned()
1085    }
1086
1087    #[test]
1088    fn at_120_columns_the_status_line_is_whole() {
1089        assert_eq!(
1090            status_at(&keyed(SERVER, Some(LONG_ID)), 120),
1091            format!("{SERVER} | tenant {LONG_ID} | connected"),
1092            "everything fits"
1093        );
1094    }
1095
1096    #[test]
1097    fn at_80_columns_the_address_loses_only_its_scheme() {
1098        assert_eq!(
1099            status_at(&keyed(SERVER, Some(LONG_ID)), 80),
1100            format!("vcon.example.com:8443 | tenant {LONG_ID} | connected"),
1101            "https:// says nothing a reader needs: every address has it"
1102        );
1103    }
1104
1105    #[test]
1106    fn at_60_columns_the_tenant_id_is_shortened_and_the_address_is_not() {
1107        assert_eq!(
1108            status_at(&keyed(SERVER, Some(LONG_ID)), 60),
1109            "vcon.example.com:8443 | tenant 658a6d102142fe... | connected",
1110            "the tenant gives way before the server does"
1111        );
1112    }
1113
1114    #[test]
1115    fn at_40_columns_the_tenant_is_left_out_and_the_address_is_not() {
1116        assert_eq!(
1117            status_at(&keyed(SERVER, Some(LONG_ID)), 40),
1118            "vcon.example.com:8443 | connected",
1119            "the server and the connection"
1120        );
1121    }
1122
1123    #[test]
1124    fn a_line_that_fits_exactly_keeps_its_scheme() {
1125        assert_eq!(
1126            status_at(&keyed(SERVER, Some(LONG_ID)), 83),
1127            format!("{SERVER} | tenant {LONG_ID} | connected"),
1128            "83 characters in 83 columns"
1129        );
1130    }
1131
1132    #[test]
1133    fn a_short_tenant_id_is_whole_at_60_columns() {
1134        assert_eq!(
1135            status_at(&keyed(SERVER, Some("t_example")), 60),
1136            format!("{SERVER} | tenant t_example | connected"),
1137            "60 characters in 60 columns"
1138        );
1139    }
1140
1141    #[test]
1142    fn an_address_with_a_path_is_shown_with_it() {
1143        let line = status_at(
1144            &keyed("https://vcon.example.com:8443/base", Some("t_example")),
1145            120,
1146        );
1147        assert!(
1148            line.starts_with("https://vcon.example.com:8443/base | "),
1149            "the path is part of the address: {line}"
1150        );
1151    }
1152
1153    #[test]
1154    fn a_refused_key_at_40_columns_shows_the_address_and_not_connected() {
1155        assert_eq!(
1156            status_at(&refused(SERVER), 40),
1157            "vcon.example.com:8443 | not connected",
1158            "`tenant unknown` is the part left out"
1159        );
1160    }
1161
1162    #[test]
1163    fn a_refused_key_at_60_columns_keeps_tenant_unknown() {
1164        assert_eq!(
1165            status_at(&refused(SERVER), 60),
1166            "vcon.example.com:8443 | tenant unknown | not connected",
1167            "without the scheme the three parts fit"
1168        );
1169    }
1170
1171    #[test]
1172    fn a_refused_key_at_80_columns_is_whole() {
1173        assert_eq!(
1174            status_at(&refused(SERVER), 80),
1175            format!("{SERVER} | tenant unknown | not connected"),
1176            "everything fits"
1177        );
1178    }
1179
1180    #[test]
1181    fn connecting_at_40_columns_shows_the_address_and_connecting() {
1182        assert_eq!(
1183            status_at(&State::new(SERVER, (40, 24)).0, 40),
1184            "vcon.example.com:8443 | connecting",
1185            "`tenant unknown` is the part left out"
1186        );
1187    }
1188
1189    #[test]
1190    fn an_operator_key_at_60_columns_is_named_whole() {
1191        assert_eq!(
1192            status_at(&keyed(SERVER, None), 60),
1193            "vcon.example.com:8443 | no tenant (operator key) | connected",
1194            "60 characters in 60 columns"
1195        );
1196    }
1197
1198    #[test]
1199    fn an_operator_key_at_40_columns_is_left_out_not_cut() {
1200        assert_eq!(
1201            status_at(&keyed(SERVER, None), 40),
1202            "vcon.example.com:8443 | connected",
1203            "a phrase is whole or absent"
1204        );
1205    }
1206
1207    #[test]
1208    fn a_long_address_is_cut_at_its_end_and_the_connection_is_whole() {
1209        let server = format!("https://{}.example.com:8443", "a".repeat(90));
1210        assert_eq!(
1211            status_at(&refused(&server), 40),
1212            format!("{}... | not connected", "a".repeat(21)),
1213            "40 columns: 21 of the address, the mark, and the connection"
1214        );
1215    }
1216
1217    #[test]
1218    fn four_characters_of_a_tenant_id_are_the_fewest_shown() {
1219        assert_eq!(
1220            status_at(&keyed(SERVER, Some(LONG_ID)), 50),
1221            "vcon.example.com:8443 | tenant 658a... | connected",
1222            "50 columns leave room for four"
1223        );
1224    }
1225
1226    #[test]
1227    fn a_tenant_id_with_room_for_three_characters_is_left_out() {
1228        assert_eq!(
1229            status_at(&keyed(SERVER, Some(LONG_ID)), 49),
1230            "vcon.example.com:8443 | connected",
1231            "three characters name no tenant"
1232        );
1233    }
1234
1235    #[test]
1236    fn one_column_short_of_whole_the_scheme_goes_first() {
1237        assert_eq!(
1238            status_at(&keyed(SERVER, Some(LONG_ID)), 82),
1239            format!("vcon.example.com:8443 | tenant {LONG_ID} | connected"),
1240            "the tenant id stays whole"
1241        );
1242    }
1243
1244    #[test]
1245    fn one_column_short_of_a_whole_id_shortens_it_to_fit() {
1246        let line = status_at(&keyed(SERVER, Some(LONG_ID)), 74);
1247        assert_eq!(
1248            line,
1249            format!(
1250                "vcon.example.com:8443 | tenant {}... | connected",
1251                &LONG_ID[..28]
1252            ),
1253            "74 columns: 28 characters and the mark"
1254        );
1255    }
1256
1257    #[test]
1258    fn an_address_that_is_not_https_is_shown_as_it_is() {
1259        assert_eq!(
1260            status_at(&refused("vcon.example.com:8443"), 40),
1261            "vcon.example.com:8443 | not connected",
1262            "there is no scheme to leave out"
1263        );
1264    }
1265
1266    #[test]
1267    fn an_address_that_fits_exactly_at_40_columns_is_whole() {
1268        let server = format!("https://{}", "b".repeat(28));
1269        assert_eq!(
1270            status_at(&keyed(&server, Some(LONG_ID)), 40),
1271            format!("{} | connected", "b".repeat(28)),
1272            "28 characters, the separator and the connection are 40"
1273        );
1274    }
1275
1276    #[test]
1277    fn the_status_line_fits_and_ends_with_the_connection_at_every_width() {
1278        let long = format!("https://{}.example.com:8443", "a".repeat(90));
1279        for server in [SERVER, long.as_str()] {
1280            let states = [
1281                (State::new(server, (80, 24)).0, "connecting"),
1282                (refused(server), "not connected"),
1283                (keyed(server, Some(LONG_ID)), "connected"),
1284                (keyed(server, None), "connected"),
1285            ];
1286            for (state, word) in &states {
1287                for columns in 40..=130 {
1288                    let line = status_at(state, columns);
1289                    assert!(
1290                        line.chars().count() <= usize::from(columns),
1291                        "{columns} columns: {line}"
1292                    );
1293                    assert!(
1294                        line.ends_with(&format!(" | {word}")),
1295                        "{columns} columns, the connection is whole and last: {line}"
1296                    );
1297                }
1298            }
1299        }
1300    }
1301
1302    #[test]
1303    fn a_tenant_phrase_is_whole_or_absent_at_every_width() {
1304        for (state, phrase) in [
1305            (refused(SERVER), "tenant unknown"),
1306            (keyed(SERVER, None), "no tenant (operator key)"),
1307        ] {
1308            for columns in 40..=130 {
1309                let line = status_at(&state, columns);
1310                assert!(
1311                    line.contains(phrase) || !line.contains("tenant"),
1312                    "{columns} columns: {line}"
1313                );
1314            }
1315        }
1316    }
1317
1318    #[test]
1319    fn the_help_view_states_the_time_zone() {
1320        let shown = text(&press(listed(1, None), &[Action::Help]));
1321        assert!(
1322            shown.contains("UTC+00:00"),
1323            "times are UTC, stated: {shown}"
1324        );
1325    }
1326
1327    // The last two lines in a narrow terminal.
1328
1329    /// The last line of the screen: the key hints.
1330    fn footer_at(state: &State, columns: u16) -> String {
1331        screen(state, columns, 24)[23].trim_end().to_owned()
1332    }
1333
1334    #[test]
1335    fn at_40_columns_the_list_footer_still_shows_help_and_quit() {
1336        let footer = footer_at(&listed(2, None), 40);
1337        assert!(
1338            footer.ends_with("? help  q quit"),
1339            "how to get help and how to leave are whole: {footer:?}"
1340        );
1341        assert!(
1342            footer.starts_with("j down  k up"),
1343            "the first keys stay first: {footer:?}"
1344        );
1345    }
1346
1347    #[test]
1348    fn at_40_columns_the_detail_footer_still_shows_help_and_quit() {
1349        let footer = footer_at(&press(listed(2, None), &[Action::Open]), 40);
1350        assert!(
1351            footer.ends_with("? help  q quit"),
1352            "how to get help and how to leave are whole: {footer:?}"
1353        );
1354        assert!(
1355            footer.starts_with("Esc back"),
1356            "how to go back stays first: {footer:?}"
1357        );
1358    }
1359
1360    #[test]
1361    fn at_80_columns_the_footers_are_whole() {
1362        assert_eq!(
1363            footer_at(&listed(2, None), 80),
1364            "j down  k up  Enter open  r refresh  n more  ? help  q quit",
1365            "the list's keys"
1366        );
1367        assert_eq!(
1368            footer_at(&press(listed(2, None), &[Action::Open]), 80),
1369            "Esc back  j down  k up  r refresh  ? help  q quit",
1370            "the detail's keys"
1371        );
1372        assert_eq!(
1373            footer_at(&press(listed(2, None), &[Action::Help]), 80),
1374            "Esc back  q quit",
1375            "help's keys"
1376        );
1377    }
1378
1379    #[test]
1380    fn no_footer_ends_in_a_cut_hint_at_any_width() {
1381        for view in [&[][..], &[Action::Open][..], &[Action::Help][..]] {
1382            let state = press(listed(2, None), view);
1383            for columns in 40..=100 {
1384                let footer = footer_at(&state, columns);
1385                assert!(
1386                    footer.ends_with("q quit"),
1387                    "at {columns} columns the last hint is whole: {footer:?}"
1388                );
1389                assert!(
1390                    footer.chars().count() <= usize::from(columns),
1391                    "at {columns} columns the footer fits: {footer:?}"
1392                );
1393            }
1394        }
1395    }
1396
1397    #[test]
1398    fn one_column_short_of_the_whole_list_footer_drops_one_hint() {
1399        assert_eq!(
1400            footer_at(&listed(2, None), 58),
1401            "j down  k up  Enter open  r refresh  ? help  q quit",
1402            "the hint before help goes first"
1403        );
1404        assert_eq!(
1405            footer_at(&listed(2, None), 59),
1406            "j down  k up  Enter open  r refresh  n more  ? help  q quit",
1407            "at its own width the footer is whole"
1408        );
1409    }
1410
1411    /// The text of the lines from `first` on, without the key hints, joined
1412    /// as a reader reads a wrapped sentence.
1413    fn joined(lines: &[String], first: usize) -> String {
1414        lines[first..lines.len().saturating_sub(1)]
1415            .iter()
1416            .map(|line| line.trim())
1417            .collect::<Vec<_>>()
1418            .join(" ")
1419    }
1420
1421    #[test]
1422    fn a_notice_longer_than_the_terminal_is_wrapped_not_cut() {
1423        let mut state = press(listed(2, Some("cursor-1")), &[Action::More]);
1424        state.step(
1425            Event::Page(Err(ApiError::Unreachable(
1426                "error sending request for url (https://vcon.example.com:8443/vcons): client error (Connect): tcp connect error: Connection refused (os error 111)".to_owned(),
1427            ))),
1428            NOW,
1429        );
1430        let lines = screen(&state, 80, 24);
1431        let said = joined(&lines, 19);
1432        assert!(
1433            said.contains("The next page was not read: the server did not answer: ")
1434                && said.ends_with("Connection refused (os error 111)."),
1435            "the whole sentence is on screen, to its end: {said}"
1436        );
1437        assert!(
1438            lines[2].contains(&row(0).uuid),
1439            "the rows stay: {}",
1440            lines[2]
1441        );
1442    }
1443
1444    #[test]
1445    fn a_short_notice_takes_one_line() {
1446        let mut state = press(listed(2, Some("cursor-1")), &[Action::More]);
1447        state.step(
1448            Event::Page(Err(ApiError::Unreachable("timed out".to_owned()))),
1449            NOW,
1450        );
1451        let lines = screen(&state, 80, 24);
1452        assert!(
1453            lines[22].starts_with("The next page was not read"),
1454            "on the line above the key hints: {}",
1455            lines[22]
1456        );
1457        assert_eq!(lines[21].trim(), "", "and the line above it is empty");
1458    }
1459
1460    #[test]
1461    fn at_60_columns_the_position_line_keeps_when_the_list_was_read() {
1462        let lines = screen(&listed(2, Some("cursor-1")), 60, 24);
1463        let said = joined(&lines, 20);
1464        assert!(
1465            said.contains("1 of 2 read, more on the server")
1466                && said.ends_with("as of 2026-11-10 01:20:00 UTC+00:00"),
1467            "the position and the time are whole: {said}"
1468        );
1469    }
1470
1471    // A failure whose remedy is in a file the UI read at start.
1472
1473    /// What `r` cannot do, as the screen says it.
1474    const AT_START: &str =
1475        "A change to the client file or the key file takes effect at the next start.";
1476
1477    #[test]
1478    fn a_refused_key_says_that_a_new_key_file_needs_a_new_start() {
1479        let shown = text(&shown_refusal(ApiError::Status(401, None)));
1480        assert!(
1481            shown.contains(AT_START),
1482            "the token is read once, so r cannot read a corrected key file: {shown}"
1483        );
1484    }
1485
1486    #[test]
1487    fn a_refused_certificate_says_that_a_new_ca_needs_a_new_start() {
1488        let advice =
1489            client::certificate_advice(&rustls::CertificateError::UnknownIssuer).expect("advice");
1490        let shown = text(&shown_refusal(ApiError::Untrusted(advice.to_owned())));
1491        assert!(
1492            shown
1493                .replace('\n', " ")
1494                .contains("set ca in the client file")
1495                && shown.contains(AT_START),
1496            "the advice names the client file, which is read once: {shown}"
1497        );
1498    }
1499
1500    #[test]
1501    fn a_key_that_may_not_list_says_that_another_key_needs_a_new_start() {
1502        for state in [
1503            shown_key(None, &[]),
1504            shown_key(Some(SHOWN_TENANT), &["write"]),
1505        ] {
1506            let shown = text(&state);
1507            assert!(
1508                shown.contains(AT_START),
1509                "another key is another key file, read at start: {shown}"
1510            );
1511        }
1512    }
1513
1514    #[test]
1515    fn a_failure_still_names_r_and_q() {
1516        let shown = text(&shown_refusal(client::no_answer(client::TIMEOUT)));
1517        assert!(
1518            shown.contains("Press r to try again, or q to quit."),
1519            "a server that did not answer may answer the next request: {shown}"
1520        );
1521    }
1522
1523    #[test]
1524    fn an_empty_tenant_does_not_mention_the_files() {
1525        let shown = text(&shown_page(
1526            shown_key(Some(SHOWN_TENANT), &["read"]),
1527            0..0,
1528            false,
1529        ));
1530        assert!(
1531            !shown.contains(AT_START),
1532            "nothing failed, so there is nothing to correct: {shown}"
1533        );
1534    }
1535
1536    // The screens the site shows.
1537
1538    /// The file the terminal UI's page and the home page draw their screens
1539    /// from: `tui_screen` in website/templates/components.html.
1540    fn screens_file() -> std::path::PathBuf {
1541        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../website/data/tui-screens.json")
1542    }
1543
1544    /// A tenant's first page of 100 vCons, newest first, with more on the
1545    /// server, and the third one selected: the list the site shows.
1546    fn shown_list() -> State {
1547        let state = shown_page(shown_key(Some(SHOWN_TENANT), &["read"]), 0..100, true);
1548        press(state, &[Action::Down, Action::Down])
1549    }
1550
1551    /// The tenant of the screens the site shows.
1552    const SHOWN_TENANT: &str = "8c41f2d9a07e4b5c9d13e6f0a2b4c7d8";
1553
1554    /// The state once the server has answered for a key of `tenant` (an
1555    /// operator key has none) that holds `scopes`.
1556    fn shown_key(tenant: Option<&str>, scopes: &[&str]) -> State {
1557        let mut state = connecting();
1558        state.step(
1559            Event::KeyInfo(Ok(KeyInfo {
1560                id: "5b0c3f9a1d2e4f60".to_owned(),
1561                tenant: tenant.map(str::to_owned),
1562                scopes: scopes.iter().map(|scope| (*scope).to_owned()).collect(),
1563            })),
1564            NOW,
1565        );
1566        state
1567    }
1568
1569    /// `state` after a page with the vCons `rows` arrived, with `more` on
1570    /// the server or not.
1571    fn shown_page(mut state: State, rows: std::ops::Range<u64>, more: bool) -> State {
1572        state.step(
1573            Event::Page(Ok(Page {
1574                vcons: rows.map(shown_row).collect(),
1575                next: more.then(|| "cursor-2".to_owned()),
1576            })),
1577            NOW,
1578        );
1579        state
1580    }
1581
1582    /// The state at start when the server's answer for the key is `error`.
1583    fn shown_refusal(error: ApiError) -> State {
1584        let mut state = connecting();
1585        state.step(Event::KeyInfo(Err(error)), NOW);
1586        state
1587    }
1588
1589    /// Every screen the site shows: its name in the file, the state drawn,
1590    /// and the terminal's columns and lines.
1591    fn shown_screens() -> Vec<(&'static str, State, u16, u16)> {
1592        let reader = || shown_key(Some(SHOWN_TENANT), &["read"]);
1593        let no_answer = || client::no_answer(client::TIMEOUT);
1594        let mut next_page_failed = press(shown_list(), &[Action::More]);
1595        next_page_failed.step(Event::Page(Err(no_answer())), NOW);
1596        // The vCon open in the detail view is deleted; r reads a list
1597        // without it.
1598        let detail_gone = shown_page(
1599            press(shown_list(), &[Action::Open, Action::Refresh]),
1600            3..100,
1601            true,
1602        );
1603        let unknown_issuer = client::certificate_advice(&rustls::CertificateError::UnknownIssuer)
1604            .expect("advice for a certificate no trusted authority signed");
1605        vec![
1606            ("list", shown_list(), 80, 24),
1607            ("detail", press(shown_list(), &[Action::Open]), 80, 24),
1608            ("help", press(shown_list(), &[Action::Help]), 80, 24),
1609            ("list-end", shown_page(reader(), 0..3, false), 80, 10),
1610            (
1611                "more-read",
1612                shown_page(press(shown_list(), &[Action::More]), 100..200, false),
1613                80,
1614                10,
1615            ),
1616            ("empty", shown_page(reader(), 0..0, false), 80, 10),
1617            ("not-connected", shown_refusal(no_answer()), 80, 10),
1618            (
1619                "refused-key",
1620                shown_refusal(ApiError::Status(401, None)),
1621                80,
1622                10,
1623            ),
1624            (
1625                "refused-certificate",
1626                shown_refusal(ApiError::Untrusted(unknown_issuer.to_owned())),
1627                80,
1628                10,
1629            ),
1630            ("operator-key", shown_key(None, &[]), 80, 10),
1631            ("next-page-failed", next_page_failed, 80, 10),
1632            ("detail-gone", detail_gone, 80, 10),
1633            ("narrow", shown_list(), 60, 10),
1634            ("narrowest", shown_list(), 40, 10),
1635            ("wide", shown_list(), 120, 10),
1636            ("too-small", shown_list(), 36, 6),
1637        ]
1638    }
1639
1640    /// The `n`th vCon of the shown list: a version 8 uuid made from `n`,
1641    /// stored 37 minutes before the one above it, some updated since.
1642    fn shown_row(n: u64) -> Row {
1643        let mix = n
1644            .wrapping_add(1)
1645            .wrapping_mul(0x9e37_79b9_7f4a_7c15)
1646            .rotate_left(17);
1647        let minutes = i64::try_from(n).expect("a small number").saturating_mul(37);
1648        let stored = NOW
1649            - Duration::minutes(minutes.saturating_add(11))
1650            - Duration::seconds(i64::try_from(mix % 60).expect("under 60"));
1651        let updated =
1652            stored + Duration::minutes(i64::try_from(n % 4).expect("under 4").saturating_mul(6));
1653        let time = |at: OffsetDateTime| at.format(&Rfc3339).expect("an RFC 3339 time");
1654        Row {
1655            uuid: format!(
1656                "{:08x}-{:04x}-8{:03x}-b{:03x}-{:012x}",
1657                mix >> 32,
1658                (mix >> 16) & 0xffff,
1659                mix & 0xfff,
1660                (mix >> 20) & 0xfff,
1661                mix.rotate_left(29) & 0xffff_ffff_ffff
1662            ),
1663            stored_at: time(stored),
1664            updated_at: time(updated),
1665            version: format!("{mix:016x}{:016x}", mix.rotate_left(7)),
1666        }
1667    }
1668
1669    /// The class names website/sass/style.scss styles a cell with.
1670    fn classes(cell: &Cell) -> String {
1671        assert_eq!(cell.bg, Color::Reset, "the site draws no background color");
1672        let mut out = Vec::new();
1673        if cell.modifier.contains(Modifier::BOLD) {
1674            out.push("bold");
1675        }
1676        if cell.modifier.contains(Modifier::REVERSED) {
1677            out.push("reversed");
1678        }
1679        match cell.fg {
1680            Color::Reset => {}
1681            Color::Green => out.push("green"),
1682            Color::Yellow => out.push("yellow"),
1683            Color::Red => out.push("red"),
1684            other => panic!("the site has no class for {other:?}"),
1685        }
1686        out.join(" ")
1687    }
1688
1689    /// The screen, in color, in a terminal of `columns` by `rows`: each line as runs of text that
1690    /// share one style, without the plain blanks that end a line.
1691    fn styled(state: &State, columns: u16, rows: u16) -> serde_json::Value {
1692        let terminal = terminal(state, columns, rows, COLOR);
1693        let buffer = terminal.backend().buffer();
1694        let lines: Vec<serde_json::Value> = (0..rows)
1695            .map(|y| {
1696                let mut runs: Vec<(String, String)> = Vec::new();
1697                for x in 0..columns {
1698                    let cell = &buffer[(x, y)];
1699                    let class = classes(cell);
1700                    match runs.last_mut() {
1701                        Some((last, text)) if *last == class => text.push_str(cell.symbol()),
1702                        _ => runs.push((class, cell.symbol().to_owned())),
1703                    }
1704                }
1705                if let Some((class, text)) = runs.last_mut()
1706                    && class.is_empty()
1707                {
1708                    text.truncate(text.trim_end().len());
1709                }
1710                runs.retain(|(_, text)| !text.is_empty());
1711                runs.into_iter()
1712                    .map(|(class, text)| serde_json::json!({"class": class, "text": text}))
1713                    .collect()
1714            })
1715            .collect();
1716        serde_json::json!({"columns": columns, "lines": lines})
1717    }
1718
1719    #[test]
1720    fn the_site_shows_the_screens_draw_makes() {
1721        let mut made = serde_json::Map::new();
1722        for (name, state, columns, rows) in shown_screens() {
1723            let before = made.insert(name.to_owned(), styled(&state, columns, rows));
1724            assert!(before.is_none(), "the screen {name} is made once");
1725        }
1726        let made = format!(
1727            "{}\n",
1728            serde_json::to_string_pretty(&serde_json::Value::Object(made)).expect("JSON")
1729        );
1730        let path = screens_file();
1731        if std::env::var_os("VCON_SERVER_WRITE_SCREENS").is_some() {
1732            std::fs::write(&path, &made)
1733                .unwrap_or_else(|e| panic!("write {}: {e}", path.display()));
1734        }
1735        let shown = std::fs::read_to_string(&path)
1736            .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
1737        assert!(
1738            shown == made,
1739            "{} is not the screens draw makes now: run this test with VCON_SERVER_WRITE_SCREENS=1 to write them again",
1740            path.display()
1741        );
1742    }
1743}