//! Turning the ten value kinds into something on screen. //! //! This module is the entire reason producers are forbidden from formatting //! their own values. Every `progress` in the UI gets the same bar, every //! `instant` the same relative phrasing, every `ident` the same truncation — //! and consistency survives a new producer written a year from now by someone //! who never read this file, because the producer never gets a say. //! //! Everything here is a pure function. `instant` takes `now` as an argument //! rather than reading the clock, which is what keeps the whole render //! snapshot-testable. use chrono::{DateTime, Utc}; use ops_status::{Status, Value}; use ratatui::style::{Color, Modifier, Style}; /// The one place a status becomes a color. pub(crate) fn status_style(status: Status) -> Style { match status { Status::Ok => Style::default().fg(Color::Green), Status::Degraded => Style::default().fg(Color::Yellow), Status::Failed => Style::default().fg(Color::Red).add_modifier(Modifier::BOLD), Status::Pending => Style::default().fg(Color::Blue), // Magenta, not gray: an unreachable source is not a quiet absence, it // is the loudest thing a viewer can fail to tell you. Status::Unknown => Style::default().fg(Color::Magenta), } } /// A short, fixed-width-ish marker so columns line up. pub(crate) fn status_mark(status: Status) -> &'static str { match status { Status::Ok => "ok", Status::Degraded => "degr", Status::Failed => "FAIL", Status::Pending => "pend", Status::Unknown => "????", } } /// Render one value. `width` is the budget for things that elide. pub(crate) fn render(value: &Value, now: DateTime, width: usize) -> String { match value { Value::Text { value } => value.clone(), Value::Ident { value, abbrev_to } => abbreviate(value, abbrev_to.unwrap_or(12)), Value::Version { value } => value.clone(), Value::Instant { value } => relative(*value, now), Value::Duration { seconds } => duration(*seconds), Value::Progress { value, max, unit } => progress(*value, *max, unit.as_deref(), width), Value::Quantity { value, unit } => quantity(*value, unit.as_deref()), Value::State { value } => status_mark(*value).to_string(), Value::Link { url, text } => text.clone().unwrap_or_else(|| url.clone()), Value::Path { value } => middle_elide(value, width.max(12)), } } /// The style a value carries on its own, if any. pub(crate) fn style(value: &Value) -> Style { match value { Value::State { value } => status_style(*value), Value::Ident { .. } | Value::Path { .. } => Style::default().fg(Color::Cyan), Value::Link { .. } => Style::default() .fg(Color::Cyan) .add_modifier(Modifier::UNDERLINED), _ => Style::default(), } } /// Truncate an identifier at a character boundary. /// /// Char-wise rather than byte-wise: a digest is ASCII, but nothing in the /// contract promises that, and slicing a multi-byte value at a byte index /// panics. pub(crate) fn abbreviate(value: &str, to: usize) -> String { if value.chars().count() <= to { return value.to_string(); } value.chars().take(to).collect() } /// Elide the middle of a path, keeping both ends: the leading directories say /// where you are and the basename says what it is. Truncating either end alone /// throws away the half you needed. pub(crate) fn middle_elide(value: &str, max: usize) -> String { let chars: Vec = value.chars().collect(); if chars.len() <= max { return value.to_string(); } if max <= 3 { return "...".into(); } let keep = max - 3; let head = keep.div_ceil(2); let tail = keep - head; let mut out: String = chars[..head].iter().collect(); out.push_str("..."); out.extend(&chars[chars.len() - tail..]); out } /// "3m ago", "in 2m", "just now". pub(crate) fn relative(at: DateTime, now: DateTime) -> String { let delta = now - at; let secs = delta.num_seconds(); if secs.abs() < 5 { return "just now".into(); } let magnitude = duration(secs.abs()); if secs > 0 { format!("{magnitude} ago") } else { format!("in {magnitude}") } } /// Humanize a span. Two units at most: "2h 14m" is useful, "2h 14m 7s" is /// noise at every scale where hours matter. pub(crate) fn duration(seconds: i64) -> String { let s = seconds.abs(); let (d, h, m, sec) = (s / 86_400, (s % 86_400) / 3600, (s % 3600) / 60, s % 60); match (d, h, m) { (0, 0, 0) => format!("{sec}s"), (0, 0, _) => format!("{m}m {sec}s"), (0, _, 0) => format!("{h}h"), (0, _, _) => format!("{h}h {m}m"), (_, 0, _) => format!("{d}d"), (_, _, _) => format!("{d}d {h}h"), } } /// A magnitude with its unit. The number is humanized; the unit is the /// producer's, verbatim. pub(crate) fn quantity(value: f64, unit: Option<&str>) -> String { let n = humanize_number(value); match unit { Some(u) => format!("{n} {u}"), None => n, } } fn humanize_number(value: f64) -> String { let abs = value.abs(); let (scaled, suffix) = if abs >= 1e9 { (value / 1e9, "G") } else if abs >= 1e6 { (value / 1e6, "M") } else if abs >= 1_000.0 { (value / 1_000.0, "k") } else { (value, "") }; let rendered = if scaled.fract().abs() < 0.05 { format!("{scaled:.0}") } else { format!("{scaled:.1}") }; format!("{rendered}{suffix}") } /// A progress bar plus its numbers, e.g. `[####------] 31/48 hour`. pub(crate) fn progress(value: f64, max: f64, unit: Option<&str>, width: usize) -> String { let numbers = match unit { Some(u) => format!("{}/{} {u}", humanize_number(value), humanize_number(max)), None => format!("{}/{}", humanize_number(value), humanize_number(max)), }; // The bar is whatever is left after the numbers, floored at something still // readable and capped so it does not sprawl across a wide terminal. let bar_width = width.saturating_sub(numbers.len() + 3).clamp(4, 24); let fraction = if max > 0.0 { (value / max).clamp(0.0, 1.0) } else { 0.0 }; let filled = (fraction * bar_width as f64).round() as usize; let bar: String = "#".repeat(filled) + &"-".repeat(bar_width - filled); format!("[{bar}] {numbers}") } /// How a progress value should be colored: complete is done, not merely far /// along. pub(crate) fn progress_style(value: f64, max: f64) -> Style { if max > 0.0 && value >= max { Style::default().fg(Color::Green) } else { Style::default().fg(Color::Blue) } } #[cfg(test)] mod tests { use super::*; use chrono::TimeDelta; fn now() -> DateTime { "2026-07-21T18:00:00Z".parse().unwrap() } #[test] fn durations_stop_at_two_units() { assert_eq!(duration(45), "45s"); assert_eq!(duration(125), "2m 5s"); assert_eq!(duration(7200), "2h"); assert_eq!(duration(8040), "2h 14m"); assert_eq!(duration(172_800), "2d"); assert_eq!(duration(180_000), "2d 2h"); } #[test] fn relative_time_reads_in_both_directions() { let base = now(); assert_eq!(relative(base, base), "just now"); assert_eq!(relative(base - TimeDelta::minutes(3), base), "3m 0s ago"); // A producer whose clock runs ahead must not render as a negative age. assert_eq!(relative(base + TimeDelta::minutes(2), base), "in 2m 0s"); } #[test] fn identifiers_truncate_at_a_character_boundary() { assert_eq!(abbreviate("a3f9c21b7e4d8056", 8), "a3f9c21b"); assert_eq!(abbreviate("short", 8), "short"); // Multi-byte: byte slicing here would panic. assert_eq!(abbreviate("ααααββββ", 4), "αααα"); } #[test] fn paths_keep_both_ends() { let path = "/srv/sando/releases/a3f9c21b7e4d8056/bin/makenotwork"; let out = middle_elide(path, 30); assert_eq!(out.chars().count(), 30); assert!(out.starts_with("/srv/sando"), "{out}"); assert!(out.ends_with("makenotwork"), "{out}"); assert!(out.contains("...")); } #[test] fn a_short_path_is_left_alone() { assert_eq!(middle_elide("/etc/sando", 30), "/etc/sando"); } #[test] fn quantities_humanize_the_number_and_keep_the_producers_unit() { assert_eq!(quantity(43.5, Some("MB")), "43.5 MB"); assert_eq!(quantity(1_200.0, None), "1.2k"); assert_eq!(quantity(2_000_000.0, None), "2M"); assert_eq!(quantity(7.0, Some("node")), "7 node"); } #[test] fn progress_renders_a_bar_and_its_numbers() { let out = progress(31.0, 48.0, Some("hour"), 40); assert!(out.contains("31/48 hour"), "{out}"); assert!(out.starts_with('['), "{out}"); assert!(out.contains('#') && out.contains('-'), "{out}"); } #[test] fn progress_survives_nonsense_without_panicking() { // A producer bug must not take the viewer down. assert!(progress(5.0, 0.0, None, 40).contains("5/0")); assert!(progress(-1.0, 10.0, None, 40).starts_with('[')); assert!(progress(99.0, 10.0, None, 40).starts_with('[')); // Width smaller than the numbers still yields a bar, not a panic. assert!(progress(31.0, 48.0, Some("hour"), 1).starts_with('[')); } #[test] fn a_complete_bar_reads_as_done() { assert_eq!( progress_style(48.0, 48.0), Style::default().fg(Color::Green) ); assert_eq!(progress_style(31.0, 48.0), Style::default().fg(Color::Blue)); } #[test] fn every_kind_renders_to_something_non_empty() { let values = vec![ Value::Text { value: "x".into() }, Value::Ident { value: "a3f9c21b7e4d8056".into(), abbrev_to: Some(8), }, Value::Version { value: "0.10.14".into(), }, Value::Instant { value: now() - TimeDelta::minutes(3), }, Value::Duration { seconds: 3600 }, Value::Progress { value: 31.0, max: 48.0, unit: Some("hour".into()), }, Value::Quantity { value: 43.5, unit: Some("MB".into()), }, Value::State { value: Status::Degraded, }, Value::Link { url: "https://makenot.work".into(), text: None, }, Value::Path { value: "/srv/sando".into(), }, ]; for value in values { let out = render(&value, now(), 40); assert!(!out.is_empty(), "{} rendered empty", value.kind()); assert!(!out.contains('\n'), "{} rendered multi-line", value.kind()); } } #[test] fn a_link_prefers_its_text_and_falls_back_to_the_url() { let with = Value::Link { url: "https://makenot.work".into(), text: Some("site".into()), }; assert_eq!(render(&with, now(), 40), "site"); let without = Value::Link { url: "https://makenot.work".into(), text: None, }; assert_eq!(render(&without, now(), 40), "https://makenot.work"); } #[test] fn an_unknown_status_is_loud_not_gray() { // A source nobody can reach must not read as a quiet absence. assert_eq!(status_style(Status::Unknown).fg, Some(Color::Magenta)); assert_eq!(status_style(Status::Ok).fg, Some(Color::Green)); } }