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::reveal::Part;
17use crate::tui::keys::{BINDINGS, binding};
18use crate::tui::state::{Action, Connection, Content, Listing, Revealed, Row, State, View};
19
20/// The smallest terminal a view is drawn in.
21const MIN_COLUMNS: u16 = 40;
22const MIN_LINES: u16 = 8;
23/// The offset every time on screen is in, as it is written beside them.
24const ZONE: &str = "UTC+00:00";
25/// The columns of a list row: the marker and the uuid, then each time, then
26/// the version.
27const UUID_COLUMNS: u16 = 38;
28const TIME_COLUMNS: u16 = 21;
29const VERSION_COLUMNS: u16 = 34;
30
31/// Whether color may be used.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub struct Theme {
34    /// False for a monochrome terminal or a user who asked for none.
35    pub color: bool,
36}
37
38/// The theme for an environment: no color when `NO_COLOR` is set to
39/// anything but the empty string (<https://no-color.org>), when `TERM` is
40/// `dumb`, or when there is no `TERM`.
41#[must_use]
42pub fn theme(no_color: Option<&str>, term: Option<&str>) -> Theme {
43    let refused = no_color.is_some_and(|value| !value.is_empty());
44    let capable = term.is_some_and(|term| term != "dumb");
45    Theme {
46        color: capable && !refused,
47    }
48}
49
50/// An RFC 3339 time as `YYYY-MM-DD HH:MM:SS` in UTC; text that is not one
51/// is returned as it is.
52#[must_use]
53pub fn utc(text: &str) -> String {
54    OffsetDateTime::parse(text, &Rfc3339).map_or_else(|_| text.to_owned(), stamp)
55}
56
57/// `at` as `YYYY-MM-DD HH:MM:SS` in UTC.
58fn stamp(at: OffsetDateTime) -> String {
59    let at = at.to_offset(UtcOffset::UTC);
60    format!(
61        "{:04}-{:02}-{:02} {:02}:{:02}:{:02}",
62        at.year(),
63        u8::from(at.month()),
64        at.day(),
65        at.hour(),
66        at.minute(),
67        at.second()
68    )
69}
70
71/// Draws `state` on the whole frame.
72pub fn draw(frame: &mut Frame<'_>, state: &State, theme: Theme) {
73    let area = frame.area();
74    if area.width < MIN_COLUMNS || area.height < MIN_LINES {
75        let message = format!(
76            "Terminal too small: {MIN_COLUMNS}x{MIN_LINES} is needed. Enlarge it, or press q to quit."
77        );
78        frame.render_widget(Paragraph::new(message).wrap(Wrap { trim: true }), area);
79        return;
80    }
81    let line = |y: u16| Rect {
82        y: area.y.saturating_add(y),
83        height: 1,
84        ..area
85    };
86    // The notice takes the lines it needs, up to half of what is left
87    // after the status line and the key hints, and one line when empty.
88    let most = usize::from(area.height.saturating_sub(2) / 2).max(1);
89    let said = fitted(&notice(state), usize::from(area.width), most);
90    let notice_lines = u16::try_from(said.len()).unwrap_or(1).max(1);
91    let body = Rect {
92        y: area.y.saturating_add(1),
93        height: area.height.saturating_sub(notice_lines.saturating_add(2)),
94        ..area
95    };
96    frame.render_widget(Paragraph::new(status(state, area.width, theme)), line(0));
97    match state.view {
98        View::List => list(frame, state, body),
99        View::Detail => detail(frame, state, body),
100        View::Help => help(frame, body),
101    }
102    let said: Vec<Line<'_>> = said.into_iter().map(Line::from).collect();
103    frame.render_widget(
104        Paragraph::new(said),
105        Rect {
106            y: area.y.saturating_add(body.height).saturating_add(1),
107            height: notice_lines,
108            ..area
109        },
110    );
111    frame.render_widget(
112        Paragraph::new(hints(state, usize::from(area.width))),
113        line(area.height.saturating_sub(1)),
114    );
115}
116
117/// `text` as lines of at most `columns` characters, broken between words;
118/// a word longer than a line is broken where the line ends.
119fn wrapped(text: &str, columns: usize) -> Vec<String> {
120    let columns = columns.max(1);
121    let mut lines: Vec<String> = Vec::new();
122    let mut line = String::new();
123    let mut used = 0_usize;
124    for word in text.split(' ').filter(|word| !word.is_empty()) {
125        let mut rest: Vec<char> = word.chars().collect();
126        if used > 0 && used.saturating_add(1).saturating_add(rest.len()) > columns {
127            lines.push(std::mem::take(&mut line));
128            used = 0;
129        }
130        while rest.len() > columns {
131            lines.push(rest.drain(..columns).collect());
132        }
133        if used > 0 {
134            line.push(' ');
135            used = used.saturating_add(1);
136        }
137        used = used.saturating_add(rest.len());
138        line.extend(rest);
139    }
140    if !line.is_empty() {
141        lines.push(line);
142    }
143    lines
144}
145
146/// The parts of the notice as the lines drawn: on one line, joined by
147/// [`BETWEEN`], when that fits `columns`; otherwise each part on lines of
148/// its own, wrapped. At most `most` lines: when there are more, the last
149/// one drawn ends with [`CUT`].
150fn fitted(parts: &[String], columns: usize, most: usize) -> Vec<String> {
151    let whole = parts.join(BETWEEN);
152    if whole.chars().count() <= columns {
153        return vec![whole];
154    }
155    let mut lines: Vec<String> = parts
156        .iter()
157        .flat_map(|part| wrapped(part, columns))
158        .collect();
159    if lines.len() > most {
160        lines.truncate(most);
161        if let Some(last) = lines.last_mut() {
162            let kept = columns.saturating_sub(CUT.chars().count());
163            *last = last.chars().take(kept).collect();
164            last.push_str(CUT);
165        }
166    }
167    lines
168}
169
170/// Whose key the server answered for, as the status line names it.
171enum Owner<'a> {
172    /// The server has not answered for the key.
173    Unknown,
174    /// An operator key, which has no tenant.
175    Operator,
176    /// A tenant key, with the tenant's id.
177    Tenant(&'a str),
178}
179
180/// The scheme every server address has, and so the first thing left out.
181const SCHEME: &str = "https://";
182/// Between the parts of the status line.
183const BETWEEN: &str = " | ";
184/// Ends a part that was shortened.
185const CUT: &str = "...";
186/// The fewest characters of a tenant id worth showing.
187const ID_MIN: usize = 4;
188
189/// The status line before the connection word, which the caller appends:
190/// the server's address and whose key it is, each followed by [`BETWEEN`].
191///
192/// THE RULE for a line longer than `columns`. An operator needs the
193/// connection first, then the server, then the tenant, so the parts give
194/// way in the other order, and nothing that carries information goes
195/// before something that carries none:
196///
197/// 1. The connection word is never shortened or left out.
198/// 2. The address loses `https://`, which every address has.
199/// 3. A tenant id is shortened to what fits, with `...`, down to
200///    [`ID_MIN`] characters. A phrase (`tenant unknown`, `no tenant
201///    (operator key)`) is never cut.
202/// 4. The tenant part is left out.
203/// 5. Only then is the address shortened, at its end, with `...`.
204fn status_lead(server: &str, owner: &Owner<'_>, word: &str, columns: usize) -> String {
205    let length = |text: &str| text.chars().count();
206    let owner_whole = match owner {
207        Owner::Unknown => "tenant unknown".to_owned(),
208        Owner::Operator => "no tenant (operator key)".to_owned(),
209        Owner::Tenant(id) => format!("tenant {id}"),
210    };
211    // What the address and the tenant part may take together.
212    let room = columns.saturating_sub(length(word));
213    let with_owner = |address: &str, owner: &str| format!("{address}{BETWEEN}{owner}{BETWEEN}");
214    let whole = with_owner(server, &owner_whole);
215    if length(&whole) <= room {
216        return whole;
217    }
218    let bare = server.strip_prefix(SCHEME).unwrap_or(server);
219    let unschemed = with_owner(bare, &owner_whole);
220    if length(&unschemed) <= room {
221        return unschemed;
222    }
223    if let Owner::Tenant(id) = owner {
224        let around = length(&with_owner(bare, "tenant ")).saturating_add(length(CUT));
225        let kept = room.saturating_sub(around);
226        if kept >= ID_MIN {
227            let id: String = id.chars().take(kept).collect();
228            return with_owner(bare, &format!("tenant {id}{CUT}"));
229        }
230    }
231    let alone = format!("{bare}{BETWEEN}");
232    if length(&alone) <= room {
233        return alone;
234    }
235    let kept = room.saturating_sub(length(BETWEEN).saturating_add(length(CUT)));
236    let address: String = bare.chars().take(kept).collect();
237    format!("{address}{CUT}{BETWEEN}")
238}
239
240/// The status line: the server, the tenant and the connection, shortened
241/// by [`status_lead`]'s rule when the terminal is narrower than the line.
242fn status(state: &State, columns: u16, theme: Theme) -> Line<'static> {
243    let (owner, word, color) = match &state.connection {
244        Connection::Connecting => (Owner::Unknown, "connecting", Color::Yellow),
245        Connection::Failed(_) => (Owner::Unknown, "not connected", Color::Red),
246        Connection::Connected(info) => (
247            info.tenant
248                .as_deref()
249                .map_or(Owner::Operator, Owner::Tenant),
250            "connected",
251            Color::Green,
252        ),
253    };
254    let lead = status_lead(&state.server, &owner, word, usize::from(columns));
255    let mut style = Style::new().add_modifier(Modifier::BOLD);
256    if theme.color {
257        style = style.fg(color);
258    }
259    Line::from(vec![Span::raw(lead), Span::styled(word, style)])
260}
261
262/// A message in place of a view's content, wrapped to the body.
263fn message(frame: &mut Frame<'_>, body: Rect, lines: Vec<String>) {
264    let lines: Vec<Line<'_>> = lines.into_iter().map(Line::from).collect();
265    frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), body);
266}
267
268/// What a view shows instead of its content while there is no list: the
269/// connecting, loading and error states. `None` when the list is ready.
270fn waiting(state: &State, loading: &str) -> Option<Vec<String>> {
271    if state.connection == Connection::Connecting {
272        return Some(vec![
273            "Connecting to the server...".to_owned(),
274            String::new(),
275            "Press q to quit.".to_owned(),
276        ]);
277    }
278    match &state.listing {
279        Listing::Ready => None,
280        Listing::Loading => Some(vec![
281            loading.to_owned(),
282            String::new(),
283            "Press q to quit.".to_owned(),
284        ]),
285        Listing::Failed(why) => {
286            let mut lines = vec![format!("Could not list vCons: {why}."), String::new()];
287            if why.contains("(401)") {
288                lines
289                    .push("Check that key_file holds a key the server has not revoked.".to_owned());
290            }
291            // r asks the server again. For a key that may not list there
292            // is nothing to ask: the answer depends on the key alone.
293            lines.push(if state.acts(Action::Refresh) {
294                "Press r to try again, or q to quit.".to_owned()
295            } else {
296                "Press q to quit.".to_owned()
297            });
298            // The client file, the token and the CA are read once, before
299            // the first screen, so r cannot pick up a corrected file.
300            lines.push(
301                "A change to the client file or the key file takes effect at the next start."
302                    .to_owned(),
303            );
304            Some(lines)
305        }
306    }
307}
308
309/// The list view.
310fn list(frame: &mut Frame<'_>, state: &State, body: Rect) {
311    if let Some(lines) = waiting(state, "Loading vCons...") {
312        return message(frame, body, lines);
313    }
314    if state.rows.is_empty() {
315        let lines = vec![
316            "This tenant has no vCons.".to_owned(),
317            String::new(),
318            "Press r to read again, or q to quit.".to_owned(),
319        ];
320        return message(frame, body, lines);
321    }
322    let times = u16::from(body.width >= UUID_COLUMNS.saturating_add(TIME_COLUMNS)).saturating_add(
323        u16::from(body.width >= UUID_COLUMNS.saturating_add(TIME_COLUMNS.saturating_mul(2))),
324    );
325    let version = body.width
326        >= UUID_COLUMNS
327            .saturating_add(TIME_COLUMNS.saturating_mul(2))
328            .saturating_add(VERSION_COLUMNS);
329    let columns = |marker: &str, uuid: &str, stored: &str, updated: &str, tag: &str| {
330        let mut text = format!("{marker}{uuid:<36}");
331        if times >= 1 {
332            text.push_str(&format!("  {stored:<19}"));
333        }
334        if times >= 2 {
335            text.push_str(&format!("  {updated:<19}"));
336        }
337        if version {
338            text.push_str(&format!("  {tag}"));
339        }
340        text
341    };
342    let visible = usize::from(body.height.saturating_sub(1));
343    let first = state.selected.saturating_add(1).saturating_sub(visible);
344    let mut lines = vec![Line::styled(
345        columns(
346            "  ",
347            "UUID",
348            &format!("STORED ({ZONE})"),
349            &format!("UPDATED ({ZONE})"),
350            "VERSION",
351        ),
352        Style::new().add_modifier(Modifier::BOLD),
353    )];
354    for (index, row) in state.rows.iter().enumerate().skip(first).take(visible) {
355        let selected = index == state.selected;
356        let text = columns(
357            if selected { "> " } else { "  " },
358            &row.uuid,
359            &utc(&row.stored_at),
360            &utc(&row.updated_at),
361            &row.version,
362        );
363        let style = if selected {
364            Style::new().add_modifier(Modifier::REVERSED)
365        } else {
366            Style::new()
367        };
368        lines.push(Line::styled(text, style));
369    }
370    frame.render_widget(Paragraph::new(lines), body);
371}
372
373/// The detail view: one vCon's metadata, from its row of the list, its
374/// masked view and the part revealed, from [`State::scroll`] down.
375fn detail(frame: &mut Frame<'_>, state: &State, body: Rect) {
376    let lines = detail_lines(state, body.width);
377    let shown = usize::from(body.height);
378    let first = state.scroll.min(lines.len().saturating_sub(shown));
379    let lines: Vec<Line<'_>> = lines.into_iter().skip(first).map(Line::from).collect();
380    frame.render_widget(Paragraph::new(lines), body);
381}
382
383/// The lines of the detail view in a terminal of `columns` columns, every
384/// one of them, as [`State`] counts them to move the view and the view
385/// draws them. Text that came from a vCon is made printable first.
386#[must_use]
387pub fn detail_lines(state: &State, columns: u16) -> Vec<String> {
388    let lines = if let Some(lines) = waiting(state, "Reading the list again...") {
389        lines
390    } else {
391        match state.detail_row() {
392            Some(row) => detail_text(state, row),
393            None => vec![
394                "This vCon is no longer in the list: it was deleted, or it is past the pages read."
395                    .to_owned(),
396                String::new(),
397                "Press Esc to go back.".to_owned(),
398            ],
399        }
400    };
401    lines
402        .iter()
403        .flat_map(|line| broken(&printable(line), usize::from(columns)))
404        .collect()
405}
406
407/// What stands for a character a terminal would act on.
408const REPLACED: char = '\u{fffd}';
409
410/// `text` with every control character a terminal acts on replaced, so text
411/// from a vCon cannot move the cursor, change colors or write to the
412/// terminal's title; a tab becomes a space.
413fn printable(text: &str) -> String {
414    text.chars()
415        .map(|c| match c {
416            '\t' => ' ',
417            c if c.is_control() => REPLACED,
418            c => c,
419        })
420        .collect()
421}
422
423/// `line` as lines of at most `columns` characters: broken at the last
424/// space that fits, else where the line ends, so indentation is kept.
425fn broken(line: &str, columns: usize) -> Vec<String> {
426    let columns = columns.max(1);
427    let mut rest: Vec<char> = line.chars().collect();
428    let mut lines = Vec::new();
429    while rest.len() > columns {
430        // A space at the place just past the line is a break too.
431        let room = rest.get(..=columns).unwrap_or_default();
432        let space = room.iter().rposition(|c| *c == ' ').filter(|at| {
433            room.get(..*at)
434                .is_some_and(|head| head.iter().any(|c| *c != ' '))
435        });
436        let at = space.unwrap_or(columns);
437        lines.push(rest.drain(..at).collect());
438        if space.is_some() {
439            rest.remove(0);
440        }
441    }
442    lines.push(rest.into_iter().collect());
443    lines
444}
445
446/// What the detail view says of each part a key reveals.
447fn noun(part: Part) -> &'static str {
448    match part {
449        Part::Parties => "the parties",
450        Part::Subject => "the subject",
451        Part::Dialog => "the dialog",
452        Part::Analysis => "the analysis",
453        Part::Links => "the links",
454        Part::All | Part::Audio => "the whole vCon",
455    }
456}
457
458/// `text` with its first letter in upper case.
459fn sentence(text: &str) -> String {
460    let mut chars = text.chars();
461    chars.next().map_or_else(String::new, |first| {
462        first.to_uppercase().chain(chars).collect()
463    })
464}
465
466/// The lines of one vCon: its metadata, its masked view, and the part
467/// revealed.
468fn detail_text(state: &State, row: &Row) -> Vec<String> {
469    let mut lines = vec![
470        format!("vCon {}", row.uuid),
471        String::new(),
472        format!("Version       {}", row.version),
473        format!("First stored  {} {ZONE}", utc(&row.stored_at)),
474        format!("Last updated  {} {ZONE}", utc(&row.updated_at)),
475        String::new(),
476    ];
477    match &state.content {
478        Content::None | Content::Reading => lines.push("Reading the masked view...".to_owned()),
479        Content::Failed(why) => {
480            lines.push(format!("The masked view was not read: {why}."));
481            lines.push("Press r to try again.".to_owned());
482        }
483        Content::Ready(masked) => {
484            lines.extend(masked.iter().cloned());
485            lines.push(String::new());
486            lines.push(
487                "A reveal shows one part, recorded in the audit log; help has the keys.".to_owned(),
488            );
489        }
490    }
491    match &state.revealed {
492        None => {}
493        Some(Revealed::Reading(part)) => {
494            lines.push(String::new());
495            lines.push(format!("Revealing {}...", noun(*part)));
496        }
497        Some(Revealed::Shown(part, text)) => {
498            lines.push(String::new());
499            lines.push(format!("{}, revealed:", sentence(noun(*part))));
500            lines.extend(text.split('\n').map(str::to_owned));
501        }
502        Some(Revealed::Failed(part, why)) => {
503            lines.push(String::new());
504            lines.push(format!("The reveal of {} failed: {why}.", noun(*part)));
505        }
506    }
507    lines
508}
509
510/// The help view: every binding, from the table the key reader uses.
511fn help(frame: &mut Frame<'_>, body: Rect) {
512    let mut lines = vec!["Keys".to_owned()];
513    for binding in &BINDINGS {
514        lines.push(format!("  {:<7}{}", binding.label, binding.does));
515    }
516    lines.push(String::new());
517    lines.push(format!("Every time shown is in UTC ({ZONE})."));
518    message(frame, body, lines);
519}
520
521/// The notice above the key hints, as its parts: what went wrong with the
522/// last request, or where the selection is and when the list was read.
523/// [`fitted`] makes lines of them.
524fn notice(state: &State) -> Vec<String> {
525    if let Some(notice) = &state.notice {
526        return vec![notice.clone()];
527    }
528    if state.more {
529        return vec!["Reading the next page...".to_owned()];
530    }
531    let (Listing::Ready, Some(as_of)) = (&state.listing, state.as_of) else {
532        return Vec::new();
533    };
534    let as_of = format!("as of {} {ZONE}", stamp(as_of));
535    if state.rows.is_empty() {
536        return vec![as_of];
537    }
538    let more = if state.next.is_some() {
539        ", more on the server"
540    } else {
541        ""
542    };
543    vec![
544        format!(
545            "{} of {} read{more}",
546            state.selected.saturating_add(1),
547            state.rows.len()
548        ),
549        as_of,
550    ]
551}
552
553/// The key hints of a state, from the bindings, in `columns` columns. Help
554/// and quit end every line. When the line is longer than the terminal is
555/// wide, the hint before those two is left out, then the one before it,
556/// until the line fits: a hint is whole or absent, and `?` lists every key.
557fn hints(state: &State, columns: usize) -> String {
558    /// The hints never left out: the last two of a view.
559    const KEPT: usize = 2;
560    let mut shown = state_hints(state);
561    let length = |shown: &[String]| {
562        shown
563            .iter()
564            .map(|hint| hint.chars().count())
565            .sum::<usize>()
566            .saturating_add(shown.len().saturating_sub(1).saturating_mul(2))
567    };
568    while shown.len() > KEPT && length(&shown) > columns {
569        shown.remove(shown.len().saturating_sub(KEPT).saturating_sub(1));
570    }
571    shown.join("  ")
572}
573
574/// The key hints of a state, each a key and a word: those of its view
575/// whose key acts in the state ([`State::acts`]). A screen with nothing to
576/// select names no key that selects.
577fn state_hints(state: &State) -> Vec<String> {
578    let actions: &[Action] = match state.view {
579        View::List => &[
580            Action::Down,
581            Action::Up,
582            Action::Open,
583            Action::Refresh,
584            Action::More,
585            Action::Help,
586            Action::Quit,
587        ],
588        View::Detail => &[
589            Action::Back,
590            Action::Down,
591            Action::Up,
592            Action::Reveal(Part::Parties),
593            Action::Reveal(Part::Subject),
594            Action::Reveal(Part::Dialog),
595            Action::Reveal(Part::Analysis),
596            Action::Reveal(Part::Links),
597            Action::Reveal(Part::All),
598            Action::PageDown,
599            Action::PageUp,
600            Action::Refresh,
601            Action::Help,
602            Action::Quit,
603        ],
604        View::Help => &[Action::Back, Action::Quit],
605    };
606    actions
607        .iter()
608        .filter(|action| state.acts(**action))
609        .filter_map(|action| binding(*action))
610        .map(|binding| format!("{} {}", binding.label, binding.hint))
611        .collect()
612}
613
614#[cfg(test)]
615mod tests {
616    use ratatui::Terminal;
617    use ratatui::backend::TestBackend;
618    use ratatui::buffer::Cell;
619    use ratatui::style::{Color, Modifier};
620    use time::OffsetDateTime;
621    use time::macros::datetime;
622
623    use super::{Theme, broken, detail_lines, draw, theme, utc};
624    use crate::reveal::Part;
625    use crate::tui::client;
626    use crate::tui::keys::BINDINGS;
627    use crate::tui::screens::{SHOWN_TENANT, Screen, shown_key, shown_page, shown_refusal};
628    use crate::tui::state::{Action, ApiError, Event, KeyInfo, Page, Row, State};
629
630    const NOW: OffsetDateTime = datetime!(2026-11-10 01:20:00 UTC);
631    const MONO: Theme = Theme { color: false };
632    const COLOR: Theme = Theme { color: true };
633
634    fn row(n: u8) -> Row {
635        Row {
636            uuid: format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc{n:02}"),
637            stored_at: "2026-10-25T12:00:00.123456789Z".to_owned(),
638            updated_at: "2026-10-25T12:30:00Z".to_owned(),
639            version: format!("4f0c4b0a1d2e3f405162738495a6b7{n:02}"),
640        }
641    }
642
643    fn connecting() -> State {
644        State::new("https://vcon.example.com:8443", (80, 24)).0
645    }
646
647    fn connected() -> State {
648        let mut state = connecting();
649        state.step(
650            Event::KeyInfo(Ok(KeyInfo {
651                id: "0123456789abcdef".to_owned(),
652                tenant: Some("t_example".to_owned()),
653                scopes: vec!["read".to_owned()],
654            })),
655            NOW,
656        );
657        state
658    }
659
660    fn listed(rows: u8, next: Option<&str>) -> State {
661        let mut state = connected();
662        state.step(
663            Event::Page(Ok(Page {
664                vcons: (0..rows).map(row).collect(),
665                next: next.map(str::to_owned),
666            })),
667            NOW,
668        );
669        state
670    }
671
672    fn press(mut state: State, actions: &[Action]) -> State {
673        for action in actions {
674            state.step(Event::Action(*action), NOW);
675        }
676        state
677    }
678
679    fn terminal(state: &State, columns: u16, lines: u16, theme: Theme) -> Terminal<TestBackend> {
680        let mut terminal = Terminal::new(TestBackend::new(columns, lines)).expect("a terminal");
681        terminal
682            .draw(|frame| draw(frame, state, theme))
683            .expect("a frame");
684        terminal
685    }
686
687    /// The screen's lines as text.
688    fn screen(state: &State, columns: u16, lines: u16) -> Vec<String> {
689        let terminal = terminal(state, columns, lines, MONO);
690        let buffer = terminal.backend().buffer();
691        (0..lines)
692            .map(|y| (0..columns).map(|x| buffer[(x, y)].symbol()).collect())
693            .collect()
694    }
695
696    fn text(state: &State) -> String {
697        screen(state, 80, 24).join("\n")
698    }
699
700    // Success.
701
702    #[test]
703    fn the_status_line_names_the_server_the_tenant_and_the_connection() {
704        let lines = screen(&listed(1, None), 80, 24);
705        assert!(
706            lines[0].contains("https://vcon.example.com:8443"),
707            "the server: {}",
708            lines[0]
709        );
710        assert!(
711            lines[0].contains("tenant t_example"),
712            "the tenant: {}",
713            lines[0]
714        );
715        assert!(
716            lines[0].contains("connected"),
717            "the connection, in words: {}",
718            lines[0]
719        );
720    }
721
722    #[test]
723    fn the_list_shows_each_vcon_with_its_times_in_utc() {
724        let lines = screen(&listed(2, None), 80, 24);
725        assert!(
726            lines[1].contains("STORED (UTC+00:00)"),
727            "the header states the offset: {}",
728            lines[1]
729        );
730        assert!(
731            lines[2].contains(&row(0).uuid),
732            "the first row's uuid: {}",
733            lines[2]
734        );
735        assert!(
736            lines[2].contains("2026-10-25 12:00:00"),
737            "its stored time: {}",
738            lines[2]
739        );
740        assert!(
741            lines[2].contains("2026-10-25 12:30:00"),
742            "its updated time: {}",
743            lines[2]
744        );
745        assert!(
746            lines[3].contains(&row(1).uuid),
747            "the second row: {}",
748            lines[3]
749        );
750    }
751
752    #[test]
753    fn the_selected_row_is_marked_with_a_character() {
754        let lines = screen(&press(listed(3, None), &[Action::Down]), 80, 24);
755        assert!(
756            lines[3].starts_with("> "),
757            "the selected row has a marker: {}",
758            lines[3]
759        );
760        assert!(
761            lines[2].starts_with("  "),
762            "the others do not: {}",
763            lines[2]
764        );
765    }
766
767    #[test]
768    fn the_list_footer_hints_are_real_bindings() {
769        let lines = screen(&listed(1, None), 80, 24);
770        let footer = &lines[23];
771        for wanted in [Action::Open, Action::Refresh, Action::Help, Action::Quit] {
772            let binding = BINDINGS
773                .iter()
774                .find(|b| b.action == wanted)
775                .expect("a binding");
776            assert!(
777                footer.contains(&format!("{} {}", binding.label, binding.hint)),
778                "the footer shows {wanted:?} as bound: {footer}"
779            );
780        }
781    }
782
783    #[test]
784    fn the_notice_line_says_how_many_are_loaded_and_as_of_when() {
785        let lines = screen(&listed(2, Some("cursor-1")), 80, 24);
786        assert!(lines[22].contains("1 of 2"), "the position: {}", lines[22]);
787        assert!(
788            lines[22].contains("more on the server"),
789            "that more exist: {}",
790            lines[22]
791        );
792        assert!(
793            lines[22].contains("as of 2026-11-10 01:20:00 UTC+00:00"),
794            "when it was read, with the offset: {}",
795            lines[22]
796        );
797    }
798
799    #[test]
800    fn the_detail_view_shows_the_metadata_and_reads_the_masked_view() {
801        let shown = text(&press(listed(2, None), &[Action::Open]));
802        assert!(shown.contains(&row(0).uuid), "the uuid: {shown}");
803        assert!(shown.contains(&row(0).version), "the version: {shown}");
804        assert!(
805            shown.contains("2026-10-25 12:00:00 UTC+00:00"),
806            "first stored: {shown}"
807        );
808        assert!(
809            shown.contains("2026-10-25 12:30:00 UTC+00:00"),
810            "last updated: {shown}"
811        );
812        assert!(
813            shown.contains("Reading the masked view..."),
814            "what is read: {shown}"
815        );
816        assert!(shown.contains("Esc back"), "how to leave: {shown}");
817    }
818
819    /// The second vCon open, its masked view `lines` arrived.
820    fn masked_open(lines: &[&str]) -> State {
821        let mut state = press(listed(2, None), &[Action::Open]);
822        state.step(
823            Event::Masked(
824                row(0).uuid,
825                Ok(lines.iter().map(|line| (*line).to_owned()).collect()),
826            ),
827            NOW,
828        );
829        state
830    }
831
832    /// `state` after the reveal of `part` answered `answer`.
833    fn answered(mut state: State, part: Part, answer: Result<String, ApiError>) -> State {
834        state.step(Event::Action(Action::Reveal(part)), NOW);
835        state.step(Event::Revealed(row(0).uuid, part, answer), NOW);
836        state
837    }
838
839    #[test]
840    fn the_masked_view_is_shown_under_the_metadata_with_what_a_reveal_does() {
841        let shown = text(&masked_open(&["Masked view", "Form          unsigned"]));
842        assert!(shown.contains("Form          unsigned"), "{shown}");
843        assert!(shown.contains("recorded in the audit log"), "{shown}");
844        assert!(shown.contains("p parties"), "the reveal keys act: {shown}");
845    }
846
847    #[test]
848    fn a_revealed_part_is_shown_under_its_title() {
849        let state = answered(
850            masked_open(&["Masked view"]),
851            Part::Subject,
852            Ok("Renewal call".to_owned()),
853        );
854        let shown = text(&state);
855        assert!(shown.contains("The subject, revealed:"), "{shown}");
856        assert!(shown.contains("Renewal call"), "{shown}");
857    }
858
859    #[test]
860    fn a_reveal_in_flight_says_so() {
861        let mut state = masked_open(&["Masked view"]);
862        state.step(Event::Action(Action::Reveal(Part::All)), NOW);
863        assert!(
864            text(&state).contains("Revealing the whole vCon..."),
865            "{}",
866            text(&state)
867        );
868    }
869
870    #[test]
871    fn a_failed_reveal_says_why_and_shows_no_text() {
872        let error = ApiError::Status(403, Some("forbidden".to_owned()));
873        let shown = text(&answered(
874            masked_open(&["Masked view"]),
875            Part::Dialog,
876            Err(error),
877        ));
878        assert!(
879            shown.contains("The reveal of the dialog failed: the server answered 403 (forbidden)."),
880            "{shown}"
881        );
882        assert!(!shown.contains("revealed:"), "{shown}");
883    }
884
885    #[test]
886    fn a_failed_masked_view_says_why_and_what_to_press() {
887        let mut state = press(listed(2, None), &[Action::Open]);
888        state.step(
889            Event::Masked(row(0).uuid, Err(ApiError::Status(404, None))),
890            NOW,
891        );
892        let shown = text(&state);
893        assert!(
894            shown.contains("The masked view was not read: the server answered 404."),
895            "{shown}"
896        );
897        assert!(shown.contains("Press r to try again."), "{shown}");
898        assert!(!shown.contains("p parties"), "no reveal key acts: {shown}");
899    }
900
901    /// Text from a vCon is drawn, never sent to the terminal as commands.
902    #[test]
903    fn control_characters_from_a_vcon_are_replaced() {
904        let state = answered(
905            masked_open(&["Masked view", "  Party 1: address at \u{1b}]0;title\u{7}"]),
906            Part::Subject,
907            Ok("Renewal\u{1b}[2J\u{9b}call\tnow".to_owned()),
908        );
909        let lines = detail_lines(&state, 80);
910        let joined = lines.join("\n");
911        assert!(
912            !joined.chars().any(|c| c.is_control() && c != '\n'),
913            "{joined:?}"
914        );
915        assert!(
916            joined.contains("Renewal\u{fffd}[2J\u{fffd}call now"),
917            "{joined:?}"
918        );
919        assert!(
920            joined.contains("address at \u{fffd}]0;title\u{fffd}"),
921            "{joined:?}"
922        );
923    }
924
925    #[test]
926    fn a_long_line_is_broken_at_a_space_and_its_indentation_kept() {
927        assert_eq!(
928            broken("    \"name\": \"Ada Example\"", 16),
929            ["    \"name\": \"Ada", "Example\""],
930            "at the space just past the line, which is dropped"
931        );
932        assert_eq!(
933            broken("    \"name\": \"Ada Example\"", 14),
934            ["    \"name\":", "\"Ada Example\""],
935            "at the last space that fits"
936        );
937        assert_eq!(
938            broken("abcdefghij", 4),
939            ["abcd", "efgh", "ij"],
940            "a word longer than a line"
941        );
942        assert_eq!(broken("", 4), [""], "an empty line stays a line");
943        assert_eq!(
944            broken("    abcdefgh", 6),
945            ["    ab", "cdefgh"],
946            "indentation alone is no break"
947        );
948    }
949
950    #[test]
951    fn a_detail_view_moved_down_starts_at_its_line() {
952        let long: String = (0..100).map(|n| format!("line {n}\n")).collect();
953        let mut state = answered(masked_open(&["Masked view"]), Part::All, Ok(long));
954        state.step(Event::Action(Action::PageDown), NOW);
955        let shown = text(&state);
956        assert!(
957            !shown.contains(&format!("vCon {}", row(0).uuid)),
958            "the top is above: {shown}"
959        );
960        assert!(
961            shown.contains("line 20 "),
962            "lines below the first screen: {shown}"
963        );
964    }
965
966    #[test]
967    fn the_help_view_lists_every_binding() {
968        let shown = text(&press(listed(1, None), &[Action::Help]));
969        for binding in &BINDINGS {
970            assert!(
971                shown.contains(binding.label),
972                "{} is listed: {shown}",
973                binding.label
974            );
975            assert!(
976                shown.contains(binding.does),
977                "{} is described: {shown}",
978                binding.does
979            );
980        }
981    }
982
983    #[test]
984    fn the_list_scrolls_to_keep_the_selection_on_screen() {
985        let state = press(listed(60, None), &[Action::Bottom]);
986        let shown = text(&state);
987        assert!(
988            shown.contains(&format!("> {}", row(59).uuid)),
989            "the last row is drawn selected"
990        );
991        assert!(
992            !shown.contains(&row(0).uuid),
993            "the first row has scrolled off"
994        );
995    }
996
997    #[test]
998    fn with_color_the_connection_is_colored_and_still_in_words() {
999        let state = listed(1, None);
1000        let terminal = terminal(&state, 80, 24, COLOR);
1001        let buffer = terminal.backend().buffer();
1002        let colored = (0..80).any(|x| buffer[(x, 0)].fg != Color::Reset);
1003        assert!(colored, "a color terminal gets color");
1004        assert!(
1005            screen(&state, 80, 24)[0].contains("connected"),
1006            "and the word is still there"
1007        );
1008    }
1009
1010    #[test]
1011    fn rfc_3339_times_are_shown_to_the_second_in_utc() {
1012        assert_eq!(
1013            utc("2026-10-25T12:00:00.123456789Z"),
1014            "2026-10-25 12:00:00",
1015            "fractions dropped"
1016        );
1017        assert_eq!(
1018            utc("2026-10-25T14:30:00+02:00"),
1019            "2026-10-25 12:30:00",
1020            "an offset is converted"
1021        );
1022    }
1023
1024    #[test]
1025    fn a_color_terminal_gets_color() {
1026        assert_eq!(
1027            theme(None, Some("xterm-256color")),
1028            COLOR,
1029            "nothing asks for none"
1030        );
1031    }
1032
1033    #[test]
1034    fn a_wider_terminal_shows_the_version_column() {
1035        let lines = screen(&listed(1, None), 132, 43);
1036        assert!(lines[1].contains("VERSION"), "the header: {}", lines[1]);
1037        assert!(
1038            lines[2].contains(&row(0).version),
1039            "the version: {}",
1040            lines[2]
1041        );
1042    }
1043
1044    // Failure.
1045
1046    #[test]
1047    fn a_failed_connection_is_said_in_the_status_line_and_the_list() {
1048        let mut state = connecting();
1049        state.step(
1050            Event::KeyInfo(Err(ApiError::Unreachable("connection refused".to_owned()))),
1051            NOW,
1052        );
1053        let lines = screen(&state, 80, 24);
1054        assert!(
1055            lines[0].contains("not connected"),
1056            "the status line: {}",
1057            lines[0]
1058        );
1059        let shown = lines.join("\n");
1060        assert!(shown.contains("connection refused"), "why: {shown}");
1061        assert!(
1062            shown.contains("Press r to try again"),
1063            "what to press: {shown}"
1064        );
1065    }
1066
1067    #[test]
1068    fn a_long_error_wraps_instead_of_being_cut() {
1069        let mut state = connected();
1070        let long = format!("{} the-end", "word ".repeat(30));
1071        state.step(Event::Page(Err(ApiError::Malformed(long))), NOW);
1072        assert!(
1073            text(&state).contains("the-end"),
1074            "the whole reason is on screen"
1075        );
1076    }
1077
1078    #[test]
1079    fn an_operator_key_is_named_in_the_status_line() {
1080        let mut state = connecting();
1081        state.step(
1082            Event::KeyInfo(Ok(KeyInfo {
1083                id: "0123456789abcdef".to_owned(),
1084                tenant: None,
1085                scopes: vec!["admin".to_owned()],
1086            })),
1087            NOW,
1088        );
1089        let lines = screen(&state, 80, 24);
1090        assert!(
1091            lines[0].contains("no tenant (operator key)"),
1092            "the status line: {}",
1093            lines[0]
1094        );
1095        assert!(
1096            lines
1097                .join("\n")
1098                .contains("this is an operator key, which reaches no vCon"),
1099            "and the list says why it is empty"
1100        );
1101    }
1102
1103    #[test]
1104    fn a_failed_next_page_shows_its_notice_over_the_rows() {
1105        let mut state = press(listed(2, Some("cursor-1")), &[Action::More]);
1106        state.step(
1107            Event::Page(Err(ApiError::Unreachable("timed out".to_owned()))),
1108            NOW,
1109        );
1110        let lines = screen(&state, 80, 24);
1111        assert!(
1112            lines[22].contains("The next page was not read"),
1113            "the notice: {}",
1114            lines[22]
1115        );
1116        assert!(
1117            lines[2].contains(&row(0).uuid),
1118            "the rows stay: {}",
1119            lines[2]
1120        );
1121    }
1122
1123    #[test]
1124    fn the_detail_of_a_vcon_no_longer_listed_says_so() {
1125        let mut state = press(listed(2, None), &[Action::Open, Action::Refresh]);
1126        state.step(
1127            Event::Page(Ok(Page {
1128                vcons: vec![row(1)],
1129                next: None,
1130            })),
1131            NOW,
1132        );
1133        let shown = text(&state);
1134        assert!(
1135            shown.contains("no longer in the list"),
1136            "what happened: {shown}"
1137        );
1138        assert!(
1139            shown.contains("Press Esc to go back"),
1140            "what to press: {shown}"
1141        );
1142    }
1143
1144    #[test]
1145    fn the_detail_view_shows_a_failed_refresh() {
1146        let mut state = press(listed(2, None), &[Action::Open, Action::Refresh]);
1147        state.step(Event::Page(Err(ApiError::Status(503, None))), NOW);
1148        let shown = text(&state);
1149        assert!(shown.contains("the server answered 503"), "why: {shown}");
1150        assert!(
1151            shown.contains("Press r to try again"),
1152            "what to press: {shown}"
1153        );
1154    }
1155
1156    #[test]
1157    fn a_terminal_too_small_says_so_and_how_to_quit() {
1158        let lines = screen(&listed(3, None), 30, 5);
1159        let shown = lines.join("\n");
1160        assert!(shown.contains("too small"), "what is wrong: {shown}");
1161        assert!(shown.contains("q"), "the way out: {shown}");
1162        assert!(!shown.contains("01a07da8"), "no half-drawn list");
1163    }
1164
1165    #[test]
1166    fn a_time_that_does_not_parse_is_shown_as_sent() {
1167        assert_eq!(utc("yesterday"), "yesterday", "nothing is invented for it");
1168    }
1169
1170    #[test]
1171    fn a_refused_key_says_to_check_the_key_file() {
1172        let mut state = connecting();
1173        state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
1174        let shown = text(&state);
1175        assert!(shown.contains("refused the key (401)"), "why: {shown}");
1176        assert!(shown.contains("key_file"), "where to look: {shown}");
1177    }
1178
1179    // Edge.
1180
1181    #[test]
1182    fn the_loading_state_says_so_and_how_to_quit() {
1183        let shown = text(&connected());
1184        assert!(
1185            shown.contains("Loading vCons"),
1186            "what is happening: {shown}"
1187        );
1188        assert!(shown.contains("q quit"), "the way out: {shown}");
1189    }
1190
1191    #[test]
1192    fn the_connecting_state_is_in_the_status_line() {
1193        let lines = screen(&connecting(), 80, 24);
1194        assert!(
1195            lines[0].contains("connecting"),
1196            "the status line: {}",
1197            lines[0]
1198        );
1199        assert!(
1200            lines.join("\n").contains("Connecting to the server"),
1201            "and the body"
1202        );
1203    }
1204
1205    #[test]
1206    fn an_empty_tenant_says_so_and_what_to_press() {
1207        let shown = text(&listed(0, None));
1208        assert!(
1209            shown.contains("This tenant has no vCons"),
1210            "what happened: {shown}"
1211        );
1212        assert!(
1213            shown.contains("Press r to read again"),
1214            "what to press: {shown}"
1215        );
1216    }
1217
1218    #[test]
1219    fn the_detail_view_says_refreshing_while_a_refresh_is_in_flight() {
1220        let shown = text(&press(listed(2, None), &[Action::Open, Action::Refresh]));
1221        assert!(
1222            shown.contains("Reading the list again"),
1223            "what is happening: {shown}"
1224        );
1225    }
1226
1227    #[test]
1228    fn at_80_columns_every_list_column_fits() {
1229        let lines = screen(&listed(1, None), 80, 24);
1230        assert!(
1231            lines[2].trim_end().ends_with("2026-10-25 12:30:00"),
1232            "the last column is whole: {}",
1233            lines[2]
1234        );
1235    }
1236
1237    #[test]
1238    fn below_80_columns_the_updated_column_is_dropped_not_cut() {
1239        let lines = screen(&listed(1, None), 60, 24);
1240        assert!(
1241            lines[2].contains("2026-10-25 12:00:00"),
1242            "stored stays: {}",
1243            lines[2]
1244        );
1245        assert!(
1246            !lines[2].contains("2026-10-25 12:3"),
1247            "no part of updated: {}",
1248            lines[2]
1249        );
1250        assert!(
1251            !lines[1].contains("UPDATED"),
1252            "nor its header: {}",
1253            lines[1]
1254        );
1255    }
1256
1257    #[test]
1258    fn every_size_from_1x1_up_draws_without_a_panic() {
1259        let states = [
1260            connecting(),
1261            listed(0, None),
1262            listed(60, Some("cursor-1")),
1263            press(listed(3, None), &[Action::Open]),
1264            press(listed(3, None), &[Action::Help]),
1265        ];
1266        for state in &states {
1267            for columns in [1, 2, 10, 39, 40, 79, 80, 200] {
1268                for lines in [1, 2, 7, 8, 24, 60] {
1269                    let drawn = screen(state, columns, lines);
1270                    assert_eq!(
1271                        drawn.len(),
1272                        usize::from(lines),
1273                        "{columns}x{lines} drew a frame"
1274                    );
1275                }
1276            }
1277        }
1278    }
1279
1280    #[test]
1281    fn no_color_and_a_dumb_terminal_turn_color_off() {
1282        assert_eq!(
1283            theme(Some("1"), Some("xterm-256color")),
1284            MONO,
1285            "NO_COLOR set"
1286        );
1287        assert_eq!(theme(None, Some("dumb")), MONO, "a terminal with no color");
1288        assert_eq!(theme(None, None), MONO, "no TERM at all");
1289        assert_eq!(
1290            theme(Some(""), Some("xterm")),
1291            COLOR,
1292            "an empty NO_COLOR is not set"
1293        );
1294    }
1295
1296    #[test]
1297    fn without_color_no_cell_has_a_color() {
1298        for state in [
1299            listed(3, None),
1300            press(listed(3, None), &[Action::Help]),
1301            connecting(),
1302        ] {
1303            let terminal = terminal(&state, 80, 24, MONO);
1304            let buffer = terminal.backend().buffer();
1305            for cell in buffer.content() {
1306                assert_eq!(cell.fg, Color::Reset, "no foreground color");
1307                assert_eq!(cell.bg, Color::Reset, "no background color");
1308            }
1309        }
1310    }
1311
1312    #[test]
1313    fn the_status_line_keeps_the_connection_when_the_address_is_long() {
1314        let mut state = State::new(
1315            &format!("https://{}.example.com:8443", "a".repeat(90)),
1316            (80, 24),
1317        )
1318        .0;
1319        state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
1320        let lines = screen(&state, 80, 24);
1321        assert!(
1322            lines[0].contains("not connected"),
1323            "the state is never pushed off: {}",
1324            lines[0]
1325        );
1326    }
1327
1328    // The status line at each width. The rule: the connection is never
1329    // shortened; then the server's address; then the tenant.
1330
1331    const SERVER: &str = "https://vcon.example.com:8443";
1332    const LONG_ID: &str = "658a6d102142fea77f47ee8a332323d8";
1333
1334    /// A state for the server at `server` whose key answered with `tenant`.
1335    fn keyed(server: &str, tenant: Option<&str>) -> State {
1336        let mut state = State::new(server, (80, 24)).0;
1337        state.step(
1338            Event::KeyInfo(Ok(KeyInfo {
1339                id: "0123456789abcdef".to_owned(),
1340                tenant: tenant.map(str::to_owned),
1341                scopes: vec!["read".to_owned()],
1342            })),
1343            NOW,
1344        );
1345        state
1346    }
1347
1348    /// A state whose server refused the key.
1349    fn refused(server: &str) -> State {
1350        let mut state = State::new(server, (80, 24)).0;
1351        state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
1352        state
1353    }
1354
1355    /// The status line of `state` in a terminal of `columns`.
1356    fn status_at(state: &State, columns: u16) -> String {
1357        screen(state, columns, 24)[0].trim_end().to_owned()
1358    }
1359
1360    #[test]
1361    fn at_120_columns_the_status_line_is_whole() {
1362        assert_eq!(
1363            status_at(&keyed(SERVER, Some(LONG_ID)), 120),
1364            format!("{SERVER} | tenant {LONG_ID} | connected"),
1365            "everything fits"
1366        );
1367    }
1368
1369    #[test]
1370    fn at_80_columns_the_address_loses_only_its_scheme() {
1371        assert_eq!(
1372            status_at(&keyed(SERVER, Some(LONG_ID)), 80),
1373            format!("vcon.example.com:8443 | tenant {LONG_ID} | connected"),
1374            "https:// says nothing a reader needs: every address has it"
1375        );
1376    }
1377
1378    #[test]
1379    fn at_60_columns_the_tenant_id_is_shortened_and_the_address_is_not() {
1380        assert_eq!(
1381            status_at(&keyed(SERVER, Some(LONG_ID)), 60),
1382            "vcon.example.com:8443 | tenant 658a6d102142fe... | connected",
1383            "the tenant gives way before the server does"
1384        );
1385    }
1386
1387    #[test]
1388    fn at_40_columns_the_tenant_is_left_out_and_the_address_is_not() {
1389        assert_eq!(
1390            status_at(&keyed(SERVER, Some(LONG_ID)), 40),
1391            "vcon.example.com:8443 | connected",
1392            "the server and the connection"
1393        );
1394    }
1395
1396    #[test]
1397    fn a_line_that_fits_exactly_keeps_its_scheme() {
1398        assert_eq!(
1399            status_at(&keyed(SERVER, Some(LONG_ID)), 83),
1400            format!("{SERVER} | tenant {LONG_ID} | connected"),
1401            "83 characters in 83 columns"
1402        );
1403    }
1404
1405    #[test]
1406    fn a_short_tenant_id_is_whole_at_60_columns() {
1407        assert_eq!(
1408            status_at(&keyed(SERVER, Some("t_example")), 60),
1409            format!("{SERVER} | tenant t_example | connected"),
1410            "60 characters in 60 columns"
1411        );
1412    }
1413
1414    #[test]
1415    fn an_address_with_a_path_is_shown_with_it() {
1416        let line = status_at(
1417            &keyed("https://vcon.example.com:8443/base", Some("t_example")),
1418            120,
1419        );
1420        assert!(
1421            line.starts_with("https://vcon.example.com:8443/base | "),
1422            "the path is part of the address: {line}"
1423        );
1424    }
1425
1426    #[test]
1427    fn a_refused_key_at_40_columns_shows_the_address_and_not_connected() {
1428        assert_eq!(
1429            status_at(&refused(SERVER), 40),
1430            "vcon.example.com:8443 | not connected",
1431            "`tenant unknown` is the part left out"
1432        );
1433    }
1434
1435    #[test]
1436    fn a_refused_key_at_60_columns_keeps_tenant_unknown() {
1437        assert_eq!(
1438            status_at(&refused(SERVER), 60),
1439            "vcon.example.com:8443 | tenant unknown | not connected",
1440            "without the scheme the three parts fit"
1441        );
1442    }
1443
1444    #[test]
1445    fn a_refused_key_at_80_columns_is_whole() {
1446        assert_eq!(
1447            status_at(&refused(SERVER), 80),
1448            format!("{SERVER} | tenant unknown | not connected"),
1449            "everything fits"
1450        );
1451    }
1452
1453    #[test]
1454    fn connecting_at_40_columns_shows_the_address_and_connecting() {
1455        assert_eq!(
1456            status_at(&State::new(SERVER, (40, 24)).0, 40),
1457            "vcon.example.com:8443 | connecting",
1458            "`tenant unknown` is the part left out"
1459        );
1460    }
1461
1462    #[test]
1463    fn an_operator_key_at_60_columns_is_named_whole() {
1464        assert_eq!(
1465            status_at(&keyed(SERVER, None), 60),
1466            "vcon.example.com:8443 | no tenant (operator key) | connected",
1467            "60 characters in 60 columns"
1468        );
1469    }
1470
1471    #[test]
1472    fn an_operator_key_at_40_columns_is_left_out_not_cut() {
1473        assert_eq!(
1474            status_at(&keyed(SERVER, None), 40),
1475            "vcon.example.com:8443 | connected",
1476            "a phrase is whole or absent"
1477        );
1478    }
1479
1480    #[test]
1481    fn a_long_address_is_cut_at_its_end_and_the_connection_is_whole() {
1482        let server = format!("https://{}.example.com:8443", "a".repeat(90));
1483        assert_eq!(
1484            status_at(&refused(&server), 40),
1485            format!("{}... | not connected", "a".repeat(21)),
1486            "40 columns: 21 of the address, the mark, and the connection"
1487        );
1488    }
1489
1490    #[test]
1491    fn four_characters_of_a_tenant_id_are_the_fewest_shown() {
1492        assert_eq!(
1493            status_at(&keyed(SERVER, Some(LONG_ID)), 50),
1494            "vcon.example.com:8443 | tenant 658a... | connected",
1495            "50 columns leave room for four"
1496        );
1497    }
1498
1499    #[test]
1500    fn a_tenant_id_with_room_for_three_characters_is_left_out() {
1501        assert_eq!(
1502            status_at(&keyed(SERVER, Some(LONG_ID)), 49),
1503            "vcon.example.com:8443 | connected",
1504            "three characters name no tenant"
1505        );
1506    }
1507
1508    #[test]
1509    fn one_column_short_of_whole_the_scheme_goes_first() {
1510        assert_eq!(
1511            status_at(&keyed(SERVER, Some(LONG_ID)), 82),
1512            format!("vcon.example.com:8443 | tenant {LONG_ID} | connected"),
1513            "the tenant id stays whole"
1514        );
1515    }
1516
1517    #[test]
1518    fn one_column_short_of_a_whole_id_shortens_it_to_fit() {
1519        let line = status_at(&keyed(SERVER, Some(LONG_ID)), 74);
1520        assert_eq!(
1521            line,
1522            format!(
1523                "vcon.example.com:8443 | tenant {}... | connected",
1524                &LONG_ID[..28]
1525            ),
1526            "74 columns: 28 characters and the mark"
1527        );
1528    }
1529
1530    #[test]
1531    fn an_address_that_is_not_https_is_shown_as_it_is() {
1532        assert_eq!(
1533            status_at(&refused("vcon.example.com:8443"), 40),
1534            "vcon.example.com:8443 | not connected",
1535            "there is no scheme to leave out"
1536        );
1537    }
1538
1539    #[test]
1540    fn an_address_that_fits_exactly_at_40_columns_is_whole() {
1541        let server = format!("https://{}", "b".repeat(28));
1542        assert_eq!(
1543            status_at(&keyed(&server, Some(LONG_ID)), 40),
1544            format!("{} | connected", "b".repeat(28)),
1545            "28 characters, the separator and the connection are 40"
1546        );
1547    }
1548
1549    #[test]
1550    fn the_status_line_fits_and_ends_with_the_connection_at_every_width() {
1551        let long = format!("https://{}.example.com:8443", "a".repeat(90));
1552        for server in [SERVER, long.as_str()] {
1553            let states = [
1554                (State::new(server, (80, 24)).0, "connecting"),
1555                (refused(server), "not connected"),
1556                (keyed(server, Some(LONG_ID)), "connected"),
1557                (keyed(server, None), "connected"),
1558            ];
1559            for (state, word) in &states {
1560                for columns in 40..=130 {
1561                    let line = status_at(state, columns);
1562                    assert!(
1563                        line.chars().count() <= usize::from(columns),
1564                        "{columns} columns: {line}"
1565                    );
1566                    assert!(
1567                        line.ends_with(&format!(" | {word}")),
1568                        "{columns} columns, the connection is whole and last: {line}"
1569                    );
1570                }
1571            }
1572        }
1573    }
1574
1575    #[test]
1576    fn a_tenant_phrase_is_whole_or_absent_at_every_width() {
1577        for (state, phrase) in [
1578            (refused(SERVER), "tenant unknown"),
1579            (keyed(SERVER, None), "no tenant (operator key)"),
1580        ] {
1581            for columns in 40..=130 {
1582                let line = status_at(&state, columns);
1583                assert!(
1584                    line.contains(phrase) || !line.contains("tenant"),
1585                    "{columns} columns: {line}"
1586                );
1587            }
1588        }
1589    }
1590
1591    #[test]
1592    fn the_help_view_states_the_time_zone() {
1593        let shown = text(&press(listed(1, None), &[Action::Help]));
1594        assert!(
1595            shown.contains("UTC+00:00"),
1596            "times are UTC, stated: {shown}"
1597        );
1598    }
1599
1600    // The last two lines in a narrow terminal.
1601
1602    /// The last line of the screen: the key hints.
1603    fn footer_at(state: &State, columns: u16) -> String {
1604        screen(state, columns, 24)[23].trim_end().to_owned()
1605    }
1606
1607    #[test]
1608    fn at_40_columns_the_list_footer_still_shows_help_and_quit() {
1609        let footer = footer_at(&listed(2, None), 40);
1610        assert!(
1611            footer.ends_with("? help  q quit"),
1612            "how to get help and how to leave are whole: {footer:?}"
1613        );
1614        assert!(
1615            footer.starts_with("j down  k up"),
1616            "the first keys stay first: {footer:?}"
1617        );
1618    }
1619
1620    #[test]
1621    fn at_40_columns_the_detail_footer_still_shows_help_and_quit() {
1622        let footer = footer_at(&press(listed(2, None), &[Action::Open]), 40);
1623        assert!(
1624            footer.ends_with("? help  q quit"),
1625            "how to get help and how to leave are whole: {footer:?}"
1626        );
1627        assert!(
1628            footer.starts_with("Esc back"),
1629            "how to go back stays first: {footer:?}"
1630        );
1631    }
1632
1633    #[test]
1634    fn at_80_columns_the_footers_are_whole() {
1635        assert_eq!(
1636            footer_at(&listed(2, Some("cursor-2")), 80),
1637            "j down  k up  Enter open  r refresh  n more  ? help  q quit",
1638            "the list's keys"
1639        );
1640        assert_eq!(
1641            footer_at(&press(listed(2, None), &[Action::Open]), 80),
1642            "Esc back  j down  k up  r refresh  ? help  q quit",
1643            "the detail's keys"
1644        );
1645        assert_eq!(
1646            footer_at(&press(listed(2, None), &[Action::Help]), 80),
1647            "Esc back  q quit",
1648            "help's keys"
1649        );
1650    }
1651
1652    #[test]
1653    fn no_footer_ends_in_a_cut_hint_at_any_width() {
1654        for view in [&[][..], &[Action::Open][..], &[Action::Help][..]] {
1655            let state = press(listed(2, None), view);
1656            for columns in 40..=100 {
1657                let footer = footer_at(&state, columns);
1658                assert!(
1659                    footer.ends_with("q quit"),
1660                    "at {columns} columns the last hint is whole: {footer:?}"
1661                );
1662                assert!(
1663                    footer.chars().count() <= usize::from(columns),
1664                    "at {columns} columns the footer fits: {footer:?}"
1665                );
1666            }
1667        }
1668    }
1669
1670    #[test]
1671    fn one_column_short_of_the_whole_list_footer_drops_one_hint() {
1672        assert_eq!(
1673            footer_at(&listed(2, Some("cursor-2")), 58),
1674            "j down  k up  Enter open  r refresh  ? help  q quit",
1675            "the hint before help goes first"
1676        );
1677        assert_eq!(
1678            footer_at(&listed(2, Some("cursor-2")), 59),
1679            "j down  k up  Enter open  r refresh  n more  ? help  q quit",
1680            "at its own width the footer is whole"
1681        );
1682    }
1683
1684    // The last line names the keys that act in the state, and no other.
1685
1686    const HELP_QUIT: &str = "? help  q quit";
1687    const RETRY: &str = "r refresh  ? help  q quit";
1688    const LIST_KEYS: &str = "j down  k up  Enter open  r refresh  n more  ? help  q quit";
1689
1690    fn failed(error: ApiError) -> State {
1691        let mut state = connecting();
1692        state.step(Event::KeyInfo(Err(error)), NOW);
1693        state
1694    }
1695
1696    fn with_key(tenant: Option<&str>, scope: &str) -> State {
1697        let mut state = connecting();
1698        state.step(
1699            Event::KeyInfo(Ok(KeyInfo {
1700                id: "0123456789abcdef".to_owned(),
1701                tenant: tenant.map(str::to_owned),
1702                scopes: vec![scope.to_owned()],
1703            })),
1704            NOW,
1705        );
1706        state
1707    }
1708
1709    fn page_failed(mut state: State, error: ApiError) -> State {
1710        state.step(Event::Page(Err(error)), NOW);
1711        state
1712    }
1713
1714    /// The detail view of the last of five vCons after a refresh whose
1715    /// answer holds the first `left` of them.
1716    fn detail_gone(left: u8) -> State {
1717        let mut state = press(
1718            listed(5, None),
1719            &[Action::Bottom, Action::Open, Action::Refresh],
1720        );
1721        state.step(
1722            Event::Page(Ok(Page {
1723                vcons: (0..left).map(row).collect(),
1724                next: None,
1725            })),
1726            NOW,
1727        );
1728        state
1729    }
1730
1731    #[test]
1732    fn the_connecting_screen_names_help_and_quit_only() {
1733        assert_eq!(
1734            footer_at(&connecting(), 80),
1735            HELP_QUIT,
1736            "nothing is listed, and r waits for the request that is out"
1737        );
1738    }
1739
1740    #[test]
1741    fn the_loading_screen_names_help_and_quit_only() {
1742        assert_eq!(
1743            footer_at(&connected(), 80),
1744            HELP_QUIT,
1745            "the first page is on its way"
1746        );
1747    }
1748
1749    #[test]
1750    fn an_empty_tenant_names_refresh_help_and_quit() {
1751        assert_eq!(
1752            footer_at(&listed(0, None), 80),
1753            RETRY,
1754            "there is no vCon to select, open or read more of"
1755        );
1756    }
1757
1758    #[test]
1759    fn a_server_that_did_not_answer_names_refresh_help_and_quit() {
1760        assert_eq!(
1761            footer_at(&failed(client::no_answer(client::TIMEOUT)), 80),
1762            RETRY,
1763            "r asks again"
1764        );
1765    }
1766
1767    #[test]
1768    fn a_refused_key_names_refresh_help_and_quit() {
1769        assert_eq!(
1770            footer_at(&failed(ApiError::Status(401, None)), 80),
1771            RETRY,
1772            "r asks the server for the key again"
1773        );
1774    }
1775
1776    #[test]
1777    fn a_refused_certificate_names_refresh_help_and_quit() {
1778        assert_eq!(
1779            footer_at(
1780                &failed(ApiError::Untrusted("it has expired".to_owned())),
1781                80
1782            ),
1783            RETRY,
1784            "a clock that was corrected lets r succeed"
1785        );
1786    }
1787
1788    #[test]
1789    fn a_first_page_that_failed_names_refresh_help_and_quit() {
1790        let state = page_failed(connected(), ApiError::Status(503, None));
1791        assert_eq!(footer_at(&state, 80), RETRY, "r reads the first page again");
1792    }
1793
1794    #[test]
1795    fn an_operator_key_names_help_and_quit_only() {
1796        let state = with_key(None, "admin");
1797        assert_eq!(
1798            footer_at(&state, 80),
1799            HELP_QUIT,
1800            "r cannot read another key: the key file is read at start"
1801        );
1802        let shown = text(&state);
1803        assert!(
1804            shown.contains("\nPress q to quit.") && !shown.contains("Press r"),
1805            "the message names no key that does nothing: {shown}"
1806        );
1807        assert!(
1808            shown.contains(AT_START),
1809            "and says when another key is read: {shown}"
1810        );
1811    }
1812
1813    #[test]
1814    fn a_key_without_the_read_scope_names_help_and_quit_only() {
1815        let state = with_key(Some("t_example"), "write");
1816        assert_eq!(footer_at(&state, 80), HELP_QUIT, "as for an operator key");
1817        let shown = text(&state);
1818        assert!(
1819            shown.contains("\nPress q to quit.") && !shown.contains("Press r"),
1820            "the message names no key that does nothing: {shown}"
1821        );
1822    }
1823
1824    #[test]
1825    fn a_list_of_one_vcon_names_no_key_that_moves() {
1826        assert_eq!(
1827            footer_at(&listed(1, None), 80),
1828            "Enter open  r refresh  ? help  q quit",
1829            "there is no other row, and no next page"
1830        );
1831    }
1832
1833    #[test]
1834    fn a_list_that_is_all_read_does_not_name_more() {
1835        assert_eq!(
1836            footer_at(&listed(3, None), 80),
1837            "j down  k up  Enter open  r refresh  ? help  q quit",
1838            "n does nothing when the server holds no more"
1839        );
1840    }
1841
1842    #[test]
1843    fn a_list_with_more_on_the_server_names_every_list_key() {
1844        assert_eq!(
1845            footer_at(&listed(3, Some("cursor-2")), 80),
1846            LIST_KEYS,
1847            "every key acts"
1848        );
1849    }
1850
1851    #[test]
1852    fn while_the_next_page_is_read_refresh_and_more_are_not_named() {
1853        let state = press(listed(3, Some("cursor-2")), &[Action::More]);
1854        assert_eq!(
1855            footer_at(&state, 80),
1856            "j down  k up  Enter open  ? help  q quit",
1857            "a second request would race the one that is out"
1858        );
1859    }
1860
1861    #[test]
1862    fn after_a_next_page_that_failed_refresh_and_more_are_named_again() {
1863        let state = page_failed(
1864            press(listed(3, Some("cursor-2")), &[Action::More]),
1865            client::no_answer(client::TIMEOUT),
1866        );
1867        assert_eq!(footer_at(&state, 80), LIST_KEYS, "n and r both try again");
1868    }
1869
1870    #[test]
1871    fn while_the_list_is_read_again_only_help_and_quit_are_named() {
1872        let state = press(listed(3, Some("cursor-2")), &[Action::Refresh]);
1873        assert_eq!(
1874            footer_at(&state, 80),
1875            HELP_QUIT,
1876            "the rows are not on the screen"
1877        );
1878    }
1879
1880    #[test]
1881    fn the_detail_of_the_only_vcon_names_no_key_that_moves() {
1882        assert_eq!(
1883            footer_at(&press(listed(1, None), &[Action::Open]), 80),
1884            "Esc back  r refresh  ? help  q quit",
1885            "there is no other vCon to show"
1886        );
1887    }
1888
1889    #[test]
1890    fn the_detail_view_names_back_while_the_list_is_read_again() {
1891        let state = press(listed(3, None), &[Action::Open, Action::Refresh]);
1892        assert_eq!(
1893            footer_at(&state, 80),
1894            "Esc back  ? help  q quit",
1895            "Esc still returns to the list"
1896        );
1897    }
1898
1899    #[test]
1900    fn the_detail_view_names_back_and_refresh_after_a_failure() {
1901        let state = page_failed(
1902            press(listed(3, None), &[Action::Open, Action::Refresh]),
1903            ApiError::Status(503, None),
1904        );
1905        assert_eq!(
1906            footer_at(&state, 80),
1907            "Esc back  r refresh  ? help  q quit",
1908            "there is no row to move to"
1909        );
1910    }
1911
1912    #[test]
1913    fn a_detail_view_whose_vcon_is_gone_names_the_keys_that_show_another() {
1914        for left in [1, 3] {
1915            assert_eq!(
1916                footer_at(&detail_gone(left), 80),
1917                "Esc back  j down  k up  r refresh  ? help  q quit",
1918                "with {left} left, j and k show a vCon that is listed"
1919            );
1920        }
1921    }
1922
1923    #[test]
1924    fn a_detail_view_with_no_vcon_left_names_back_and_refresh() {
1925        assert_eq!(
1926            footer_at(&detail_gone(0), 80),
1927            "Esc back  r refresh  ? help  q quit",
1928            "no vCon is left to show"
1929        );
1930    }
1931
1932    #[test]
1933    fn help_names_back_and_quit_over_every_state() {
1934        for state in [
1935            connecting(),
1936            connected(),
1937            listed(0, None),
1938            listed(3, Some("cursor-2")),
1939            failed(ApiError::Status(401, None)),
1940            with_key(None, "admin"),
1941            press(listed(3, None), &[Action::Open]),
1942        ] {
1943            assert_eq!(
1944                footer_at(&press(state, &[Action::Help]), 80),
1945                "Esc back  q quit",
1946                "help has two keys of its own"
1947            );
1948        }
1949    }
1950
1951    #[test]
1952    fn at_40_columns_the_short_footers_are_whole() {
1953        for (state, wanted) in [
1954            (connecting(), HELP_QUIT),
1955            (listed(0, None), RETRY),
1956            (failed(ApiError::Status(401, None)), RETRY),
1957            (with_key(None, "admin"), HELP_QUIT),
1958        ] {
1959            assert_eq!(footer_at(&state, 40), wanted, "the hints fit 40 columns");
1960        }
1961    }
1962
1963    #[test]
1964    fn every_hint_on_every_shown_screen_is_a_key_that_acts() {
1965        for one in Screen::ALL {
1966            let (name, state, (columns, rows)) = (one.name(), one.state(), one.size());
1967            if columns < 40 || rows < 8 {
1968                continue;
1969            }
1970            let lines = screen(&state, columns, rows);
1971            let footer = lines[usize::from(rows) - 1].trim_end().to_owned();
1972            assert!(!footer.is_empty(), "{name}: the last line holds hints");
1973            for hint in footer.split("  ") {
1974                let binding = BINDINGS
1975                    .iter()
1976                    .find(|b| format!("{} {}", b.label, b.hint) == hint)
1977                    .unwrap_or_else(|| panic!("{name}: {hint:?} is a binding's hint"));
1978                assert!(
1979                    state.acts(binding.action),
1980                    "{name}: {hint:?} is shown, and the key does nothing there"
1981                );
1982            }
1983        }
1984    }
1985
1986    #[test]
1987    fn a_failure_the_server_made_still_says_to_press_r() {
1988        for state in [
1989            failed(client::no_answer(client::TIMEOUT)),
1990            failed(ApiError::Status(401, None)),
1991            page_failed(connected(), ApiError::Status(503, None)),
1992        ] {
1993            let shown = text(&state);
1994            assert!(
1995                shown.contains("Press r to try again, or q to quit."),
1996                "r asks the server again: {shown}"
1997            );
1998        }
1999    }
2000
2001    /// The text of the lines from `first` on, without the key hints, joined
2002    /// as a reader reads a wrapped sentence.
2003    fn joined(lines: &[String], first: usize) -> String {
2004        lines[first..lines.len().saturating_sub(1)]
2005            .iter()
2006            .map(|line| line.trim())
2007            .collect::<Vec<_>>()
2008            .join(" ")
2009    }
2010
2011    #[test]
2012    fn a_notice_longer_than_the_terminal_is_wrapped_not_cut() {
2013        let mut state = press(listed(2, Some("cursor-1")), &[Action::More]);
2014        state.step(
2015            Event::Page(Err(ApiError::Unreachable(
2016                "error sending request for url (https://vcon.example.com:8443/vcons): client error (Connect): tcp connect error: Connection refused (os error 111)".to_owned(),
2017            ))),
2018            NOW,
2019        );
2020        let lines = screen(&state, 80, 24);
2021        let said = joined(&lines, 19);
2022        assert!(
2023            said.contains("The next page was not read: the server did not answer: ")
2024                && said.ends_with("Connection refused (os error 111)."),
2025            "the whole sentence is on screen, to its end: {said}"
2026        );
2027        assert!(
2028            lines[2].contains(&row(0).uuid),
2029            "the rows stay: {}",
2030            lines[2]
2031        );
2032    }
2033
2034    #[test]
2035    fn a_short_notice_takes_one_line() {
2036        let mut state = press(listed(2, Some("cursor-1")), &[Action::More]);
2037        state.step(
2038            Event::Page(Err(ApiError::Unreachable("timed out".to_owned()))),
2039            NOW,
2040        );
2041        let lines = screen(&state, 80, 24);
2042        assert!(
2043            lines[22].starts_with("The next page was not read"),
2044            "on the line above the key hints: {}",
2045            lines[22]
2046        );
2047        assert_eq!(lines[21].trim(), "", "and the line above it is empty");
2048    }
2049
2050    #[test]
2051    fn at_60_columns_the_position_line_keeps_when_the_list_was_read() {
2052        let lines = screen(&listed(2, Some("cursor-1")), 60, 24);
2053        let said = joined(&lines, 20);
2054        assert!(
2055            said.contains("1 of 2 read, more on the server")
2056                && said.ends_with("as of 2026-11-10 01:20:00 UTC+00:00"),
2057            "the position and the time are whole: {said}"
2058        );
2059    }
2060
2061    // A failure whose remedy is in a file the UI read at start.
2062
2063    /// What `r` cannot do, as the screen says it.
2064    const AT_START: &str =
2065        "A change to the client file or the key file takes effect at the next start.";
2066
2067    #[test]
2068    fn a_refused_key_says_that_a_new_key_file_needs_a_new_start() {
2069        let shown = text(&shown_refusal(ApiError::Status(401, None)));
2070        assert!(
2071            shown.contains(AT_START),
2072            "the token is read once, so r cannot read a corrected key file: {shown}"
2073        );
2074    }
2075
2076    #[test]
2077    fn a_refused_certificate_says_that_a_new_ca_needs_a_new_start() {
2078        let advice =
2079            client::certificate_advice(&rustls::CertificateError::UnknownIssuer).expect("advice");
2080        let shown = text(&shown_refusal(ApiError::Untrusted(advice.to_owned())));
2081        assert!(
2082            shown
2083                .replace('\n', " ")
2084                .contains("set ca in the client file")
2085                && shown.contains(AT_START),
2086            "the advice names the client file, which is read once: {shown}"
2087        );
2088    }
2089
2090    #[test]
2091    fn a_key_that_may_not_list_says_that_another_key_needs_a_new_start() {
2092        for state in [
2093            shown_key(None, &[]),
2094            shown_key(Some(SHOWN_TENANT), &["write"]),
2095        ] {
2096            let shown = text(&state);
2097            assert!(
2098                shown.contains(AT_START),
2099                "another key is another key file, read at start: {shown}"
2100            );
2101        }
2102    }
2103
2104    #[test]
2105    fn a_failure_still_names_r_and_q() {
2106        let shown = text(&shown_refusal(client::no_answer(client::TIMEOUT)));
2107        assert!(
2108            shown.contains("Press r to try again, or q to quit."),
2109            "a server that did not answer may answer the next request: {shown}"
2110        );
2111    }
2112
2113    #[test]
2114    fn an_empty_tenant_does_not_mention_the_files() {
2115        let shown = text(&shown_page(
2116            shown_key(Some(SHOWN_TENANT), &["read"]),
2117            0..0,
2118            false,
2119        ));
2120        assert!(
2121            !shown.contains(AT_START),
2122            "nothing failed, so there is nothing to correct: {shown}"
2123        );
2124    }
2125
2126    // The screens the site shows.
2127
2128    /// The file the terminal UI's page and the home page draw their screens
2129    /// from: `tui_screen` in website/templates/components.html.
2130    fn screens_file() -> std::path::PathBuf {
2131        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../website/data/tui-screens.json")
2132    }
2133
2134    /// The class names website/sass/style.scss styles a cell with.
2135    fn classes(cell: &Cell) -> String {
2136        assert_eq!(cell.bg, Color::Reset, "the site draws no background color");
2137        let mut out = Vec::new();
2138        if cell.modifier.contains(Modifier::BOLD) {
2139            out.push("bold");
2140        }
2141        if cell.modifier.contains(Modifier::REVERSED) {
2142            out.push("reversed");
2143        }
2144        match cell.fg {
2145            Color::Reset => {}
2146            Color::Green => out.push("green"),
2147            Color::Yellow => out.push("yellow"),
2148            Color::Red => out.push("red"),
2149            other => panic!("the site has no class for {other:?}"),
2150        }
2151        out.join(" ")
2152    }
2153
2154    /// The screen, in color, in a terminal of `columns` by `rows`: each line as runs of text that
2155    /// share one style, without the plain blanks that end a line.
2156    fn styled(state: &State, columns: u16, rows: u16) -> serde_json::Value {
2157        let terminal = terminal(state, columns, rows, COLOR);
2158        let buffer = terminal.backend().buffer();
2159        let lines: Vec<serde_json::Value> = (0..rows)
2160            .map(|y| {
2161                let mut runs: Vec<(String, String)> = Vec::new();
2162                for x in 0..columns {
2163                    let cell = &buffer[(x, y)];
2164                    let class = classes(cell);
2165                    match runs.last_mut() {
2166                        Some((last, text)) if *last == class => text.push_str(cell.symbol()),
2167                        _ => runs.push((class, cell.symbol().to_owned())),
2168                    }
2169                }
2170                if let Some((class, text)) = runs.last_mut()
2171                    && class.is_empty()
2172                {
2173                    text.truncate(text.trim_end().len());
2174                }
2175                runs.retain(|(_, text)| !text.is_empty());
2176                runs.into_iter()
2177                    .map(|(class, text)| serde_json::json!({"class": class, "text": text}))
2178                    .collect()
2179            })
2180            .collect();
2181        serde_json::json!({"columns": columns, "lines": lines})
2182    }
2183
2184    #[test]
2185    fn the_site_shows_the_screens_draw_makes() {
2186        let mut made = serde_json::Map::new();
2187        for screen in Screen::ALL {
2188            let (name, (columns, rows)) = (screen.name(), screen.size());
2189            let drawn = styled(&screen.state(), columns, rows);
2190            let before = made.insert(name.to_owned(), drawn);
2191            assert!(before.is_none(), "the screen {name} is made once");
2192        }
2193        let made = format!(
2194            "{}\n",
2195            serde_json::to_string_pretty(&serde_json::Value::Object(made)).expect("JSON")
2196        );
2197        let path = screens_file();
2198        if std::env::var_os("VCON_SERVER_WRITE_SCREENS").is_some() {
2199            std::fs::write(&path, &made)
2200                .unwrap_or_else(|e| panic!("write {}: {e}", path.display()));
2201        }
2202        let shown = std::fs::read_to_string(&path)
2203            .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
2204        assert!(
2205            shown == made,
2206            "{} is not the screens draw makes now: run this test with VCON_SERVER_WRITE_SCREENS=1 to write them again",
2207            path.display()
2208        );
2209    }
2210}