rs-rich-ext 0.0.21

Extensions for the `rich` Rust port: diagnostics, structured data, clap and tracing integration, diffs, workflow renderables and a plugin registry
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//! A labelled grid of values drawn as shades.

use rich::measure::Measurement;
use rich::{Console, ConsoleOptions, Renderable, Segment, Style};

use super::{
    Charset, Line, Scale, ValueFormat, cell_units, cells, entries_width, has_colour,
    lines_to_segments, theme_style, truncate, wrap_entries,
};

/// Levels for blocks, lowest first.
const SHADES: [char; 5] = [' ', '░', '▒', '▓', '█'];
/// Levels for ASCII, lowest first.
const ASCII_SHADES: [char; 10] = [' ', '.', ':', '-', '=', '+', '*', '#', '%', '@'];
/// How many `chart.heat.N` styles there are.
const HEAT_STYLES: usize = 5;

/// A grid of values, one row per label and one column per header, each
/// cell a shade from lowest to highest.
///
/// - Values are scaled from the smallest to the largest (or
///   [`range`](Self::range)) into equal steps: five in blocks (` ░▒▓█`), ten
///   in ASCII (` .:-=+*#%@`). The shade is the value, so the grid reads in
///   black and white; with colour each step also takes a `chart.heat.N`
///   style, cold to hot.
/// - A NaN or infinite value is drawn `·` (`?` in ASCII), so a missing
///   value never passes for a low one.
/// - The legend under the grid shows the steps between the lowest and
///   highest value of the scale.
/// - Each cell is [`cell_width`](Self::cell_width) cells wide (2 by
///   default). Column headers are written at their column's first cell when
///   they fit, leaving a space after the one before, so with narrow cells
///   every second or third header shows.
/// - Given less width, the cells narrow to one cell, then the row labels
///   are cut, then neighbouring columns are merged (each shows the mean of
///   its finite values) so every value still counts.
///
/// ```
/// use rich::Console;
/// use rich_ext::chart::{Charset, Heatmap};
///
/// let console = Console::builder().width(40).color_system(None).build();
/// let map = Heatmap::new()
///     .columns(["mon", "tue", "wed", "thu"])
///     .row("api", [1.0, 4.0, 9.0, 2.0])
///     .row("web", [0.0, 6.0, 8.0, f64::NAN])
///     .cell_width(4)
///     .charset(Charset::Ascii);
/// assert_eq!(
///     console.render_export(&map),
///     concat!(
///         "    mon tue wed thu        \n",
///         "api ....====@@@@::::       \n",
///         "web     ****%%%%????       \n",
///         "0 [ .:-=+*#%@] 9  ? no data\n",
///     )
/// );
/// ```
#[derive(Clone, Debug, PartialEq)]
#[must_use = "builder methods return a new value; it does nothing until it is rendered or used"]
pub struct Heatmap {
    columns: Vec<String>,
    rows: Vec<(String, Vec<f64>)>,
    min: Option<f64>,
    max: Option<f64>,
    charset: Charset,
    cell_width: usize,
    legend: bool,
    format: ValueFormat,
}

impl Default for Heatmap {
    fn default() -> Self {
        Self::new()
    }
}

/// How a heatmap fits its width.
struct Grid {
    label: usize,
    cell: usize,
    /// For each drawn column, the range of data columns it stands for.
    buckets: Vec<(usize, usize)>,
}

impl Heatmap {
    /// An empty heatmap; add rows with [`row`](Self::row).
    pub fn new() -> Self {
        Heatmap {
            columns: Vec::new(),
            rows: Vec::new(),
            min: None,
            max: None,
            charset: Charset::Auto,
            cell_width: 2,
            legend: true,
            format: ValueFormat::Compact,
        }
    }

    /// The column headers.
    pub fn columns<S: Into<String>>(mut self, headers: impl IntoIterator<Item = S>) -> Self {
        self.columns = headers.into_iter().map(Into::into).collect();
        self
    }

    /// Add a row of values, in column order.
    pub fn row(mut self, label: impl Into<String>, values: impl IntoIterator<Item = f64>) -> Self {
        self.rows.push((label.into(), values.into_iter().collect()));
        self
    }

    /// Fix the scale; values outside it take the end shades.
    pub fn range(mut self, min: f64, max: f64) -> Self {
        self.min = Some(min);
        self.max = Some(max);
        self
    }

    /// Glyphs to draw with: [`Charset::Ascii`] asks for the ASCII shades;
    /// anything else draws blocks (ASCII on an ASCII-only console).
    pub fn charset(mut self, charset: Charset) -> Self {
        self.charset = charset;
        self
    }

    /// Cells per value (default 2, at least 1).
    pub fn cell_width(mut self, width: usize) -> Self {
        self.cell_width = width.max(1);
        self
    }

    /// Show the legend (default on).
    pub fn legend(mut self, show: bool) -> Self {
        self.legend = show;
        self
    }

    /// How the legend writes the bounds (default [`ValueFormat::Compact`]).
    pub fn format(mut self, format: ValueFormat) -> Self {
        self.format = format;
        self
    }

    /// The scale every value is shaded on.
    pub fn scale(&self) -> Scale {
        let values = self.rows.iter().flat_map(|(_, v)| v.iter().copied());
        Scale::from_values(values).bounds(self.min, self.max)
    }

    fn column_count(&self) -> usize {
        self.rows
            .iter()
            .map(|(_, v)| v.len())
            .max()
            .unwrap_or(0)
            .max(self.columns.len())
    }

    fn label_width(&self) -> usize {
        self.rows.iter().map(|(l, _)| cells(l)).max().unwrap_or(0)
    }

    fn has_missing(&self) -> bool {
        let n = self.column_count();
        self.rows
            .iter()
            .any(|(_, v)| v.len() < n || v.iter().any(|x| !x.is_finite()))
    }

    fn layout(&self, width: usize) -> Grid {
        let n = self.column_count();
        let l = self.label_width();
        let part = |l: usize| l + usize::from(l > 0);
        let each = |cell: usize| Grid {
            label: 0,
            cell,
            buckets: (0..n).map(|i| (i, i + 1)).collect(),
        };
        let room = width.saturating_sub(part(l));
        if room >= n {
            let cell = self.cell_width.min(room / n.max(1)).max(1);
            return Grid {
                label: l,
                ..each(cell)
            };
        }
        let keep = l.min(3);
        if let Some(label) = width.checked_sub(n + 1)
            && label >= keep
            && label > 0
        {
            return Grid {
                label: label.min(l),
                ..each(1)
            };
        }
        // Merge columns into as many as fit.
        let label = if width > part(keep) + 1 { keep } else { 0 };
        let slots = width.saturating_sub(part(label)).max(1);
        let buckets = (0..slots)
            .map(|i| {
                let start = i * n / slots;
                (start, ((i + 1) * n / slots).max(start + 1))
            })
            .collect();
        Grid {
            label,
            cell: 1,
            buckets,
        }
    }

    /// The step of `value` on `scale`, among `levels`.
    fn level(scale: &Scale, value: f64, levels: usize) -> Option<usize> {
        let n = scale.normalize(value)?;
        Some(((n * levels as f64).floor() as usize).min(levels - 1))
    }

    fn level_style(console: &Console, level: usize, levels: usize) -> Style {
        let key = format!("chart.heat.{}", level * HEAT_STYLES / levels + 1);
        theme_style(console, &key)
    }

    fn lines(&self, console: &Console, options: &ConsoleOptions) -> Vec<Line> {
        let width = options.max_width;
        let ascii = self.charset.resolve(console, options, Charset::Blocks) == Charset::Ascii;
        let colour = has_colour(console);
        if self.column_count() == 0 {
            let mut line = Line::new();
            line.push(&truncate("no data", width, ascii), None);
            return vec![line];
        }
        let shades: &[char] = if ascii { &ASCII_SHADES } else { &SHADES };
        let missing = if ascii { '?' } else { '·' };
        let levels = shades.len();
        let scale = self.scale();
        let grid = self.layout(width);
        let label_style = colour.then(|| theme_style(console, "chart.label"));
        let lead = if grid.label > 0 { grid.label + 1 } else { 0 };
        let mut out = Vec::new();

        // Headers at their column's first cell, where they fit.
        if self.columns.iter().any(|c| !c.is_empty()) {
            let plot = grid.buckets.len() * grid.cell;
            let mut row = vec![" ".to_string(); plot];
            let mut free = 0;
            for (i, (start, _)) in grid.buckets.iter().enumerate() {
                let Some(header) = self.columns.get(*start) else {
                    continue;
                };
                let header = truncate(header, usize::MAX, ascii);
                let at = i * grid.cell;
                let len = cells(&header);
                if at < free || at + len > plot || len == 0 {
                    continue;
                }
                for (k, unit) in cell_units(&header).into_iter().enumerate() {
                    row[at + k] = unit;
                }
                free = at + len + 1;
            }
            if row.iter().any(|c| c != " ") {
                let mut line = Line::new();
                line.pad(lead);
                line.push(&row.concat(), label_style.clone());
                out.push(line);
            }
        }

        for (label, values) in &self.rows {
            let mut line = Line::new();
            if grid.label > 0 {
                let text = truncate(label, grid.label, ascii);
                let pad = grid.label - cells(&text);
                line.push(&text, label_style.clone());
                line.pad(pad + 1);
            }
            for &(start, end) in &grid.buckets {
                let bucket: Vec<f64> = (start..end)
                    .filter_map(|i| values.get(i).copied())
                    .filter(|v| v.is_finite())
                    .collect();
                let value = if bucket.is_empty() {
                    f64::NAN
                } else {
                    bucket.iter().sum::<f64>() / bucket.len() as f64
                };
                let (glyph, style) = match Self::level(&scale, value, levels) {
                    Some(level) => (
                        shades[level],
                        colour.then(|| Self::level_style(console, level, levels)),
                    ),
                    None => (missing, None),
                };
                line.push(&glyph.to_string().repeat(grid.cell), style);
            }
            out.push(line);
        }
        if self.legend {
            out.extend(wrap_entries(
                self.legend_entries(console, ascii, colour),
                width,
            ));
        }
        out
    }

    fn legend_entries(
        &self,
        console: &Console,
        ascii: bool,
        colour: bool,
    ) -> Vec<Vec<(String, Option<Style>)>> {
        let shades: &[char] = if ascii { &ASCII_SHADES } else { &SHADES };
        let scale = self.scale();
        let label_style = colour.then(|| theme_style(console, "chart.label"));
        let mut ramp = vec![(
            format!("{} [", self.format.format(scale.min())),
            label_style.clone(),
        )];
        for (level, c) in shades.iter().enumerate() {
            let style = colour.then(|| Self::level_style(console, level, shades.len()));
            ramp.push((c.to_string(), style));
        }
        ramp.push((
            format!("] {}", self.format.format(scale.max())),
            label_style.clone(),
        ));
        let mut entries = vec![ramp];
        if self.has_missing() {
            let missing = if ascii { "?" } else { "·" };
            entries.push(vec![(format!("{missing} no data"), label_style)]);
        }
        entries
    }
}

impl crate::surface::Draw for Heatmap {
    fn draw(
        &self,
        console: &Console,
        options: &ConsoleOptions,
        screen: &mut crate::surface::Screen,
        rect: crate::surface::Rect,
    ) {
        super::draw_lines(
            self.lines(console, options),
            options.max_width,
            options,
            screen,
            rect,
        );
    }
}

impl Renderable for Heatmap {
    fn rich_render(&self, console: &Console, options: &ConsoleOptions) -> Vec<Segment> {
        lines_to_segments(self.lines(console, options), options.max_width)
    }

    fn measure(&self, console: &Console, options: &ConsoleOptions) -> Measurement {
        let n = self.column_count();
        if n == 0 {
            return Measurement::new(7, 7).with_maximum(options.max_width);
        }
        let ascii = self.charset.resolve(console, options, Charset::Blocks) == Charset::Ascii;
        let l = self.label_width();
        let grid = (l + usize::from(l > 0)).saturating_add(n.saturating_mul(self.cell_width));
        let legend = if self.legend {
            entries_width(&self.legend_entries(console, ascii, false))
        } else {
            0
        };
        let max = grid.max(legend);
        Measurement::new(n.min(max), max)
            .with_maximum(options.max_width)
            .normalize()
    }
}

/// `Heatmap, 2 rows by 4 columns, values from 0 to 9, 1 missing`, then
/// where the highest and lowest values are (`Highest 9 at api, wed; lowest
/// 0 at web, mon`).
impl crate::a11y::AccessibleText for Heatmap {
    fn accessible_text(&self, _width: usize) -> String {
        use super::describe::{count, counted, range};
        let columns = self.column_count();
        if self.rows.is_empty() || columns == 0 {
            return "Heatmap, no values".to_string();
        }
        let mut head = format!(
            "Heatmap, {} by {}",
            counted(self.rows.len(), "row", "rows"),
            counted(columns, "column", "columns")
        );
        // Every cell, a short row's missing ones included.
        let cells: Vec<(&str, usize, f64)> = self
            .rows
            .iter()
            .flat_map(|(label, values)| {
                (0..columns).map(move |c| {
                    let value = values.get(c).copied().unwrap_or(f64::NAN);
                    (label.as_str(), c, value)
                })
            })
            .collect();
        let finite: Vec<&(&str, usize, f64)> = cells.iter().filter(|c| c.2.is_finite()).collect();
        let missing = cells.len() - finite.len();
        if let Some((lo, hi)) = super::describe::extent(finite.iter().map(|c| c.2)) {
            head.push_str(&format!(", values {}", range(lo, hi, self.format)));
        }
        if missing > 0 {
            head.push_str(&format!(", {} missing", count(missing)));
        }
        let header = |c: usize| {
            self.columns
                .get(c)
                .filter(|h| !h.is_empty())
                .cloned()
                .unwrap_or_else(|| format!("column {}", c + 1))
        };
        let at = |cell: &(&str, usize, f64)| {
            let row = if cell.0.is_empty() {
                String::new()
            } else {
                format!("{}, ", cell.0)
            };
            format!("{} at {row}{}", self.format.format(cell.2), header(cell.1))
        };
        // The first highest and the first lowest, in reading order.
        let mut highest: Option<&(&str, usize, f64)> = None;
        let mut lowest: Option<&(&str, usize, f64)> = None;
        for &cell in &finite {
            if highest.is_none_or(|h| cell.2 > h.2) {
                highest = Some(cell);
            }
            if lowest.is_none_or(|l| cell.2 < l.2) {
                lowest = Some(cell);
            }
        }
        let mut out = vec![head];
        if let (Some(hi), Some(lo)) = (highest, lowest) {
            out.push(format!("Highest {}; lowest {}", at(hi), at(lo)));
        }
        out.join("\n")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::a11y::AccessibleText;

    #[test]
    fn accessible_text_finds_the_extremes() {
        let map = Heatmap::new()
            .columns(["mon", "tue", "wed", "thu"])
            .row("api", [1.0, 4.0, 9.0, 2.0])
            .row("web", [0.0, 6.0, 8.0, f64::NAN]);
        assert_eq!(
            map.accessible_text(80),
            "Heatmap, 2 rows by 4 columns, values from 0 to 9, 1 missing\n\
             Highest 9 at api, wed; lowest 0 at web, mon"
        );
        let short = Heatmap::new().row("", [3.0, 3.0]);
        assert_eq!(
            short.accessible_text(80),
            "Heatmap, 1 row by 2 columns, values at 3\n\
             Highest 3 at column 1; lowest 3 at column 1"
        );
        assert_eq!(Heatmap::new().accessible_text(80), "Heatmap, no values");
    }
}