| 1 | //! Data displays: numbers the host or an agent reports, drawn as a |
| 2 | //! sparkline, a bar list or a trend. |
| 3 | //! |
| 4 | //! - The words carry every fact (`now 42 min 3 max 57`); the ink is a |
| 5 | //! picture of the same numbers and never the only place a value appears. |
| 6 | //! - Each display takes `drawn`, a caller-clock progress in `0..=1` from |
| 7 | //! [`crate::MotionStep::drawn`]. Under reduced or still motion that is the |
| 8 | //! end state, so nothing moves and every value is shown. |
| 9 | //! - [`DataDisplay`] is the same vocabulary as data: an agent sends JSON, |
| 10 | //! the host validates it with [`DataDisplay::from_json`] and paints it with |
| 11 | //! [`DataDisplay::view`]. [`DataDisplay::describe`] says the same facts as |
| 12 | //! plain text for a transcript, a screen reader or the model's own context. |
| 13 | |
| 14 | use std::borrow::Cow; |
| 15 | use std::fmt; |
| 16 | |
| 17 | use ratatui::{ |
| 18 | buffer::Buffer, |
| 19 | layout::Rect, |
| 20 | style::{Modifier, Style}, |
| 21 | text::{Line, Span}, |
| 22 | widgets::Widget, |
| 23 | }; |
| 24 | use serde::{Deserialize, Serialize}; |
| 25 | |
| 26 | use crate::{Paint, Role, Theme, color, detect::Appearance, glyphs, text}; |
| 27 | |
| 28 | /// The most points a [`DataDisplay`] sparkline or trend may carry. |
| 29 | pub const DATA_MAX_POINTS: usize = 1024; |
| 30 | /// The most rows a [`DataDisplay`] bar list may carry. |
| 31 | pub const DATA_MAX_BARS: usize = 24; |
| 32 | /// The longest label or unit, in characters. |
| 33 | pub const DATA_MAX_LABEL: usize = 120; |
| 34 | /// The rows a trend may ask for. |
| 35 | pub const DATA_TREND_ROWS: std::ops::RangeInclusive<u16> = 3..=16; |
| 36 | |
| 37 | const SPARK: [&str; 8] = [ |
| 38 | "\u{2581}", "\u{2582}", "\u{2583}", "\u{2584}", "\u{2585}", "\u{2586}", "\u{2587}", "\u{2588}", |
| 39 | ]; |
| 40 | const SPARK_ASCII: [&str; 8] = ["_", "_", ".", "-", "-", "=", "#", "#"]; |
| 41 | const EIGHTHS: [&str; 8] = [ |
| 42 | "", "\u{258F}", "\u{258E}", "\u{258D}", "\u{258C}", "\u{258B}", "\u{258A}", "\u{2589}", |
| 43 | ]; |
| 44 | const FULL: &str = "\u{2588}"; |
| 45 | const MIN_SPARK: usize = 4; |
| 46 | const MAX_SPARK: usize = 64; |
| 47 | const MIN_BAR: usize = 4; |
| 48 | const BAR_STAGGER: f32 = 0.35; |
| 49 | |
| 50 | /// Words the data displays print. `Default` is English. |
| 51 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 52 | pub struct DataWords { |
| 53 | pub now: Cow<'static, str>, |
| 54 | pub min: Cow<'static, str>, |
| 55 | pub max: Cow<'static, str>, |
| 56 | /// Shown when there are no values yet. |
| 57 | pub empty: Cow<'static, str>, |
| 58 | /// `24 points` in [`DataDisplay::describe`]. |
| 59 | pub points: Cow<'static, str>, |
| 60 | } |
| 61 | |
| 62 | impl Default for DataWords { |
| 63 | fn default() -> Self { |
| 64 | Self { |
| 65 | now: Cow::Borrowed("now"), |
| 66 | min: Cow::Borrowed("min"), |
| 67 | max: Cow::Borrowed("max"), |
| 68 | empty: Cow::Borrowed("no data yet"), |
| 69 | points: Cow::Borrowed("points"), |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | /// A short form of `value`: `42`, `3.14`, `0.0042`, `12.4k`, `1.2M`. |
| 75 | /// |
| 76 | /// A value that is not zero never reads as `0`: small values keep two |
| 77 | /// significant digits and the smallest and largest use an exponent. |
| 78 | #[must_use] |
| 79 | pub fn data_number(value: f64) -> String { |
| 80 | const TIERS: [(f64, f64, &str); 5] = [ |
| 81 | (1.0, 1e4, ""), |
| 82 | (1e3, 1e6, "k"), |
| 83 | (1e6, 1e9, "M"), |
| 84 | (1e9, 1e12, "B"), |
| 85 | (1e12, 1e15, "T"), |
| 86 | ]; |
| 87 | if !value.is_finite() { |
| 88 | return "?".to_owned(); |
| 89 | } |
| 90 | if value == 0.0 { |
| 91 | return "0".to_owned(); |
| 92 | } |
| 93 | let a = value.abs(); |
| 94 | if a < 1e-4 { |
| 95 | return format!("{value:.1e}").replace(".0e", "e"); |
| 96 | } |
| 97 | let trim = |s: String| { |
| 98 | if s.contains('.') { |
| 99 | s.trim_end_matches('0').trim_end_matches('.').to_owned() |
| 100 | } else { |
| 101 | s |
| 102 | } |
| 103 | }; |
| 104 | if a < 0.1 { |
| 105 | let decimals = (1.0 - a.log10().floor()) as usize; |
| 106 | return trim(format!("{value:.decimals$}")); |
| 107 | } |
| 108 | let mut tier = TIERS.iter().position(|t| a < t.1).unwrap_or(TIERS.len()); |
| 109 | while let Some((unit, next, suffix)) = TIERS.get(tier).copied() { |
| 110 | let scaled = value / unit; |
| 111 | let s = if scaled.abs() >= 100.0 { |
| 112 | format!("{scaled:.0}") |
| 113 | } else if scaled.abs() >= 10.0 { |
| 114 | format!("{scaled:.1}") |
| 115 | } else { |
| 116 | format!("{scaled:.2}") |
| 117 | }; |
| 118 | let rounded = s.parse::<f64>().map_or(a, |r| r.abs() * unit); |
| 119 | if rounded >= next { |
| 120 | tier += 1; |
| 121 | continue; |
| 122 | } |
| 123 | return format!("{}{suffix}", trim(s)); |
| 124 | } |
| 125 | format!("{value:.1e}").replace(".0e", "e") |
| 126 | } |
| 127 | |
| 128 | fn with_unit(value: f64, unit: &str) -> String { |
| 129 | let n = data_number(value); |
| 130 | let unit = text::display_safe(unit); |
| 131 | match unit.as_ref() { |
| 132 | "" => n, |
| 133 | "%" => format!("{n}%"), |
| 134 | u => format!("{n} {u}"), |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | fn unit_f(v: f32) -> f32 { |
| 139 | if v.is_nan() { 1.0 } else { v.clamp(0.0, 1.0) } |
| 140 | } |
| 141 | |
| 142 | fn bounds(values: &[f64]) -> Option<(f64, f64)> { |
| 143 | let mut it = values.iter().copied().filter(|v| v.is_finite()); |
| 144 | let first = it.next()?; |
| 145 | Some(it.fold((first, first), |(lo, hi), v| (lo.min(v), hi.max(v)))) |
| 146 | } |
| 147 | |
| 148 | fn level(v: f64, lo: f64, hi: f64, steps: usize) -> usize { |
| 149 | if !v.is_finite() || steps == 0 { |
| 150 | return 0; |
| 151 | } |
| 152 | if hi <= lo { |
| 153 | return steps / 2; |
| 154 | } |
| 155 | let t = ((v - lo) / (hi - lo)).clamp(0.0, 1.0); |
| 156 | ((t * (steps - 1) as f64).round() as usize).min(steps - 1) |
| 157 | } |
| 158 | |
| 159 | struct Stats { |
| 160 | full: Vec<Span<'static>>, |
| 161 | short: Vec<Span<'static>>, |
| 162 | full_w: usize, |
| 163 | short_w: usize, |
| 164 | } |
| 165 | |
| 166 | fn stats(values: &[f64], unit: &str, words: &DataWords, theme: &Theme) -> Option<Stats> { |
| 167 | let (lo, hi) = bounds(values)?; |
| 168 | let last = values.iter().rev().copied().find(|v| v.is_finite())?; |
| 169 | let muted = theme.fg(Role::Muted); |
| 170 | let ink = theme.fg(Role::Foreground); |
| 171 | let pair = |word: &str, v: f64| { |
| 172 | [ |
| 173 | Span::styled(format!("{} ", text::display_safe(word)), muted), |
| 174 | Span::styled(with_unit(v, unit), ink), |
| 175 | ] |
| 176 | }; |
| 177 | let short: Vec<Span<'static>> = pair(&words.now, last).into(); |
| 178 | let mut full = short.clone(); |
| 179 | full.push(Span::raw(" ")); |
| 180 | full.extend(pair(&words.min, lo)); |
| 181 | full.push(Span::raw(" ")); |
| 182 | full.extend(pair(&words.max, hi)); |
| 183 | let w = |s: &[Span]| s.iter().map(|s| text::width(&s.content)).sum(); |
| 184 | Some(Stats { |
| 185 | full_w: w(&full), |
| 186 | short_w: w(&short), |
| 187 | full, |
| 188 | short, |
| 189 | }) |
| 190 | } |
| 191 | |
| 192 | fn put(area: Rect, buf: &mut Buffer, row: u16, spans: Vec<Span<'_>>) { |
| 193 | if row >= area.height { |
| 194 | return; |
| 195 | } |
| 196 | Line::from(spans).render(Rect::new(area.x, area.y + row, area.width, 1), buf); |
| 197 | } |
| 198 | |
| 199 | fn title_spans<'a>(label: &str, max: usize, theme: &Theme) -> (Span<'a>, usize) { |
| 200 | let label = text::display_safe(label); |
| 201 | let shown = text::truncate(&label, max, theme.ascii()).into_owned(); |
| 202 | let w = text::width(&shown); |
| 203 | ( |
| 204 | Span::styled( |
| 205 | shown, |
| 206 | theme.fg(Role::Foreground).add_modifier(Modifier::BOLD), |
| 207 | ), |
| 208 | w, |
| 209 | ) |
| 210 | } |
| 211 | |
| 212 | /// `Requests ▂▃▅▇█▆▄ now 42 min 3 max 57`: one row, newest on the right. |
| 213 | /// |
| 214 | /// The window shows the newest values that fit; the words describe the |
| 215 | /// whole series. While `drawn` is below one the line draws in from the left. |
| 216 | #[derive(Clone, Debug)] |
| 217 | pub struct DataSparkline<'a> { |
| 218 | pub label: Cow<'a, str>, |
| 219 | pub unit: Cow<'a, str>, |
| 220 | pub values: &'a [f64], |
| 221 | pub drawn: f32, |
| 222 | pub words: DataWords, |
| 223 | area_fill: bool, |
| 224 | } |
| 225 | |
| 226 | impl<'a> DataSparkline<'a> { |
| 227 | #[must_use] |
| 228 | pub fn new(label: impl Into<Cow<'a, str>>, values: &'a [f64]) -> Self { |
| 229 | Self { |
| 230 | label: label.into(), |
| 231 | unit: Cow::Borrowed(""), |
| 232 | values, |
| 233 | drawn: 1.0, |
| 234 | words: DataWords::default(), |
| 235 | area_fill: false, |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | #[must_use] |
| 240 | pub fn unit(mut self, unit: impl Into<Cow<'a, str>>) -> Self { |
| 241 | self.unit = unit.into(); |
| 242 | self |
| 243 | } |
| 244 | |
| 245 | #[must_use] |
| 246 | pub fn drawn(mut self, drawn: f32) -> Self { |
| 247 | self.drawn = unit_f(drawn); |
| 248 | self |
| 249 | } |
| 250 | |
| 251 | #[must_use] |
| 252 | pub fn with_words(mut self, words: &DataWords) -> Self { |
| 253 | self.words = words.clone(); |
| 254 | self |
| 255 | } |
| 256 | |
| 257 | /// Shade sparkline peaks with a perceptual OKLab height ramp and subtle |
| 258 | /// translucent under-glow on truecolor terminals with painted grounds. |
| 259 | #[must_use] |
| 260 | pub const fn area_fill(mut self, enabled: bool) -> Self { |
| 261 | self.area_fill = enabled; |
| 262 | self |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | impl Paint for DataSparkline<'_> { |
| 267 | fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) { |
| 268 | let area = area.intersection(buf.area); |
| 269 | if area.is_empty() { |
| 270 | return; |
| 271 | } |
| 272 | let width = usize::from(area.width); |
| 273 | let label_max = if self.label.is_empty() { |
| 274 | 0 |
| 275 | } else { |
| 276 | (width / 3).max(4) |
| 277 | }; |
| 278 | let (title, label_w) = title_spans(&self.label, label_max, theme); |
| 279 | let gap = if label_w > 0 { 2 } else { 0 }; |
| 280 | let mut spans = vec![title, Span::raw(" ".repeat(gap))]; |
| 281 | let Some(stats) = stats(self.values, &self.unit, &self.words, theme) else { |
| 282 | spans.push(Span::styled( |
| 283 | text::display_safe(&self.words.empty).into_owned(), |
| 284 | theme.fg(Role::Muted), |
| 285 | )); |
| 286 | put(area, buf, 0, spans); |
| 287 | return; |
| 288 | }; |
| 289 | let room = width.saturating_sub(label_w + gap); |
| 290 | let (words, words_w) = if stats.full_w + 2 + MIN_SPARK <= room { |
| 291 | (stats.full, stats.full_w) |
| 292 | } else { |
| 293 | (stats.short, stats.short_w) |
| 294 | }; |
| 295 | let cells = room |
| 296 | .saturating_sub(words_w + 2) |
| 297 | .min(MAX_SPARK) |
| 298 | .min(self.values.len()); |
| 299 | if cells >= MIN_SPARK.min(self.values.len()).max(1) { |
| 300 | let window = &self.values[self.values.len() - cells..]; |
| 301 | let (lo, hi) = bounds(window).unwrap_or((0.0, 0.0)); |
| 302 | let shown = (cells as f32 * self.drawn).ceil() as usize; |
| 303 | let ramp = if theme.ascii() { SPARK_ASCII } else { SPARK }; |
| 304 | let use_fill = self.area_fill |
| 305 | && !theme.ascii() |
| 306 | && theme.depth() == color::ColorDepth::TrueColor |
| 307 | && theme.paints_grounds(); |
| 308 | if use_fill |
| 309 | && let (Some(accent), Some(live), Some(bg_base)) = ( |
| 310 | theme.color(Role::Accent), |
| 311 | theme.color(Role::Live), |
| 312 | theme.color(Role::Background), |
| 313 | ) |
| 314 | { |
| 315 | let light = theme.caps().appearance == Appearance::Light; |
| 316 | for (i, v) in window.iter().enumerate() { |
| 317 | if i < shown && v.is_finite() { |
| 318 | let lvl = level(*v, lo, hi, ramp.len()); |
| 319 | let t = lvl as f32 / (ramp.len() - 1) as f32; |
| 320 | let bar_fg = color::mix_oklab(accent, live, t); |
| 321 | let glow_alpha = if light { |
| 322 | 0.03 + 0.09 * t |
| 323 | } else { |
| 324 | 0.04 + 0.14 * t |
| 325 | }; |
| 326 | let bar_bg = color::mix_oklab(bg_base, bar_fg, glow_alpha); |
| 327 | let safe_fg = color::contrast_safe_oklab_mix( |
| 328 | bar_fg, |
| 329 | theme.token(Role::Foreground), |
| 330 | bar_bg, |
| 331 | 0.25 * t, |
| 332 | 4.5, |
| 333 | ); |
| 334 | spans.push(Span::styled( |
| 335 | ramp[lvl], |
| 336 | Style::default().fg(safe_fg).bg(bar_bg), |
| 337 | )); |
| 338 | } else { |
| 339 | spans.push(Span::raw(" ")); |
| 340 | } |
| 341 | } |
| 342 | } else { |
| 343 | let mut line = String::with_capacity(cells * 3); |
| 344 | for (i, v) in window.iter().enumerate() { |
| 345 | line.push_str(if i < shown && v.is_finite() { |
| 346 | ramp[level(*v, lo, hi, ramp.len())] |
| 347 | } else { |
| 348 | " " |
| 349 | }); |
| 350 | } |
| 351 | spans.push(Span::styled(line, theme.fg(Role::Accent))); |
| 352 | } |
| 353 | spans.push(Span::raw(" ")); |
| 354 | } |
| 355 | spans.extend(words); |
| 356 | put(area, buf, 0, spans); |
| 357 | } |
| 358 | |
| 359 | fn height(&self, _width: u16, _theme: &Theme) -> u16 { |
| 360 | 1 |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | /// One named value in a [`DataBars`] list or a [`DataDisplay::Bars`]. |
| 365 | #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] |
| 366 | #[serde(deny_unknown_fields)] |
| 367 | pub struct DataBarItem { |
| 368 | pub label: String, |
| 369 | pub value: f64, |
| 370 | } |
| 371 | |
| 372 | impl DataBarItem { |
| 373 | #[must_use] |
| 374 | pub fn new(label: impl Into<String>, value: f64) -> Self { |
| 375 | Self { |
| 376 | label: label.into(), |
| 377 | value, |
| 378 | } |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | /// A title row, then one row per item: `opus ██████████▍ 12.4k tokens`. |
| 383 | /// |
| 384 | /// Bars scale to the largest value and fill in eighths of a cell. While |
| 385 | /// `drawn` is below one each bar grows from its `previous` value (or zero) |
| 386 | /// to its value, a little after the bar above it. A value above zero always |
| 387 | /// draws at least an eighth of a cell, so it never looks like zero. A |
| 388 | /// negative value draws no bar; its words keep the real number. On a narrow |
| 389 | /// row the label gives way before the value does. |
| 390 | #[derive(Clone, Debug)] |
| 391 | pub struct DataBars<'a> { |
| 392 | pub label: Cow<'a, str>, |
| 393 | pub unit: Cow<'a, str>, |
| 394 | pub items: &'a [DataBarItem], |
| 395 | /// The values each row grows from, by index. Missing rows grow from zero. |
| 396 | pub previous: &'a [f64], |
| 397 | pub drawn: f32, |
| 398 | pub words: DataWords, |
| 399 | } |
| 400 | |
| 401 | impl<'a> DataBars<'a> { |
| 402 | #[must_use] |
| 403 | pub fn new(label: impl Into<Cow<'a, str>>, items: &'a [DataBarItem]) -> Self { |
| 404 | Self { |
| 405 | label: label.into(), |
| 406 | unit: Cow::Borrowed(""), |
| 407 | items, |
| 408 | previous: &[], |
| 409 | drawn: 1.0, |
| 410 | words: DataWords::default(), |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | #[must_use] |
| 415 | pub fn unit(mut self, unit: impl Into<Cow<'a, str>>) -> Self { |
| 416 | self.unit = unit.into(); |
| 417 | self |
| 418 | } |
| 419 | |
| 420 | #[must_use] |
| 421 | pub fn previous(mut self, previous: &'a [f64]) -> Self { |
| 422 | self.previous = previous; |
| 423 | self |
| 424 | } |
| 425 | |
| 426 | #[must_use] |
| 427 | pub fn drawn(mut self, drawn: f32) -> Self { |
| 428 | self.drawn = unit_f(drawn); |
| 429 | self |
| 430 | } |
| 431 | |
| 432 | #[must_use] |
| 433 | pub fn with_words(mut self, words: &DataWords) -> Self { |
| 434 | self.words = words.clone(); |
| 435 | self |
| 436 | } |
| 437 | |
| 438 | fn row_progress(&self, row: usize) -> f64 { |
| 439 | let n = self.items.len(); |
| 440 | let delay = if n > 1 { |
| 441 | BAR_STAGGER * row as f32 / (n - 1) as f32 |
| 442 | } else { |
| 443 | 0.0 |
| 444 | }; |
| 445 | f64::from(((self.drawn - delay) / (1.0 - BAR_STAGGER)).clamp(0.0, 1.0)) |
| 446 | } |
| 447 | |
| 448 | fn bar(&self, eighths: usize, ascii: bool) -> String { |
| 449 | if ascii { |
| 450 | "#".repeat(eighths.div_ceil(8)) |
| 451 | } else { |
| 452 | let mut s = FULL.repeat(eighths / 8); |
| 453 | s.push_str(EIGHTHS[eighths % 8]); |
| 454 | s |
| 455 | } |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | impl Paint for DataBars<'_> { |
| 460 | fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) { |
| 461 | let area = area.intersection(buf.area); |
| 462 | if area.is_empty() { |
| 463 | return; |
| 464 | } |
| 465 | let width = usize::from(area.width); |
| 466 | let ascii = theme.ascii(); |
| 467 | let mut row = 0; |
| 468 | if !self.label.is_empty() { |
| 469 | let (title, _) = title_spans(&self.label, width, theme); |
| 470 | put(area, buf, 0, vec![title]); |
| 471 | row = 1; |
| 472 | } |
| 473 | if self.items.is_empty() { |
| 474 | put( |
| 475 | area, |
| 476 | buf, |
| 477 | row, |
| 478 | vec![Span::styled( |
| 479 | text::display_safe(&self.words.empty).into_owned(), |
| 480 | theme.fg(Role::Muted), |
| 481 | )], |
| 482 | ); |
| 483 | return; |
| 484 | } |
| 485 | let values: Vec<String> = self |
| 486 | .items |
| 487 | .iter() |
| 488 | .map(|i| with_unit(i.value, &self.unit)) |
| 489 | .collect(); |
| 490 | let value_w = values.iter().map(|v| text::width(v)).max().unwrap_or(0); |
| 491 | let labels: Vec<Cow<'_, str>> = self |
| 492 | .items |
| 493 | .iter() |
| 494 | .map(|i| text::display_safe(&i.label)) |
| 495 | .collect(); |
| 496 | let label_w = labels |
| 497 | .iter() |
| 498 | .map(|l| text::width(l)) |
| 499 | .max() |
| 500 | .unwrap_or(0) |
| 501 | .min((width / 3).max(4)) |
| 502 | .min(width.saturating_sub(value_w + 2)); |
| 503 | let cells = width.saturating_sub(label_w + 2 + 2 + value_w); |
| 504 | let peak = self |
| 505 | .items |
| 506 | .iter() |
| 507 | .map(|i| i.value) |
| 508 | .chain(self.previous.iter().copied()) |
| 509 | .filter(|v| v.is_finite()) |
| 510 | .fold(0.0_f64, f64::max); |
| 511 | for (i, (item, value)) in self.items.iter().zip(&values).enumerate() { |
| 512 | let y = row + i as u16; |
| 513 | if y >= area.height { |
| 514 | break; |
| 515 | } |
| 516 | let mut spans = Vec::new(); |
| 517 | if label_w > 0 { |
| 518 | spans.push(Span::styled( |
| 519 | text::pad(&labels[i], label_w, ascii), |
| 520 | theme.fg(Role::Foreground), |
| 521 | )); |
| 522 | spans.push(Span::raw(" ")); |
| 523 | } |
| 524 | if cells >= MIN_BAR { |
| 525 | let from = self |
| 526 | .previous |
| 527 | .get(i) |
| 528 | .copied() |
| 529 | .filter(|v| v.is_finite()) |
| 530 | .unwrap_or(0.0); |
| 531 | let to = if item.value.is_finite() { |
| 532 | item.value |
| 533 | } else { |
| 534 | 0.0 |
| 535 | }; |
| 536 | let shown = from + (to - from) * self.row_progress(i); |
| 537 | let frac = if peak > 0.0 { |
| 538 | (shown / peak).clamp(0.0, 1.0) |
| 539 | } else { |
| 540 | 0.0 |
| 541 | }; |
| 542 | let eighths = |
| 543 | ((frac * cells as f64 * 8.0).round() as usize).max(usize::from(frac > 0.0)); |
| 544 | let bar = self.bar(eighths, ascii); |
| 545 | let bar_w = text::width(&bar); |
| 546 | spans.push(Span::styled(bar, theme.fg(Role::Accent))); |
| 547 | spans.push(Span::raw(" ".repeat(cells.saturating_sub(bar_w) + 2))); |
| 548 | } |
| 549 | spans.push(Span::styled(value.clone(), theme.fg(Role::Muted))); |
| 550 | put(area, buf, y, spans); |
| 551 | } |
| 552 | } |
| 553 | |
| 554 | fn height(&self, _width: u16, _theme: &Theme) -> u16 { |
| 555 | let title = u16::from(!self.label.is_empty()); |
| 556 | title + (self.items.len().max(1)).min(usize::from(u16::MAX - 1)) as u16 |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | /// A caption row, then a braille line chart with its range on the left. |
| 561 | /// |
| 562 | /// While `drawn` is below one the line draws from the left and its pen, the |
| 563 | /// newest drawn cell, is in body ink. A series with more points than the |
| 564 | /// plot has dot columns draws each column from its lowest to its highest |
| 565 | /// value, so the line always reaches the `min` and `max` the words name. Too |
| 566 | /// small for a chart, it paints a [`DataSparkline`] instead. |
| 567 | #[derive(Clone, Debug)] |
| 568 | pub struct DataTrend<'a> { |
| 569 | pub label: Cow<'a, str>, |
| 570 | pub unit: Cow<'a, str>, |
| 571 | pub values: &'a [f64], |
| 572 | pub drawn: f32, |
| 573 | pub rows: u16, |
| 574 | pub words: DataWords, |
| 575 | area_fill: bool, |
| 576 | } |
| 577 | |
| 578 | impl<'a> DataTrend<'a> { |
| 579 | #[must_use] |
| 580 | pub fn new(label: impl Into<Cow<'a, str>>, values: &'a [f64]) -> Self { |
| 581 | Self { |
| 582 | label: label.into(), |
| 583 | unit: Cow::Borrowed(""), |
| 584 | values, |
| 585 | drawn: 1.0, |
| 586 | rows: 6, |
| 587 | words: DataWords::default(), |
| 588 | area_fill: false, |
| 589 | } |
| 590 | } |
| 591 | |
| 592 | #[must_use] |
| 593 | pub fn unit(mut self, unit: impl Into<Cow<'a, str>>) -> Self { |
| 594 | self.unit = unit.into(); |
| 595 | self |
| 596 | } |
| 597 | |
| 598 | #[must_use] |
| 599 | pub fn drawn(mut self, drawn: f32) -> Self { |
| 600 | self.drawn = unit_f(drawn); |
| 601 | self |
| 602 | } |
| 603 | |
| 604 | /// Rows including the caption. |
| 605 | #[must_use] |
| 606 | pub fn rows(mut self, rows: u16) -> Self { |
| 607 | self.rows = rows.max(1); |
| 608 | self |
| 609 | } |
| 610 | |
| 611 | #[must_use] |
| 612 | pub fn with_words(mut self, words: &DataWords) -> Self { |
| 613 | self.words = words.clone(); |
| 614 | self |
| 615 | } |
| 616 | |
| 617 | /// Paint a translucent OKLab gradient area fill beneath the plotted Braille |
| 618 | /// curve on truecolor terminals with painted grounds. |
| 619 | #[must_use] |
| 620 | pub const fn area_fill(mut self, enabled: bool) -> Self { |
| 621 | self.area_fill = enabled; |
| 622 | self |
| 623 | } |
| 624 | |
| 625 | fn sparkline(&self) -> DataSparkline<'_> { |
| 626 | DataSparkline { |
| 627 | label: Cow::Borrowed(&self.label), |
| 628 | unit: Cow::Borrowed(&self.unit), |
| 629 | values: self.values, |
| 630 | drawn: self.drawn, |
| 631 | words: self.words.clone(), |
| 632 | area_fill: self.area_fill, |
| 633 | } |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | fn sample(values: &[f64], columns: usize) -> Vec<Option<(f64, f64)>> { |
| 638 | let n = values.len(); |
| 639 | if n == 0 || columns == 0 { |
| 640 | return Vec::new(); |
| 641 | } |
| 642 | let point = |v: f64| v.is_finite().then_some((v, v)); |
| 643 | if n == 1 { |
| 644 | return vec![point(values[0]); columns]; |
| 645 | } |
| 646 | if n > columns { |
| 647 | return (0..columns) |
| 648 | .map(|c| { |
| 649 | let start = c * n / columns; |
| 650 | let end = ((c + 1) * n / columns).max(start + 1); |
| 651 | bounds(&values[start..end]) |
| 652 | }) |
| 653 | .collect(); |
| 654 | } |
| 655 | (0..columns) |
| 656 | .map(|c| { |
| 657 | let at = c as f64 * (n - 1) as f64 / (columns - 1) as f64; |
| 658 | let (i, t) = (at.floor() as usize, at.fract()); |
| 659 | let a = values[i]; |
| 660 | let b = values[(i + 1).min(n - 1)]; |
| 661 | point(if t == 0.0 { a } else { a + (b - a) * t }) |
| 662 | }) |
| 663 | .collect() |
| 664 | } |
| 665 | |
| 666 | fn braille_bit(dx: usize, dy: usize) -> u8 { |
| 667 | match (dx, dy) { |
| 668 | (0, 0) => 0x01, |
| 669 | (0, 1) => 0x02, |
| 670 | (0, 2) => 0x04, |
| 671 | (1, 0) => 0x08, |
| 672 | (1, 1) => 0x10, |
| 673 | (1, 2) => 0x20, |
| 674 | (0, _) => 0x40, |
| 675 | _ => 0x80, |
| 676 | } |
| 677 | } |
| 678 | |
| 679 | impl Paint for DataTrend<'_> { |
| 680 | fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) { |
| 681 | let area = area.intersection(buf.area); |
| 682 | if area.is_empty() { |
| 683 | return; |
| 684 | } |
| 685 | let Some((lo, hi)) = bounds(self.values) else { |
| 686 | self.sparkline().paint(area, buf, theme); |
| 687 | return; |
| 688 | }; |
| 689 | let ascii = theme.ascii(); |
| 690 | let hi_s = with_unit(hi, &self.unit); |
| 691 | let lo_s = with_unit(lo, &self.unit); |
| 692 | let axis_w = text::width(&hi_s).max(text::width(&lo_s)); |
| 693 | let plot_rows = usize::from(area.height.min(self.rows)).saturating_sub(1); |
| 694 | let plot_w = usize::from(area.width).saturating_sub(axis_w + 2); |
| 695 | if plot_rows < 2 || plot_w < MIN_SPARK * 2 { |
| 696 | self.sparkline().paint(area, buf, theme); |
| 697 | return; |
| 698 | } |
| 699 | |
| 700 | let (title, label_w) = title_spans(&self.label, usize::from(area.width) / 2, theme); |
| 701 | let mut caption = vec![title]; |
| 702 | if let Some(stats) = stats(self.values, &self.unit, &self.words, theme) { |
| 703 | let room = usize::from(area.width).saturating_sub(label_w + 2); |
| 704 | let (words, w) = if stats.full_w <= room { |
| 705 | (stats.full, stats.full_w) |
| 706 | } else { |
| 707 | (stats.short, stats.short_w) |
| 708 | }; |
| 709 | if w <= room { |
| 710 | caption.push(Span::raw(" ")); |
| 711 | caption.extend(words); |
| 712 | } |
| 713 | } |
| 714 | put(area, buf, 0, caption); |
| 715 | |
| 716 | let dots_w = plot_w * 2; |
| 717 | let dots_h = plot_rows * 4; |
| 718 | let points = sample(self.values, dots_w); |
| 719 | let shown = ((dots_w as f32 * self.drawn).ceil() as usize).min(dots_w); |
| 720 | let mut cells = vec![0u8; plot_w * plot_rows]; |
| 721 | let mut col_top_dot: Vec<Option<usize>> = vec![None; plot_w]; |
| 722 | let y_of = |v: f64| dots_h - 1 - level(v, lo, hi, dots_h); |
| 723 | let mut prev: Option<(usize, usize)> = None; |
| 724 | for (x, span) in points.iter().take(shown).enumerate() { |
| 725 | let Some((low, high)) = *span else { |
| 726 | prev = None; |
| 727 | continue; |
| 728 | }; |
| 729 | let (top, bottom) = (y_of(high), y_of(low)); |
| 730 | let col = x / 2; |
| 731 | col_top_dot[col] = Some(col_top_dot[col].map_or(top, |cur| cur.min(top))); |
| 732 | let (a, b) = match prev { |
| 733 | Some((_, below)) if below < top => (below + 1, bottom), |
| 734 | Some((above, _)) if above > bottom => (top, above - 1), |
| 735 | _ => (top, bottom), |
| 736 | }; |
| 737 | for yy in a..=b { |
| 738 | cells[(yy / 4) * plot_w + col] |= braille_bit(x % 2, yy % 4); |
| 739 | } |
| 740 | prev = Some((top, bottom)); |
| 741 | } |
| 742 | let pen = (shown < dots_w && shown > 0).then(|| (shown - 1) / 2); |
| 743 | |
| 744 | let use_area_fill = self.area_fill |
| 745 | && !ascii |
| 746 | && theme.depth() == color::ColorDepth::TrueColor |
| 747 | && theme.paints_grounds(); |
| 748 | let fill_palette = if use_area_fill { |
| 749 | match ( |
| 750 | theme.color(Role::Accent), |
| 751 | theme.color(Role::Live), |
| 752 | theme.color(Role::Foreground), |
| 753 | theme.color(Role::Background), |
| 754 | ) { |
| 755 | (Some(accent), Some(live), Some(fg), Some(bg_fallback)) => { |
| 756 | Some((accent, live, fg, bg_fallback)) |
| 757 | } |
| 758 | _ => None, |
| 759 | } |
| 760 | } else { |
| 761 | None |
| 762 | }; |
| 763 | let light = theme.caps().appearance == Appearance::Light; |
| 764 | |
| 765 | let axis_style = theme.fg(Role::Muted); |
| 766 | let rail = glyphs::pick("\u{2502}", ascii); |
| 767 | for r in 0..plot_rows { |
| 768 | let y = area.y + 1 + r as u16; |
| 769 | let tick = if r == 0 { |
| 770 | hi_s.as_str() |
| 771 | } else if r == plot_rows - 1 { |
| 772 | lo_s.as_str() |
| 773 | } else { |
| 774 | "" |
| 775 | }; |
| 776 | let tick = format!("{tick:>axis_w$} "); |
| 777 | buf.set_stringn(area.x, y, &tick, axis_w + 1, axis_style); |
| 778 | buf.set_stringn( |
| 779 | area.x + (axis_w + 1) as u16, |
| 780 | y, |
| 781 | rail, |
| 782 | 1, |
| 783 | theme.fg(Role::Dim), |
| 784 | ); |
| 785 | for c in 0..plot_w { |
| 786 | let x = area.x + (axis_w + 2 + c) as u16; |
| 787 | let bits = cells[r * plot_w + c]; |
| 788 | let mut shaded_bg = None; |
| 789 | if let Some((accent, live, _, bg_fallback)) = fill_palette |
| 790 | && let Some(top_dot) = col_top_dot[c] |
| 791 | { |
| 792 | let top_row = top_dot / 4; |
| 793 | if r >= top_row { |
| 794 | let span_rows = plot_rows.saturating_sub(top_row).max(1) as f32; |
| 795 | let depth_below = (r - top_row) as f32 / span_rows; |
| 796 | let height_ratio = |
| 797 | 1.0 - (top_dot as f32 / dots_h.saturating_sub(1).max(1) as f32); |
| 798 | let tint = color::mix_oklab(accent, live, height_ratio * 0.72); |
| 799 | let alpha = if light { |
| 800 | 0.025 + 0.135 * (1.0 - depth_below).powf(1.5) |
| 801 | } else { |
| 802 | 0.04 + 0.22 * (1.0 - depth_below).powf(1.5) |
| 803 | }; |
| 804 | if let Some(cell) = buf.cell_mut((x, y)) { |
| 805 | let under = if color::is_truecolor(cell.bg) { |
| 806 | cell.bg |
| 807 | } else { |
| 808 | bg_fallback |
| 809 | }; |
| 810 | let filled_bg = color::mix_oklab(under, tint, alpha); |
| 811 | cell.set_bg(filled_bg); |
| 812 | shaded_bg = Some(filled_bg); |
| 813 | } |
| 814 | } |
| 815 | } |
| 816 | if bits == 0 { |
| 817 | continue; |
| 818 | } |
| 819 | let style: Style = if pen == Some(c) { |
| 820 | theme.fg(Role::Foreground).add_modifier(Modifier::BOLD) |
| 821 | } else if let Some((accent, live, fg, bg_fallback)) = fill_palette { |
| 822 | let row_height = 1.0 - (r as f32 / plot_rows.saturating_sub(1).max(1) as f32); |
| 823 | let curve_base = color::mix_oklab(accent, live, row_height * 0.85); |
| 824 | let ground = shaded_bg.unwrap_or(bg_fallback); |
| 825 | let curve_fg = if row_height > 0.65 && !light { |
| 826 | let lifted = |
| 827 | color::specular_lift(curve_base, fg, (row_height - 0.65) * 0.6); |
| 828 | color::contrast_safe_oklab_mix(lifted, fg, ground, 0.2, 4.5) |
| 829 | } else { |
| 830 | color::contrast_safe_oklab_mix(curve_base, fg, ground, 0.15, 4.5) |
| 831 | }; |
| 832 | Style::default().fg(curve_fg) |
| 833 | } else { |
| 834 | theme.fg(Role::Accent) |
| 835 | }; |
| 836 | let glyph = char::from_u32(0x2800 + u32::from(bits)).unwrap_or(' '); |
| 837 | let mut encoded = [0; 4]; |
| 838 | let symbol: &str = if ascii { |
| 839 | glyphs::braille_ascii_fallback(glyph).unwrap_or(".") |
| 840 | } else { |
| 841 | glyph.encode_utf8(&mut encoded) |
| 842 | }; |
| 843 | if let Some(cell) = buf.cell_mut((x, y)) { |
| 844 | cell.set_symbol(symbol).set_style(style); |
| 845 | } |
| 846 | } |
| 847 | } |
| 848 | } |
| 849 | |
| 850 | fn height(&self, _width: u16, _theme: &Theme) -> u16 { |
| 851 | self.rows |
| 852 | } |
| 853 | } |
| 854 | |
| 855 | /// A data display as data: what an agent sends to show numbers. |
| 856 | /// |
| 857 | /// ``` |
| 858 | /// use codewhale_ratatui::DataDisplay; |
| 859 | /// |
| 860 | /// let shown = DataDisplay::from_json( |
| 861 | /// r#"{"kind":"bars","label":"Tokens by model","unit":"tokens", |
| 862 | /// "items":[{"label":"opus","value":12400},{"label":"haiku","value":3100}]}"#, |
| 863 | /// ) |
| 864 | /// .unwrap(); |
| 865 | /// assert_eq!( |
| 866 | /// shown.describe(&Default::default()), |
| 867 | /// "Tokens by model: opus 12.4k tokens, haiku 3100 tokens" |
| 868 | /// ); |
| 869 | /// ``` |
| 870 | #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] |
| 871 | #[serde(tag = "kind", rename_all = "snake_case")] |
| 872 | pub enum DataDisplay { |
| 873 | Sparkline { |
| 874 | label: String, |
| 875 | #[serde(default)] |
| 876 | unit: String, |
| 877 | values: Vec<f64>, |
| 878 | }, |
| 879 | Bars { |
| 880 | label: String, |
| 881 | #[serde(default)] |
| 882 | unit: String, |
| 883 | items: Vec<DataBarItem>, |
| 884 | }, |
| 885 | Trend { |
| 886 | label: String, |
| 887 | #[serde(default)] |
| 888 | unit: String, |
| 889 | values: Vec<f64>, |
| 890 | #[serde(default)] |
| 891 | rows: Option<u16>, |
| 892 | }, |
| 893 | } |
| 894 | |
| 895 | /// Why a [`DataDisplay`] was refused. |
| 896 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 897 | pub enum DataDisplayError { |
| 898 | Parse(String), |
| 899 | TooManyPoints { count: usize }, |
| 900 | TooManyBars { count: usize }, |
| 901 | NotFinite { index: usize }, |
| 902 | LabelTooLong { chars: usize }, |
| 903 | Rows { rows: u16 }, |
| 904 | } |
| 905 | |
| 906 | impl fmt::Display for DataDisplayError { |
| 907 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 908 | match self { |
| 909 | Self::Parse(e) => write!(f, "not a data display: {e}"), |
| 910 | Self::TooManyPoints { count } => { |
| 911 | write!(f, "{count} points; at most {DATA_MAX_POINTS}") |
| 912 | } |
| 913 | Self::TooManyBars { count } => write!(f, "{count} bars; at most {DATA_MAX_BARS}"), |
| 914 | Self::NotFinite { index } => write!(f, "value {index} is not a finite number"), |
| 915 | Self::LabelTooLong { chars } => { |
| 916 | write!(f, "a label of {chars} characters; at most {DATA_MAX_LABEL}") |
| 917 | } |
| 918 | Self::Rows { rows } => write!( |
| 919 | f, |
| 920 | "{rows} rows; a trend takes {} to {}", |
| 921 | DATA_TREND_ROWS.start(), |
| 922 | DATA_TREND_ROWS.end() |
| 923 | ), |
| 924 | } |
| 925 | } |
| 926 | } |
| 927 | |
| 928 | impl std::error::Error for DataDisplayError {} |
| 929 | |
| 930 | /// The JSON Schema for [`DataDisplay`], for an agent's tool definition. |
| 931 | pub const DATA_DISPLAY_SCHEMA: &str = r#"{ |
| 932 | "type": "object", |
| 933 | "description": "Numbers to show the person: a one-row sparkline, a list of labelled bars, or a multi-row trend.", |
| 934 | "required": ["kind", "label"], |
| 935 | "properties": { |
| 936 | "kind": { "enum": ["sparkline", "bars", "trend"] }, |
| 937 | "label": { "type": "string", "maxLength": 120 }, |
| 938 | "unit": { "type": "string", "maxLength": 120, "description": "Shown after each number, e.g. ms, tokens, %." }, |
| 939 | "values": { "type": "array", "items": { "type": "number" }, "maxItems": 1024, "description": "Oldest first. For sparkline and trend." }, |
| 940 | "items": { |
| 941 | "type": "array", |
| 942 | "maxItems": 24, |
| 943 | "description": "For bars.", |
| 944 | "items": { |
| 945 | "type": "object", |
| 946 | "required": ["label", "value"], |
| 947 | "properties": { "label": { "type": "string", "maxLength": 120 }, "value": { "type": "number" } }, |
| 948 | "additionalProperties": false |
| 949 | } |
| 950 | }, |
| 951 | "rows": { "type": "integer", "minimum": 3, "maximum": 16, "description": "Trend height including its caption." } |
| 952 | } |
| 953 | }"#; |
| 954 | |
| 955 | impl DataDisplay { |
| 956 | /// Parse and [`validate`](Self::validate) an agent's JSON. |
| 957 | pub fn from_json(json: &str) -> Result<Self, DataDisplayError> { |
| 958 | let shown: Self = |
| 959 | serde_json::from_str(json).map_err(|e| DataDisplayError::Parse(e.to_string()))?; |
| 960 | shown.validate()?; |
| 961 | Ok(shown) |
| 962 | } |
| 963 | |
| 964 | /// Refuse what the displays cannot show honestly: non-finite numbers, |
| 965 | /// more points or bars than the limits, overlong labels, a trend's rows |
| 966 | /// outside [`DATA_TREND_ROWS`]. |
| 967 | pub fn validate(&self) -> Result<(), DataDisplayError> { |
| 968 | let label_ok = |s: &str| { |
| 969 | let chars = s.chars().count(); |
| 970 | if chars > DATA_MAX_LABEL { |
| 971 | Err(DataDisplayError::LabelTooLong { chars }) |
| 972 | } else { |
| 973 | Ok(()) |
| 974 | } |
| 975 | }; |
| 976 | let finite = |values: &mut dyn Iterator<Item = f64>| { |
| 977 | values |
| 978 | .enumerate() |
| 979 | .find(|(_, v)| !v.is_finite()) |
| 980 | .map_or(Ok(()), |(index, _)| { |
| 981 | Err(DataDisplayError::NotFinite { index }) |
| 982 | }) |
| 983 | }; |
| 984 | match self { |
| 985 | Self::Sparkline { |
| 986 | label, |
| 987 | unit, |
| 988 | values, |
| 989 | } |
| 990 | | Self::Trend { |
| 991 | label, |
| 992 | unit, |
| 993 | values, |
| 994 | .. |
| 995 | } => { |
| 996 | label_ok(label)?; |
| 997 | label_ok(unit)?; |
| 998 | if values.len() > DATA_MAX_POINTS { |
| 999 | return Err(DataDisplayError::TooManyPoints { |
| 1000 | count: values.len(), |
| 1001 | }); |
| 1002 | } |
| 1003 | finite(&mut values.iter().copied())?; |
| 1004 | if let Self::Trend { |
| 1005 | rows: Some(rows), .. |
| 1006 | } = self |
| 1007 | && !DATA_TREND_ROWS.contains(rows) |
| 1008 | { |
| 1009 | return Err(DataDisplayError::Rows { rows: *rows }); |
| 1010 | } |
| 1011 | Ok(()) |
| 1012 | } |
| 1013 | Self::Bars { label, unit, items } => { |
| 1014 | label_ok(label)?; |
| 1015 | label_ok(unit)?; |
| 1016 | if items.len() > DATA_MAX_BARS { |
| 1017 | return Err(DataDisplayError::TooManyBars { count: items.len() }); |
| 1018 | } |
| 1019 | for item in items { |
| 1020 | label_ok(&item.label)?; |
| 1021 | } |
| 1022 | finite(&mut items.iter().map(|i| i.value)) |
| 1023 | } |
| 1024 | } |
| 1025 | } |
| 1026 | |
| 1027 | #[must_use] |
| 1028 | pub fn label(&self) -> &str { |
| 1029 | match self { |
| 1030 | Self::Sparkline { label, .. } |
| 1031 | | Self::Bars { label, .. } |
| 1032 | | Self::Trend { label, .. } => label, |
| 1033 | } |
| 1034 | } |
| 1035 | |
| 1036 | /// The same facts as plain text: `Latency: now 42 ms, min 3 ms, max 57 |
| 1037 | /// ms (24 points)`. |
| 1038 | #[must_use] |
| 1039 | pub fn describe(&self, words: &DataWords) -> String { |
| 1040 | let label = text::display_safe(self.label()); |
| 1041 | match self { |
| 1042 | Self::Sparkline { unit, values, .. } | Self::Trend { unit, values, .. } => { |
| 1043 | let (Some((lo, hi)), Some(last)) = |
| 1044 | (bounds(values), values.iter().rev().find(|v| v.is_finite())) |
| 1045 | else { |
| 1046 | return format!("{label}: {}", words.empty); |
| 1047 | }; |
| 1048 | format!( |
| 1049 | "{label}: {} {}, {} {}, {} {} ({} {})", |
| 1050 | words.now, |
| 1051 | with_unit(*last, unit), |
| 1052 | words.min, |
| 1053 | with_unit(lo, unit), |
| 1054 | words.max, |
| 1055 | with_unit(hi, unit), |
| 1056 | values.len(), |
| 1057 | words.points, |
| 1058 | ) |
| 1059 | } |
| 1060 | Self::Bars { unit, items, .. } => { |
| 1061 | if items.is_empty() { |
| 1062 | return format!("{label}: {}", words.empty); |
| 1063 | } |
| 1064 | let rows: Vec<String> = items |
| 1065 | .iter() |
| 1066 | .map(|i| { |
| 1067 | format!( |
| 1068 | "{} {}", |
| 1069 | text::display_safe(&i.label), |
| 1070 | with_unit(i.value, unit) |
| 1071 | ) |
| 1072 | }) |
| 1073 | .collect(); |
| 1074 | format!("{label}: {}", rows.join(", ")) |
| 1075 | } |
| 1076 | } |
| 1077 | } |
| 1078 | |
| 1079 | /// A paintable view, fully drawn. |
| 1080 | #[must_use] |
| 1081 | pub fn view(&self) -> DataDisplayView<'_> { |
| 1082 | DataDisplayView { |
| 1083 | display: self, |
| 1084 | drawn: 1.0, |
| 1085 | previous: Vec::new(), |
| 1086 | words: DataWords::default(), |
| 1087 | area_fill: false, |
| 1088 | } |
| 1089 | } |
| 1090 | } |
| 1091 | |
| 1092 | /// A [`DataDisplay`] ready to paint, with its draw-in progress. |
| 1093 | #[derive(Clone, Debug)] |
| 1094 | pub struct DataDisplayView<'a> { |
| 1095 | pub display: &'a DataDisplay, |
| 1096 | pub drawn: f32, |
| 1097 | previous: Vec<f64>, |
| 1098 | pub words: DataWords, |
| 1099 | area_fill: bool, |
| 1100 | } |
| 1101 | |
| 1102 | impl DataDisplayView<'_> { |
| 1103 | #[must_use] |
| 1104 | pub fn drawn(mut self, drawn: f32) -> Self { |
| 1105 | self.drawn = unit_f(drawn); |
| 1106 | self |
| 1107 | } |
| 1108 | |
| 1109 | /// Bars grow from the value the same label had in `before`. |
| 1110 | #[must_use] |
| 1111 | pub fn from(mut self, before: &DataDisplay) -> Self { |
| 1112 | if let (DataDisplay::Bars { items, .. }, DataDisplay::Bars { items: old, .. }) = |
| 1113 | (self.display, before) |
| 1114 | { |
| 1115 | self.previous = items |
| 1116 | .iter() |
| 1117 | .map(|i| { |
| 1118 | old.iter() |
| 1119 | .find(|o| o.label == i.label) |
| 1120 | .map_or(0.0, |o| o.value) |
| 1121 | }) |
| 1122 | .collect(); |
| 1123 | } |
| 1124 | self |
| 1125 | } |
| 1126 | |
| 1127 | #[must_use] |
| 1128 | pub fn with_words(mut self, words: &DataWords) -> Self { |
| 1129 | self.words = words.clone(); |
| 1130 | self |
| 1131 | } |
| 1132 | |
| 1133 | /// Enable translucent OKLab gradient area fill for sparkline and trend |
| 1134 | /// displays on truecolor terminals. |
| 1135 | #[must_use] |
| 1136 | pub const fn area_fill(mut self, enabled: bool) -> Self { |
| 1137 | self.area_fill = enabled; |
| 1138 | self |
| 1139 | } |
| 1140 | } |
| 1141 | |
| 1142 | impl Paint for DataDisplayView<'_> { |
| 1143 | fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) { |
| 1144 | match self.display { |
| 1145 | DataDisplay::Sparkline { |
| 1146 | label, |
| 1147 | unit, |
| 1148 | values, |
| 1149 | } => DataSparkline::new(label.as_str(), values) |
| 1150 | .unit(unit.as_str()) |
| 1151 | .drawn(self.drawn) |
| 1152 | .with_words(&self.words) |
| 1153 | .area_fill(self.area_fill) |
| 1154 | .paint(area, buf, theme), |
| 1155 | DataDisplay::Bars { label, unit, items } => DataBars::new(label.as_str(), items) |
| 1156 | .unit(unit.as_str()) |
| 1157 | .previous(&self.previous) |
| 1158 | .drawn(self.drawn) |
| 1159 | .with_words(&self.words) |
| 1160 | .paint(area, buf, theme), |
| 1161 | DataDisplay::Trend { |
| 1162 | label, |
| 1163 | unit, |
| 1164 | values, |
| 1165 | rows, |
| 1166 | } => DataTrend::new(label.as_str(), values) |
| 1167 | .unit(unit.as_str()) |
| 1168 | .rows(rows.unwrap_or(6)) |
| 1169 | .drawn(self.drawn) |
| 1170 | .with_words(&self.words) |
| 1171 | .area_fill(self.area_fill) |
| 1172 | .paint(area, buf, theme), |
| 1173 | } |
| 1174 | } |
| 1175 | |
| 1176 | fn height(&self, width: u16, theme: &Theme) -> u16 { |
| 1177 | match self.display { |
| 1178 | DataDisplay::Sparkline { .. } => 1, |
| 1179 | DataDisplay::Bars { label, items, .. } => { |
| 1180 | DataBars::new(label.as_str(), items).height(width, theme) |
| 1181 | } |
| 1182 | DataDisplay::Trend { rows, .. } => rows.unwrap_or(6), |
| 1183 | } |
| 1184 | } |
| 1185 | } |
| 1186 | |
| 1187 | #[cfg(test)] |
| 1188 | mod tests { |
| 1189 | use super::*; |
| 1190 | use crate::testing; |
| 1191 | |
| 1192 | fn series() -> Vec<f64> { |
| 1193 | (0..48) |
| 1194 | .map(|i| 40.0 + 25.0 * (f64::from(i) / 5.0).sin() + f64::from(i % 7)) |
| 1195 | .collect() |
| 1196 | } |
| 1197 | |
| 1198 | fn bars() -> Vec<DataBarItem> { |
| 1199 | vec![ |
| 1200 | DataBarItem::new("opus", 12_400.0), |
| 1201 | DataBarItem::new("sonnet", 7_900.0), |
| 1202 | DataBarItem::new("haiku", 3_100.0), |
| 1203 | DataBarItem::new("cache", 0.0), |
| 1204 | ] |
| 1205 | } |
| 1206 | |
| 1207 | #[test] |
| 1208 | fn numbers_read_short() { |
| 1209 | assert_eq!(data_number(42.0), "42"); |
| 1210 | assert_eq!(data_number(1.23456), "1.23"); |
| 1211 | assert_eq!(data_number(12_400.0), "12.4k"); |
| 1212 | assert_eq!(data_number(1_250_000.0), "1.25M"); |
| 1213 | assert_eq!(data_number(-0.0), "0"); |
| 1214 | assert_eq!(data_number(f64::NAN), "?"); |
| 1215 | assert_eq!(data_number(-0.001), "-0.001"); |
| 1216 | assert_eq!(data_number(0.0042), "0.0042"); |
| 1217 | assert_eq!(data_number(0.014), "0.014"); |
| 1218 | assert_eq!(data_number(0.000_000_42), "4.2e-7"); |
| 1219 | assert_eq!(data_number(9_999.6), "10k"); |
| 1220 | assert_eq!(data_number(999_950.0), "1M"); |
| 1221 | assert_eq!(data_number(-999_999_999.0), "-1B"); |
| 1222 | assert_eq!(data_number(2.5e12), "2.5T"); |
| 1223 | assert_eq!(data_number(3e18), "3e18"); |
| 1224 | assert_eq!(with_unit(87.0, "%"), "87%"); |
| 1225 | assert_eq!(with_unit(87.0, "ms"), "87 ms"); |
| 1226 | } |
| 1227 | |
| 1228 | #[test] |
| 1229 | fn every_display_keeps_the_rules() { |
| 1230 | let values = series(); |
| 1231 | let items = bars(); |
| 1232 | for drawn in [0.0, 0.4, 1.0] { |
| 1233 | testing::assert_rules(1, |a, b, t| { |
| 1234 | DataSparkline::new("Requests", &values) |
| 1235 | .unit("rpm") |
| 1236 | .drawn(drawn) |
| 1237 | .paint(a, b, t); |
| 1238 | }); |
| 1239 | testing::assert_rules(5, |a, b, t| { |
| 1240 | DataBars::new("Tokens by model", &items) |
| 1241 | .drawn(drawn) |
| 1242 | .paint(a, b, t); |
| 1243 | }); |
| 1244 | testing::assert_rules(6, |a, b, t| { |
| 1245 | DataTrend::new("Latency", &values) |
| 1246 | .unit("ms") |
| 1247 | .drawn(drawn) |
| 1248 | .paint(a, b, t); |
| 1249 | }); |
| 1250 | } |
| 1251 | } |
| 1252 | |
| 1253 | #[test] |
| 1254 | fn the_words_carry_every_value_before_anything_is_drawn() { |
| 1255 | let values = series(); |
| 1256 | let items = bars(); |
| 1257 | for frame in testing::frames(1, |a, b, t| { |
| 1258 | DataSparkline::new("Requests", &values) |
| 1259 | .drawn(0.0) |
| 1260 | .paint(a, b, t); |
| 1261 | }) { |
| 1262 | assert!( |
| 1263 | frame |
| 1264 | .text() |
| 1265 | .contains(&format!("now {}", data_number(values[47]))) |
| 1266 | ); |
| 1267 | } |
| 1268 | for frame in testing::frames(5, |a, b, t| { |
| 1269 | DataBars::new("Tokens", &items).drawn(0.0).paint(a, b, t); |
| 1270 | }) { |
| 1271 | let text = frame.text(); |
| 1272 | assert!(text.contains("12.4k") && text.contains("3100"), "{text}"); |
| 1273 | assert!(!text.contains(FULL) && !text.contains('#'), "{text}"); |
| 1274 | } |
| 1275 | } |
| 1276 | |
| 1277 | #[test] |
| 1278 | fn bars_reach_their_value_and_scale_to_the_largest() { |
| 1279 | let items = bars(); |
| 1280 | let frames = testing::frames(5, |a, b, t| { |
| 1281 | DataBars::new("", &items).paint(a, b, t); |
| 1282 | }); |
| 1283 | let text = frames[0].text(); |
| 1284 | let lines: Vec<&str> = text.lines().collect(); |
| 1285 | let full = |l: &str| l.matches(FULL).count(); |
| 1286 | assert!(full(lines[0]) > full(lines[1]) && full(lines[1]) > full(lines[2])); |
| 1287 | assert_eq!(full(lines[3]), 0); |
| 1288 | } |
| 1289 | |
| 1290 | #[test] |
| 1291 | fn bars_glide_from_their_previous_values() { |
| 1292 | let items = vec![DataBarItem::new("a", 10.0)]; |
| 1293 | let previous = [5.0]; |
| 1294 | let at = |drawn: f32| { |
| 1295 | let buf = testing::render(40, 1, |area, buf| { |
| 1296 | DataBars::new("", &items) |
| 1297 | .previous(&previous) |
| 1298 | .drawn(drawn) |
| 1299 | .paint(area, buf, &testing::Profile::DarkTrue.theme()); |
| 1300 | }); |
| 1301 | testing::text(&buf).matches(FULL).count() |
| 1302 | }; |
| 1303 | assert!(at(0.0) > 0); |
| 1304 | assert!(at(0.0) < at(1.0)); |
| 1305 | } |
| 1306 | |
| 1307 | #[test] |
| 1308 | fn the_trend_draws_in_from_the_left_with_a_pen() { |
| 1309 | let values = series(); |
| 1310 | let theme = testing::Profile::DarkTrue.theme(); |
| 1311 | let dots = |drawn: f32| { |
| 1312 | let buf = testing::render(60, 6, |area, buf| { |
| 1313 | DataTrend::new("Latency", &values) |
| 1314 | .drawn(drawn) |
| 1315 | .paint(area, buf, &theme); |
| 1316 | }); |
| 1317 | testing::text(&buf) |
| 1318 | .chars() |
| 1319 | .filter(|c| ('\u{2801}'..='\u{28FF}').contains(c)) |
| 1320 | .count() |
| 1321 | }; |
| 1322 | assert_eq!(dots(0.0), 0); |
| 1323 | assert!(dots(0.5) > 0 && dots(0.5) < dots(1.0)); |
| 1324 | } |
| 1325 | |
| 1326 | #[test] |
| 1327 | fn a_dense_trend_still_reaches_its_extremes() { |
| 1328 | let mut values = vec![10.0; 1000]; |
| 1329 | values[333] = 90.0; |
| 1330 | values[700] = 1.0; |
| 1331 | let buf = testing::render(40, 6, |area, buf| { |
| 1332 | DataTrend::new("", &values).paint(area, buf, &testing::Profile::DarkTrue.theme()); |
| 1333 | }); |
| 1334 | let text = testing::text(&buf); |
| 1335 | let dots = |line: &str| { |
| 1336 | line.chars() |
| 1337 | .filter(|c| ('\u{2801}'..='\u{28FF}').contains(c)) |
| 1338 | .count() |
| 1339 | }; |
| 1340 | let lines: Vec<&str> = text.lines().collect(); |
| 1341 | assert!(dots(lines[1]) > 0, "the spike to max is drawn:\n{text}"); |
| 1342 | assert!(dots(lines[5]) > 0, "the dip to min is drawn:\n{text}"); |
| 1343 | } |
| 1344 | |
| 1345 | #[test] |
| 1346 | fn a_small_bar_is_not_drawn_as_zero_and_a_narrow_row_keeps_its_value() { |
| 1347 | let items = vec![ |
| 1348 | DataBarItem::new("cached", 61_000.0), |
| 1349 | DataBarItem::new("wrote", 4.0), |
| 1350 | DataBarItem::new("none", 0.0), |
| 1351 | ]; |
| 1352 | let theme = testing::Profile::DarkTrue.theme(); |
| 1353 | let buf = testing::render(40, 3, |area, buf| { |
| 1354 | DataBars::new("", &items).paint(area, buf, &theme); |
| 1355 | }); |
| 1356 | let text = testing::text(&buf); |
| 1357 | let lines: Vec<&str> = text.lines().collect(); |
| 1358 | assert!(lines[1].contains(EIGHTHS[1]), "{text}"); |
| 1359 | assert!(!lines[2].contains(EIGHTHS[1]) && !lines[2].contains(FULL)); |
| 1360 | |
| 1361 | let long = vec![DataBarItem::new("a long label", 12_400.0)]; |
| 1362 | let buf = testing::render(12, 1, |area, buf| { |
| 1363 | DataBars::new("", &long) |
| 1364 | .unit("tokens") |
| 1365 | .paint(area, buf, &theme); |
| 1366 | }); |
| 1367 | assert!(testing::text(&buf).contains("12.4k tokens")); |
| 1368 | } |
| 1369 | |
| 1370 | #[test] |
| 1371 | fn a_tiny_trend_falls_back_to_a_sparkline() { |
| 1372 | let values = series(); |
| 1373 | let buf = testing::render(40, 1, |area, buf| { |
| 1374 | DataTrend::new("Latency", &values).paint( |
| 1375 | area, |
| 1376 | buf, |
| 1377 | &testing::Profile::DarkTrue.theme(), |
| 1378 | ); |
| 1379 | }); |
| 1380 | assert!(testing::text(&buf).contains(SPARK[7]) || testing::text(&buf).contains("now")); |
| 1381 | } |
| 1382 | |
| 1383 | #[test] |
| 1384 | fn empty_displays_say_so() { |
| 1385 | let buf = testing::render(40, 2, |area, buf| { |
| 1386 | DataBars::new("Tokens", &[]).paint(area, buf, &testing::Profile::DarkTrue.theme()); |
| 1387 | }); |
| 1388 | assert!(testing::text(&buf).contains("no data yet")); |
| 1389 | let buf = testing::render(40, 6, |area, buf| { |
| 1390 | DataTrend::new("Latency", &[]).paint(area, buf, &testing::Profile::DarkTrue.theme()); |
| 1391 | }); |
| 1392 | assert!(testing::text(&buf).contains("no data yet")); |
| 1393 | } |
| 1394 | |
| 1395 | #[test] |
| 1396 | fn agent_json_is_validated_before_paint() { |
| 1397 | let ok = DataDisplay::from_json( |
| 1398 | r#"{"kind":"trend","label":"Latency","unit":"ms","values":[3,9,4],"rows":5}"#, |
| 1399 | ) |
| 1400 | .unwrap(); |
| 1401 | assert_eq!( |
| 1402 | ok.describe(&DataWords::default()), |
| 1403 | "Latency: now 4 ms, min 3 ms, max 9 ms (3 points)" |
| 1404 | ); |
| 1405 | assert_eq!(ok.view().height(80, &testing::Profile::DarkTrue.theme()), 5); |
| 1406 | |
| 1407 | let refused = |json: &str| DataDisplay::from_json(json).unwrap_err(); |
| 1408 | assert!(matches!( |
| 1409 | refused(r#"{"kind":"pie","label":"x"}"#), |
| 1410 | DataDisplayError::Parse(_) |
| 1411 | )); |
| 1412 | assert_eq!( |
| 1413 | refused(r#"{"kind":"trend","label":"x","values":[1],"rows":40}"#), |
| 1414 | DataDisplayError::Rows { rows: 40 } |
| 1415 | ); |
| 1416 | let long = "x".repeat(DATA_MAX_LABEL + 1); |
| 1417 | assert_eq!( |
| 1418 | refused(&format!( |
| 1419 | r#"{{"kind":"sparkline","label":"{long}","values":[]}}"# |
| 1420 | )), |
| 1421 | DataDisplayError::LabelTooLong { |
| 1422 | chars: DATA_MAX_LABEL + 1 |
| 1423 | } |
| 1424 | ); |
| 1425 | let many = vec!["1"; DATA_MAX_POINTS + 1].join(","); |
| 1426 | assert_eq!( |
| 1427 | refused(&format!( |
| 1428 | r#"{{"kind":"sparkline","label":"x","values":[{many}]}}"# |
| 1429 | )), |
| 1430 | DataDisplayError::TooManyPoints { |
| 1431 | count: DATA_MAX_POINTS + 1 |
| 1432 | } |
| 1433 | ); |
| 1434 | let built = DataDisplay::Sparkline { |
| 1435 | label: "x".into(), |
| 1436 | unit: String::new(), |
| 1437 | values: vec![1.0, f64::INFINITY], |
| 1438 | }; |
| 1439 | assert_eq!( |
| 1440 | built.validate(), |
| 1441 | Err(DataDisplayError::NotFinite { index: 1 }) |
| 1442 | ); |
| 1443 | } |
| 1444 | |
| 1445 | #[test] |
| 1446 | fn the_schema_is_json_and_names_every_kind() { |
| 1447 | let schema: serde_json::Value = serde_json::from_str(DATA_DISPLAY_SCHEMA).unwrap(); |
| 1448 | let kinds = &schema["properties"]["kind"]["enum"]; |
| 1449 | for kind in ["sparkline", "bars", "trend"] { |
| 1450 | assert!(kinds.as_array().unwrap().iter().any(|k| k == kind)); |
| 1451 | } |
| 1452 | } |
| 1453 | |
| 1454 | #[test] |
| 1455 | fn bars_view_grows_from_the_same_label() { |
| 1456 | let before = DataDisplay::Bars { |
| 1457 | label: "t".into(), |
| 1458 | unit: String::new(), |
| 1459 | items: vec![DataBarItem::new("b", 8.0), DataBarItem::new("a", 2.0)], |
| 1460 | }; |
| 1461 | let after = DataDisplay::Bars { |
| 1462 | label: "t".into(), |
| 1463 | unit: String::new(), |
| 1464 | items: vec![DataBarItem::new("a", 4.0), DataBarItem::new("c", 1.0)], |
| 1465 | }; |
| 1466 | assert_eq!(after.view().from(&before).previous, vec![2.0, 0.0]); |
| 1467 | } |
| 1468 | |
| 1469 | #[test] |
| 1470 | fn snapshot() { |
| 1471 | let values = series(); |
| 1472 | let items = bars(); |
| 1473 | insta::assert_snapshot!( |
| 1474 | "data-displays", |
| 1475 | testing::snapshot(12, |area, buf, theme| { |
| 1476 | let row = |y: u16, h: u16| { |
| 1477 | Rect::new(area.x, area.y + y, area.width, h).intersection(area) |
| 1478 | }; |
| 1479 | DataSparkline::new("Requests", &values) |
| 1480 | .unit("rpm") |
| 1481 | .paint(row(0, 1), buf, theme); |
| 1482 | DataBars::new("Tokens by model", &items) |
| 1483 | .unit("tokens") |
| 1484 | .paint(row(2, 5), buf, theme); |
| 1485 | DataTrend::new("Latency", &values) |
| 1486 | .unit("ms") |
| 1487 | .rows(5) |
| 1488 | .paint(row(7, 5), buf, theme); |
| 1489 | }) |
| 1490 | ); |
| 1491 | } |
| 1492 | } |
| 1493 |