Skip to main content

ferrokit/
charts.rs

1//! Charts on the [canvas](crate::canvas): bars (plain, stacked or grouped)
2//! for categories, lines, areas and points for numeric series, pies,
3//! histograms, heatmaps and sparklines, with [rules](Rule) for thresholds.
4//! Axes with round-number ticks and gridlines, values on hover, a
5//! VoiceOver summary, and lines of millions of points drawn at one or two
6//! points per pixel column.
7
8use std::cell::RefCell;
9use std::collections::HashMap;
10use std::rc::Rc;
11
12use ferrokit_core::text::Color;
13
14use objc2::rc::Retained;
15use objc2_foundation::{NSLocale, NSNumber, NSNumberFormatter, NSNumberFormatterStyle, NSString};
16
17use crate::canvas::{Canvas, Painter, canvas};
18use crate::signal::{Effect, Signal, keep_with_owner, untrack};
19use crate::view::Align;
20
21/// Colours of the series, in order.
22const PALETTE: [Color; 8] = [
23    Color::Blue,
24    Color::Orange,
25    Color::Green,
26    Color::Pink,
27    Color::Purple,
28    Color::Teal,
29    Color::Yellow,
30    Color::Brown,
31];
32
33const FONT: f64 = 11.0;
34
35/// One line of a [`line_chart`]: a name and its points (sorted by x or
36/// not; they're sorted for drawing).
37#[derive(Debug, Clone, PartialEq)]
38pub struct Series {
39    /// The name in the legend and the hover readout.
40    pub name: String,
41    /// `(x, y)` points.
42    pub points: Vec<(f64, f64)>,
43    /// Its own colour (else the chart's next one).
44    pub color: Option<Color>,
45}
46
47impl Series {
48    /// A series named `name` through `points`.
49    pub fn new(name: &str, points: Vec<(f64, f64)>) -> Self {
50        Series { name: name.into(), points, color: None }
51    }
52
53    /// The same series drawn in `color`.
54    pub fn color(mut self, color: Color) -> Self {
55        self.color = Some(color);
56        self
57    }
58}
59
60/// A straight line across a chart at a value: a threshold, a target, an
61/// average. [`Rule::y`] runs across at a value (bar, line, area, scatter
62/// and histogram charts, and sparklines); [`Rule::x`] runs down at an x
63/// (line, area and scatter charts, and histograms). The chart's range
64/// takes it in, so a target above every value still shows.
65///
66/// ```no_run
67/// use ferrokit::*;
68///
69/// let chart = bar_chart(|| vec![("Mon".to_string(), 1200.0), ("Tue".to_string(), 800.0)])
70///     .rule(Rule::y(1000.0).label("Target").color(Color::Green));
71/// # let _ = chart;
72/// ```
73#[derive(Debug, Clone, PartialEq)]
74pub struct Rule {
75    value: f64,
76    vertical: bool,
77    label: Option<String>,
78    color: Color,
79}
80
81impl Rule {
82    /// A line across the chart at `value` on the value axis.
83    pub fn y(value: f64) -> Rule {
84        Rule { value, vertical: false, label: None, color: Color::Red }
85    }
86
87    /// A line down the chart at `x`.
88    pub fn x(x: f64) -> Rule {
89        Rule { vertical: true, ..Rule::y(x) }
90    }
91
92    /// A label at its end, also read by VoiceOver.
93    pub fn label(mut self, label: &str) -> Rule {
94        self.label = Some(label.into());
95        self
96    }
97
98    /// Its colour (red unless set).
99    pub fn color(mut self, color: Color) -> Rule {
100        self.color = color;
101        self
102    }
103}
104
105/// `lo..hi` widened to take in the chart's rules across (or, with
106/// `vertical`, down).
107fn with_rules(o: &Options, vertical: bool, lo: f64, hi: f64) -> (f64, f64) {
108    o.rules.iter().filter(|r| r.vertical == vertical && r.value.is_finite()).fold((lo, hi), |(a, b), r| (a.min(r.value), b.max(r.value)))
109}
110
111/// Draws the rules over the plot, labels at their right or top end; rules
112/// down need an x scale, and are left out where it doesn't reach.
113fn draw_rules(p: &mut Painter, o: &Options, plot: &Plot, to_y: &dyn Fn(f64) -> f64, to_x: Option<&dyn Fn(f64) -> f64>) {
114    for r in &o.rules {
115        if r.vertical {
116            let Some(x) = to_x.map(|f| f(r.value)).filter(|x| *x >= plot.x - 0.5 && *x <= plot.x + plot.w + 0.5) else { continue };
117            p.line(x, plot.y, x, plot.y + plot.h, r.color, 1.5);
118            if let Some(l) = &r.label {
119                let end = x + 4.0 + p.measure(l, FONT).0 > plot.x + plot.w;
120                rule_label(p, if end { x - 5.0 } else { x + 5.0 }, plot.y + 1.0, l, r.color, if end { Align::End } else { Align::Start });
121            }
122        } else {
123            let y = to_y(r.value);
124            p.line(plot.x, y, plot.x + plot.w, y, r.color, 1.5);
125            if let Some(l) = &r.label {
126                rule_label(p, plot.x + plot.w - 4.0, y - FONT - 6.0, l, r.color, Align::End);
127            }
128        }
129    }
130}
131
132/// A rule's label on a patch of the background, so it reads over the data.
133fn rule_label(p: &mut Painter, x: f64, y: f64, text: &str, color: Color, align: Align) {
134    let w = p.measure(text, FONT).0;
135    let left = match align {
136        Align::End => x - w,
137        Align::Center => x - w / 2.0,
138        Align::Start => x,
139    };
140    p.set_opacity(0.85);
141    p.fill_rounded_rect(left - 3.0, y - 1.0, w + 6.0, FONT + 4.0, 3.0, Color::Background);
142    p.set_opacity(1.0);
143    p.text(x, y, text, FONT, color, align);
144}
145
146/// The rules for VoiceOver: "; Target at $1,000".
147fn rules_text(o: &Options, x: &Format, y: &Format) -> String {
148    o.rules
149        .iter()
150        .map(|r| {
151            let v = if r.vertical { x.value(r.value) } else { y.value(r.value) };
152            match &r.label {
153                Some(l) => format!("; {l} at {v}"),
154                None => format!("; a rule at {v}"),
155            }
156        })
157        .collect()
158}
159
160/// Round-number ticks covering `min..=max`, about `target` of them.
161pub(crate) fn ticks(min: f64, max: f64, target: usize) -> (Vec<f64>, f64) {
162    // An empty or flat range (or NaN) still gets an axis around it.
163    let (min, max) = if max.partial_cmp(&min) != Some(std::cmp::Ordering::Greater) {
164        if min == 0.0 { (0.0, 1.0) } else { (min - min.abs() * 0.1, max + max.abs() * 0.1) }
165    } else {
166        (min, max)
167    };
168    let raw = (max - min) / target.max(1) as f64;
169    let mag = 10f64.powf(raw.log10().floor());
170    let norm = raw / mag;
171    let step = mag * if norm < 1.5 { 1.0 } else if norm < 3.0 { 2.0 } else if norm < 7.0 { 5.0 } else { 10.0 };
172    let (start, end) = ((min / step).floor(), (max / step).ceil());
173    let ticks = (start as i64..=end as i64).map(|i| i as f64 * step).collect();
174    (ticks, step)
175}
176
177/// A tick label: compact for large numbers (12k, 1.5M), with as many
178/// decimals as the step needs.
179pub(crate) fn tick_label(v: f64, step: f64) -> String {
180    let a = v.abs();
181    if a >= 1e9 && step >= 1e8 {
182        return format!("{}B", trim(v / 1e9, step / 1e9));
183    }
184    if a >= 1e6 && step >= 1e5 {
185        return format!("{}M", trim(v / 1e6, step / 1e6));
186    }
187    if a >= 1e4 && step >= 1e3 {
188        return format!("{}k", trim(v / 1e3, step / 1e3));
189    }
190    trim(v, step)
191}
192
193fn trim(v: f64, step: f64) -> String {
194    let decimals = if step >= 1.0 { 0 } else { (-step.log10().floor()) as usize };
195    let s = format!("{v:.decimals$}");
196    if s == "-0" { "0".into() } else { s }
197}
198
199/// A value for the readout: up to 4 significant decimals, no trailing zeros.
200fn value_label(v: f64) -> String {
201    if v.fract() == 0.0 && v.abs() < 1e15 {
202        return format!("{v:.0}");
203    }
204    let s = format!("{v:.4}");
205    s.trim_end_matches('0').trim_end_matches('.').to_string()
206}
207
208/// The plot area inside the axes' labels.
209struct Plot {
210    x: f64,
211    y: f64,
212    w: f64,
213    h: f64,
214}
215
216/// Draws the y axis (ticks, labels, gridlines) and returns the plot area
217/// and the value → y mapping.
218fn y_axis(p: &mut Painter, lo: f64, hi: f64, top: f64, bottom: f64, format: &Format) -> (Plot, impl Fn(f64) -> f64 + use<>) {
219    let (ticks, step) = ticks(lo, hi, ((p.height() - top - bottom) / 40.0).clamp(2.0, 8.0) as usize);
220    let labels: Vec<String> = ticks.iter().map(|&t| format.tick(t, step)).collect();
221    let label_w = labels.iter().map(|l| p.measure(l, FONT).0).fold(0.0, f64::max);
222    let plot = Plot { x: label_w + 10.0, y: top, w: (p.width() - label_w - 22.0).max(1.0), h: (p.height() - top - bottom).max(1.0) };
223    let (t0, t1) = (ticks[0], *ticks.last().unwrap());
224    let (py, ph) = (plot.y, plot.h);
225    let to_y = move |v: f64| py + ph - (v - t0) / (t1 - t0).max(f64::MIN_POSITIVE) * ph;
226    for (t, label) in ticks.iter().zip(&labels) {
227        let y = to_y(*t);
228        p.line(plot.x, y, plot.x + plot.w, y, Color::Separator, 1.0);
229        p.text(plot.x - 6.0, y - FONT * 0.65, label, FONT, Color::Secondary, Align::End);
230    }
231    (plot, to_y)
232}
233
234/// A tooltip box with `lines` near `x, y`, kept inside the canvas.
235fn tooltip(p: &mut Painter, x: f64, y: f64, lines: &[String]) {
236    let w = lines.iter().map(|l| p.measure(l, FONT).0).fold(0.0, f64::max) + 12.0;
237    let h = lines.len() as f64 * (FONT + 4.0) + 8.0;
238    let bx = if x + 12.0 + w > p.width() { x - 12.0 - w } else { x + 12.0 };
239    let by = (y - h / 2.0).clamp(0.0, (p.height() - h).max(0.0));
240    p.set_opacity(0.95);
241    p.fill_rounded_rect(bx, by, w, h, 5.0, Color::Background);
242    p.set_opacity(1.0);
243    p.stroke_rect(bx, by, w, h, Color::Separator, 1.0);
244    for (i, l) in lines.iter().enumerate() {
245        p.text(bx + 6.0, by + 4.0 + i as f64 * (FONT + 4.0), l, FONT, Color::Primary, Align::Start);
246    }
247}
248
249fn no_data(p: &mut Painter) {
250    p.text(p.width() / 2.0, p.height() / 2.0 - FONT, &crate::t("No data"), FONT + 2.0, Color::Secondary, Align::Center);
251}
252
253/// Keeps `data()` in a signal, recomputed when what it reads changes (so
254/// hovering redraws without recomputing it).
255fn hold<T: 'static>(data: impl Fn() -> T + 'static) -> Signal<Option<Rc<T>>> {
256    let held = Signal::new(None);
257    // Runs now (so it's never `None` when drawn) and when `data` changes.
258    let effect = Effect::new(move || {
259        let v = Rc::new(data());
260        untrack(|| held.set(Some(v)));
261    });
262    keep_with_owner(effect);
263    held
264}
265
266/// Points sorted by x, and their x's (for finding the one under the pointer).
267struct Prepared {
268    name: String,
269    points: Vec<(f64, f64)>,
270    color: Option<Color>,
271}
272
273/// One or two points per pixel column (the first, lowest and highest, and
274/// last of each), so a million points draw like the line they make.
275pub(crate) fn decimate(points: &[(f64, f64)], x0: f64, x1: f64, columns: usize) -> Vec<(f64, f64)> {
276    if points.len() <= columns * 4 || columns == 0 || x1 <= x0 {
277        return points.to_vec();
278    }
279    let mut out = Vec::with_capacity(columns * 4);
280    let width = (x1 - x0) / columns as f64;
281    let mut i = 0;
282    while i < points.len() {
283        let col = ((points[i].0 - x0) / width).floor();
284        let start = i;
285        let (mut lo, mut hi) = (i, i);
286        while i < points.len() && ((points[i].0 - x0) / width).floor() == col {
287            if points[i].1 < points[lo].1 {
288                lo = i;
289            }
290            if points[i].1 > points[hi].1 {
291                hi = i;
292            }
293            i += 1;
294        }
295        let mut keep = [start, lo, hi, i - 1];
296        keep.sort_unstable();
297        for (k, &j) in keep.iter().enumerate() {
298            if k == 0 || keep[k - 1] != j {
299                out.push(points[j]);
300            }
301        }
302    }
303    out
304}
305
306/// How a chart prints its values: on the axes, in the hover readout and
307/// in what VoiceOver reads.
308#[derive(Debug, Clone, PartialEq)]
309#[non_exhaustive]
310pub enum Format {
311    /// Plain numbers; large ones compact on the axis (12k, 1.5M).
312    Number,
313    /// Numbers with this many decimals, grouped as the user's locale does.
314    Decimals(usize),
315    /// Money in the currency with this ISO code (`"USD"`, `"EUR"`), as the
316    /// user's locale writes it.
317    Currency(String),
318    /// Fractions as percentages: 0.25 is 25%.
319    Percent,
320    /// Dates: values are seconds since 1970 (UTC), shown in the user's
321    /// time zone, with ticks on whole days, weeks, months or years.
322    Date,
323    /// Dates with times of day, ticks on whole hours where they fit.
324    DateTime,
325}
326
327impl Format {
328    fn is_date(&self) -> bool {
329        matches!(self, Format::Date | Format::DateTime)
330    }
331
332    fn formatter(&self, decimals: usize) -> Option<Retained<NSNumberFormatter>> {
333        let f = NSNumberFormatter::new();
334        f.setLocale(Some(&NSLocale::currentLocale()));
335        match self {
336            Format::Currency(code) => {
337                f.setNumberStyle(NSNumberFormatterStyle::CurrencyStyle);
338                f.setCurrencyCode(Some(&NSString::from_str(code)));
339            }
340            Format::Percent => f.setNumberStyle(NSNumberFormatterStyle::PercentStyle),
341            Format::Decimals(_) => f.setNumberStyle(NSNumberFormatterStyle::DecimalStyle),
342            _ => return None,
343        }
344        f.setMinimumFractionDigits(decimals);
345        f.setMaximumFractionDigits(decimals);
346        Some(f)
347    }
348
349    fn number(&self, v: f64, decimals: usize) -> Option<String> {
350        let f = self.formatter(decimals)?;
351        f.stringFromNumber(&NSNumber::new_f64(v)).map(|s| s.to_string())
352    }
353
354    /// An axis label for `v` among ticks `step` apart.
355    fn tick(&self, v: f64, step: f64) -> String {
356        let places = |step: f64| if step >= 1.0 { 0 } else { (-step.log10().floor()) as usize };
357        let text = match self {
358            Format::Decimals(d) => self.number(v, *d),
359            Format::Currency(_) => self.number(v, places(step)),
360            Format::Percent => self.number(v, places(step * 100.0)),
361            Format::Date | Format::DateTime => Some(date_text(v, if *self == Format::Date { "yMMMd" } else { "MMMd jm" })),
362            Format::Number => None,
363        };
364        text.unwrap_or_else(|| tick_label(v, step))
365    }
366
367    /// `v` in full, for the readout and VoiceOver.
368    fn value(&self, v: f64) -> String {
369        let text = match self {
370            Format::Decimals(d) => self.number(v, *d),
371            Format::Currency(_) => self.number(v, if v.fract() == 0.0 { 0 } else { 2 }),
372            Format::Percent => self.number(v, if (v * 100.0).fract() == 0.0 { 0 } else { 1 }),
373            Format::Date => Some(date_text(v, "yMMMd")),
374            Format::DateTime => Some(date_text(v, "yMMMd jm")),
375            Format::Number => None,
376        };
377        text.unwrap_or_else(|| value_label(v))
378    }
379}
380
381fn date_text(seconds: f64, template: &str) -> String {
382    crate::l10n::format_date(seconds, template)
383}
384
385/// Days since 1970-01-01 for a civil date (proleptic Gregorian).
386fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
387    let y = if m <= 2 { y - 1 } else { y };
388    let era = y.div_euclid(400);
389    let yoe = y - era * 400;
390    let doy = (153 * (m + if m > 2 { -3 } else { 9 }) + 2) / 5 + d - 1;
391    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
392    era * 146_097 + doe - 719_468
393}
394
395/// The civil date (year, month) of a day since 1970.
396fn civil_from_days(z: i64) -> (i64, i64) {
397    let z = z + 719_468;
398    let era = z.div_euclid(146_097);
399    let doe = z - era * 146_097;
400    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
401    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
402    let mp = (5 * doy + 2) / 153;
403    let m = if mp < 10 { mp + 3 } else { mp - 9 };
404    (yoe + era * 400 + i64::from(m <= 2), m)
405}
406
407/// Date ticks within `min..=max` (seconds since 1970), about `target` of
408/// them, on whole local hours, days, weeks (Mondays), months or years; with
409/// the date format template their labels use. `offset` is the local time
410/// zone's offset from UTC at a moment (it changes with daylight saving).
411pub(crate) fn date_ticks(min: f64, max: f64, target: usize, offset: &dyn Fn(f64) -> f64) -> (Vec<f64>, &'static str) {
412    const H: f64 = 3600.0;
413    const D: f64 = 86_400.0;
414    let span = (max - min).max(1.0);
415    let target = target.max(1) as f64;
416    // Local midnight starting day `d` (days since 1970, local), in UTC.
417    let midnight = |d: i64| {
418        let guess = d as f64 * D - offset(d as f64 * D);
419        d as f64 * D - offset(guess)
420    };
421    let first_day = ((min + offset(min)) / D).floor() as i64;
422    let hours = [(60.0, "jm"), (300.0, "jm"), (900.0, "jm"), (1800.0, "jm"), (H, "jm"), (3.0 * H, "jm"), (6.0 * H, "MMMd jm"), (12.0 * H, "MMMd jm")];
423    if let Some(&(step, template)) = hours.iter().find(|(step, _)| span / step <= target) {
424        let shift = offset(min);
425        let first = ((min + shift) / step).ceil() * step - shift;
426        return ((0..).map(|i| first + i as f64 * step).take_while(|t| *t <= max).collect(), template);
427    }
428    if let Some(days) = [1i64, 2, 7].into_iter().find(|d| span / (*d as f64 * D) <= target) {
429        // Every day or two, or Mondays (day 4, 1970-01-05, was one).
430        let mut d = first_day;
431        while (if days == 7 { d - 4 } else { d }).rem_euclid(days) != 0 {
432            d += 1;
433        }
434        let ticks = (0..).map(|i| midnight(d + i * days)).skip_while(|t| *t < min).take_while(|t| *t <= max).collect();
435        return (ticks, "MMMd");
436    }
437    // Months (1, 3 or 6 at a time) or years: on the first of the month.
438    let months = [1, 3, 6, 12, 24, 60, 120].into_iter().find(|m| span / (*m as f64 * 30.44 * D) <= target).unwrap_or(120);
439    let (y0, m0) = civil_from_days(first_day);
440    let mut index = y0 * 12 + (m0 - 1);
441    index += (months - index.rem_euclid(months)) % months;
442    let mut ticks = Vec::new();
443    loop {
444        let (y, m) = (index.div_euclid(12), index.rem_euclid(12) + 1);
445        let t = midnight(days_from_civil(y, m, 1));
446        if t > max {
447            break;
448        }
449        if t >= min {
450            ticks.push(t);
451        }
452        index += months;
453    }
454    (ticks, if months >= 12 { "y" } else if span > 330.0 * D { "MMMy" } else { "MMM" })
455}
456
457/// The local time zone's offset from UTC at `seconds` since 1970.
458fn local_offset(seconds: f64) -> f64 {
459    crate::l10n::local_offset(seconds)
460}
461
462/// What a chart draws (see the chart functions).
463enum Data {
464    Bars(Box<dyn Fn() -> Vec<(String, f64)>>),
465    Stacked(Box<dyn Fn() -> Vec<(String, Vec<f64>)>>),
466    Lines(Box<dyn Fn() -> Vec<Series>>, Mark),
467    Pie(Box<dyn Fn() -> Vec<(String, f64)>>),
468    Histogram(Box<dyn Fn() -> Vec<f64>>),
469    Heatmap(Box<dyn Fn() -> Vec<(String, String, f64)>>),
470    Spark(Box<dyn Fn() -> Vec<f64>>),
471}
472
473#[derive(Clone, Copy, PartialEq, Eq)]
474enum Mark {
475    Line,
476    Area,
477    Points,
478}
479
480/// A chart, made by [`bar_chart`], [`stacked_bar_chart`], [`line_chart`],
481/// [`area_chart`], [`scatter_chart`], [`pie_chart`], [`histogram`],
482/// [`heatmap`] or [`sparkline`]: drawn on a canvas,
483/// redrawn when the signals its data function reads change, with values
484/// on hover, a legend for more than one series, and a summary for
485/// VoiceOver.
486pub struct Chart {
487    data: Data,
488    options: Options,
489    min: Option<(f64, f64)>,
490    export: Option<String>,
491}
492
493#[derive(Clone)]
494struct Options {
495    values: Format,
496    x: Format,
497    colors: Vec<Color>,
498    names: Vec<String>,
499    grouped: bool,
500    donut: bool,
501    legend: bool,
502    rules: Vec<Rule>,
503    bins: usize,
504    selection: Option<Signal<Option<usize>>>,
505    x_selection: Option<Signal<Option<f64>>>,
506    x_range: Option<Signal<Option<(f64, f64)>>>,
507    zoomable: bool,
508}
509
510impl Options {
511    fn color(&self, i: usize) -> Color {
512        if self.colors.is_empty() { PALETTE[i % PALETTE.len()] } else { self.colors[i % self.colors.len()] }
513    }
514
515    /// The selected mark, if the chart has a [selection](Chart::selection).
516    fn selected(&self) -> Option<usize> {
517        self.selection.and_then(|s| s.get())
518    }
519
520    /// Mark `i`'s opacity: dimmed while another is selected.
521    fn emphasis(&self, i: usize) -> f64 {
522        match self.selected() {
523            Some(s) if s != i => 0.35,
524            _ => 1.0,
525        }
526    }
527}
528
529/// What's under a click: the mark's index, from the layout last drawn.
530type Hit = Rc<RefCell<Option<Rc<dyn Fn(f64, f64) -> Option<usize>>>>>;
531
532/// Clicking selects the mark under the pointer, or nothing off the marks.
533fn selectable(c: Canvas, o: &Options, hit: &Hit) -> Canvas {
534    let Some(selection) = o.selection else { return c };
535    let hit = hit.clone();
536    c.on_click(move |x, y| {
537        let i = hit.borrow().as_ref().and_then(|h| h(x, y));
538        selection.set(i);
539    })
540}
541
542/// "; selected Mar ($1,370)", for VoiceOver.
543fn selected_text(o: &Options, label: impl Fn(usize) -> Option<String>) -> String {
544    o.selected().and_then(label).map(|l| format!("; selected {l}")).unwrap_or_default()
545}
546
547/// `range` kept within `full` and at least a millionth of it wide; `None`
548/// when it covers all of it.
549pub(crate) fn clamp_range((a, b): (f64, f64), (f0, f1): (f64, f64)) -> Option<(f64, f64)> {
550    let full = f1 - f0;
551    if !(a.is_finite() && b.is_finite()) || full <= 0.0 {
552        return None;
553    }
554    let span = (b - a).abs().max(full * 1e-6);
555    if span >= full * 0.999 {
556        return None;
557    }
558    let a = a.min(b).clamp(f0, f1 - span);
559    Some((a, a + span))
560}
561
562/// The points of a sorted series within `a..=b`; for a line, with points
563/// at `a` and `b` where its segments cross them.
564fn visible(points: &[(f64, f64)], a: f64, b: f64, line: bool) -> Vec<(f64, f64)> {
565    let lo = points.partition_point(|p| p.0 < a);
566    let hi = points.partition_point(|p| p.0 <= b);
567    let at = |p: (f64, f64), q: (f64, f64), x: f64| (x, p.1 + (q.1 - p.1) * (x - p.0) / (q.0 - p.0));
568    let mut out = Vec::with_capacity(hi.saturating_sub(lo) + 2);
569    if line && lo > 0 && lo < points.len() && points[lo].0 > a {
570        out.push(at(points[lo - 1], points[lo], a));
571    }
572    out.extend_from_slice(&points[lo..hi.max(lo)]);
573    if line && hi > 0 && hi < points.len() && points[hi - 1].0 < b {
574        out.push(at(points[hi - 1], points[hi], b));
575    }
576    out
577}
578
579impl Chart {
580    fn new(data: Data) -> Chart {
581        Chart {
582            data,
583            options: Options { values: Format::Number, x: Format::Number, colors: Vec::new(), names: Vec::new(), grouped: false, donut: false, legend: true, rules: Vec::new(), bins: 10, selection: None, x_selection: None, x_range: None, zoomable: false },
584            min: None,
585            export: None,
586        }
587    }
588
589    /// How values print (the value axis, the readout, VoiceOver):
590    /// [`Format::Currency`], [`Format::Percent`]…
591    pub fn value_format(mut self, format: Format) -> Self {
592        self.options.values = format;
593        self
594    }
595
596    /// How x values print on line, area and scatter charts: dates with
597    /// [`Format::Date`], money, percentages…
598    pub fn x_format(mut self, format: Format) -> Self {
599        self.options.x = format;
600        self
601    }
602
603    /// The colours of the series (or bars, or slices), in order, repeating.
604    /// A [`Series`] with its own colour keeps it.
605    pub fn colors(mut self, colors: &[Color]) -> Self {
606        self.options.colors = colors.to_vec();
607        self
608    }
609
610    /// The names of a stacked bar chart's series, in the order of each
611    /// category's values (for the legend and the readout).
612    pub fn series_names(mut self, names: &[&str]) -> Self {
613        self.options.names = names.iter().map(|n| n.to_string()).collect();
614        self
615    }
616
617    /// A stacked bar chart's series side by side instead of stacked.
618    pub fn grouped(mut self) -> Self {
619        self.options.grouped = true;
620        self
621    }
622
623    /// A pie chart with a hole in the middle, showing the total.
624    pub fn donut(mut self) -> Self {
625        self.options.donut = true;
626        self
627    }
628
629    /// A [`Rule`] across or down the chart: a threshold, a target, an
630    /// average. Add as many as needed.
631    pub fn rule(mut self, rule: Rule) -> Self {
632        self.options.rules.push(rule);
633        self
634    }
635
636    /// Clicking a bar, a stacked bar's category, a slice, a histogram's
637    /// bin or a heatmap's cell (row × columns + column) sets `selected` to
638    /// its index, and clicking off the marks to `None`; the others dim
639    /// while one is selected. Setting the signal selects from code.
640    pub fn selection(mut self, selected: &Signal<Option<usize>>) -> Self {
641        self.options.selection = Some(*selected);
642        self
643    }
644
645    /// Clicking a line, area or scatter chart sets `x` to the nearest
646    /// point's x (on a scatter chart, the point's under the pointer), and
647    /// clicking off it to `None`; a line marks it, with each series' value.
648    pub fn x_selection(mut self, x: &Signal<Option<f64>>) -> Self {
649        self.options.x_selection = Some(*x);
650        self
651    }
652
653    /// The x range a line, area or scatter chart shows, bound two ways:
654    /// `None` shows all of it; `Some((from, to))` zooms in (the value axis
655    /// fits what's shown). With [`zoomable`](Chart::zoomable), pinching and
656    /// scrolling change it.
657    pub fn x_range(mut self, range: &Signal<Option<(f64, f64)>>) -> Self {
658        self.options.x_range = Some(*range);
659        self
660    }
661
662    /// Pinching (or ⌘-scrolling) zooms a line, area or scatter chart in and
663    /// out around the pointer, and scrolling sideways moves along; zooming
664    /// out all the way shows everything again. Vertical scrolling still
665    /// scrolls what the chart is in.
666    pub fn zoomable(mut self) -> Self {
667        self.options.zoomable = true;
668        self
669    }
670
671    /// About how many bins a [`histogram`] sorts its values into (10
672    /// unless set); their edges fall on round numbers.
673    pub fn bins(mut self, bins: usize) -> Self {
674        self.options.bins = bins.max(1);
675        self
676    }
677
678    /// Hides the legend (shown when there's more than one series, and a
679    /// heatmap's scale).
680    pub fn no_legend(mut self) -> Self {
681        self.options.legend = false;
682        self
683    }
684
685    /// The smallest size it's laid out at (default 200 × 120); it takes the
686    /// room it's given beyond that.
687    pub fn min_size(mut self, width: f64, height: f64) -> Self {
688        self.min = Some((width, height));
689        self
690    }
691
692    /// Copy Image and Save Image… on its right-click menu, and dragging it
693    /// out gives `name`.png (see [`Canvas::exportable`]).
694    pub fn exportable(mut self, name: &str) -> Self {
695        self.export = Some(name.into());
696        self
697    }
698}
699
700impl crate::view::View for Chart {
701    fn build(mut self, cx: &mut crate::view::Cx) -> crate::view::Node {
702        if self.options.zoomable && self.options.x_range.is_none() {
703            self.options.x_range = Some(Signal::new(None));
704        }
705        let o = Rc::new(self.options);
706        let mut c = match self.data {
707            Data::Bars(f) => bars(f, o),
708            Data::Stacked(f) => stacked(f, o),
709            Data::Lines(f, mark) => lines(f, mark, o),
710            Data::Pie(f) => pie(f, o),
711            Data::Histogram(f) => histogram_canvas(f, o),
712            Data::Heatmap(f) => heatmap_canvas(f, o),
713            Data::Spark(f) => spark(f, o),
714        };
715        if let Some((w, h)) = self.min {
716            c = c.min_size(w, h);
717        }
718        if let Some(name) = &self.export {
719            c = c.exportable(name);
720        }
721        c.build(cx)
722    }
723}
724
725/// A row of legend entries (a colour swatch and a name) from `x, y`,
726/// wrapping within `width`; returns its height.
727fn legend(p: &mut Painter, items: &[(String, Color)], x: f64, y: f64, width: f64) -> f64 {
728    let (mut cx, mut cy) = (x, y);
729    for (name, color) in items {
730        let w = 24.0 + p.measure(name, FONT).0;
731        if cx > x && cx + w > x + width {
732            cx = x;
733            cy += FONT + 7.0;
734        }
735        p.fill_rounded_rect(cx, cy + 2.0, 10.0, 10.0, 2.0, *color);
736        p.text(cx + 14.0, cy, name, FONT, Color::Secondary, Align::Start);
737        cx += w;
738    }
739    cy - y + FONT + 7.0
740}
741
742/// A bar chart of labelled values. Hovering a bar shows its value.
743///
744/// ```no_run
745/// use ferrokit::*;
746///
747/// let sales = Signal::new(vec![("Mon".to_string(), 1200.0), ("Tue".to_string(), 3000.0)]);
748/// let chart = bar_chart(move || sales.get()).value_format(Format::Currency("USD".into())).min_size(300.0, 200.0);
749/// # let _ = chart;
750/// ```
751pub fn bar_chart(data: impl Fn() -> Vec<(String, f64)> + 'static) -> Chart {
752    Chart::new(Data::Bars(Box::new(data)))
753}
754
755/// Bars made of several series per category, stacked (or side by side
756/// with [`grouped`](Chart::grouped)): each category's values are in the
757/// order of [`series_names`](Chart::series_names).
758///
759/// ```no_run
760/// use ferrokit::*;
761///
762/// let chart = stacked_bar_chart(|| vec![("Jan".to_string(), vec![1200.0, 420.0, 180.0]), ("Feb".to_string(), vec![1200.0, 380.0, 260.0])])
763///     .series_names(&["Rent", "Food", "Fun"])
764///     .value_format(Format::Currency("USD".into()));
765/// # let _ = chart;
766/// ```
767pub fn stacked_bar_chart(data: impl Fn() -> Vec<(String, Vec<f64>)> + 'static) -> Chart {
768    Chart::new(Data::Stacked(Box::new(data)))
769}
770
771/// A line chart of one or more series. Hovering shows each series' value
772/// at that x. Series of any length draw quickly: at most a few points per
773/// pixel column are kept.
774///
775/// ```no_run
776/// use ferrokit::*;
777///
778/// let chart = line_chart(|| {
779///     let wave: Vec<(f64, f64)> = (0..1_000).map(|i| (i as f64, (i as f64 / 50.0).sin())).collect();
780///     vec![Series::new("sine", wave)]
781/// });
782/// # let _ = chart;
783/// ```
784pub fn line_chart(series: impl Fn() -> Vec<Series> + 'static) -> Chart {
785    Chart::new(Data::Lines(Box::new(series), Mark::Line))
786}
787
788/// A line chart filled down to zero under each line: totals over time.
789pub fn area_chart(series: impl Fn() -> Vec<Series> + 'static) -> Chart {
790    Chart::new(Data::Lines(Box::new(series), Mark::Area))
791}
792
793/// Points without lines: how two values relate. Hovering shows the point
794/// nearest the pointer.
795pub fn scatter_chart(series: impl Fn() -> Vec<Series> + 'static) -> Chart {
796    Chart::new(Data::Lines(Box::new(series), Mark::Points))
797}
798
799/// Shares of a whole as slices, with a legend of names, values and
800/// percentages. [`donut`](Chart::donut) makes a ring with the total in its
801/// middle. Values of zero or less are left out.
802///
803/// ```no_run
804/// use ferrokit::*;
805///
806/// let chart = pie_chart(|| vec![("Rent".to_string(), 1200.0), ("Food".to_string(), 420.0)]).donut();
807/// # let _ = chart;
808/// ```
809pub fn pie_chart(data: impl Fn() -> Vec<(String, f64)> + 'static) -> Chart {
810    Chart::new(Data::Pie(Box::new(data)))
811}
812
813/// How many values fall in each range: bars side by side over round-number
814/// bins (about 10, or [`bins`](Chart::bins)). The values print with
815/// [`value_format`](Chart::value_format); hovering a bar shows its range
816/// and count.
817///
818/// ```no_run
819/// use ferrokit::*;
820///
821/// let minutes = vec![12.0, 18.0, 25.0, 31.0, 33.0, 47.0, 52.0];
822/// let chart = histogram(move || minutes.clone()).bins(5).rule(Rule::x(30.0).label("Average"));
823/// # let _ = chart;
824/// ```
825pub fn histogram(values: impl Fn() -> Vec<f64> + 'static) -> Chart {
826    Chart::new(Data::Histogram(Box::new(values)))
827}
828
829/// A grid of cells shaded by their values: `(column, row, value)`, with
830/// rows and columns in the order they first appear. A missing cell stays
831/// empty; hovering shows a cell's value, and a scale from the lowest to
832/// the highest is drawn above (unless [`no_legend`](Chart::no_legend)).
833/// The shade is the first of [`colors`](Chart::colors), else blue.
834///
835/// ```no_run
836/// use ferrokit::*;
837///
838/// let days = ["Mon", "Tue", "Wed"];
839/// let chart = heatmap(move || {
840///     let mut cells = Vec::new();
841///     for hour in 9..17 {
842///         for (d, day) in days.iter().enumerate() {
843///             cells.push((format!("{hour}"), day.to_string(), ((hour * 7 + d * 3) % 10) as f64));
844///         }
845///     }
846///     cells
847/// });
848/// # let _ = chart;
849/// ```
850pub fn heatmap(cells: impl Fn() -> Vec<(String, String, f64)> + 'static) -> Chart {
851    Chart::new(Data::Heatmap(Box::new(cells)))
852}
853
854/// A small line with no axes, its last value marked: a trend beside a
855/// number or in a row. It takes the width it's given at a fixed height (80
856/// × 24 unless [`min_size`](Chart::min_size) says). A [`Rule::y`] draws a
857/// faint target line.
858///
859/// ```no_run
860/// use ferrokit::*;
861///
862/// let week = vec![3.0, 5.0, 4.0, 7.0, 6.0, 8.0, 9.0];
863/// let trend = sparkline(move || week.clone()).colors(&[Color::Green]);
864/// # let _ = trend;
865/// ```
866pub fn sparkline(values: impl Fn() -> Vec<f64> + 'static) -> Chart {
867    Chart { min: Some((80.0, 24.0)), ..Chart::new(Data::Spark(Box::new(values))) }
868}
869
870fn bars(data: Box<dyn Fn() -> Vec<(String, f64)>>, o: Rc<Options>) -> Canvas {
871    let o3 = o.clone();
872    let data = hold(data);
873    let hover = Signal::new(None::<(f64, f64)>);
874    let o2 = o.clone();
875    let hit: Hit = Rc::default();
876    let h2 = hit.clone();
877    let c = canvas(move |p| {
878        let Some(bars) = data.get().filter(|b| !b.is_empty()) else { return no_data(p) };
879        let lo = bars.iter().map(|b| b.1).fold(0.0, f64::min);
880        let hi = bars.iter().map(|b| b.1).fold(0.0, f64::max);
881        let (lo, hi) = with_rules(&o, false, lo, hi);
882        let (plot, to_y) = y_axis(p, lo, hi, 10.0, 22.0, &o.values);
883        let n = bars.len() as f64;
884        let slot = plot.w / n;
885        let bar_w = (slot * 0.75).max(1.0);
886        let zero = to_y(0.0);
887        let hovered = hover.get().filter(|&(x, y)| x >= plot.x && x < plot.x + plot.w && y >= 0.0).map(|(x, _)| ((x - plot.x) / slot) as usize);
888        let (px, py, ph, count) = (plot.x, plot.y, plot.h, bars.len());
889        *h2.borrow_mut() = Some(Rc::new(move |x, y| (x >= px && y >= py && y <= py + ph).then(|| ((x - px) / slot) as usize).filter(|i| *i < count)));
890        let base = o.colors.first().copied();
891        for (i, (_, v)) in bars.iter().enumerate() {
892            let x = plot.x + i as f64 * slot + (slot - bar_w) / 2.0;
893            let (top, bottom) = (to_y(*v).min(zero), to_y(*v).max(zero));
894            let lit = hovered == Some(i);
895            let color = match base {
896                None if lit => Color::Indigo,
897                None => Color::Blue,
898                Some(c) => c,
899            };
900            p.set_opacity(o.emphasis(i) * if lit && base.is_some() { 0.75 } else { 1.0 });
901            p.fill_rect(x, top, bar_w, (bottom - top).max(0.5), color);
902            p.set_opacity(1.0);
903        }
904        category_labels(p, &plot, bars.iter().map(|b| b.0.as_str()));
905        p.line(plot.x, zero, plot.x + plot.w, zero, Color::Secondary, 1.0);
906        draw_rules(p, &o, &plot, &to_y, None);
907        if let Some((i, (x, y))) = hovered.zip(hover.get()).filter(|(i, _)| *i < bars.len()) {
908            tooltip(p, x, y, &[format!("{}: {}", bars[i].0, o.values.value(bars[i].1))]);
909        }
910    })
911    .on_hover(move |at| hover.set(at))
912    .description(move || {
913        let bars = data.get().unwrap_or_default();
914        let max = bars.iter().max_by(|a, b| a.1.total_cmp(&b.1));
915        let min = bars.iter().min_by(|a, b| a.1.total_cmp(&b.1));
916        match (min, max) {
917            (Some(min), Some(max)) => {
918                let rules = rules_text(&o2, &o2.x, &o2.values);
919                let selected = selected_text(&o2, |i| bars.get(i).map(|b| format!("{} ({})", b.0, o2.values.value(b.1))));
920                format!("Bar chart, {} bars, from {} ({}) to {} ({}){rules}{selected}", bars.len(), o2.values.value(min.1), min.0, o2.values.value(max.1), max.0)
921            }
922            _ => "Bar chart, no data".into(),
923        }
924    });
925    selectable(c, &o3, &hit)
926}
927
928/// Category labels under the bars: every k-th one so they don't overlap.
929fn category_labels<'a>(p: &mut Painter, plot: &Plot, labels: impl Iterator<Item = &'a str> + Clone) {
930    let n = labels.clone().count().max(1);
931    let slot = plot.w / n as f64;
932    let widest = labels.clone().map(|l| p.measure(l, FONT).0).fold(0.0, f64::max) + 6.0;
933    let every = ((widest / slot).ceil() as usize).max(1);
934    for (i, label) in labels.enumerate().step_by(every) {
935        p.text(plot.x + (i as f64 + 0.5) * slot, plot.y + plot.h + 4.0, label, FONT, Color::Secondary, Align::Center);
936    }
937}
938
939fn stacked(data: Box<dyn Fn() -> Vec<(String, Vec<f64>)>>, o: Rc<Options>) -> Canvas {
940    let o3 = o.clone();
941    let data = hold(data);
942    let hover = Signal::new(None::<(f64, f64)>);
943    let o2 = o.clone();
944    let hit: Hit = Rc::default();
945    let h2 = hit.clone();
946    let name = |o: &Options, j: usize| o.names.get(j).cloned().unwrap_or_else(|| format!("Series {}", j + 1));
947    let c = canvas(move |p| {
948        let Some(rows) = data.get().filter(|b| !b.is_empty()) else { return no_data(p) };
949        let series = rows.iter().map(|r| r.1.len()).max().unwrap_or(0);
950        let items: Vec<(String, Color)> = (0..series).map(|j| (name(&o, j), o.color(j))).collect();
951        let top = 10.0 + if o.legend && series > 1 { legend(p, &items, 8.0, 2.0, p.width() - 16.0) } else { 0.0 };
952        // The range: sums of the positive and negative parts when stacked.
953        let (mut lo, mut hi) = (0.0f64, 0.0f64);
954        for (_, vs) in rows.iter() {
955            if o.grouped {
956                vs.iter().for_each(|v| (lo, hi) = (lo.min(*v), hi.max(*v)));
957            } else {
958                hi = hi.max(vs.iter().filter(|v| **v > 0.0).sum());
959                lo = lo.min(vs.iter().filter(|v| **v < 0.0).sum());
960            }
961        }
962        let (lo, hi) = with_rules(&o, false, lo, hi);
963        let (plot, to_y) = y_axis(p, lo, hi, top, 22.0, &o.values);
964        let slot = plot.w / rows.len() as f64;
965        let bar_w = (slot * 0.75).max(1.0);
966        let zero = to_y(0.0);
967        let hovered = hover.get().filter(|&(x, y)| x >= plot.x && x < plot.x + plot.w && y >= plot.y).map(|(x, _)| ((x - plot.x) / slot) as usize);
968        let (px, py, ph, count) = (plot.x, plot.y, plot.h, rows.len());
969        *h2.borrow_mut() = Some(Rc::new(move |x, y| (x >= px && y >= py && y <= py + ph).then(|| ((x - px) / slot) as usize).filter(|i| *i < count)));
970        for (i, (_, vs)) in rows.iter().enumerate() {
971            let x = plot.x + i as f64 * slot + (slot - bar_w) / 2.0;
972            if hovered == Some(i) {
973                p.set_opacity(0.08);
974                p.fill_rect(plot.x + i as f64 * slot, plot.y, slot, plot.h, Color::Primary);
975                p.set_opacity(1.0);
976            }
977            let (mut up, mut down) = (0.0, 0.0);
978            for (j, v) in vs.iter().enumerate() {
979                let (a, b, bx, bw) = if o.grouped {
980                    let w = bar_w / vs.len().max(1) as f64;
981                    (0.0, *v, x + j as f64 * w, (w - 1.0).max(1.0))
982                } else if *v >= 0.0 {
983                    up += v;
984                    (up - v, up, x, bar_w)
985                } else {
986                    down += v;
987                    (down - v, down, x, bar_w)
988                };
989                let (y1, y2) = (to_y(a), to_y(b));
990                p.set_opacity(o.emphasis(i));
991                p.fill_rect(bx, y1.min(y2), bw, (y1 - y2).abs().max(0.5), o.color(j));
992                p.set_opacity(1.0);
993            }
994        }
995        category_labels(p, &plot, rows.iter().map(|r| r.0.as_str()));
996        p.line(plot.x, zero, plot.x + plot.w, zero, Color::Secondary, 1.0);
997        draw_rules(p, &o, &plot, &to_y, None);
998        if let Some((i, (x, y))) = hovered.zip(hover.get()).filter(|(i, _)| *i < rows.len()) {
999            let (label, vs) = &rows[i];
1000            let mut lines = vec![label.clone()];
1001            lines.extend(vs.iter().enumerate().map(|(j, v)| format!("{}: {}", name(&o, j), o.values.value(*v))));
1002            if !o.grouped && vs.len() > 1 {
1003                lines.push(format!("{}: {}", crate::t("Total"), o.values.value(vs.iter().sum())));
1004            }
1005            tooltip(p, x, y, &lines);
1006        }
1007    })
1008    .on_hover(move |at| hover.set(at))
1009    .description(move || {
1010        let rows = data.get().unwrap_or_default();
1011        if rows.is_empty() {
1012            return "Bar chart, no data".into();
1013        }
1014        let series = rows.iter().map(|r| r.1.len()).max().unwrap_or(0);
1015        let names: Vec<String> = (0..series).map(|j| name(&o2, j)).collect();
1016        let totals: Vec<(String, f64)> = rows.iter().map(|(l, vs)| (l.clone(), vs.iter().sum())).collect();
1017        let max = totals.iter().max_by(|a, b| a.1.total_cmp(&b.1)).unwrap();
1018        format!(
1019            "{} bar chart of {}, {} categories; the largest total is {} ({}){}{}",
1020            if o2.grouped { "Grouped" } else { "Stacked" },
1021            names.join(", "),
1022            rows.len(),
1023            o2.values.value(max.1),
1024            max.0,
1025            rules_text(&o2, &o2.x, &o2.values),
1026            selected_text(&o2, |i| totals.get(i).map(|t| format!("{} ({})", t.0, o2.values.value(t.1))))
1027        )
1028    });
1029    selectable(c, &o3, &hit)
1030}
1031
1032/// A line chart's layout as last drawn, for clicks, scrolling and pinching.
1033#[derive(Clone, Copy, Default)]
1034struct Layout {
1035    plot: (f64, f64, f64, f64),
1036    /// The x range of all the data (and rules down).
1037    full: (f64, f64),
1038    /// The x range shown.
1039    shown: (f64, f64),
1040}
1041
1042/// The point of a sorted series nearest `at` in x.
1043fn nearest(points: &[(f64, f64)], at: f64) -> Option<(f64, f64)> {
1044    let j = points.partition_point(|q| q.0 < at);
1045    [j.wrapping_sub(1), j].into_iter().filter_map(|k| points.get(k)).min_by(|a, b| (a.0 - at).abs().total_cmp(&(b.0 - at).abs())).copied()
1046}
1047
1048fn lines(series: Box<dyn Fn() -> Vec<Series>>, mark: Mark, o: Rc<Options>) -> Canvas {
1049    let data = hold(move || {
1050        series()
1051            .into_iter()
1052            .map(|s| {
1053                let mut points: Vec<(f64, f64)> = s.points.into_iter().filter(|(x, y)| x.is_finite() && y.is_finite()).collect();
1054                if !points.is_sorted_by(|a, b| a.0 <= b.0) {
1055                    points.sort_by(|a, b| a.0.total_cmp(&b.0));
1056                }
1057                Prepared { name: s.name, points, color: s.color }
1058            })
1059            .collect::<Vec<_>>()
1060    });
1061    let hover = Signal::new(None::<(f64, f64)>);
1062    // The decimated lines, for the data, plot width and x range they were made for.
1063    type Cache = Option<((usize, i64, u64, u64), Rc<Vec<Vec<(f64, f64)>>>)>;
1064    let cache: Rc<RefCell<Cache>> = Rc::default();
1065    let layout: Rc<std::cell::Cell<Layout>> = Rc::default();
1066    let o2 = o.clone();
1067    let o3 = o.clone();
1068    let lay = layout.clone();
1069    let range = o.x_range;
1070    let c = canvas(move |p| {
1071        let Some(all) = data.get() else { return no_data(p) };
1072        let points = || all.iter().flat_map(|s| s.points.iter());
1073        if points().next().is_none() {
1074            return no_data(p);
1075        }
1076        let color = |i: usize| all[i].color.unwrap_or_else(|| o.color(i));
1077        let full = points().fold((f64::MAX, f64::MIN), |(a, b), &(x, _)| (a.min(x), b.max(x)));
1078        let full = with_rules(&o, true, full.0, full.1);
1079        // Zoomed in: the points within the range (and where lines cross
1080        // its ends); the value axis fits them.
1081        let zoom = range.and_then(|r| r.get()).and_then(|r| clamp_range(r, full));
1082        let (x0, x1) = zoom.unwrap_or(full);
1083        let shown: Option<Vec<Vec<(f64, f64)>>> = zoom.map(|(a, b)| all.iter().map(|s| visible(&s.points, a, b, mark != Mark::Points)).collect());
1084        let series_points = |i: usize| -> &[(f64, f64)] { shown.as_ref().map_or(&all[i].points, |v| &v[i]) };
1085        let in_view = || (0..all.len()).flat_map(|i| series_points(i).iter());
1086        let (y0, y1) = in_view().fold((f64::MAX, f64::MIN), |(a, b), &(_, y)| (a.min(y), b.max(y)));
1087        let (mut y0, mut y1) = if y0 > y1 { (0.0, 1.0) } else { (y0, y1) };
1088        if mark == Mark::Area {
1089            y0 = y0.min(0.0); // areas fill down to zero
1090        }
1091        (y0, y1) = with_rules(&o, false, y0, y1);
1092        let items: Vec<(String, Color)> = all.iter().enumerate().map(|(i, s)| (s.name.clone(), color(i))).collect();
1093        let top = 10.0 + if o.legend && all.len() > 1 { legend(p, &items, 8.0, 2.0, p.width() - 16.0) } else { 0.0 };
1094        let (plot, to_y) = y_axis(p, y0, y1, top, 22.0, &o.values);
1095        lay.set(Layout { plot: (plot.x, plot.y, plot.w, plot.h), full, shown: (x0, x1) });
1096        let span = (x1 - x0).max(f64::MIN_POSITIVE);
1097        let to_x = |x: f64| plot.x + (x - x0) / span * plot.w;
1098        // X ticks: dates on whole days, months…; numbers on round values.
1099        let target = (plot.w / 90.0).clamp(2.0, 10.0) as usize;
1100        let xticks: Vec<(f64, String)> = if o.x.is_date() {
1101            let (ts, template) = date_ticks(x0, x1, target, &local_offset);
1102            ts.into_iter().map(|t| (t, date_text(t, template))).collect()
1103        } else {
1104            let (xt, xstep) = ticks(x0, x1, target);
1105            xt.into_iter().filter(|t| *t >= x0 - xstep * 1e-9 && *t <= x1 + xstep * 1e-9).map(|t| (t, o.x.tick(t, xstep))).collect()
1106        };
1107        for (t, label) in &xticks {
1108            p.text(to_x(*t), plot.y + plot.h + 4.0, label, FONT, Color::Secondary, Align::Center);
1109        }
1110        // Lines, decimated once per data, width and range.
1111        let key = (Rc::as_ptr(&all) as usize, plot.w.round() as i64, x0.to_bits(), x1.to_bits());
1112        let lines = {
1113            let mut c = cache.borrow_mut();
1114            match c.as_ref() {
1115                Some((k, lines)) if *k == key => lines.clone(),
1116                _ => {
1117                    let lines = Rc::new((0..all.len()).map(|i| decimate(series_points(i), x0, x1 + span * 1e-9, plot.w.ceil() as usize)).collect::<Vec<_>>());
1118                    *c = Some((key, lines.clone()));
1119                    lines
1120                }
1121            }
1122        };
1123        let base = to_y(0.0_f64.clamp(y0, y1)).min(plot.y + plot.h);
1124        for (i, line) in lines.iter().enumerate() {
1125            let mapped: Vec<(f64, f64)> = line.iter().map(|&(x, y)| (to_x(x), to_y(y))).collect();
1126            let c = color(i);
1127            match mark {
1128                Mark::Points => mapped.iter().for_each(|&(x, y)| p.fill_circle(x, y, 3.0, c)),
1129                Mark::Line | Mark::Area => {
1130                    if mark == Mark::Area && mapped.len() > 1 {
1131                        let mut shape = mapped.clone();
1132                        shape.push((mapped.last().unwrap().0, base));
1133                        shape.push((mapped[0].0, base));
1134                        p.set_opacity(0.22);
1135                        p.fill_polygon(&shape, c);
1136                        p.set_opacity(1.0);
1137                    }
1138                    if mapped.len() == 1 {
1139                        p.fill_circle(mapped[0].0, mapped[0].1, 2.5, c);
1140                    }
1141                    p.polyline(&mapped, c, if mark == Mark::Area { 2.0 } else { 1.5 });
1142                }
1143            }
1144        }
1145        draw_rules(p, &o, &plot, &to_y, Some(&to_x));
1146        // The selected x: a line down, each series' value marked.
1147        if let Some(sx) = o.x_selection.and_then(|s| s.get()).filter(|x| *x >= x0 && *x <= x1) {
1148            let hx = to_x(sx);
1149            p.line(hx, plot.y, hx, plot.y + plot.h, Color::Accent, 1.5);
1150            for (i, s) in all.iter().enumerate() {
1151                if let Some((x, y)) = nearest(&s.points, sx).filter(|q| mark != Mark::Points || q.0 == sx) {
1152                    p.fill_circle(to_x(x), to_y(y), 4.5, Color::Background);
1153                    p.fill_circle(to_x(x), to_y(y), 3.5, color(i));
1154                }
1155            }
1156            let label = o.x.value(sx);
1157            let end = hx + 5.0 + p.measure(&label, FONT).0 > plot.x + plot.w;
1158            rule_label(p, if end { hx - 5.0 } else { hx + 5.0 }, plot.y + 1.0, &label, Color::Accent, if end { Align::End } else { Align::Start });
1159        }
1160        let Some((hx, hy)) = hover.get().filter(|&(x, _)| x >= plot.x && x <= plot.x + plot.w) else { return };
1161        if mark == Mark::Points {
1162            // The point nearest the pointer, if it's close.
1163            let near = (0..all.len())
1164                .flat_map(|i| series_points(i).iter().map(move |q| (i, *q)))
1165                .map(|(i, (x, y))| (i, x, y, (to_x(x) - hx).hypot(to_y(y) - hy)))
1166                .min_by(|a, b| a.3.total_cmp(&b.3))
1167                .filter(|n| n.3 < 14.0);
1168            if let Some((i, x, y, _)) = near {
1169                p.stroke_circle(to_x(x), to_y(y), 5.5, color(i), 2.0);
1170                let mut lines = vec![format!("{}: {}", crate::t("x"), o.x.value(x)), format!("{}: {}", crate::t("y"), o.values.value(y))];
1171                if all.len() > 1 {
1172                    lines.insert(0, all[i].name.clone());
1173                }
1174                tooltip(p, hx, hy, &lines);
1175            }
1176            return;
1177        }
1178        // The values under the pointer.
1179        let at = x0 + (hx - plot.x) / plot.w * span;
1180        p.line(hx, plot.y, hx, plot.y + plot.h, Color::Secondary, 1.0);
1181        let mut lines = Vec::new();
1182        let mut nearest_x = None;
1183        for (i, s) in all.iter().enumerate() {
1184            if let Some((x, y)) = nearest(&s.points, at) {
1185                p.fill_circle(to_x(x), to_y(y), 3.5, color(i));
1186                nearest_x.get_or_insert(x);
1187                lines.push(if all.len() > 1 { format!("{}: {}", s.name, o.values.value(y)) } else { o.values.value(y) });
1188            }
1189        }
1190        if let Some(x) = nearest_x {
1191            lines.insert(0, if o.x == Format::Number { format!("x = {}", value_label(x)) } else { o.x.value(x) });
1192        }
1193        tooltip(p, hx, hy, &lines);
1194    })
1195    .on_hover(move |at| hover.set(at))
1196    .description(move || {
1197        let o = &o2;
1198        let all = data.get().unwrap_or_default();
1199        let n: usize = all.iter().map(|s| s.points.len()).sum();
1200        let pts = || all.iter().flat_map(|s| s.points.iter());
1201        let kind = match mark {
1202            Mark::Line => "Line chart",
1203            Mark::Area => "Area chart",
1204            Mark::Points => "Scatter chart",
1205        };
1206        if n == 0 {
1207            return format!("{kind}, no data");
1208        }
1209        let (x0, x1) = pts().fold((f64::MAX, f64::MIN), |(a, b), &(x, _)| (a.min(x), b.max(x)));
1210        let (y0, y1) = pts().fold((f64::MAX, f64::MIN), |(a, b), &(_, y)| (a.min(y), b.max(y)));
1211        let names: Vec<&str> = all.iter().map(|s| s.name.as_str()).collect();
1212        let zoom = range.and_then(|r| r.get()).and_then(|r| clamp_range(r, with_rules(o, true, x0, x1)));
1213        let zoom = zoom.map(|(a, b)| format!("; showing x from {} to {}", o.x.value(a), o.x.value(b))).unwrap_or_default();
1214        let selected = o.x_selection.and_then(|s| s.get()).map(|x| format!("; selected x {}", o.x.value(x))).unwrap_or_default();
1215        format!(
1216            "{kind} of {}, {n} points, x from {} to {}, values from {} to {}{}{zoom}{selected}",
1217            names.join(", "),
1218            o.x.value(x0),
1219            o.x.value(x1),
1220            o.values.value(y0),
1221            o.values.value(y1),
1222            rules_text(o, &o.x, &o.values)
1223        )
1224    });
1225    // Clicking selects the nearest x (a scatter chart's point under the pointer).
1226    let c = match o3.x_selection {
1227        Some(selection) => {
1228            let lay = layout.clone();
1229            c.on_click(move |x, y| {
1230                let l = lay.get();
1231                let (px, py, pw, ph) = l.plot;
1232                let inside = x >= px && x <= px + pw && y >= py && y <= py + ph;
1233                let all = data.get_untracked().unwrap_or_default();
1234                let at = l.shown.0 + (x - px) / pw.max(1.0) * (l.shown.1 - l.shown.0);
1235                let picked = if !inside {
1236                    None
1237                } else if mark == Mark::Points {
1238                    // Within 14 points, as the hover readout finds it.
1239                    let per_x = pw / (l.shown.1 - l.shown.0).max(f64::MIN_POSITIVE);
1240                    all.iter().flat_map(|s| s.points.iter()).filter(|q| ((q.0 - at) * per_x).abs() < 14.0).min_by(|a, b| (a.0 - at).abs().total_cmp(&(b.0 - at).abs())).map(|q| q.0)
1241                } else {
1242                    all.iter().filter_map(|s| nearest(&s.points, at)).min_by(|a, b| (a.0 - at).abs().total_cmp(&(b.0 - at).abs())).map(|q| q.0)
1243                };
1244                selection.set(picked);
1245            })
1246        }
1247        None => c,
1248    };
1249    let Some(range) = range.filter(|_| o3.zoomable) else { return c };
1250    let (l1, l2) = (layout.clone(), layout);
1251    // The range as it is now (the drawing may not have caught up).
1252    let shown = move |l: Layout| range.get_untracked().and_then(|r| clamp_range(r, l.full)).unwrap_or(l.full);
1253    c.on_magnify(move |amount, x, _| {
1254        let l = l1.get();
1255        let (a, b) = shown(l);
1256        let factor = (1.0 + amount).max(0.1);
1257        let anchor = a + ((x - l.plot.0) / l.plot.2.max(1.0)).clamp(0.0, 1.0) * (b - a);
1258        range.set(clamp_range((anchor - (anchor - a) / factor, anchor + (b - anchor) / factor), l.full));
1259        true
1260    })
1261    .on_scroll(move |dx, dy, _, _| {
1262        // Sideways scrolling moves along a zoomed chart; the rest scrolls on.
1263        let l = l2.get();
1264        let (a, b) = shown(l);
1265        if dx.abs() <= dy.abs() || (a, b) == l.full {
1266            return false;
1267        }
1268        let shift = -dx / l.plot.2.max(1.0) * (b - a);
1269        range.set(clamp_range((a + shift, b + shift), l.full));
1270        true
1271    })
1272}
1273
1274/// The points of an arc around `(cx, cy)` from angle `a0` to `a1`
1275/// (radians, clockwise from three o'clock on screen).
1276fn arc(cx: f64, cy: f64, r: f64, a0: f64, a1: f64) -> Vec<(f64, f64)> {
1277    let steps = (((a1 - a0).abs() / std::f64::consts::TAU) * 96.0).ceil().max(2.0) as usize;
1278    (0..=steps).map(|k| a0 + (a1 - a0) * k as f64 / steps as f64).map(|a| (cx + r * a.cos(), cy + r * a.sin())).collect()
1279}
1280
1281fn pie(data: Box<dyn Fn() -> Vec<(String, f64)>>, o: Rc<Options>) -> Canvas {
1282    let o3 = o.clone();
1283    // Empty slices aren't drawn, but each slice keeps its index in the data:
1284    // for its colour and for the selection.
1285    let data = hold(move || data().into_iter().enumerate().filter(|(_, (_, v))| *v > 0.0 && v.is_finite()).map(|(k, (n, v))| (k, n, v)).collect::<Vec<_>>());
1286    let hover = Signal::new(None::<(f64, f64)>);
1287    let o2 = o.clone();
1288    let hit: Hit = Rc::default();
1289    let h2 = hit.clone();
1290    let c = canvas(move |p| {
1291        let Some(slices) = data.get().filter(|s| !s.is_empty()) else { return no_data(p) };
1292        let total: f64 = slices.iter().map(|s| s.2).sum();
1293        let percent = |v: f64| Format::Percent.value((v / total * 1000.0).round() / 1000.0);
1294        // The legend on the right: swatch, name, value and share.
1295        let entries: Vec<String> = slices.iter().map(|(_, n, v)| format!("{n}  {} ({})", o.values.value(*v), percent(*v))).collect();
1296        let legend_w = if o.legend { entries.iter().map(|e| p.measure(e, FONT).0).fold(0.0, f64::max) + 30.0 } else { 0.0 };
1297        let r = ((p.width() - legend_w - 16.0).min(p.height() - 16.0) / 2.0).max(4.0);
1298        let (cx, cy) = (8.0 + r, p.height() / 2.0);
1299        let inner = if o.donut { r * 0.58 } else { 0.0 };
1300        let start = -std::f64::consts::FRAC_PI_2;
1301        // The slice under a point.
1302        let ends: Vec<f64> = slices
1303            .iter()
1304            .scan(0.0, |acc, s| {
1305                *acc += s.2 / total * std::f64::consts::TAU;
1306                Some(*acc)
1307            })
1308            .collect();
1309        let under = move |x: f64, y: f64| {
1310            let d = (x - cx).hypot(y - cy);
1311            if d > r || d < inner {
1312                return None;
1313            }
1314            let a = ((y - cy).atan2(x - cx) - start).rem_euclid(std::f64::consts::TAU);
1315            ends.iter().position(|e| a < *e)
1316        };
1317        let hovered = hover.get().and_then(|(x, y)| under(x, y));
1318        let keys: Vec<usize> = slices.iter().map(|s| s.0).collect();
1319        *h2.borrow_mut() = Some(Rc::new(move |x, y| under(x, y).map(|i| keys[i])));
1320        let mut a = start;
1321        for (i, &(k, _, v)) in slices.iter().enumerate() {
1322            let sweep = v / total * std::f64::consts::TAU;
1323            // The hovered (or selected) slice moves out a little.
1324            let (dx, dy) = if hovered == Some(i) || o.selected() == Some(k) { let m = a + sweep / 2.0; (4.0 * m.cos(), 4.0 * m.sin()) } else { (0.0, 0.0) };
1325            let mut shape = arc(cx + dx, cy + dy, r, a, a + sweep);
1326            if inner > 0.0 {
1327                shape.extend(arc(cx + dx, cy + dy, inner, a + sweep, a));
1328            } else {
1329                shape.push((cx + dx, cy + dy));
1330            }
1331            p.set_opacity(o.emphasis(k));
1332            p.fill_polygon(&shape, o.color(k));
1333            p.set_opacity(1.0);
1334            // A thin gap between slices.
1335            if slices.len() > 1 {
1336                p.line(cx + inner * a.cos(), cy + inner * a.sin(), cx + r * a.cos(), cy + r * a.sin(), Color::Background, 1.5);
1337            }
1338            a += sweep;
1339        }
1340        if inner > 0.0 {
1341            let total_text = o.values.value(total);
1342            p.bold_text(cx, cy - FONT * 1.2, &total_text, FONT + 4.0, Color::Primary, Align::Center);
1343            p.text(cx, cy + 4.0, &crate::t("Total"), FONT, Color::Secondary, Align::Center);
1344        }
1345        if o.legend {
1346            let x = cx + r + 22.0;
1347            let mut y = (cy - slices.len() as f64 * (FONT + 7.0) / 2.0).max(4.0);
1348            for (i, e) in entries.iter().enumerate() {
1349                p.fill_rounded_rect(x, y + 2.0, 10.0, 10.0, 2.0, o.color(slices[i].0));
1350                p.text(x + 16.0, y, e, FONT, if hovered == Some(i) { Color::Primary } else { Color::Secondary }, Align::Start);
1351                y += FONT + 7.0;
1352            }
1353        }
1354        if let Some((i, (x, y))) = hovered.zip(hover.get()) {
1355            tooltip(p, x, y, &[format!("{}: {} ({})", slices[i].1, o.values.value(slices[i].2), percent(slices[i].2))]);
1356        }
1357    })
1358    .on_hover(move |at| hover.set(at))
1359    .description(move || {
1360        let slices = data.get().unwrap_or_default();
1361        if slices.is_empty() {
1362            return "Pie chart, no data".into();
1363        }
1364        let total: f64 = slices.iter().map(|s| s.2).sum();
1365        let parts: Vec<String> = slices.iter().map(|(_, n, v)| format!("{n} {}", Format::Percent.value((v / total * 1000.0).round() / 1000.0))).collect();
1366        let selected = selected_text(&o2, |k| slices.iter().find(|s| s.0 == k).map(|s| format!("{} ({})", s.1, o2.values.value(s.2))));
1367        format!("{} chart, {} slices, total {}: {}{selected}", if o2.donut { "Donut" } else { "Pie" }, slices.len(), o2.values.value(total), parts.join(", "))
1368    });
1369    selectable(c, &o3, &hit)
1370}
1371
1372/// `values` sorted into bins on round-number edges, about `target` of
1373/// them: the edges (one more than the bins) and the count in each. A value
1374/// on the last edge counts in the last bin.
1375pub(crate) fn bin(values: &[f64], target: usize) -> (Vec<f64>, Vec<usize>) {
1376    let finite: Vec<f64> = values.iter().copied().filter(|v| v.is_finite()).collect();
1377    if finite.is_empty() {
1378        return (Vec::new(), Vec::new());
1379    }
1380    let (lo, hi) = finite.iter().fold((f64::MAX, f64::MIN), |(a, b), &v| (a.min(v), b.max(v)));
1381    let (mut edges, step) = ticks(lo, hi, target);
1382    if edges.len() < 2 {
1383        edges.push(edges[0] + step);
1384    }
1385    let n = edges.len() - 1;
1386    let mut counts = vec![0; n];
1387    for v in finite {
1388        counts[(((v - edges[0]) / step).floor().max(0.0) as usize).min(n - 1)] += 1;
1389    }
1390    (edges, counts)
1391}
1392
1393fn histogram_canvas(values: Box<dyn Fn() -> Vec<f64>>, o: Rc<Options>) -> Canvas {
1394    let o3 = o.clone();
1395    let bins = o.bins;
1396    let data = hold(move || bin(&values(), bins));
1397    let hover = Signal::new(None::<(f64, f64)>);
1398    let o2 = o.clone();
1399    let hit: Hit = Rc::default();
1400    let h2 = hit.clone();
1401    let c = canvas(move |p| {
1402        let Some(h) = data.get().filter(|h| !h.1.is_empty()) else { return no_data(p) };
1403        let (edges, counts) = (&h.0, &h.1);
1404        let most = counts.iter().copied().max().unwrap_or(0) as f64;
1405        let (lo, hi) = with_rules(&o, false, 0.0, most);
1406        let (plot, to_y) = y_axis(p, lo, hi, 10.0, 22.0, &Format::Number);
1407        let (x0, x1) = (edges[0], edges[counts.len()]);
1408        let to_x = move |x: f64| plot.x + (x - x0) / (x1 - x0) * plot.w;
1409        let n = counts.len();
1410        let hovered = hover.get().filter(|&(x, y)| x >= plot.x && x < plot.x + plot.w && y >= plot.y).map(|(x, _)| (((x - plot.x) / plot.w * n as f64) as usize).min(n - 1));
1411        let (px, pw, py, ph) = (plot.x, plot.w, plot.y, plot.h);
1412        *h2.borrow_mut() = Some(Rc::new(move |x, y| (x >= px && x < px + pw && y >= py && y <= py + ph).then(|| (((x - px) / pw * n as f64) as usize).min(n - 1))));
1413        let color = o.colors.first().copied().unwrap_or(Color::Blue);
1414        let zero = to_y(0.0);
1415        for (i, &c) in counts.iter().enumerate().filter(|(_, c)| **c > 0) {
1416            let (a, b) = (to_x(edges[i]), to_x(edges[i + 1]));
1417            let top = to_y(c as f64);
1418            p.set_opacity(o.emphasis(i) * if hovered == Some(i) { 0.75 } else { 1.0 });
1419            p.fill_rect(a + 0.5, top, (b - a - 1.0).max(0.5), (zero - top).max(0.5), color);
1420            p.set_opacity(1.0);
1421        }
1422        // The edges, every k-th so they don't overlap.
1423        let step = edges[1] - edges[0];
1424        let labels: Vec<String> = edges.iter().map(|e| o.values.tick(*e, step)).collect();
1425        let widest = labels.iter().map(|l| p.measure(l, FONT).0).fold(0.0, f64::max) + 6.0;
1426        let every = ((widest / (plot.w / n as f64)).ceil() as usize).max(1);
1427        for (i, label) in labels.iter().enumerate().step_by(every) {
1428            p.text(to_x(edges[i]), plot.y + plot.h + 4.0, label, FONT, Color::Secondary, Align::Center);
1429        }
1430        p.line(plot.x, zero, plot.x + plot.w, zero, Color::Secondary, 1.0);
1431        draw_rules(p, &o, &plot, &to_y, Some(&to_x));
1432        if let Some((i, (x, y))) = hovered.zip(hover.get()) {
1433            tooltip(p, x, y, &[format!("{} – {}: {}", o.values.value(edges[i]), o.values.value(edges[i + 1]), counts[i])]);
1434        }
1435    })
1436    .on_hover(move |at| hover.set(at))
1437    .description(move || {
1438        let h = data.get().unwrap_or_default();
1439        let (edges, counts) = (&h.0, &h.1);
1440        let Some((i, most)) = counts.iter().enumerate().max_by_key(|(i, c)| (**c, std::cmp::Reverse(*i))) else { return "Histogram, no data".into() };
1441        let v = |x: f64| o2.values.value(x);
1442        format!(
1443            "Histogram of {} values in {} bins from {} to {}; the most, {most}, from {} to {}{}{}",
1444            counts.iter().sum::<usize>(),
1445            counts.len(),
1446            v(edges[0]),
1447            v(edges[counts.len()]),
1448            v(edges[i]),
1449            v(edges[i + 1]),
1450            rules_text(&o2, &o2.values, &Format::Number),
1451            selected_text(&o2, |i| counts.get(i).map(|c| format!("{} to {} ({c})", v(edges[i]), v(edges[i + 1]))))
1452        )
1453    });
1454    selectable(c, &o3, &hit)
1455}
1456
1457/// A heatmap's cells by row and column, in the order they first appeared.
1458#[derive(Default)]
1459struct Cells {
1460    columns: Vec<String>,
1461    rows: Vec<String>,
1462    /// Row by row.
1463    values: Vec<Option<f64>>,
1464}
1465
1466impl Cells {
1467    fn new(cells: Vec<(String, String, f64)>) -> Cells {
1468        let (mut columns, mut rows) = (Vec::new(), Vec::new());
1469        let (mut col_at, mut row_at) = (HashMap::new(), HashMap::new());
1470        let mut found = Vec::new();
1471        for (c, r, v) in cells.into_iter().filter(|c| c.2.is_finite()) {
1472            let ci = *col_at.entry(c.clone()).or_insert_with(|| {
1473                columns.push(c);
1474                columns.len() - 1
1475            });
1476            let ri = *row_at.entry(r.clone()).or_insert_with(|| {
1477                rows.push(r);
1478                rows.len() - 1
1479            });
1480            found.push((ri, ci, v));
1481        }
1482        let mut values = vec![None; rows.len() * columns.len()];
1483        for (r, c, v) in found {
1484            values[r * columns.len() + c] = Some(v);
1485        }
1486        Cells { columns, rows, values }
1487    }
1488
1489    fn range(&self) -> Option<(f64, f64)> {
1490        self.values.iter().flatten().fold(None, |acc, &v| Some(acc.map_or((v, v), |(a, b): (f64, f64)| (a.min(v), b.max(v)))))
1491    }
1492
1493    /// The cell with the lowest (or, with `highest`, the highest) value:
1494    /// its row, column and value.
1495    fn extreme(&self, highest: bool) -> Option<(&str, &str, f64)> {
1496        let n = self.columns.len();
1497        let pick = self.values.iter().enumerate().filter_map(|(i, v)| v.map(|v| (i, v)));
1498        let (i, v) = if highest { pick.max_by(|a, b| a.1.total_cmp(&b.1)) } else { pick.min_by(|a, b| a.1.total_cmp(&b.1)) }?;
1499        Some((&self.rows[i / n], &self.columns[i % n], v))
1500    }
1501}
1502
1503fn heatmap_canvas(cells: Box<dyn Fn() -> Vec<(String, String, f64)>>, o: Rc<Options>) -> Canvas {
1504    let o3 = o.clone();
1505    let data = hold(move || Cells::new(cells()));
1506    let hover = Signal::new(None::<(f64, f64)>);
1507    let o2 = o.clone();
1508    let hit: Hit = Rc::default();
1509    let h2 = hit.clone();
1510    let c = canvas(move |p| {
1511        let Some(g) = data.get().filter(|g| !g.values.is_empty()) else { return no_data(p) };
1512        let Some((lo, hi)) = g.range() else { return no_data(p) };
1513        let color = o.colors.first().copied().unwrap_or(Color::Blue);
1514        let shade = |v: f64| if hi > lo { 0.12 + 0.88 * (v - lo) / (hi - lo) } else { 1.0 };
1515        // The scale above: lowest, five steps, highest.
1516        let mut top = 6.0;
1517        if o.legend {
1518            let (low, high) = (o.values.value(lo), o.values.value(hi));
1519            let mut x = p.width() - 8.0 - p.measure(&high, FONT).0;
1520            p.text(x, 2.0, &high, FONT, Color::Secondary, Align::Start);
1521            for k in (0..5).rev() {
1522                x -= 13.0;
1523                p.set_opacity(0.12 + 0.88 * k as f64 / 4.0);
1524                p.fill_rounded_rect(x, 4.0, 10.0, 10.0, 2.0, color);
1525                p.set_opacity(1.0);
1526            }
1527            p.text(x - 4.0, 2.0, &low, FONT, Color::Secondary, Align::End);
1528            top += FONT + 9.0;
1529        }
1530        let label_w = g.rows.iter().map(|r| p.measure(r, FONT).0).fold(0.0, f64::max);
1531        let plot = Plot { x: label_w + 10.0, y: top, w: (p.width() - label_w - 18.0).max(1.0), h: (p.height() - top - 22.0).max(1.0) };
1532        let (nc, nr) = (g.columns.len(), g.rows.len());
1533        let (cw, ch) = (plot.w / nc as f64, plot.h / nr as f64);
1534        let gap = if cw.min(ch) > 6.0 { 1.5 } else { 0.0 };
1535        let hovered = hover
1536            .get()
1537            .filter(|&(x, y)| x >= plot.x && x < plot.x + plot.w && y >= plot.y && y < plot.y + plot.h)
1538            .map(|(x, y)| ((((y - plot.y) / ch) as usize).min(nr - 1), (((x - plot.x) / cw) as usize).min(nc - 1)));
1539        let (px, py, pw, ph) = (plot.x, plot.y, plot.w, plot.h);
1540        let present: Vec<bool> = g.values.iter().map(Option::is_some).collect();
1541        *h2.borrow_mut() = Some(Rc::new(move |x, y| {
1542            let inside = x >= px && x < px + pw && y >= py && y < py + ph;
1543            let i = (((y - py) / ch) as usize).min(nr - 1) * nc + (((x - px) / cw) as usize).min(nc - 1);
1544            (inside && present.get(i) == Some(&true)).then_some(i)
1545        }));
1546        for (i, v) in g.values.iter().enumerate() {
1547            let Some(v) = v else { continue };
1548            let (r, c) = (i / nc, i % nc);
1549            p.set_opacity(shade(*v) * o.emphasis(i));
1550            p.fill_rect(plot.x + c as f64 * cw + gap / 2.0, plot.y + r as f64 * ch + gap / 2.0, (cw - gap).max(0.5), (ch - gap).max(0.5), color);
1551            p.set_opacity(1.0);
1552        }
1553        // Row labels (every k-th when rows are short), then columns'.
1554        let every = (((FONT + 2.0) / ch).ceil() as usize).max(1);
1555        for (r, label) in g.rows.iter().enumerate().step_by(every) {
1556            p.text(plot.x - 6.0, plot.y + (r as f64 + 0.5) * ch - FONT * 0.65, label, FONT, Color::Secondary, Align::End);
1557        }
1558        category_labels(p, &plot, g.columns.iter().map(String::as_str));
1559        if let Some(((r, c), (x, y))) = hovered.zip(hover.get()) {
1560            p.stroke_rect(plot.x + c as f64 * cw, plot.y + r as f64 * ch, cw, ch, Color::Primary, 1.5);
1561            let value = g.values[r * nc + c].map_or_else(|| crate::t("No value"), |v| o.values.value(v));
1562            tooltip(p, x, y, &[format!("{}, {}: {value}", g.rows[r], g.columns[c])]);
1563        }
1564    })
1565    .on_hover(move |at| hover.set(at))
1566    .description(move || {
1567        let g = data.get().unwrap_or_default();
1568        match (g.extreme(false), g.extreme(true)) {
1569            (Some(lo), Some(hi)) => format!(
1570                "Heatmap, {} rows by {} columns, values from {} ({}, {}) to {} ({}, {})",
1571                g.rows.len(),
1572                g.columns.len(),
1573                o2.values.value(lo.2),
1574                lo.0,
1575                lo.1,
1576                o2.values.value(hi.2),
1577                hi.0,
1578                hi.1
1579            ) + &selected_text(&o2, |i| {
1580                let (n, v) = (g.columns.len(), g.values.get(i).copied().flatten()?);
1581                Some(format!("{}, {} ({})", g.rows[i / n], g.columns[i % n], o2.values.value(v)))
1582            }),
1583            _ => "Heatmap, no data".into(),
1584        }
1585    });
1586    selectable(c, &o3, &hit)
1587}
1588
1589fn spark(values: Box<dyn Fn() -> Vec<f64>>, o: Rc<Options>) -> Canvas {
1590    let data = hold(move || values().into_iter().filter(|v| v.is_finite()).collect::<Vec<f64>>());
1591    let o2 = o.clone();
1592    canvas(move |p| {
1593        // Too small for "No data": an empty sparkline draws nothing.
1594        let Some(vs) = data.get().filter(|v| !v.is_empty()) else { return };
1595        let (lo, hi) = vs.iter().fold((f64::MAX, f64::MIN), |(a, b), &v| (a.min(v), b.max(v)));
1596        let (lo, hi) = with_rules(&o, false, lo, hi);
1597        let pad = 3.0;
1598        let (w, h) = ((p.width() - pad * 2.0).max(1.0), (p.height() - pad * 2.0).max(1.0));
1599        let to_y = move |v: f64| if hi > lo { pad + h - (v - lo) / (hi - lo) * h } else { pad + h / 2.0 };
1600        let last = (vs.len() - 1) as f64;
1601        let to_x = move |i: f64| pad + if last > 0.0 { i / last * w } else { w / 2.0 };
1602        for r in o.rules.iter().filter(|r| !r.vertical) {
1603            p.set_opacity(0.6);
1604            p.line(pad, to_y(r.value), pad + w, to_y(r.value), r.color, 1.0);
1605            p.set_opacity(1.0);
1606        }
1607        let color = o.colors.first().copied().unwrap_or(Color::Blue);
1608        let points: Vec<(f64, f64)> = vs.iter().enumerate().map(|(i, v)| (i as f64, *v)).collect();
1609        let line: Vec<(f64, f64)> = decimate(&points, 0.0, last + 1.0, w.ceil() as usize).into_iter().map(|(i, v)| (to_x(i), to_y(v))).collect();
1610        p.polyline(&line, color, 1.5);
1611        p.fill_circle(to_x(last), to_y(vs[vs.len() - 1]), 2.5, color);
1612    })
1613    .description(move || {
1614        let vs = data.get().unwrap_or_default();
1615        let Some(last) = vs.last() else { return "Sparkline, no data".into() };
1616        let (lo, hi) = vs.iter().fold((f64::MAX, f64::MIN), |(a, b), &v| (a.min(v), b.max(v)));
1617        let v = |x: f64| o2.values.value(x);
1618        format!("Sparkline, {} values from {} to {}, last {}{}", vs.len(), v(lo), v(hi), v(*last), rules_text(&o2, &o2.x, &o2.values))
1619    })
1620    .fixed_height()
1621}
1622
1623#[cfg(test)]
1624mod tests {
1625    use super::*;
1626
1627    #[test]
1628    fn round_ticks() {
1629        assert_eq!(ticks(0.0, 97.0, 5), (vec![0.0, 20.0, 40.0, 60.0, 80.0, 100.0], 20.0));
1630        assert_eq!(ticks(0.0, 1785.24, 5).0.last(), Some(&2000.0));
1631        let (t, step) = ticks(-3.2, 7.9, 4);
1632        assert_eq!((t.first(), t.last(), step), (Some(&-4.0), Some(&8.0), 2.0));
1633        // A flat series still gets an axis.
1634        assert!(ticks(5.0, 5.0, 4).0.len() >= 2);
1635        assert_eq!(ticks(0.0, 0.0, 4).0, vec![0.0, 0.2, 0.4, 0.6000000000000001, 0.8, 1.0]);
1636    }
1637
1638    #[test]
1639    fn labels() {
1640        assert_eq!(tick_label(250_000.0, 50_000.0), "250k");
1641        assert_eq!(tick_label(1_500_000.0, 500_000.0), "1.5M");
1642        assert_eq!(tick_label(0.25, 0.05), "0.25");
1643        assert_eq!(tick_label(-0.0, 1.0), "0");
1644        assert_eq!(value_label(96.25), "96.25");
1645        assert_eq!(value_label(42.0), "42");
1646    }
1647
1648    #[test]
1649    fn civil_dates() {
1650        assert_eq!(days_from_civil(1970, 1, 1), 0);
1651        assert_eq!(days_from_civil(2000, 3, 1), 11_017);
1652        assert_eq!(days_from_civil(2026, 10, 31), 20_757);
1653        for d in [-1000, 0, 59, 11_017, 20_757, 50_000] {
1654            let (y, m) = civil_from_days(d);
1655            assert!(days_from_civil(y, m, 1) <= d && d < days_from_civil(y + i64::from(m == 12), m % 12 + 1, 1), "day {d} in {y}-{m}");
1656        }
1657    }
1658
1659    #[test]
1660    fn date_ticks_fall_on_whole_units() {
1661        const D: f64 = 86_400.0;
1662        let start = days_from_civil(2026, 1, 1) as f64 * D;
1663        // Ten days, UTC: a tick every day or two, at midnight.
1664        let (t, template) = date_ticks(start + 3_600.0, start + 10.0 * D, 6, &|_| 0.0);
1665        assert!(t.iter().all(|t| t % D == 0.0) && t.len() >= 4 && template == "MMMd", "{t:?} {template}");
1666        // In UTC+2, midnights are two hours earlier.
1667        let (t, _) = date_ticks(start, start + 10.0 * D, 6, &|_| 7_200.0);
1668        assert!(t.iter().all(|t| (t + 7_200.0) % D == 0.0), "{t:?}");
1669        // Two years: the first of a month, every 3 or 6 months.
1670        let (t, template) = date_ticks(start, start + 730.0 * D, 6, &|_| 0.0);
1671        let firsts = t.iter().all(|t| {
1672            let day = (t / D) as i64;
1673            let (y, m) = civil_from_days(day);
1674            days_from_civil(y, m, 1) == day
1675        });
1676        assert!(firsts && (4..=9).contains(&t.len()) && template == "MMMy", "{t:?} {template}");
1677        // Daylight saving: an offset of -5 h before day 20_500 and -4 h
1678        // after still puts every tick at local midnight.
1679        let dst = |t: f64| if t < 20_500.0 * D { -18_000.0 } else { -14_400.0 };
1680        let (t, _) = date_ticks(20_490.0 * D, 20_510.0 * D, 10, &dst);
1681        assert!(t.iter().all(|t| (t + dst(*t)) % D == 0.0) && t.len() >= 8, "{t:?}");
1682        // Hours.
1683        let (t, template) = date_ticks(start, start + 6.0 * 3_600.0, 6, &|_| 0.0);
1684        assert!(t.iter().all(|t| t % 3_600.0 == 0.0) && template == "jm", "{t:?}");
1685    }
1686
1687    #[test]
1688    fn bins_on_round_edges() {
1689        let (edges, counts) = bin(&[12.0, 18.0, 25.0, 31.0, 33.0, 47.0, 52.0, f64::NAN], 5);
1690        assert_eq!(edges, vec![10.0, 20.0, 30.0, 40.0, 50.0, 60.0]);
1691        assert_eq!(counts, vec![2, 1, 2, 1, 1]);
1692        // A value on the last edge counts in the last bin.
1693        let (edges, counts) = bin(&[0.0, 5.0, 10.0], 2);
1694        assert_eq!((edges.len() - 1, counts.iter().sum::<usize>(), *counts.last().unwrap() >= 1), (counts.len(), 3, true));
1695        // One value still makes a bin.
1696        assert_eq!(bin(&[4.0], 10).1.iter().sum::<usize>(), 1);
1697        assert_eq!(bin(&[], 10), (vec![], vec![]));
1698    }
1699
1700    #[test]
1701    fn heatmap_cells_by_row_and_column() {
1702        let g = Cells::new(vec![("9".into(), "Mon".into(), 1.0), ("10".into(), "Mon".into(), 4.0), ("9".into(), "Tue".into(), 2.0)]);
1703        assert_eq!((g.columns.clone(), g.rows.clone()), (vec!["9".to_string(), "10".to_string()], vec!["Mon".to_string(), "Tue".to_string()]));
1704        assert_eq!(g.values, vec![Some(1.0), Some(4.0), Some(2.0), None]);
1705        assert_eq!(g.extreme(true), Some(("Mon", "10", 4.0)));
1706        assert_eq!(g.range(), Some((1.0, 4.0)));
1707    }
1708
1709    #[test]
1710    fn ranges_stay_inside_the_data() {
1711        assert_eq!(clamp_range((20.0, 40.0), (0.0, 100.0)), Some((20.0, 40.0)));
1712        // Moved past an end: kept inside, the same width.
1713        assert_eq!(clamp_range((90.0, 110.0), (0.0, 100.0)), Some((80.0, 100.0)));
1714        assert_eq!(clamp_range((40.0, 20.0), (0.0, 100.0)), Some((20.0, 40.0)));
1715        // All of it (or more) is no zoom.
1716        assert_eq!(clamp_range((-10.0, 120.0), (0.0, 100.0)), None);
1717        assert_eq!(clamp_range((f64::NAN, 1.0), (0.0, 100.0)), None);
1718    }
1719
1720    #[test]
1721    fn visible_points_meet_the_edges() {
1722        let pts = [(0.0, 0.0), (10.0, 10.0), (20.0, 0.0)];
1723        assert_eq!(visible(&pts, 5.0, 15.0, true), vec![(5.0, 5.0), (10.0, 10.0), (15.0, 5.0)]);
1724        assert_eq!(visible(&pts, 5.0, 15.0, false), vec![(10.0, 10.0)]);
1725        // A range between two points: the segment across it.
1726        assert_eq!(visible(&pts, 2.0, 4.0, true), vec![(2.0, 2.0), (4.0, 4.0)]);
1727    }
1728
1729    #[test]
1730    fn decimation_keeps_extremes() {
1731        let points: Vec<(f64, f64)> = (0..1_000_000).map(|i| (i as f64, if i == 500_123 { 99.0 } else { (i % 7) as f64 })).collect();
1732        let d = decimate(&points, 0.0, 1_000_000.0, 500);
1733        assert!(d.len() <= 2_000, "{} points", d.len());
1734        assert!(d.contains(&(500_123.0, 99.0)), "the spike survives");
1735        assert_eq!(d.first(), points.first());
1736        assert_eq!(d.last(), points.last());
1737        assert!(d.is_sorted_by(|a, b| a.0 <= b.0));
1738    }
1739}