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::style::Color;
401 use time::OffsetDateTime;
402 use time::macros::datetime;
403
404 use super::{Theme, draw, theme, utc};
405 use crate::tui::keys::BINDINGS;
406 use crate::tui::state::{Action, ApiError, Event, KeyInfo, Page, Row, State};
407
408 const NOW: OffsetDateTime = datetime!(2026-11-10 01:20:00 UTC);
409 const MONO: Theme = Theme { color: false };
410 const COLOR: Theme = Theme { color: true };
411
412 fn row(n: u8) -> Row {
413 Row {
414 uuid: format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc{n:02}"),
415 stored_at: "2026-10-25T12:00:00.123456789Z".to_owned(),
416 updated_at: "2026-10-25T12:30:00Z".to_owned(),
417 version: format!("4f0c4b0a1d2e3f405162738495a6b7{n:02}"),
418 }
419 }
420
421 fn connecting() -> State {
422 State::new("https://vcon.example.com:8443", (80, 24)).0
423 }
424
425 fn connected() -> State {
426 let mut state = connecting();
427 state.step(
428 Event::KeyInfo(Ok(KeyInfo {
429 id: "0123456789abcdef".to_owned(),
430 tenant: Some("t_example".to_owned()),
431 scopes: vec!["read".to_owned()],
432 })),
433 NOW,
434 );
435 state
436 }
437
438 fn listed(rows: u8, next: Option<&str>) -> State {
439 let mut state = connected();
440 state.step(
441 Event::Page(Ok(Page {
442 vcons: (0..rows).map(row).collect(),
443 next: next.map(str::to_owned),
444 })),
445 NOW,
446 );
447 state
448 }
449
450 fn press(mut state: State, actions: &[Action]) -> State {
451 for action in actions {
452 state.step(Event::Action(*action), NOW);
453 }
454 state
455 }
456
457 fn terminal(state: &State, columns: u16, lines: u16, theme: Theme) -> Terminal<TestBackend> {
458 let mut terminal = Terminal::new(TestBackend::new(columns, lines)).expect("a terminal");
459 terminal
460 .draw(|frame| draw(frame, state, theme))
461 .expect("a frame");
462 terminal
463 }
464
465 fn screen(state: &State, columns: u16, lines: u16) -> Vec<String> {
467 let terminal = terminal(state, columns, lines, MONO);
468 let buffer = terminal.backend().buffer();
469 (0..lines)
470 .map(|y| (0..columns).map(|x| buffer[(x, y)].symbol()).collect())
471 .collect()
472 }
473
474 fn text(state: &State) -> String {
475 screen(state, 80, 24).join("\n")
476 }
477
478 #[test]
481 fn the_status_line_names_the_server_the_tenant_and_the_connection() {
482 let lines = screen(&listed(1, None), 80, 24);
483 assert!(
484 lines[0].contains("https://vcon.example.com:8443"),
485 "the server: {}",
486 lines[0]
487 );
488 assert!(
489 lines[0].contains("tenant t_example"),
490 "the tenant: {}",
491 lines[0]
492 );
493 assert!(
494 lines[0].contains("connected"),
495 "the connection, in words: {}",
496 lines[0]
497 );
498 }
499
500 #[test]
501 fn the_list_shows_each_vcon_with_its_times_in_utc() {
502 let lines = screen(&listed(2, None), 80, 24);
503 assert!(
504 lines[1].contains("STORED (UTC+00:00)"),
505 "the header states the offset: {}",
506 lines[1]
507 );
508 assert!(
509 lines[2].contains(&row(0).uuid),
510 "the first row's uuid: {}",
511 lines[2]
512 );
513 assert!(
514 lines[2].contains("2026-10-25 12:00:00"),
515 "its stored time: {}",
516 lines[2]
517 );
518 assert!(
519 lines[2].contains("2026-10-25 12:30:00"),
520 "its updated time: {}",
521 lines[2]
522 );
523 assert!(
524 lines[3].contains(&row(1).uuid),
525 "the second row: {}",
526 lines[3]
527 );
528 }
529
530 #[test]
531 fn the_selected_row_is_marked_with_a_character() {
532 let lines = screen(&press(listed(3, None), &[Action::Down]), 80, 24);
533 assert!(
534 lines[3].starts_with("> "),
535 "the selected row has a marker: {}",
536 lines[3]
537 );
538 assert!(
539 lines[2].starts_with(" "),
540 "the others do not: {}",
541 lines[2]
542 );
543 }
544
545 #[test]
546 fn the_list_footer_hints_are_real_bindings() {
547 let lines = screen(&listed(1, None), 80, 24);
548 let footer = &lines[23];
549 for wanted in [Action::Open, Action::Refresh, Action::Help, Action::Quit] {
550 let binding = BINDINGS
551 .iter()
552 .find(|b| b.action == wanted)
553 .expect("a binding");
554 assert!(
555 footer.contains(&format!("{} {}", binding.label, binding.hint)),
556 "the footer shows {wanted:?} as bound: {footer}"
557 );
558 }
559 }
560
561 #[test]
562 fn the_notice_line_says_how_many_are_loaded_and_as_of_when() {
563 let lines = screen(&listed(2, Some("cursor-1")), 80, 24);
564 assert!(lines[22].contains("1 of 2"), "the position: {}", lines[22]);
565 assert!(
566 lines[22].contains("more on the server"),
567 "that more exist: {}",
568 lines[22]
569 );
570 assert!(
571 lines[22].contains("as of 2026-11-10 01:20:00 UTC+00:00"),
572 "when it was read, with the offset: {}",
573 lines[22]
574 );
575 }
576
577 #[test]
578 fn the_detail_view_shows_the_metadata_and_says_content_is_not_shown() {
579 let shown = text(&press(listed(2, None), &[Action::Open]));
580 assert!(shown.contains(&row(0).uuid), "the uuid: {shown}");
581 assert!(shown.contains(&row(0).version), "the version: {shown}");
582 assert!(
583 shown.contains("2026-10-25 12:00:00 UTC+00:00"),
584 "first stored: {shown}"
585 );
586 assert!(
587 shown.contains("2026-10-25 12:30:00 UTC+00:00"),
588 "last updated: {shown}"
589 );
590 assert!(
591 shown.contains("Content is not shown"),
592 "what is left out: {shown}"
593 );
594 assert!(shown.contains("Esc back"), "how to leave: {shown}");
595 }
596
597 #[test]
598 fn the_help_view_lists_every_binding() {
599 let shown = text(&press(listed(1, None), &[Action::Help]));
600 for binding in &BINDINGS {
601 assert!(
602 shown.contains(binding.label),
603 "{} is listed: {shown}",
604 binding.label
605 );
606 assert!(
607 shown.contains(binding.does),
608 "{} is described: {shown}",
609 binding.does
610 );
611 }
612 }
613
614 #[test]
615 fn the_list_scrolls_to_keep_the_selection_on_screen() {
616 let state = press(listed(60, None), &[Action::Bottom]);
617 let shown = text(&state);
618 assert!(
619 shown.contains(&format!("> {}", row(59).uuid)),
620 "the last row is drawn selected"
621 );
622 assert!(
623 !shown.contains(&row(0).uuid),
624 "the first row has scrolled off"
625 );
626 }
627
628 #[test]
629 fn with_color_the_connection_is_colored_and_still_in_words() {
630 let state = listed(1, None);
631 let terminal = terminal(&state, 80, 24, COLOR);
632 let buffer = terminal.backend().buffer();
633 let colored = (0..80).any(|x| buffer[(x, 0)].fg != Color::Reset);
634 assert!(colored, "a color terminal gets color");
635 assert!(
636 screen(&state, 80, 24)[0].contains("connected"),
637 "and the word is still there"
638 );
639 }
640
641 #[test]
642 fn rfc_3339_times_are_shown_to_the_second_in_utc() {
643 assert_eq!(
644 utc("2026-10-25T12:00:00.123456789Z"),
645 "2026-10-25 12:00:00",
646 "fractions dropped"
647 );
648 assert_eq!(
649 utc("2026-10-25T14:30:00+02:00"),
650 "2026-10-25 12:30:00",
651 "an offset is converted"
652 );
653 }
654
655 #[test]
656 fn a_color_terminal_gets_color() {
657 assert_eq!(
658 theme(None, Some("xterm-256color")),
659 COLOR,
660 "nothing asks for none"
661 );
662 }
663
664 #[test]
665 fn a_wider_terminal_shows_the_version_column() {
666 let lines = screen(&listed(1, None), 132, 43);
667 assert!(lines[1].contains("VERSION"), "the header: {}", lines[1]);
668 assert!(
669 lines[2].contains(&row(0).version),
670 "the version: {}",
671 lines[2]
672 );
673 }
674
675 #[test]
678 fn a_failed_connection_is_said_in_the_status_line_and_the_list() {
679 let mut state = connecting();
680 state.step(
681 Event::KeyInfo(Err(ApiError::Unreachable("connection refused".to_owned()))),
682 NOW,
683 );
684 let lines = screen(&state, 80, 24);
685 assert!(
686 lines[0].contains("not connected"),
687 "the status line: {}",
688 lines[0]
689 );
690 let shown = lines.join("\n");
691 assert!(shown.contains("connection refused"), "why: {shown}");
692 assert!(
693 shown.contains("Press r to try again"),
694 "what to press: {shown}"
695 );
696 }
697
698 #[test]
699 fn a_long_error_wraps_instead_of_being_cut() {
700 let mut state = connected();
701 let long = format!("{} the-end", "word ".repeat(30));
702 state.step(Event::Page(Err(ApiError::Malformed(long))), NOW);
703 assert!(
704 text(&state).contains("the-end"),
705 "the whole reason is on screen"
706 );
707 }
708
709 #[test]
710 fn an_operator_key_is_named_in_the_status_line() {
711 let mut state = connecting();
712 state.step(
713 Event::KeyInfo(Ok(KeyInfo {
714 id: "0123456789abcdef".to_owned(),
715 tenant: None,
716 scopes: vec!["admin".to_owned()],
717 })),
718 NOW,
719 );
720 let lines = screen(&state, 80, 24);
721 assert!(
722 lines[0].contains("no tenant (operator key)"),
723 "the status line: {}",
724 lines[0]
725 );
726 assert!(
727 lines
728 .join("\n")
729 .contains("this is an operator key, which reaches no vCon"),
730 "and the list says why it is empty"
731 );
732 }
733
734 #[test]
735 fn a_failed_next_page_shows_its_notice_over_the_rows() {
736 let mut state = press(listed(2, Some("cursor-1")), &[Action::More]);
737 state.step(
738 Event::Page(Err(ApiError::Unreachable("timed out".to_owned()))),
739 NOW,
740 );
741 let lines = screen(&state, 80, 24);
742 assert!(
743 lines[22].contains("The next page was not read"),
744 "the notice: {}",
745 lines[22]
746 );
747 assert!(
748 lines[2].contains(&row(0).uuid),
749 "the rows stay: {}",
750 lines[2]
751 );
752 }
753
754 #[test]
755 fn the_detail_of_a_vcon_no_longer_listed_says_so() {
756 let mut state = press(listed(2, None), &[Action::Open, Action::Refresh]);
757 state.step(
758 Event::Page(Ok(Page {
759 vcons: vec![row(1)],
760 next: None,
761 })),
762 NOW,
763 );
764 let shown = text(&state);
765 assert!(
766 shown.contains("no longer in the list"),
767 "what happened: {shown}"
768 );
769 assert!(
770 shown.contains("Press Esc to go back"),
771 "what to press: {shown}"
772 );
773 }
774
775 #[test]
776 fn the_detail_view_shows_a_failed_refresh() {
777 let mut state = press(listed(2, None), &[Action::Open, Action::Refresh]);
778 state.step(Event::Page(Err(ApiError::Status(503, None))), NOW);
779 let shown = text(&state);
780 assert!(shown.contains("the server answered 503"), "why: {shown}");
781 assert!(
782 shown.contains("Press r to try again"),
783 "what to press: {shown}"
784 );
785 }
786
787 #[test]
788 fn a_terminal_too_small_says_so_and_how_to_quit() {
789 let lines = screen(&listed(3, None), 30, 5);
790 let shown = lines.join("\n");
791 assert!(shown.contains("too small"), "what is wrong: {shown}");
792 assert!(shown.contains("q"), "the way out: {shown}");
793 assert!(!shown.contains("01a07da8"), "no half-drawn list");
794 }
795
796 #[test]
797 fn a_time_that_does_not_parse_is_shown_as_sent() {
798 assert_eq!(utc("yesterday"), "yesterday", "nothing is invented for it");
799 }
800
801 #[test]
802 fn a_refused_key_says_to_check_the_key_file() {
803 let mut state = connecting();
804 state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
805 let shown = text(&state);
806 assert!(shown.contains("refused the key (401)"), "why: {shown}");
807 assert!(shown.contains("key_file"), "where to look: {shown}");
808 }
809
810 #[test]
813 fn the_loading_state_says_so_and_how_to_quit() {
814 let shown = text(&connected());
815 assert!(
816 shown.contains("Loading vCons"),
817 "what is happening: {shown}"
818 );
819 assert!(shown.contains("q quit"), "the way out: {shown}");
820 }
821
822 #[test]
823 fn the_connecting_state_is_in_the_status_line() {
824 let lines = screen(&connecting(), 80, 24);
825 assert!(
826 lines[0].contains("connecting"),
827 "the status line: {}",
828 lines[0]
829 );
830 assert!(
831 lines.join("\n").contains("Connecting to the server"),
832 "and the body"
833 );
834 }
835
836 #[test]
837 fn an_empty_tenant_says_so_and_what_to_press() {
838 let shown = text(&listed(0, None));
839 assert!(
840 shown.contains("This tenant has no vCons"),
841 "what happened: {shown}"
842 );
843 assert!(
844 shown.contains("Press r to read again"),
845 "what to press: {shown}"
846 );
847 }
848
849 #[test]
850 fn the_detail_view_says_refreshing_while_a_refresh_is_in_flight() {
851 let shown = text(&press(listed(2, None), &[Action::Open, Action::Refresh]));
852 assert!(
853 shown.contains("Reading the list again"),
854 "what is happening: {shown}"
855 );
856 }
857
858 #[test]
859 fn at_80_columns_every_list_column_fits() {
860 let lines = screen(&listed(1, None), 80, 24);
861 assert!(
862 lines[2].trim_end().ends_with("2026-10-25 12:30:00"),
863 "the last column is whole: {}",
864 lines[2]
865 );
866 }
867
868 #[test]
869 fn below_80_columns_the_updated_column_is_dropped_not_cut() {
870 let lines = screen(&listed(1, None), 60, 24);
871 assert!(
872 lines[2].contains("2026-10-25 12:00:00"),
873 "stored stays: {}",
874 lines[2]
875 );
876 assert!(
877 !lines[2].contains("2026-10-25 12:3"),
878 "no part of updated: {}",
879 lines[2]
880 );
881 assert!(
882 !lines[1].contains("UPDATED"),
883 "nor its header: {}",
884 lines[1]
885 );
886 }
887
888 #[test]
889 fn every_size_from_1x1_up_draws_without_a_panic() {
890 let states = [
891 connecting(),
892 listed(0, None),
893 listed(60, Some("cursor-1")),
894 press(listed(3, None), &[Action::Open]),
895 press(listed(3, None), &[Action::Help]),
896 ];
897 for state in &states {
898 for columns in [1, 2, 10, 39, 40, 79, 80, 200] {
899 for lines in [1, 2, 7, 8, 24, 60] {
900 let drawn = screen(state, columns, lines);
901 assert_eq!(
902 drawn.len(),
903 usize::from(lines),
904 "{columns}x{lines} drew a frame"
905 );
906 }
907 }
908 }
909 }
910
911 #[test]
912 fn no_color_and_a_dumb_terminal_turn_color_off() {
913 assert_eq!(
914 theme(Some("1"), Some("xterm-256color")),
915 MONO,
916 "NO_COLOR set"
917 );
918 assert_eq!(theme(None, Some("dumb")), MONO, "a terminal with no color");
919 assert_eq!(theme(None, None), MONO, "no TERM at all");
920 assert_eq!(
921 theme(Some(""), Some("xterm")),
922 COLOR,
923 "an empty NO_COLOR is not set"
924 );
925 }
926
927 #[test]
928 fn without_color_no_cell_has_a_color() {
929 for state in [
930 listed(3, None),
931 press(listed(3, None), &[Action::Help]),
932 connecting(),
933 ] {
934 let terminal = terminal(&state, 80, 24, MONO);
935 let buffer = terminal.backend().buffer();
936 for cell in buffer.content() {
937 assert_eq!(cell.fg, Color::Reset, "no foreground color");
938 assert_eq!(cell.bg, Color::Reset, "no background color");
939 }
940 }
941 }
942
943 #[test]
944 fn the_status_line_keeps_the_connection_when_the_address_is_long() {
945 let mut state = State::new(
946 &format!("https://{}.example.com:8443", "a".repeat(90)),
947 (80, 24),
948 )
949 .0;
950 state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
951 let lines = screen(&state, 80, 24);
952 assert!(
953 lines[0].contains("not connected"),
954 "the state is never pushed off: {}",
955 lines[0]
956 );
957 }
958
959 const SERVER: &str = "https://vcon.example.com:8443";
963 const LONG_ID: &str = "658a6d102142fea77f47ee8a332323d8";
964
965 fn keyed(server: &str, tenant: Option<&str>) -> State {
967 let mut state = State::new(server, (80, 24)).0;
968 state.step(
969 Event::KeyInfo(Ok(KeyInfo {
970 id: "0123456789abcdef".to_owned(),
971 tenant: tenant.map(str::to_owned),
972 scopes: vec!["read".to_owned()],
973 })),
974 NOW,
975 );
976 state
977 }
978
979 fn refused(server: &str) -> State {
981 let mut state = State::new(server, (80, 24)).0;
982 state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
983 state
984 }
985
986 fn status_at(state: &State, columns: u16) -> String {
988 screen(state, columns, 24)[0].trim_end().to_owned()
989 }
990
991 #[test]
992 fn at_120_columns_the_status_line_is_whole() {
993 assert_eq!(
994 status_at(&keyed(SERVER, Some(LONG_ID)), 120),
995 format!("{SERVER} | tenant {LONG_ID} | connected"),
996 "everything fits"
997 );
998 }
999
1000 #[test]
1001 fn at_80_columns_the_address_loses_only_its_scheme() {
1002 assert_eq!(
1003 status_at(&keyed(SERVER, Some(LONG_ID)), 80),
1004 format!("vcon.example.com:8443 | tenant {LONG_ID} | connected"),
1005 "https:// says nothing a reader needs: every address has it"
1006 );
1007 }
1008
1009 #[test]
1010 fn at_60_columns_the_tenant_id_is_shortened_and_the_address_is_not() {
1011 assert_eq!(
1012 status_at(&keyed(SERVER, Some(LONG_ID)), 60),
1013 "vcon.example.com:8443 | tenant 658a6d102142fe... | connected",
1014 "the tenant gives way before the server does"
1015 );
1016 }
1017
1018 #[test]
1019 fn at_40_columns_the_tenant_is_left_out_and_the_address_is_not() {
1020 assert_eq!(
1021 status_at(&keyed(SERVER, Some(LONG_ID)), 40),
1022 "vcon.example.com:8443 | connected",
1023 "the server and the connection"
1024 );
1025 }
1026
1027 #[test]
1028 fn a_line_that_fits_exactly_keeps_its_scheme() {
1029 assert_eq!(
1030 status_at(&keyed(SERVER, Some(LONG_ID)), 83),
1031 format!("{SERVER} | tenant {LONG_ID} | connected"),
1032 "83 characters in 83 columns"
1033 );
1034 }
1035
1036 #[test]
1037 fn a_short_tenant_id_is_whole_at_60_columns() {
1038 assert_eq!(
1039 status_at(&keyed(SERVER, Some("t_example")), 60),
1040 format!("{SERVER} | tenant t_example | connected"),
1041 "60 characters in 60 columns"
1042 );
1043 }
1044
1045 #[test]
1046 fn an_address_with_a_path_is_shown_with_it() {
1047 let line = status_at(
1048 &keyed("https://vcon.example.com:8443/base", Some("t_example")),
1049 120,
1050 );
1051 assert!(
1052 line.starts_with("https://vcon.example.com:8443/base | "),
1053 "the path is part of the address: {line}"
1054 );
1055 }
1056
1057 #[test]
1058 fn a_refused_key_at_40_columns_shows_the_address_and_not_connected() {
1059 assert_eq!(
1060 status_at(&refused(SERVER), 40),
1061 "vcon.example.com:8443 | not connected",
1062 "`tenant unknown` is the part left out"
1063 );
1064 }
1065
1066 #[test]
1067 fn a_refused_key_at_60_columns_keeps_tenant_unknown() {
1068 assert_eq!(
1069 status_at(&refused(SERVER), 60),
1070 "vcon.example.com:8443 | tenant unknown | not connected",
1071 "without the scheme the three parts fit"
1072 );
1073 }
1074
1075 #[test]
1076 fn a_refused_key_at_80_columns_is_whole() {
1077 assert_eq!(
1078 status_at(&refused(SERVER), 80),
1079 format!("{SERVER} | tenant unknown | not connected"),
1080 "everything fits"
1081 );
1082 }
1083
1084 #[test]
1085 fn connecting_at_40_columns_shows_the_address_and_connecting() {
1086 assert_eq!(
1087 status_at(&State::new(SERVER, (40, 24)).0, 40),
1088 "vcon.example.com:8443 | connecting",
1089 "`tenant unknown` is the part left out"
1090 );
1091 }
1092
1093 #[test]
1094 fn an_operator_key_at_60_columns_is_named_whole() {
1095 assert_eq!(
1096 status_at(&keyed(SERVER, None), 60),
1097 "vcon.example.com:8443 | no tenant (operator key) | connected",
1098 "60 characters in 60 columns"
1099 );
1100 }
1101
1102 #[test]
1103 fn an_operator_key_at_40_columns_is_left_out_not_cut() {
1104 assert_eq!(
1105 status_at(&keyed(SERVER, None), 40),
1106 "vcon.example.com:8443 | connected",
1107 "a phrase is whole or absent"
1108 );
1109 }
1110
1111 #[test]
1112 fn a_long_address_is_cut_at_its_end_and_the_connection_is_whole() {
1113 let server = format!("https://{}.example.com:8443", "a".repeat(90));
1114 assert_eq!(
1115 status_at(&refused(&server), 40),
1116 format!("{}... | not connected", "a".repeat(21)),
1117 "40 columns: 21 of the address, the mark, and the connection"
1118 );
1119 }
1120
1121 #[test]
1122 fn four_characters_of_a_tenant_id_are_the_fewest_shown() {
1123 assert_eq!(
1124 status_at(&keyed(SERVER, Some(LONG_ID)), 50),
1125 "vcon.example.com:8443 | tenant 658a... | connected",
1126 "50 columns leave room for four"
1127 );
1128 }
1129
1130 #[test]
1131 fn a_tenant_id_with_room_for_three_characters_is_left_out() {
1132 assert_eq!(
1133 status_at(&keyed(SERVER, Some(LONG_ID)), 49),
1134 "vcon.example.com:8443 | connected",
1135 "three characters name no tenant"
1136 );
1137 }
1138
1139 #[test]
1140 fn one_column_short_of_whole_the_scheme_goes_first() {
1141 assert_eq!(
1142 status_at(&keyed(SERVER, Some(LONG_ID)), 82),
1143 format!("vcon.example.com:8443 | tenant {LONG_ID} | connected"),
1144 "the tenant id stays whole"
1145 );
1146 }
1147
1148 #[test]
1149 fn one_column_short_of_a_whole_id_shortens_it_to_fit() {
1150 let line = status_at(&keyed(SERVER, Some(LONG_ID)), 74);
1151 assert_eq!(
1152 line,
1153 format!(
1154 "vcon.example.com:8443 | tenant {}... | connected",
1155 &LONG_ID[..28]
1156 ),
1157 "74 columns: 28 characters and the mark"
1158 );
1159 }
1160
1161 #[test]
1162 fn an_address_that_is_not_https_is_shown_as_it_is() {
1163 assert_eq!(
1164 status_at(&refused("vcon.example.com:8443"), 40),
1165 "vcon.example.com:8443 | not connected",
1166 "there is no scheme to leave out"
1167 );
1168 }
1169
1170 #[test]
1171 fn an_address_that_fits_exactly_at_40_columns_is_whole() {
1172 let server = format!("https://{}", "b".repeat(28));
1173 assert_eq!(
1174 status_at(&keyed(&server, Some(LONG_ID)), 40),
1175 format!("{} | connected", "b".repeat(28)),
1176 "28 characters, the separator and the connection are 40"
1177 );
1178 }
1179
1180 #[test]
1181 fn the_status_line_fits_and_ends_with_the_connection_at_every_width() {
1182 let long = format!("https://{}.example.com:8443", "a".repeat(90));
1183 for server in [SERVER, long.as_str()] {
1184 let states = [
1185 (State::new(server, (80, 24)).0, "connecting"),
1186 (refused(server), "not connected"),
1187 (keyed(server, Some(LONG_ID)), "connected"),
1188 (keyed(server, None), "connected"),
1189 ];
1190 for (state, word) in &states {
1191 for columns in 40..=130 {
1192 let line = status_at(state, columns);
1193 assert!(
1194 line.chars().count() <= usize::from(columns),
1195 "{columns} columns: {line}"
1196 );
1197 assert!(
1198 line.ends_with(&format!(" | {word}")),
1199 "{columns} columns, the connection is whole and last: {line}"
1200 );
1201 }
1202 }
1203 }
1204 }
1205
1206 #[test]
1207 fn a_tenant_phrase_is_whole_or_absent_at_every_width() {
1208 for (state, phrase) in [
1209 (refused(SERVER), "tenant unknown"),
1210 (keyed(SERVER, None), "no tenant (operator key)"),
1211 ] {
1212 for columns in 40..=130 {
1213 let line = status_at(&state, columns);
1214 assert!(
1215 line.contains(phrase) || !line.contains("tenant"),
1216 "{columns} columns: {line}"
1217 );
1218 }
1219 }
1220 }
1221
1222 #[test]
1223 fn the_help_view_states_the_time_zone() {
1224 let shown = text(&press(listed(1, None), &[Action::Help]));
1225 assert!(
1226 shown.contains("UTC+00:00"),
1227 "times are UTC, stated: {shown}"
1228 );
1229 }
1230}