Skip to main content

schedr_ui/
chart.rs

1//! Charts drawn by the server as SVG (decision 466): bars (a task's attempts, decision 467), lines over time, an "others" band, dashed
2//! limits, axes, and a hover strip per point whose `<title>` gives every value there. No
3//! JavaScript; the colours are the stylesheet's series tokens (`--series-1` to `--series-8`),
4//! light and dark.
5
6use std::fmt::Write as _;
7
8use jiff::Timestamp;
9use jiff::tz::TimeZone;
10
11/// A chart's drawing width (the SVG scales to its box).
12pub const WIDTH: f64 = 720.0;
13/// A chart's in a panel: its text stays the same size.
14pub const NARROW: f64 = 420.0;
15/// Its drawing height.
16pub const HEIGHT: f64 = 220.0;
17/// Room left of the plot (the y labels).
18const LEFT: f64 = 64.0;
19/// Room right of it.
20const RIGHT: f64 = 12.0;
21/// Room above it.
22const TOP: f64 = 10.0;
23/// Room below it (the x labels).
24const BOTTOM: f64 = 24.0;
25/// The series a chart draws at most; the rest go into the band (decision 465).
26pub const SERIES: usize = 8;
27
28/// What the values are.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum Unit {
31    /// Bytes, shown as KiB, MiB, GiB.
32    Bytes,
33    /// CPU cores.
34    Cores,
35    /// A count of things (attempts), whole numbers.
36    Count,
37    /// Milliseconds, shown as ms below a second, then seconds.
38    Millis,
39}
40
41impl Unit {
42    /// `value` as people read it.
43    #[must_use]
44    pub fn show(self, value: f64) -> String {
45        match self {
46            Self::Bytes => bytes(value),
47            Self::Cores => format!("{value:.2} cores"),
48            Self::Count => format!("{value:.0}"),
49            Self::Millis => millis(value),
50        }
51    }
52}
53
54/// `n` bytes as people read it: `512 B`, `1.5 KiB`, `20.0 MiB`.
55#[must_use]
56pub fn bytes(n: f64) -> String {
57    const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
58    let mut value = n.max(0.0);
59    let mut unit = 0;
60    while value >= 1024.0 && unit < UNITS.len() - 1 {
61        value /= 1024.0;
62        unit += 1;
63    }
64    if unit == 0 {
65        format!("{value:.0} B")
66    } else {
67        format!("{value:.1} {}", UNITS[unit])
68    }
69}
70
71/// `ms` milliseconds as people read it: `850 ms`, `1.2 s`.
72#[must_use]
73pub fn millis(ms: f64) -> String {
74    let ms = ms.max(0.0);
75    if ms < 1000.0 {
76        format!("{ms:.0} ms")
77    } else {
78        format!("{:.1} s", ms / 1000.0)
79    }
80}
81
82/// One line: a label, its colour slot (1 to 8), and its points (seconds, value), oldest first.
83#[derive(Debug, Clone, PartialEq)]
84pub struct Line {
85    /// What it is.
86    pub label: String,
87    /// Its colour, `--series-<slot>`.
88    pub slot: usize,
89    /// Its points.
90    pub points: Vec<(i64, f64)>,
91}
92
93/// A band: its label, and each point's time, lowest and highest.
94pub type Band = (String, Vec<(i64, f64, f64)>);
95
96/// A chart's content.
97#[derive(Debug, Clone, PartialEq)]
98pub struct Spec {
99    /// What it shows, for screen readers.
100    pub title: String,
101    /// What the values are.
102    pub unit: Unit,
103    /// Its drawing width: [`WIDTH`], or [`NARROW`] in a panel.
104    pub width: f64,
105    /// Its start and end, in seconds.
106    pub from: i64,
107    /// Its end.
108    pub to: i64,
109    /// A point's width, in seconds: points further apart leave a gap.
110    pub step: i64,
111    /// The lines, at most [`SERIES`].
112    pub lines: Vec<Line>,
113    /// Layers stacked on each other, the first at the bottom (memory by kind); a layer
114    /// without a point at a time counts 0 there.
115    pub stacked: Vec<Line>,
116    /// The stacked layers as a bar per point, across its step, instead of areas: counts in
117    /// buckets (attempts ended), which an area would draw as spikes between empty buckets.
118    pub bars: bool,
119    /// The rest as one band, if any.
120    pub band: Option<Band>,
121    /// Dashed limits: a label, the slot of the line it belongs to, the value.
122    pub limits: Vec<(String, usize, f64)>,
123    /// The axis's zone.
124    pub zone: TimeZone,
125}
126
127/// `text` safe in SVG text and attributes.
128fn escape(text: &str) -> String {
129    let mut out = String::with_capacity(text.len());
130    for c in text.chars() {
131        match c {
132            '&' => out.push_str("&amp;"),
133            '<' => out.push_str("&lt;"),
134            '>' => out.push_str("&gt;"),
135            '"' => out.push_str("&quot;"),
136            '\'' => out.push_str("&#39;"),
137            c => out.push(c),
138        }
139    }
140    out
141}
142
143/// A round step for about `ticks` ticks up to `max`: 1, 2 or 5 times a power of `base`'s
144/// unit. Returns the step.
145fn nice_step(max: f64, ticks: f64) -> f64 {
146    let raw = (max / ticks).max(f64::MIN_POSITIVE);
147    let power = 10_f64.powf(raw.log10().floor());
148    let fraction = raw / power;
149    let nice = if fraction <= 1.0 {
150        1.0
151    } else if fraction <= 2.0 {
152        2.0
153    } else if fraction <= 5.0 {
154        5.0
155    } else {
156        10.0
157    };
158    nice * power
159}
160
161/// The y axis's top and ticks for values up to `max` in `unit`.
162fn y_axis(max: f64, unit: Unit) -> (f64, Vec<f64>) {
163    // Whole ticks for whole things: no 0.2 of an attempt or of a millisecond.
164    let whole = unit == Unit::Count || (unit == Unit::Millis && max < 1000.0);
165    let (scale, max) = match unit {
166        // Ticks in the unit the top is shown in: 512 MiB, 1 GiB, 1.5 GiB.
167        Unit::Bytes => {
168            let mut scale = 1.0;
169            while max / scale >= 1024.0 {
170                scale *= 1024.0;
171            }
172            (scale, max / scale)
173        }
174        // Ticks in seconds from a second up: 0.5 s, 1 s, 1.5 s.
175        Unit::Millis if max >= 1000.0 => (1000.0, max / 1000.0),
176        Unit::Cores | Unit::Count | Unit::Millis => (1.0, max),
177    };
178    let max = if max > 0.0 { max } else { 1.0 };
179    let step = nice_step(max, 4.0);
180    let step = if whole { step.max(1.0) } else { step };
181    let top = (max / step).ceil() * step;
182    #[expect(
183        clippy::cast_possible_truncation,
184        clippy::cast_sign_loss,
185        reason = "a handful of ticks"
186    )]
187    let count = (top / step).round() as usize;
188    let ticks = (0..=count)
189        .map(|i| {
190            #[expect(clippy::cast_precision_loss, reason = "a handful of ticks")]
191            let i = i as f64;
192            i * step * scale
193        })
194        .collect();
195    (top * scale, ticks)
196}
197
198/// The x axis's ticks for `from..to` seconds: a round interval for the span.
199fn x_ticks(from: i64, to: i64) -> (i64, &'static str) {
200    let span = to - from;
201    if span <= 2 * 3600 {
202        (600, "%H:%M")
203    } else if span <= 2 * 86_400 {
204        (3 * 3600, "%H:%M")
205    } else if span <= 10 * 86_400 {
206        (86_400, "%b %d")
207    } else {
208        (5 * 86_400, "%b %d")
209    }
210}
211
212/// A chart drawn: its SVG.
213#[must_use]
214pub fn draw(spec: &Spec) -> String {
215    let plot_w = spec.width - LEFT - RIGHT;
216    let plot_h = HEIGHT - TOP - BOTTOM;
217    let span = (spec.to - spec.from).max(1);
218    #[expect(clippy::cast_precision_loss, reason = "screen coordinates")]
219    let x = |t: i64| LEFT + plot_w * ((t - spec.from) as f64 / span as f64);
220    let data_max = spec
221        .lines
222        .iter()
223        .flat_map(|l| l.points.iter().map(|p| p.1))
224        .chain(
225            spec.band
226                .iter()
227                .flat_map(|(_, points)| points.iter().map(|p| p.2)),
228        )
229        .chain(
230            stack(&spec.stacked)
231                .into_iter()
232                .filter_map(|(_, tops)| tops.last().copied()),
233        )
234        .fold(0.0_f64, f64::max);
235    // A limit far above the lines would flatten them: shown only within 4 times their top.
236    let limits: Vec<_> = spec
237        .limits
238        .iter()
239        .filter(|(_, _, value)| data_max == 0.0 || *value <= data_max * 4.0)
240        .collect();
241    let max = limits.iter().map(|l| l.2).fold(data_max, f64::max);
242    let (top, y_ticks) = y_axis(max, spec.unit);
243    let y = |v: f64| TOP + plot_h * (1.0 - v / top);
244
245    let mut svg = String::new();
246    let _ = write!(
247        svg,
248        r#"<svg class="chart" viewBox="0 0 {} {HEIGHT}" role="img" aria-label="{}">"#,
249        spec.width,
250        escape(&spec.title)
251    );
252    axes(&mut svg, spec, &y_ticks, &x, &y);
253    if let Some((label, points)) = &spec.band {
254        for run in runs(points, spec.step, |p| p.0) {
255            let d = area(
256                run.iter().map(|p| (x(p.0), y(p.2))),
257                run.iter().rev().map(|p| (x(p.0), y(p.1))),
258            );
259            let _ = write!(
260                svg,
261                r#"<path class="band" d="{d}Z"><title>{}</title></path>"#,
262                escape(label)
263            );
264        }
265    }
266    stacked_layers(&mut svg, spec, (&x, &y));
267    for (label, slot, value) in &limits {
268        let _ = write!(
269            svg,
270            r#"<line class="limit s{slot}" x1="{LEFT}" x2="{}" y1="{y:.1}" y2="{y:.1}"><title>{}: {}</title></line>"#,
271            spec.width - RIGHT,
272            escape(label),
273            escape(&spec.unit.show(*value)),
274            y = y(*value),
275        );
276    }
277    for line in &spec.lines {
278        for run in runs(&line.points, spec.step, |p| p.0) {
279            let d = path(run.iter().map(|p| (x(p.0), y(p.1))));
280            // A point alone: a dot, so it shows.
281            if run.len() == 1 {
282                let _ = write!(
283                    svg,
284                    r#"<circle class="dot s{}" cx="{:.1}" cy="{:.1}" r="3"></circle>"#,
285                    line.slot,
286                    x(run[0].0),
287                    y(run[0].1)
288                );
289            } else {
290                let _ = write!(svg, r#"<path class="line s{}" d="{d}"></path>"#, line.slot);
291            }
292        }
293    }
294    hover_strips(&mut svg, spec, &x, plot_h);
295    svg.push_str("</svg>");
296    svg
297}
298
299/// One bar: its value (none: not read, drawn as a gap with its label), its class (how it
300/// ended: `ok`, `failed`, `other`), whether it is marked (killed for its memory), where it
301/// links, and its hover text.
302#[derive(Debug, Clone, PartialEq)]
303pub struct Bar {
304    /// Its value; none when there is none (a gap).
305    pub value: Option<f64>,
306    /// Its colour class.
307    pub class: &'static str,
308    /// Marked with a cross above it.
309    pub marked: bool,
310    /// Where it links.
311    pub href: String,
312    /// Its hover text.
313    pub title: String,
314}
315
316/// A bar chart's content: bars side by side, oldest first, a dashed limit, a label under
317/// the first and the last.
318#[derive(Debug, Clone, PartialEq)]
319pub struct Bars {
320    /// What it shows, for screen readers.
321    pub title: String,
322    /// What the values are.
323    pub unit: Unit,
324    /// Its drawing width.
325    pub width: f64,
326    /// The bars.
327    pub bars: Vec<Bar>,
328    /// A dashed limit: its label and value.
329    pub limit: Option<(String, f64)>,
330    /// The labels under the first bar and the last.
331    pub ends: (String, String),
332}
333
334/// The stacked layers: areas, a lone point a bar; or all bars with [`Spec::bars`].
335fn stacked_layers(
336    svg: &mut String,
337    spec: &Spec,
338    (x, y): (&impl Fn(i64) -> f64, &impl Fn(f64) -> f64),
339) {
340    let layers = stack(&spec.stacked);
341    if spec.bars {
342        stacked_bars(svg, spec, &layers, (x, y));
343    } else {
344        // A point alone between gaps has no area: a bar, so it shows (as a line's dot).
345        let lone: Vec<(i64, Vec<f64>)> = runs(&layers, spec.step, |p| p.0)
346            .into_iter()
347            .filter(|run| run.len() == 1)
348            .flat_map(|run| run.iter().cloned())
349            .collect();
350        stacked_bars(svg, spec, &lone, (x, y));
351    }
352    for (layer, line) in spec.stacked.iter().enumerate().filter(|_| !spec.bars) {
353        for run in runs(&layers, spec.step, |p| p.0)
354            .into_iter()
355            .filter(|run| run.len() > 1)
356        {
357            let below = |p: &(i64, Vec<f64>)| if layer == 0 { 0.0 } else { p.1[layer - 1] };
358            let d = area(
359                run.iter().map(|p| (x(p.0), y(p.1[layer]))),
360                run.iter().rev().map(|p| (x(p.0), y(below(p)))),
361            );
362            let _ = write!(
363                svg,
364                r#"<path class="area s{}" d="{d}Z"><title>{}</title></path>"#,
365                line.slot,
366                escape(&line.label)
367            );
368        }
369    }
370}
371
372/// `layers` (the stacked tops at each point) as a bar per point across its step, a little
373/// narrower than it, each layer's part in its colour; an empty part isn't drawn.
374fn stacked_bars(
375    svg: &mut String,
376    spec: &Spec,
377    layers: &[(i64, Vec<f64>)],
378    (x, y): (&impl Fn(i64) -> f64, &impl Fn(f64) -> f64),
379) {
380    for (at, tops) in layers {
381        // The current bucket only up to the chart's end.
382        let left = x(*at);
383        let width = (x((at + spec.step).min(spec.to)) - left) * 0.8;
384        let left = left + width * 0.125;
385        for (layer, line) in spec.stacked.iter().enumerate() {
386            let below = if layer == 0 { 0.0 } else { tops[layer - 1] };
387            let top = tops[layer];
388            if top <= below {
389                continue;
390            }
391            let _ = write!(
392                svg,
393                r#"<rect class="area s{}" x="{left:.1}" y="{:.1}" width="{width:.1}" height="{:.1}"><title>{}: {}</title></rect>"#,
394                line.slot,
395                y(top),
396                y(below) - y(top),
397                escape(&line.label),
398                escape(&spec.unit.show(top - below)),
399            );
400        }
401    }
402}
403
404/// A bar chart drawn: its SVG.
405#[must_use]
406pub fn draw_bars(spec: &Bars) -> String {
407    let plot_w = spec.width - LEFT - RIGHT;
408    let plot_h = HEIGHT - TOP - BOTTOM;
409    let data_max = spec
410        .bars
411        .iter()
412        .filter_map(|b| b.value)
413        .fold(0.0_f64, f64::max);
414    let limit = spec
415        .limit
416        .as_ref()
417        .filter(|(_, value)| data_max == 0.0 || *value <= data_max * 4.0);
418    let max = limit.map_or(data_max, |l| l.1.max(data_max));
419    let (top, y_ticks) = y_axis(max, spec.unit);
420    let y = |v: f64| TOP + plot_h * (1.0 - v / top);
421    #[expect(clippy::cast_precision_loss, reason = "a few dozen bars")]
422    let slot = plot_w / spec.bars.len().max(1) as f64;
423    // Thin bars, a gap between: at most 14 wide.
424    let bar_w = (slot * 0.6).clamp(2.0, 14.0);
425    #[expect(clippy::cast_precision_loss, reason = "a few dozen bars")]
426    let center = |i: usize| LEFT + slot * (i as f64 + 0.5);
427
428    let mut svg = String::new();
429    let _ = write!(
430        svg,
431        r#"<svg class="chart bars" viewBox="0 0 {} {HEIGHT}" role="img" aria-label="{}">"#,
432        spec.width,
433        escape(&spec.title)
434    );
435    y_grid(&mut svg, spec.width, &y_ticks, spec.unit, &y);
436    if let Some(last) = spec.bars.len().checked_sub(1) {
437        let first = center(0) - bar_w / 2.0;
438        end_labels(
439            &mut svg,
440            &spec.ends,
441            first,
442            (last > 0).then(|| center(last) + bar_w / 2.0),
443        );
444    }
445    let base = y(0.0);
446    for (i, bar) in spec.bars.iter().enumerate() {
447        let left = center(i) - bar_w / 2.0;
448        let _ = write!(
449            svg,
450            r#"<a href="{}"><title>{}</title>"#,
451            escape(&bar.href),
452            escape(&bar.title)
453        );
454        // The whole slot's height takes the hover and the click, wider than the bar.
455        let _ = write!(
456            svg,
457            r#"<rect class="hover" x="{:.1}" y="{TOP}" width="{slot:.1}" height="{plot_h:.1}"></rect>"#,
458            center(i) - slot / 2.0
459        );
460        if let Some(value) = bar.value {
461            let top_y = y(value);
462            let _ = write!(
463                svg,
464                r#"<path class="bar {}" d="{}"></path>"#,
465                bar.class,
466                bar_outline(left, bar_w, base, top_y)
467            );
468            if bar.marked {
469                let _ = write!(
470                    svg,
471                    r#"<text class="mark" x="{:.1}" y="{:.1}" text-anchor="middle">✕</text>"#,
472                    center(i),
473                    (top_y - 4.0).max(TOP + 8.0)
474                );
475            }
476        }
477        svg.push_str("</a>");
478    }
479    if let Some((label, value)) = limit {
480        let _ = write!(
481            svg,
482            r#"<line class="limit" x1="{LEFT}" x2="{}" y1="{y:.1}" y2="{y:.1}"><title>{}: {}</title></line>"#,
483            spec.width - RIGHT,
484            escape(label),
485            escape(&spec.unit.show(*value)),
486            y = y(*value),
487        );
488    }
489    let _ = write!(
490        svg,
491        r#"<line class="baseline" x1="{LEFT}" x2="{}" y1="{base:.1}" y2="{base:.1}"></line>"#,
492        spec.width - RIGHT,
493    );
494    svg.push_str("</svg>");
495    svg
496}
497
498/// The labels under a bar chart's first bar (from `first`) and its last (to `last`; none for
499/// one bar).
500fn end_labels(svg: &mut String, (start, end): &(String, String), first: f64, last: Option<f64>) {
501    let mut label = |x: f64, anchor: &str, text: &str| {
502        let _ = write!(
503            svg,
504            r#"<text class="axis" x="{x:.1}" y="{}" text-anchor="{anchor}">{}</text>"#,
505            HEIGHT - 6.0,
506            escape(text)
507        );
508    };
509    label(first, "start", start);
510    if let Some(last) = last {
511        label(last, "end", end);
512    }
513}
514
515/// The y grid lines and their labels, across a chart `width` wide.
516fn y_grid(svg: &mut String, width: f64, y_ticks: &[f64], unit: Unit, y: &impl Fn(f64) -> f64) {
517    for tick in y_ticks {
518        let _ = write!(
519            svg,
520            r#"<line class="grid" x1="{LEFT}" x2="{}" y1="{y:.1}" y2="{y:.1}"></line><text class="axis" x="{}" y="{:.1}" text-anchor="end">{}</text>"#,
521            width - RIGHT,
522            LEFT - 6.0,
523            y(*tick) + 4.0,
524            escape(&axis_value(*tick, unit)),
525            y = y(*tick),
526        );
527    }
528}
529
530/// A bar's outline from `left`, `width` wide, from the baseline `base` up to `top`: rounded at
531/// the top only, flat on the baseline.
532fn bar_outline(left: f64, width: f64, base: f64, top: f64) -> String {
533    let r = (width / 2.0).min(4.0).min((base - top).max(0.0));
534    let right = left + width;
535    format!(
536        "M{left:.1},{base:.1}V{:.1}Q{left:.1},{top:.1} {:.1},{top:.1}H{:.1}Q{right:.1},{top:.1} {right:.1},{:.1}V{base:.1}Z",
537        top + r,
538        left + r,
539        right - r,
540        top + r,
541    )
542}
543
544/// The grid, the y labels, the time labels and the baseline.
545fn axes(
546    svg: &mut String,
547    spec: &Spec,
548    y_ticks: &[f64],
549    x: &impl Fn(i64) -> f64,
550    y: &impl Fn(f64) -> f64,
551) {
552    y_grid(svg, spec.width, y_ticks, spec.unit, y);
553    let (every, format) = x_ticks(spec.from, spec.to);
554    let mut tick = (spec.from + every - 1).div_euclid(every) * every;
555    while tick <= spec.to {
556        if let Ok(at) = Timestamp::from_second(tick) {
557            let label = at.to_zoned(spec.zone.clone()).strftime(format).to_string();
558            let _ = write!(
559                svg,
560                r#"<text class="axis" x="{:.1}" y="{}" text-anchor="middle">{}</text>"#,
561                x(tick),
562                HEIGHT - 6.0,
563                escape(&label)
564            );
565        }
566        tick += every;
567    }
568    let _ = write!(
569        svg,
570        r#"<line class="baseline" x1="{LEFT}" x2="{}" y1="{:.1}" y2="{:.1}"></line>"#,
571        spec.width - RIGHT,
572        y(0.0),
573        y(0.0)
574    );
575}
576
577/// A line through `points` (SVG path data).
578fn path(points: impl Iterator<Item = (f64, f64)>) -> String {
579    let mut d = String::new();
580    for (i, (px, py)) in points.enumerate() {
581        let _ = write!(d, "{}{px:.1},{py:.1}", if i == 0 { "M" } else { "L" });
582    }
583    d
584}
585
586/// An area along `top`, then back along `bottom` (given back to front).
587fn area(top: impl Iterator<Item = (f64, f64)>, bottom: impl Iterator<Item = (f64, f64)>) -> String {
588    let mut d = path(top);
589    for (px, py) in bottom {
590        let _ = write!(d, "L{px:.1},{py:.1}");
591    }
592    d
593}
594
595/// A tick's label: in the unit the chart's top is shown in.
596fn axis_value(value: f64, unit: Unit) -> String {
597    match unit {
598        Unit::Bytes | Unit::Millis if value == 0.0 => "0".to_owned(),
599        Unit::Bytes => {
600            let text = bytes(value);
601            text.replace(".0 ", " ")
602        }
603        Unit::Cores => {
604            let text = format!("{value:.2}");
605            text.trim_end_matches('0').trim_end_matches('.').to_owned()
606        }
607        Unit::Count => format!("{value:.0}"),
608        Unit::Millis if value < 1000.0 => format!("{value:.0} ms"),
609        Unit::Millis => {
610            let text = format!("{:.1}", value / 1000.0);
611            format!("{} s", text.trim_end_matches(".0"))
612        }
613    }
614}
615
616/// `points` split where two are further apart than one and a half steps (no samples there).
617fn runs<P>(points: &[P], step: i64, at: impl Fn(&P) -> i64) -> Vec<&[P]> {
618    let gap = step + step / 2;
619    points.chunk_by(|a, b| at(b) - at(a) <= gap).collect()
620}
621
622/// The stacked layers' tops at each time any has a point: the running sums, bottom first.
623fn stack(layers: &[Line]) -> Vec<(i64, Vec<f64>)> {
624    let mut times: Vec<i64> = layers
625        .iter()
626        .flat_map(|l| l.points.iter().map(|p| p.0))
627        .collect();
628    times.sort_unstable();
629    times.dedup();
630    times
631        .into_iter()
632        .map(|at| {
633            let mut sum = 0.0;
634            let tops = layers
635                .iter()
636                .map(|l| {
637                    sum += l.points.iter().find(|p| p.0 == at).map_or(0.0, |p| p.1);
638                    sum
639                })
640                .collect();
641            (at, tops)
642        })
643        .collect()
644}
645
646/// A transparent strip per point in time, its `<title>` every value there.
647fn hover_strips(svg: &mut String, spec: &Spec, x: &impl Fn(i64) -> f64, plot_h: f64) {
648    let mut times: Vec<i64> = spec
649        .lines
650        .iter()
651        .flat_map(|l| l.points.iter().map(|p| p.0))
652        .chain(
653            spec.band
654                .iter()
655                .flat_map(|(_, points)| points.iter().map(|p| p.0)),
656        )
657        .collect();
658    times.extend(
659        spec.stacked
660            .iter()
661            .flat_map(|l| l.points.iter().map(|p| p.0)),
662    );
663    times.sort_unstable();
664    times.dedup();
665    let width = (x(spec.from + spec.step) - x(spec.from)).max(1.0);
666    for at in times {
667        let Ok(when) = Timestamp::from_second(at) else {
668            continue;
669        };
670        let mut title = when
671            .to_zoned(spec.zone.clone())
672            .strftime("%Y-%m-%d %H:%M %Z")
673            .to_string();
674        for line in &spec.lines {
675            if let Some(p) = line.points.iter().find(|p| p.0 == at) {
676                let _ = write!(title, "\n{}: {}", line.label, spec.unit.show(p.1));
677            }
678        }
679        let mut total = 0.0;
680        for line in spec.stacked.iter().rev() {
681            if let Some(p) = line.points.iter().find(|p| p.0 == at) {
682                total += p.1;
683                let _ = write!(title, "\n{}: {}", line.label, spec.unit.show(p.1));
684            }
685        }
686        if !spec.stacked.is_empty() {
687            let _ = write!(title, "\ntogether: {}", spec.unit.show(total));
688        }
689        if let Some((label, points)) = &spec.band
690            && let Some(p) = points.iter().find(|p| p.0 == at)
691        {
692            let _ = write!(
693                title,
694                "\n{label}: {} to {}",
695                spec.unit.show(p.1),
696                spec.unit.show(p.2)
697            );
698        }
699        let _ = write!(
700            svg,
701            r#"<rect class="hover" x="{:.1}" y="{TOP}" width="{width:.1}" height="{plot_h:.1}"><title>{}</title></rect>"#,
702            x(at),
703            escape(&title)
704        );
705    }
706}
707
708/// A sparkline of `points` (seconds, value) over `from..to`: a small line, no axes.
709#[must_use]
710pub fn sparkline(points: &[(i64, f64)], from: i64, to: i64, step: i64, title: &str) -> String {
711    const W: f64 = 120.0;
712    const H: f64 = 24.0;
713    let span = (to - from).max(1);
714    let max = points.iter().map(|p| p.1).fold(0.0_f64, f64::max);
715    let max = if max > 0.0 { max } else { 1.0 };
716    #[expect(clippy::cast_precision_loss, reason = "screen coordinates")]
717    let x = |t: i64| W * ((t - from) as f64 / span as f64);
718    let y = |v: f64| 2.0 + (H - 4.0) * (1.0 - v / max);
719    let mut svg = format!(
720        r#"<svg class="sparkline" viewBox="0 0 {W} {H}" width="{W}" height="{H}" role="img" aria-label="{}"><title>{}</title>"#,
721        escape(title),
722        escape(title)
723    );
724    for run in runs(points, step, |p| p.0) {
725        let mut d = String::new();
726        for (i, p) in run.iter().enumerate() {
727            let _ = write!(
728                d,
729                "{}{:.1},{:.1}",
730                if i == 0 { "M" } else { "L" },
731                x(p.0),
732                y(p.1)
733            );
734        }
735        let _ = write!(svg, r#"<path class="line s1" d="{d}"></path>"#);
736    }
737    svg.push_str("</svg>");
738    svg
739}
740
741#[cfg(test)]
742mod tests {
743    use pretty_assertions::assert_eq;
744
745    use super::*;
746
747    #[test]
748    fn stacked_bars_draw_each_points_parts_and_skip_the_empty_ones() {
749        let layer = |label: &str, slot, points: Vec<(i64, f64)>| Line {
750            label: label.to_owned(),
751            slot,
752            points,
753        };
754        let svg = draw(&Spec {
755            unit: Unit::Count,
756            stacked: vec![
757                layer("succeeded", 1, vec![(0, 3.0), (60, 0.0), (120, 2.0)]),
758                layer("failed", 2, vec![(0, 1.0), (60, 0.0), (120, 0.0)]),
759            ],
760            bars: true,
761            ..spec()
762        });
763        // Three parts: 3 and 1 at the first point, 2 at the third; none for the zeros, and no
764        // area.
765        assert_eq!(svg.matches("<rect class=\"area s1\"").count(), 2, "{svg}");
766        assert_eq!(svg.matches("<rect class=\"area s2\"").count(), 1, "{svg}");
767        assert!(!svg.contains("<path class=\"area"), "{svg}");
768        assert!(svg.contains("<title>failed: 1</title>"), "{svg}");
769    }
770
771    #[test]
772    fn a_stacked_point_alone_between_gaps_is_a_bar() {
773        // Samples three minutes apart on a minute's step: each point alone, no area.
774        let svg = draw(&Spec {
775            stacked: vec![Line {
776                label: "tasks".to_owned(),
777                slot: 5,
778                points: vec![(0, 1024.0), (180, 2048.0), (240, 1024.0)],
779            }],
780            ..spec()
781        });
782        assert_eq!(svg.matches("<rect class=\"area s5\"").count(), 1, "{svg}");
783        assert_eq!(svg.matches("<path class=\"area s5\"").count(), 1, "{svg}");
784    }
785
786    fn spec() -> Spec {
787        Spec {
788            title: "Memory <prod>".to_owned(),
789            unit: Unit::Bytes,
790            width: WIDTH,
791            from: 0,
792            to: 3600,
793            step: 60,
794            lines: vec![Line {
795                label: "worker \"a\"".to_owned(),
796                slot: 1,
797                // A gap between 120 and 600: two runs.
798                points: vec![(0, 1024.0), (60, 2048.0), (120, 3072.0), (600, 1024.0)],
799            }],
800            band: Some((
801                "3 others".to_owned(),
802                vec![(0, 10.0, 500.0), (60, 20.0, 600.0)],
803            )),
804            stacked: Vec::new(),
805            limits: vec![("worker a's limit".to_owned(), 1, 4096.0)],
806            zone: TimeZone::UTC,
807            bars: false,
808        }
809    }
810
811    #[test]
812    fn a_chart_draws_its_lines_band_limits_axes_and_hover_titles_escaped() {
813        let svg = draw(&spec());
814        assert!(svg.starts_with(r#"<svg class="chart""#), "{svg}");
815        assert!(svg.contains(r#"aria-label="Memory &lt;prod&gt;""#));
816        assert_eq!(
817            svg.matches(r#"class="line s1""#).count(),
818            1,
819            "the run of three"
820        );
821        assert_eq!(
822            svg.matches(r#"class="dot s1""#).count(),
823            1,
824            "the point alone"
825        );
826        assert_eq!(svg.matches(r#"class="band""#).count(), 1);
827        assert!(svg.contains(r#"class="limit s1""#));
828        assert!(svg.contains(">4 KiB</text>"), "the top tick: {svg}");
829        assert!(svg.contains(">00:10</text>"), "a time tick");
830        assert_eq!(svg.matches(r#"class="hover""#).count(), 4);
831        assert!(svg.contains("worker &quot;a&quot;: 2.0 KiB"));
832        assert!(svg.contains("3 others: 20 B to 600 B"));
833    }
834
835    #[test]
836    fn stacked_layers_are_drawn_on_each_other_with_their_sum_on_hover() {
837        let layer = |label: &str, slot, points: Vec<(i64, f64)>| Line {
838            label: label.to_owned(),
839            slot,
840            points,
841        };
842        let svg = draw(&Spec {
843            lines: Vec::new(),
844            band: None,
845            limits: Vec::new(),
846            stacked: vec![
847                layer("workers", 1, vec![(0, 1024.0), (60, 1024.0)]),
848                layer("tasks", 2, vec![(60, 3072.0)]),
849            ],
850            ..spec()
851        });
852        assert_eq!(svg.matches(r#"class="area s1""#).count(), 1);
853        assert_eq!(svg.matches(r#"class="area s2""#).count(), 1);
854        assert!(svg.contains(">4 KiB</text>"), "the top is the sum: {svg}");
855        assert!(
856            svg.contains("tasks: 3.0 KiB\nworkers: 1.0 KiB\ntogether: 4.0 KiB"),
857            "{svg}"
858        );
859    }
860
861    #[test]
862    fn a_limit_far_above_the_lines_is_left_off() {
863        let svg = draw(&Spec {
864            limits: vec![("limit".to_owned(), 1, 1e12)],
865            ..spec()
866        });
867        assert!(!svg.contains("class=\"limit"));
868    }
869
870    #[test]
871    fn the_y_axis_has_round_ticks_in_the_unit_of_its_top() {
872        let (top, ticks) = y_axis(3.3 * 1024.0 * 1024.0 * 1024.0, Unit::Bytes);
873        assert_eq!(
874            top.to_bits(),
875            (4.0_f64 * 1024.0 * 1024.0 * 1024.0).to_bits()
876        );
877        assert_eq!(ticks.len(), 5);
878        let (top, ticks) = y_axis(0.0, Unit::Cores);
879        let bits = |v: &[f64]| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
880        assert_eq!(
881            (top.to_bits(), bits(&ticks)),
882            (1.0_f64.to_bits(), bits(&[0.0, 0.5, 1.0]))
883        );
884        assert_eq!(axis_value(1.5 * 1024.0 * 1024.0, Unit::Bytes), "1.5 MiB");
885        assert_eq!(axis_value(0.25, Unit::Cores), "0.25");
886    }
887
888    #[test]
889    fn a_sparkline_is_a_small_line() {
890        let svg = sparkline(&[(0, 1.0), (60, 2.0)], 0, 120, 60, "Memory");
891        assert!(svg.contains(r#"class="line s1""#) && svg.contains("<title>Memory</title>"));
892    }
893
894    fn bar(value: Option<f64>, marked: bool) -> Bar {
895        Bar {
896            value,
897            class: "ok",
898            marked,
899            href: "/r?a=1&b=2".to_owned(),
900            title: "try <1>".to_owned(),
901        }
902    }
903
904    #[test]
905    fn bars_stand_on_the_baseline_rounded_at_the_top_and_link_to_their_attempts() {
906        let spec = Bars {
907            title: "Peaks".to_owned(),
908            unit: Unit::Bytes,
909            width: NARROW,
910            bars: vec![
911                bar(Some(512.0), false),
912                bar(None, false),
913                bar(Some(1024.0), true),
914            ],
915            limit: Some(("its memory limit".to_owned(), 2048.0)),
916            ends: ("Nov 13 10:00".to_owned(), "Nov 14 10:00".to_owned()),
917        };
918        let svg = draw_bars(&spec);
919        // A bar for each value; the one without stays an empty link with its title.
920        assert_eq!(svg.matches(r#"<path class="bar ok""#).count(), 2);
921        assert_eq!(svg.matches("<a href=").count(), 3);
922        assert!(svg.contains(r#"<a href="/r?a=1&amp;b=2"><title>try &lt;1&gt;</title>"#));
923        assert_eq!(svg.matches(r#"<text class="mark""#).count(), 1);
924        assert!(svg.contains("<title>its memory limit: 2.0 KiB</title>"));
925        assert!(svg.contains(">Nov 13 10:00</text>") && svg.contains(">Nov 14 10:00</text>"));
926        // A limit far above the bars would flatten them: left out.
927        let far = Bars {
928            limit: Some(("its memory limit".to_owned(), 1e12)),
929            ..spec.clone()
930        };
931        assert!(!draw_bars(&far).contains("class=\"limit\""));
932        // One bar: one label.
933        let one = Bars {
934            bars: vec![bar(Some(1.0), false)],
935            ..spec
936        };
937        let svg = draw_bars(&one);
938        assert!(svg.contains(">Nov 13 10:00</text>") && !svg.contains(">Nov 14 10:00</text>"));
939    }
940
941    #[test]
942    fn a_bars_outline_is_flat_on_the_baseline() {
943        assert_eq!(
944            bar_outline(10.0, 8.0, 100.0, 50.0),
945            "M10.0,100.0V54.0Q10.0,50.0 14.0,50.0H14.0Q18.0,50.0 18.0,54.0V100.0Z"
946        );
947    }
948}