1use 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
19const MIN_COLUMNS: u16 = 40;
21const MIN_LINES: u16 = 8;
22const ZONE: &str = "UTC+00:00";
24const UUID_COLUMNS: u16 = 38;
27const TIME_COLUMNS: u16 = 21;
28const VERSION_COLUMNS: u16 = 34;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct Theme {
33 pub color: bool,
35}
36
37#[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#[must_use]
52pub fn utc(text: &str) -> String {
53 OffsetDateTime::parse(text, &Rfc3339).map_or_else(|_| text.to_owned(), stamp)
54}
55
56fn 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
70pub 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 let body = Rect {
86 y: area.y.saturating_add(1),
87 height: area.height.saturating_sub(3),
88 ..area
89 };
90 frame.render_widget(Paragraph::new(status(state, area.width, theme)), line(0));
91 match state.view {
92 View::List => list(frame, state, body),
93 View::Detail => detail(frame, state, body),
94 View::Help => help(frame, body),
95 }
96 frame.render_widget(
97 Paragraph::new(notice(state)),
98 line(area.height.saturating_sub(2)),
99 );
100 frame.render_widget(
101 Paragraph::new(hints(state.view)),
102 line(area.height.saturating_sub(1)),
103 );
104}
105
106enum Owner<'a> {
108 Unknown,
110 Operator,
112 Tenant(&'a str),
114}
115
116const SCHEME: &str = "https://";
118const BETWEEN: &str = " | ";
120const CUT: &str = "...";
122const ID_MIN: usize = 4;
124
125fn status_lead(server: &str, owner: &Owner<'_>, word: &str, columns: usize) -> String {
141 let length = |text: &str| text.chars().count();
142 let owner_whole = match owner {
143 Owner::Unknown => "tenant unknown".to_owned(),
144 Owner::Operator => "no tenant (operator key)".to_owned(),
145 Owner::Tenant(id) => format!("tenant {id}"),
146 };
147 let room = columns.saturating_sub(length(word));
149 let with_owner = |address: &str, owner: &str| format!("{address}{BETWEEN}{owner}{BETWEEN}");
150 let whole = with_owner(server, &owner_whole);
151 if length(&whole) <= room {
152 return whole;
153 }
154 let bare = server.strip_prefix(SCHEME).unwrap_or(server);
155 let unschemed = with_owner(bare, &owner_whole);
156 if length(&unschemed) <= room {
157 return unschemed;
158 }
159 if let Owner::Tenant(id) = owner {
160 let around = length(&with_owner(bare, "tenant ")).saturating_add(length(CUT));
161 let kept = room.saturating_sub(around);
162 if kept >= ID_MIN {
163 let id: String = id.chars().take(kept).collect();
164 return with_owner(bare, &format!("tenant {id}{CUT}"));
165 }
166 }
167 let alone = format!("{bare}{BETWEEN}");
168 if length(&alone) <= room {
169 return alone;
170 }
171 let kept = room.saturating_sub(length(BETWEEN).saturating_add(length(CUT)));
172 let address: String = bare.chars().take(kept).collect();
173 format!("{address}{CUT}{BETWEEN}")
174}
175
176fn status(state: &State, columns: u16, theme: Theme) -> Line<'static> {
179 let (owner, word, color) = match &state.connection {
180 Connection::Connecting => (Owner::Unknown, "connecting", Color::Yellow),
181 Connection::Failed(_) => (Owner::Unknown, "not connected", Color::Red),
182 Connection::Connected(info) => (
183 info.tenant
184 .as_deref()
185 .map_or(Owner::Operator, Owner::Tenant),
186 "connected",
187 Color::Green,
188 ),
189 };
190 let lead = status_lead(&state.server, &owner, word, usize::from(columns));
191 let mut style = Style::new().add_modifier(Modifier::BOLD);
192 if theme.color {
193 style = style.fg(color);
194 }
195 Line::from(vec![Span::raw(lead), Span::styled(word, style)])
196}
197
198fn message(frame: &mut Frame<'_>, body: Rect, lines: Vec<String>) {
200 let lines: Vec<Line<'_>> = lines.into_iter().map(Line::from).collect();
201 frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), body);
202}
203
204fn waiting(state: &State, loading: &str) -> Option<Vec<String>> {
207 if state.connection == Connection::Connecting {
208 return Some(vec![
209 "Connecting to the server...".to_owned(),
210 String::new(),
211 "Press q to quit.".to_owned(),
212 ]);
213 }
214 match &state.listing {
215 Listing::Ready => None,
216 Listing::Loading => Some(vec![
217 loading.to_owned(),
218 String::new(),
219 "Press q to quit.".to_owned(),
220 ]),
221 Listing::Failed(why) => {
222 let mut lines = vec![format!("Could not list vCons: {why}."), String::new()];
223 if why.contains("(401)") {
224 lines
225 .push("Check that key_file holds a key the server has not revoked.".to_owned());
226 }
227 lines.push("Press r to try again, or q to quit.".to_owned());
228 Some(lines)
229 }
230 }
231}
232
233fn list(frame: &mut Frame<'_>, state: &State, body: Rect) {
235 if let Some(lines) = waiting(state, "Loading vCons...") {
236 return message(frame, body, lines);
237 }
238 if state.rows.is_empty() {
239 let lines = vec![
240 "This tenant has no vCons.".to_owned(),
241 String::new(),
242 "Press r to read again, or q to quit.".to_owned(),
243 ];
244 return message(frame, body, lines);
245 }
246 let times = u16::from(body.width >= UUID_COLUMNS.saturating_add(TIME_COLUMNS)).saturating_add(
247 u16::from(body.width >= UUID_COLUMNS.saturating_add(TIME_COLUMNS.saturating_mul(2))),
248 );
249 let version = body.width
250 >= UUID_COLUMNS
251 .saturating_add(TIME_COLUMNS.saturating_mul(2))
252 .saturating_add(VERSION_COLUMNS);
253 let columns = |marker: &str, uuid: &str, stored: &str, updated: &str, tag: &str| {
254 let mut text = format!("{marker}{uuid:<36}");
255 if times >= 1 {
256 text.push_str(&format!(" {stored:<19}"));
257 }
258 if times >= 2 {
259 text.push_str(&format!(" {updated:<19}"));
260 }
261 if version {
262 text.push_str(&format!(" {tag}"));
263 }
264 text
265 };
266 let visible = usize::from(body.height.saturating_sub(1));
267 let first = state.selected.saturating_add(1).saturating_sub(visible);
268 let mut lines = vec![Line::styled(
269 columns(
270 " ",
271 "UUID",
272 &format!("STORED ({ZONE})"),
273 &format!("UPDATED ({ZONE})"),
274 "VERSION",
275 ),
276 Style::new().add_modifier(Modifier::BOLD),
277 )];
278 for (index, row) in state.rows.iter().enumerate().skip(first).take(visible) {
279 let selected = index == state.selected;
280 let text = columns(
281 if selected { "> " } else { " " },
282 &row.uuid,
283 &utc(&row.stored_at),
284 &utc(&row.updated_at),
285 &row.version,
286 );
287 let style = if selected {
288 Style::new().add_modifier(Modifier::REVERSED)
289 } else {
290 Style::new()
291 };
292 lines.push(Line::styled(text, style));
293 }
294 frame.render_widget(Paragraph::new(lines), body);
295}
296
297fn detail(frame: &mut Frame<'_>, state: &State, body: Rect) {
299 if let Some(lines) = waiting(state, "Reading the list again...") {
300 return message(frame, body, lines);
301 }
302 let lines = match state.detail_row() {
303 Some(row) => metadata(row),
304 None => vec![
305 "This vCon is no longer in the list: it was deleted, or it is past the pages read."
306 .to_owned(),
307 String::new(),
308 "Press Esc to go back.".to_owned(),
309 ],
310 };
311 message(frame, body, lines);
312}
313
314fn metadata(row: &Row) -> Vec<String> {
316 vec![
317 format!("vCon {}", row.uuid),
318 String::new(),
319 format!("Version {}", row.version),
320 format!("First stored {} {ZONE}", utc(&row.stored_at)),
321 format!("Last updated {} {ZONE}", utc(&row.updated_at)),
322 String::new(),
323 "Content is not shown: this view lists metadata only.".to_owned(),
324 ]
325}
326
327fn help(frame: &mut Frame<'_>, body: Rect) {
329 let mut lines = vec!["Keys".to_owned()];
330 for binding in &BINDINGS {
331 lines.push(format!(" {:<7}{}", binding.label, binding.does));
332 }
333 lines.push(String::new());
334 lines.push(format!("Every time shown is in UTC ({ZONE})."));
335 message(frame, body, lines);
336}
337
338fn notice(state: &State) -> String {
341 if let Some(notice) = &state.notice {
342 return notice.clone();
343 }
344 if state.more {
345 return "Reading the next page...".to_owned();
346 }
347 let (Listing::Ready, Some(as_of)) = (&state.listing, state.as_of) else {
348 return String::new();
349 };
350 if state.rows.is_empty() {
351 return format!("as of {} {ZONE}", stamp(as_of));
352 }
353 let more = if state.next.is_some() {
354 ", more on the server"
355 } else {
356 ""
357 };
358 format!(
359 "{} of {} read{more} | as of {} {ZONE}",
360 state.selected.saturating_add(1),
361 state.rows.len(),
362 stamp(as_of)
363 )
364}
365
366fn hints(view: View) -> String {
368 let actions: &[Action] = match view {
369 View::List => &[
370 Action::Down,
371 Action::Up,
372 Action::Open,
373 Action::Refresh,
374 Action::More,
375 Action::Help,
376 Action::Quit,
377 ],
378 View::Detail => &[
379 Action::Back,
380 Action::Down,
381 Action::Up,
382 Action::Refresh,
383 Action::Help,
384 Action::Quit,
385 ],
386 View::Help => &[Action::Back, Action::Quit],
387 };
388 actions
389 .iter()
390 .filter_map(|action| binding(*action))
391 .map(|binding| format!("{} {}", binding.label, binding.hint))
392 .collect::<Vec<_>>()
393 .join(" ")
394}
395
396#[cfg(test)]
397mod tests {
398 use ratatui::Terminal;
399 use ratatui::backend::TestBackend;
400 use ratatui::buffer::Cell;
401 use ratatui::style::{Color, Modifier};
402 use time::format_description::well_known::Rfc3339;
403 use time::macros::datetime;
404 use time::{Duration, OffsetDateTime};
405
406 use super::{Theme, draw, theme, utc};
407 use crate::tui::keys::BINDINGS;
408 use crate::tui::state::{Action, ApiError, Event, KeyInfo, Page, Row, State};
409
410 const NOW: OffsetDateTime = datetime!(2026-11-10 01:20:00 UTC);
411 const MONO: Theme = Theme { color: false };
412 const COLOR: Theme = Theme { color: true };
413
414 fn row(n: u8) -> Row {
415 Row {
416 uuid: format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc{n:02}"),
417 stored_at: "2026-10-25T12:00:00.123456789Z".to_owned(),
418 updated_at: "2026-10-25T12:30:00Z".to_owned(),
419 version: format!("4f0c4b0a1d2e3f405162738495a6b7{n:02}"),
420 }
421 }
422
423 fn connecting() -> State {
424 State::new("https://vcon.example.com:8443", (80, 24)).0
425 }
426
427 fn connected() -> State {
428 let mut state = connecting();
429 state.step(
430 Event::KeyInfo(Ok(KeyInfo {
431 id: "0123456789abcdef".to_owned(),
432 tenant: Some("t_example".to_owned()),
433 scopes: vec!["read".to_owned()],
434 })),
435 NOW,
436 );
437 state
438 }
439
440 fn listed(rows: u8, next: Option<&str>) -> State {
441 let mut state = connected();
442 state.step(
443 Event::Page(Ok(Page {
444 vcons: (0..rows).map(row).collect(),
445 next: next.map(str::to_owned),
446 })),
447 NOW,
448 );
449 state
450 }
451
452 fn press(mut state: State, actions: &[Action]) -> State {
453 for action in actions {
454 state.step(Event::Action(*action), NOW);
455 }
456 state
457 }
458
459 fn terminal(state: &State, columns: u16, lines: u16, theme: Theme) -> Terminal<TestBackend> {
460 let mut terminal = Terminal::new(TestBackend::new(columns, lines)).expect("a terminal");
461 terminal
462 .draw(|frame| draw(frame, state, theme))
463 .expect("a frame");
464 terminal
465 }
466
467 fn screen(state: &State, columns: u16, lines: u16) -> Vec<String> {
469 let terminal = terminal(state, columns, lines, MONO);
470 let buffer = terminal.backend().buffer();
471 (0..lines)
472 .map(|y| (0..columns).map(|x| buffer[(x, y)].symbol()).collect())
473 .collect()
474 }
475
476 fn text(state: &State) -> String {
477 screen(state, 80, 24).join("\n")
478 }
479
480 #[test]
483 fn the_status_line_names_the_server_the_tenant_and_the_connection() {
484 let lines = screen(&listed(1, None), 80, 24);
485 assert!(
486 lines[0].contains("https://vcon.example.com:8443"),
487 "the server: {}",
488 lines[0]
489 );
490 assert!(
491 lines[0].contains("tenant t_example"),
492 "the tenant: {}",
493 lines[0]
494 );
495 assert!(
496 lines[0].contains("connected"),
497 "the connection, in words: {}",
498 lines[0]
499 );
500 }
501
502 #[test]
503 fn the_list_shows_each_vcon_with_its_times_in_utc() {
504 let lines = screen(&listed(2, None), 80, 24);
505 assert!(
506 lines[1].contains("STORED (UTC+00:00)"),
507 "the header states the offset: {}",
508 lines[1]
509 );
510 assert!(
511 lines[2].contains(&row(0).uuid),
512 "the first row's uuid: {}",
513 lines[2]
514 );
515 assert!(
516 lines[2].contains("2026-10-25 12:00:00"),
517 "its stored time: {}",
518 lines[2]
519 );
520 assert!(
521 lines[2].contains("2026-10-25 12:30:00"),
522 "its updated time: {}",
523 lines[2]
524 );
525 assert!(
526 lines[3].contains(&row(1).uuid),
527 "the second row: {}",
528 lines[3]
529 );
530 }
531
532 #[test]
533 fn the_selected_row_is_marked_with_a_character() {
534 let lines = screen(&press(listed(3, None), &[Action::Down]), 80, 24);
535 assert!(
536 lines[3].starts_with("> "),
537 "the selected row has a marker: {}",
538 lines[3]
539 );
540 assert!(
541 lines[2].starts_with(" "),
542 "the others do not: {}",
543 lines[2]
544 );
545 }
546
547 #[test]
548 fn the_list_footer_hints_are_real_bindings() {
549 let lines = screen(&listed(1, None), 80, 24);
550 let footer = &lines[23];
551 for wanted in [Action::Open, Action::Refresh, Action::Help, Action::Quit] {
552 let binding = BINDINGS
553 .iter()
554 .find(|b| b.action == wanted)
555 .expect("a binding");
556 assert!(
557 footer.contains(&format!("{} {}", binding.label, binding.hint)),
558 "the footer shows {wanted:?} as bound: {footer}"
559 );
560 }
561 }
562
563 #[test]
564 fn the_notice_line_says_how_many_are_loaded_and_as_of_when() {
565 let lines = screen(&listed(2, Some("cursor-1")), 80, 24);
566 assert!(lines[22].contains("1 of 2"), "the position: {}", lines[22]);
567 assert!(
568 lines[22].contains("more on the server"),
569 "that more exist: {}",
570 lines[22]
571 );
572 assert!(
573 lines[22].contains("as of 2026-11-10 01:20:00 UTC+00:00"),
574 "when it was read, with the offset: {}",
575 lines[22]
576 );
577 }
578
579 #[test]
580 fn the_detail_view_shows_the_metadata_and_says_content_is_not_shown() {
581 let shown = text(&press(listed(2, None), &[Action::Open]));
582 assert!(shown.contains(&row(0).uuid), "the uuid: {shown}");
583 assert!(shown.contains(&row(0).version), "the version: {shown}");
584 assert!(
585 shown.contains("2026-10-25 12:00:00 UTC+00:00"),
586 "first stored: {shown}"
587 );
588 assert!(
589 shown.contains("2026-10-25 12:30:00 UTC+00:00"),
590 "last updated: {shown}"
591 );
592 assert!(
593 shown.contains("Content is not shown"),
594 "what is left out: {shown}"
595 );
596 assert!(shown.contains("Esc back"), "how to leave: {shown}");
597 }
598
599 #[test]
600 fn the_help_view_lists_every_binding() {
601 let shown = text(&press(listed(1, None), &[Action::Help]));
602 for binding in &BINDINGS {
603 assert!(
604 shown.contains(binding.label),
605 "{} is listed: {shown}",
606 binding.label
607 );
608 assert!(
609 shown.contains(binding.does),
610 "{} is described: {shown}",
611 binding.does
612 );
613 }
614 }
615
616 #[test]
617 fn the_list_scrolls_to_keep_the_selection_on_screen() {
618 let state = press(listed(60, None), &[Action::Bottom]);
619 let shown = text(&state);
620 assert!(
621 shown.contains(&format!("> {}", row(59).uuid)),
622 "the last row is drawn selected"
623 );
624 assert!(
625 !shown.contains(&row(0).uuid),
626 "the first row has scrolled off"
627 );
628 }
629
630 #[test]
631 fn with_color_the_connection_is_colored_and_still_in_words() {
632 let state = listed(1, None);
633 let terminal = terminal(&state, 80, 24, COLOR);
634 let buffer = terminal.backend().buffer();
635 let colored = (0..80).any(|x| buffer[(x, 0)].fg != Color::Reset);
636 assert!(colored, "a color terminal gets color");
637 assert!(
638 screen(&state, 80, 24)[0].contains("connected"),
639 "and the word is still there"
640 );
641 }
642
643 #[test]
644 fn rfc_3339_times_are_shown_to_the_second_in_utc() {
645 assert_eq!(
646 utc("2026-10-25T12:00:00.123456789Z"),
647 "2026-10-25 12:00:00",
648 "fractions dropped"
649 );
650 assert_eq!(
651 utc("2026-10-25T14:30:00+02:00"),
652 "2026-10-25 12:30:00",
653 "an offset is converted"
654 );
655 }
656
657 #[test]
658 fn a_color_terminal_gets_color() {
659 assert_eq!(
660 theme(None, Some("xterm-256color")),
661 COLOR,
662 "nothing asks for none"
663 );
664 }
665
666 #[test]
667 fn a_wider_terminal_shows_the_version_column() {
668 let lines = screen(&listed(1, None), 132, 43);
669 assert!(lines[1].contains("VERSION"), "the header: {}", lines[1]);
670 assert!(
671 lines[2].contains(&row(0).version),
672 "the version: {}",
673 lines[2]
674 );
675 }
676
677 #[test]
680 fn a_failed_connection_is_said_in_the_status_line_and_the_list() {
681 let mut state = connecting();
682 state.step(
683 Event::KeyInfo(Err(ApiError::Unreachable("connection refused".to_owned()))),
684 NOW,
685 );
686 let lines = screen(&state, 80, 24);
687 assert!(
688 lines[0].contains("not connected"),
689 "the status line: {}",
690 lines[0]
691 );
692 let shown = lines.join("\n");
693 assert!(shown.contains("connection refused"), "why: {shown}");
694 assert!(
695 shown.contains("Press r to try again"),
696 "what to press: {shown}"
697 );
698 }
699
700 #[test]
701 fn a_long_error_wraps_instead_of_being_cut() {
702 let mut state = connected();
703 let long = format!("{} the-end", "word ".repeat(30));
704 state.step(Event::Page(Err(ApiError::Malformed(long))), NOW);
705 assert!(
706 text(&state).contains("the-end"),
707 "the whole reason is on screen"
708 );
709 }
710
711 #[test]
712 fn an_operator_key_is_named_in_the_status_line() {
713 let mut state = connecting();
714 state.step(
715 Event::KeyInfo(Ok(KeyInfo {
716 id: "0123456789abcdef".to_owned(),
717 tenant: None,
718 scopes: vec!["admin".to_owned()],
719 })),
720 NOW,
721 );
722 let lines = screen(&state, 80, 24);
723 assert!(
724 lines[0].contains("no tenant (operator key)"),
725 "the status line: {}",
726 lines[0]
727 );
728 assert!(
729 lines
730 .join("\n")
731 .contains("this is an operator key, which reaches no vCon"),
732 "and the list says why it is empty"
733 );
734 }
735
736 #[test]
737 fn a_failed_next_page_shows_its_notice_over_the_rows() {
738 let mut state = press(listed(2, Some("cursor-1")), &[Action::More]);
739 state.step(
740 Event::Page(Err(ApiError::Unreachable("timed out".to_owned()))),
741 NOW,
742 );
743 let lines = screen(&state, 80, 24);
744 assert!(
745 lines[22].contains("The next page was not read"),
746 "the notice: {}",
747 lines[22]
748 );
749 assert!(
750 lines[2].contains(&row(0).uuid),
751 "the rows stay: {}",
752 lines[2]
753 );
754 }
755
756 #[test]
757 fn the_detail_of_a_vcon_no_longer_listed_says_so() {
758 let mut state = press(listed(2, None), &[Action::Open, Action::Refresh]);
759 state.step(
760 Event::Page(Ok(Page {
761 vcons: vec![row(1)],
762 next: None,
763 })),
764 NOW,
765 );
766 let shown = text(&state);
767 assert!(
768 shown.contains("no longer in the list"),
769 "what happened: {shown}"
770 );
771 assert!(
772 shown.contains("Press Esc to go back"),
773 "what to press: {shown}"
774 );
775 }
776
777 #[test]
778 fn the_detail_view_shows_a_failed_refresh() {
779 let mut state = press(listed(2, None), &[Action::Open, Action::Refresh]);
780 state.step(Event::Page(Err(ApiError::Status(503, None))), NOW);
781 let shown = text(&state);
782 assert!(shown.contains("the server answered 503"), "why: {shown}");
783 assert!(
784 shown.contains("Press r to try again"),
785 "what to press: {shown}"
786 );
787 }
788
789 #[test]
790 fn a_terminal_too_small_says_so_and_how_to_quit() {
791 let lines = screen(&listed(3, None), 30, 5);
792 let shown = lines.join("\n");
793 assert!(shown.contains("too small"), "what is wrong: {shown}");
794 assert!(shown.contains("q"), "the way out: {shown}");
795 assert!(!shown.contains("01a07da8"), "no half-drawn list");
796 }
797
798 #[test]
799 fn a_time_that_does_not_parse_is_shown_as_sent() {
800 assert_eq!(utc("yesterday"), "yesterday", "nothing is invented for it");
801 }
802
803 #[test]
804 fn a_refused_key_says_to_check_the_key_file() {
805 let mut state = connecting();
806 state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
807 let shown = text(&state);
808 assert!(shown.contains("refused the key (401)"), "why: {shown}");
809 assert!(shown.contains("key_file"), "where to look: {shown}");
810 }
811
812 #[test]
815 fn the_loading_state_says_so_and_how_to_quit() {
816 let shown = text(&connected());
817 assert!(
818 shown.contains("Loading vCons"),
819 "what is happening: {shown}"
820 );
821 assert!(shown.contains("q quit"), "the way out: {shown}");
822 }
823
824 #[test]
825 fn the_connecting_state_is_in_the_status_line() {
826 let lines = screen(&connecting(), 80, 24);
827 assert!(
828 lines[0].contains("connecting"),
829 "the status line: {}",
830 lines[0]
831 );
832 assert!(
833 lines.join("\n").contains("Connecting to the server"),
834 "and the body"
835 );
836 }
837
838 #[test]
839 fn an_empty_tenant_says_so_and_what_to_press() {
840 let shown = text(&listed(0, None));
841 assert!(
842 shown.contains("This tenant has no vCons"),
843 "what happened: {shown}"
844 );
845 assert!(
846 shown.contains("Press r to read again"),
847 "what to press: {shown}"
848 );
849 }
850
851 #[test]
852 fn the_detail_view_says_refreshing_while_a_refresh_is_in_flight() {
853 let shown = text(&press(listed(2, None), &[Action::Open, Action::Refresh]));
854 assert!(
855 shown.contains("Reading the list again"),
856 "what is happening: {shown}"
857 );
858 }
859
860 #[test]
861 fn at_80_columns_every_list_column_fits() {
862 let lines = screen(&listed(1, None), 80, 24);
863 assert!(
864 lines[2].trim_end().ends_with("2026-10-25 12:30:00"),
865 "the last column is whole: {}",
866 lines[2]
867 );
868 }
869
870 #[test]
871 fn below_80_columns_the_updated_column_is_dropped_not_cut() {
872 let lines = screen(&listed(1, None), 60, 24);
873 assert!(
874 lines[2].contains("2026-10-25 12:00:00"),
875 "stored stays: {}",
876 lines[2]
877 );
878 assert!(
879 !lines[2].contains("2026-10-25 12:3"),
880 "no part of updated: {}",
881 lines[2]
882 );
883 assert!(
884 !lines[1].contains("UPDATED"),
885 "nor its header: {}",
886 lines[1]
887 );
888 }
889
890 #[test]
891 fn every_size_from_1x1_up_draws_without_a_panic() {
892 let states = [
893 connecting(),
894 listed(0, None),
895 listed(60, Some("cursor-1")),
896 press(listed(3, None), &[Action::Open]),
897 press(listed(3, None), &[Action::Help]),
898 ];
899 for state in &states {
900 for columns in [1, 2, 10, 39, 40, 79, 80, 200] {
901 for lines in [1, 2, 7, 8, 24, 60] {
902 let drawn = screen(state, columns, lines);
903 assert_eq!(
904 drawn.len(),
905 usize::from(lines),
906 "{columns}x{lines} drew a frame"
907 );
908 }
909 }
910 }
911 }
912
913 #[test]
914 fn no_color_and_a_dumb_terminal_turn_color_off() {
915 assert_eq!(
916 theme(Some("1"), Some("xterm-256color")),
917 MONO,
918 "NO_COLOR set"
919 );
920 assert_eq!(theme(None, Some("dumb")), MONO, "a terminal with no color");
921 assert_eq!(theme(None, None), MONO, "no TERM at all");
922 assert_eq!(
923 theme(Some(""), Some("xterm")),
924 COLOR,
925 "an empty NO_COLOR is not set"
926 );
927 }
928
929 #[test]
930 fn without_color_no_cell_has_a_color() {
931 for state in [
932 listed(3, None),
933 press(listed(3, None), &[Action::Help]),
934 connecting(),
935 ] {
936 let terminal = terminal(&state, 80, 24, MONO);
937 let buffer = terminal.backend().buffer();
938 for cell in buffer.content() {
939 assert_eq!(cell.fg, Color::Reset, "no foreground color");
940 assert_eq!(cell.bg, Color::Reset, "no background color");
941 }
942 }
943 }
944
945 #[test]
946 fn the_status_line_keeps_the_connection_when_the_address_is_long() {
947 let mut state = State::new(
948 &format!("https://{}.example.com:8443", "a".repeat(90)),
949 (80, 24),
950 )
951 .0;
952 state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
953 let lines = screen(&state, 80, 24);
954 assert!(
955 lines[0].contains("not connected"),
956 "the state is never pushed off: {}",
957 lines[0]
958 );
959 }
960
961 const SERVER: &str = "https://vcon.example.com:8443";
965 const LONG_ID: &str = "658a6d102142fea77f47ee8a332323d8";
966
967 fn keyed(server: &str, tenant: Option<&str>) -> State {
969 let mut state = State::new(server, (80, 24)).0;
970 state.step(
971 Event::KeyInfo(Ok(KeyInfo {
972 id: "0123456789abcdef".to_owned(),
973 tenant: tenant.map(str::to_owned),
974 scopes: vec!["read".to_owned()],
975 })),
976 NOW,
977 );
978 state
979 }
980
981 fn refused(server: &str) -> State {
983 let mut state = State::new(server, (80, 24)).0;
984 state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
985 state
986 }
987
988 fn status_at(state: &State, columns: u16) -> String {
990 screen(state, columns, 24)[0].trim_end().to_owned()
991 }
992
993 #[test]
994 fn at_120_columns_the_status_line_is_whole() {
995 assert_eq!(
996 status_at(&keyed(SERVER, Some(LONG_ID)), 120),
997 format!("{SERVER} | tenant {LONG_ID} | connected"),
998 "everything fits"
999 );
1000 }
1001
1002 #[test]
1003 fn at_80_columns_the_address_loses_only_its_scheme() {
1004 assert_eq!(
1005 status_at(&keyed(SERVER, Some(LONG_ID)), 80),
1006 format!("vcon.example.com:8443 | tenant {LONG_ID} | connected"),
1007 "https:// says nothing a reader needs: every address has it"
1008 );
1009 }
1010
1011 #[test]
1012 fn at_60_columns_the_tenant_id_is_shortened_and_the_address_is_not() {
1013 assert_eq!(
1014 status_at(&keyed(SERVER, Some(LONG_ID)), 60),
1015 "vcon.example.com:8443 | tenant 658a6d102142fe... | connected",
1016 "the tenant gives way before the server does"
1017 );
1018 }
1019
1020 #[test]
1021 fn at_40_columns_the_tenant_is_left_out_and_the_address_is_not() {
1022 assert_eq!(
1023 status_at(&keyed(SERVER, Some(LONG_ID)), 40),
1024 "vcon.example.com:8443 | connected",
1025 "the server and the connection"
1026 );
1027 }
1028
1029 #[test]
1030 fn a_line_that_fits_exactly_keeps_its_scheme() {
1031 assert_eq!(
1032 status_at(&keyed(SERVER, Some(LONG_ID)), 83),
1033 format!("{SERVER} | tenant {LONG_ID} | connected"),
1034 "83 characters in 83 columns"
1035 );
1036 }
1037
1038 #[test]
1039 fn a_short_tenant_id_is_whole_at_60_columns() {
1040 assert_eq!(
1041 status_at(&keyed(SERVER, Some("t_example")), 60),
1042 format!("{SERVER} | tenant t_example | connected"),
1043 "60 characters in 60 columns"
1044 );
1045 }
1046
1047 #[test]
1048 fn an_address_with_a_path_is_shown_with_it() {
1049 let line = status_at(
1050 &keyed("https://vcon.example.com:8443/base", Some("t_example")),
1051 120,
1052 );
1053 assert!(
1054 line.starts_with("https://vcon.example.com:8443/base | "),
1055 "the path is part of the address: {line}"
1056 );
1057 }
1058
1059 #[test]
1060 fn a_refused_key_at_40_columns_shows_the_address_and_not_connected() {
1061 assert_eq!(
1062 status_at(&refused(SERVER), 40),
1063 "vcon.example.com:8443 | not connected",
1064 "`tenant unknown` is the part left out"
1065 );
1066 }
1067
1068 #[test]
1069 fn a_refused_key_at_60_columns_keeps_tenant_unknown() {
1070 assert_eq!(
1071 status_at(&refused(SERVER), 60),
1072 "vcon.example.com:8443 | tenant unknown | not connected",
1073 "without the scheme the three parts fit"
1074 );
1075 }
1076
1077 #[test]
1078 fn a_refused_key_at_80_columns_is_whole() {
1079 assert_eq!(
1080 status_at(&refused(SERVER), 80),
1081 format!("{SERVER} | tenant unknown | not connected"),
1082 "everything fits"
1083 );
1084 }
1085
1086 #[test]
1087 fn connecting_at_40_columns_shows_the_address_and_connecting() {
1088 assert_eq!(
1089 status_at(&State::new(SERVER, (40, 24)).0, 40),
1090 "vcon.example.com:8443 | connecting",
1091 "`tenant unknown` is the part left out"
1092 );
1093 }
1094
1095 #[test]
1096 fn an_operator_key_at_60_columns_is_named_whole() {
1097 assert_eq!(
1098 status_at(&keyed(SERVER, None), 60),
1099 "vcon.example.com:8443 | no tenant (operator key) | connected",
1100 "60 characters in 60 columns"
1101 );
1102 }
1103
1104 #[test]
1105 fn an_operator_key_at_40_columns_is_left_out_not_cut() {
1106 assert_eq!(
1107 status_at(&keyed(SERVER, None), 40),
1108 "vcon.example.com:8443 | connected",
1109 "a phrase is whole or absent"
1110 );
1111 }
1112
1113 #[test]
1114 fn a_long_address_is_cut_at_its_end_and_the_connection_is_whole() {
1115 let server = format!("https://{}.example.com:8443", "a".repeat(90));
1116 assert_eq!(
1117 status_at(&refused(&server), 40),
1118 format!("{}... | not connected", "a".repeat(21)),
1119 "40 columns: 21 of the address, the mark, and the connection"
1120 );
1121 }
1122
1123 #[test]
1124 fn four_characters_of_a_tenant_id_are_the_fewest_shown() {
1125 assert_eq!(
1126 status_at(&keyed(SERVER, Some(LONG_ID)), 50),
1127 "vcon.example.com:8443 | tenant 658a... | connected",
1128 "50 columns leave room for four"
1129 );
1130 }
1131
1132 #[test]
1133 fn a_tenant_id_with_room_for_three_characters_is_left_out() {
1134 assert_eq!(
1135 status_at(&keyed(SERVER, Some(LONG_ID)), 49),
1136 "vcon.example.com:8443 | connected",
1137 "three characters name no tenant"
1138 );
1139 }
1140
1141 #[test]
1142 fn one_column_short_of_whole_the_scheme_goes_first() {
1143 assert_eq!(
1144 status_at(&keyed(SERVER, Some(LONG_ID)), 82),
1145 format!("vcon.example.com:8443 | tenant {LONG_ID} | connected"),
1146 "the tenant id stays whole"
1147 );
1148 }
1149
1150 #[test]
1151 fn one_column_short_of_a_whole_id_shortens_it_to_fit() {
1152 let line = status_at(&keyed(SERVER, Some(LONG_ID)), 74);
1153 assert_eq!(
1154 line,
1155 format!(
1156 "vcon.example.com:8443 | tenant {}... | connected",
1157 &LONG_ID[..28]
1158 ),
1159 "74 columns: 28 characters and the mark"
1160 );
1161 }
1162
1163 #[test]
1164 fn an_address_that_is_not_https_is_shown_as_it_is() {
1165 assert_eq!(
1166 status_at(&refused("vcon.example.com:8443"), 40),
1167 "vcon.example.com:8443 | not connected",
1168 "there is no scheme to leave out"
1169 );
1170 }
1171
1172 #[test]
1173 fn an_address_that_fits_exactly_at_40_columns_is_whole() {
1174 let server = format!("https://{}", "b".repeat(28));
1175 assert_eq!(
1176 status_at(&keyed(&server, Some(LONG_ID)), 40),
1177 format!("{} | connected", "b".repeat(28)),
1178 "28 characters, the separator and the connection are 40"
1179 );
1180 }
1181
1182 #[test]
1183 fn the_status_line_fits_and_ends_with_the_connection_at_every_width() {
1184 let long = format!("https://{}.example.com:8443", "a".repeat(90));
1185 for server in [SERVER, long.as_str()] {
1186 let states = [
1187 (State::new(server, (80, 24)).0, "connecting"),
1188 (refused(server), "not connected"),
1189 (keyed(server, Some(LONG_ID)), "connected"),
1190 (keyed(server, None), "connected"),
1191 ];
1192 for (state, word) in &states {
1193 for columns in 40..=130 {
1194 let line = status_at(state, columns);
1195 assert!(
1196 line.chars().count() <= usize::from(columns),
1197 "{columns} columns: {line}"
1198 );
1199 assert!(
1200 line.ends_with(&format!(" | {word}")),
1201 "{columns} columns, the connection is whole and last: {line}"
1202 );
1203 }
1204 }
1205 }
1206 }
1207
1208 #[test]
1209 fn a_tenant_phrase_is_whole_or_absent_at_every_width() {
1210 for (state, phrase) in [
1211 (refused(SERVER), "tenant unknown"),
1212 (keyed(SERVER, None), "no tenant (operator key)"),
1213 ] {
1214 for columns in 40..=130 {
1215 let line = status_at(&state, columns);
1216 assert!(
1217 line.contains(phrase) || !line.contains("tenant"),
1218 "{columns} columns: {line}"
1219 );
1220 }
1221 }
1222 }
1223
1224 #[test]
1225 fn the_help_view_states_the_time_zone() {
1226 let shown = text(&press(listed(1, None), &[Action::Help]));
1227 assert!(
1228 shown.contains("UTC+00:00"),
1229 "times are UTC, stated: {shown}"
1230 );
1231 }
1232
1233 fn screens_file() -> std::path::PathBuf {
1238 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../website/data/tui-screens.json")
1239 }
1240
1241 fn shown_list() -> State {
1244 let mut state = connecting();
1245 state.step(
1246 Event::KeyInfo(Ok(KeyInfo {
1247 id: "5b0c3f9a1d2e4f60".to_owned(),
1248 tenant: Some("8c41f2d9a07e4b5c9d13e6f0a2b4c7d8".to_owned()),
1249 scopes: vec!["read".to_owned()],
1250 })),
1251 NOW,
1252 );
1253 let vcons = (0..100_u64).map(shown_row).collect();
1254 state.step(
1255 Event::Page(Ok(Page {
1256 vcons,
1257 next: Some("cursor-2".to_owned()),
1258 })),
1259 NOW,
1260 );
1261 press(state, &[Action::Down, Action::Down])
1262 }
1263
1264 fn shown_row(n: u64) -> Row {
1267 let mix = n
1268 .wrapping_add(1)
1269 .wrapping_mul(0x9e37_79b9_7f4a_7c15)
1270 .rotate_left(17);
1271 let minutes = i64::try_from(n).expect("a small number").saturating_mul(37);
1272 let stored = NOW
1273 - Duration::minutes(minutes.saturating_add(11))
1274 - Duration::seconds(i64::try_from(mix % 60).expect("under 60"));
1275 let updated =
1276 stored + Duration::minutes(i64::try_from(n % 4).expect("under 4").saturating_mul(6));
1277 let time = |at: OffsetDateTime| at.format(&Rfc3339).expect("an RFC 3339 time");
1278 Row {
1279 uuid: format!(
1280 "{:08x}-{:04x}-8{:03x}-b{:03x}-{:012x}",
1281 mix >> 32,
1282 (mix >> 16) & 0xffff,
1283 mix & 0xfff,
1284 (mix >> 20) & 0xfff,
1285 mix.rotate_left(29) & 0xffff_ffff_ffff
1286 ),
1287 stored_at: time(stored),
1288 updated_at: time(updated),
1289 version: format!("{mix:016x}{:016x}", mix.rotate_left(7)),
1290 }
1291 }
1292
1293 fn classes(cell: &Cell) -> String {
1295 assert_eq!(cell.bg, Color::Reset, "the site draws no background color");
1296 let mut out = Vec::new();
1297 if cell.modifier.contains(Modifier::BOLD) {
1298 out.push("bold");
1299 }
1300 if cell.modifier.contains(Modifier::REVERSED) {
1301 out.push("reversed");
1302 }
1303 match cell.fg {
1304 Color::Reset => {}
1305 Color::Green => out.push("green"),
1306 Color::Yellow => out.push("yellow"),
1307 Color::Red => out.push("red"),
1308 other => panic!("the site has no class for {other:?}"),
1309 }
1310 out.join(" ")
1311 }
1312
1313 fn styled(state: &State) -> serde_json::Value {
1316 let terminal = terminal(state, 80, 24, COLOR);
1317 let buffer = terminal.backend().buffer();
1318 let lines: Vec<serde_json::Value> = (0..24_u16)
1319 .map(|y| {
1320 let mut runs: Vec<(String, String)> = Vec::new();
1321 for x in 0..80_u16 {
1322 let cell = &buffer[(x, y)];
1323 let class = classes(cell);
1324 match runs.last_mut() {
1325 Some((last, text)) if *last == class => text.push_str(cell.symbol()),
1326 _ => runs.push((class, cell.symbol().to_owned())),
1327 }
1328 }
1329 if let Some((class, text)) = runs.last_mut()
1330 && class.is_empty()
1331 {
1332 text.truncate(text.trim_end().len());
1333 }
1334 runs.retain(|(_, text)| !text.is_empty());
1335 runs.into_iter()
1336 .map(|(class, text)| serde_json::json!({"class": class, "text": text}))
1337 .collect()
1338 })
1339 .collect();
1340 serde_json::json!({"columns": 80, "lines": lines})
1341 }
1342
1343 #[test]
1344 fn the_site_shows_the_screens_draw_makes() {
1345 let list = shown_list();
1346 let made = serde_json::json!({
1347 "list": styled(&list),
1348 "detail": styled(&press(list, &[Action::Open])),
1349 });
1350 let made = format!("{}\n", serde_json::to_string_pretty(&made).expect("JSON"));
1351 let path = screens_file();
1352 if std::env::var_os("VCON_SERVER_WRITE_SCREENS").is_some() {
1353 std::fs::write(&path, &made)
1354 .unwrap_or_else(|e| panic!("write {}: {e}", path.display()));
1355 }
1356 let shown = std::fs::read_to_string(&path)
1357 .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
1358 assert!(
1359 shown == made,
1360 "{} is not the screens draw makes now: run this test with VCON_SERVER_WRITE_SCREENS=1 to write them again",
1361 path.display()
1362 );
1363 }
1364}