kazam 1.0.0

Beautiful static sites from simple YAML. One Rust binary, no framework, no npm, no runtime JS.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
//! Build-time SVG chart renderer. Three kinds — pie, bar, timeseries — with an
//! optional second dimension via `series:`. No JS, no runtime deps.
//!
//! Chart colors use the canonical `SemColor` hexes (teal/green/yellow/red)
//! rather than the theme's CSS vars on purpose: themes like `dark` remap
//! `--teal` and `--green` onto the same sage tone, which destroys stack
//! contrast. Charts must stay distinguishable across every theme, so they
//! bypass theme overrides even when the user writes `color: green`.

use super::{esc, Rendered};
use crate::types::{ChartKind, ChartOrientation, ChartPoint, ChartSeries, SemColor};

const VB_W: f64 = 720.0;

/// Bundle of chart render inputs. Mirrors the `Component::Chart` fields —
/// passed as one arg so the entry point isn't a 7-positional-parameter blob.
pub struct ChartSpec<'a> {
    pub kind: ChartKind,
    pub title: &'a Option<String>,
    pub height: Option<u32>,
    pub x_label: &'a Option<String>,
    pub y_label: &'a Option<String>,
    pub orientation: ChartOrientation,
    pub data: &'a Option<Vec<ChartPoint>>,
    pub series: &'a Option<Vec<ChartSeries>>,
}

pub fn render(spec: ChartSpec<'_>) -> Rendered {
    let series_vec = coerce_series(spec.data, spec.series);
    let h = spec.height.unwrap_or_else(|| default_height(spec.kind));
    let aria = spec
        .title
        .clone()
        .unwrap_or_else(|| default_aria(spec.kind));

    let svg = match spec.kind {
        ChartKind::Pie => render_pie(&series_vec, h),
        ChartKind::Bar => render_bar(&series_vec, h, spec.orientation, spec.x_label, spec.y_label),
        ChartKind::Timeseries => render_timeseries(&series_vec, h, spec.x_label, spec.y_label),
    };

    let title_html = spec
        .title
        .as_deref()
        .filter(|s| !s.is_empty())
        .map(|t| {
            format!(
                r#"<figcaption class="c-chart-title">{}</figcaption>"#,
                esc(t)
            )
        })
        .unwrap_or_default();

    let legend = render_legend(spec.kind, &series_vec);

    let html = format!(
        r#"<figure class="c-chart c-chart-{k}" role="img" aria-label="{aria}">{title}{svg}{legend}</figure>"#,
        k = kind_class(spec.kind),
        aria = esc(&aria),
        title = title_html,
        svg = svg,
        legend = legend,
    );

    Rendered::new(html)
}

fn kind_class(k: ChartKind) -> &'static str {
    match k {
        ChartKind::Pie => "pie",
        ChartKind::Bar => "bar",
        ChartKind::Timeseries => "timeseries",
    }
}

fn default_height(k: ChartKind) -> u32 {
    match k {
        ChartKind::Pie => 280,
        ChartKind::Bar => 300,
        ChartKind::Timeseries => 280,
    }
}

fn default_aria(k: ChartKind) -> String {
    match k {
        ChartKind::Pie => "Pie chart".into(),
        ChartKind::Bar => "Bar chart".into(),
        ChartKind::Timeseries => "Time series chart".into(),
    }
}

/// Normalize `data:` / `series:` into a single `Vec<Series>` so the renderers
/// only ever deal with one shape. A lone `data:` becomes a nameless series of
/// index 0; a `series:` list passes through as-is.
struct NormSeries<'a> {
    label: &'a str,
    color: Option<SemColor>,
    points: &'a [ChartPoint],
}

fn coerce_series<'a>(
    data: &'a Option<Vec<ChartPoint>>,
    series: &'a Option<Vec<ChartSeries>>,
) -> Vec<NormSeries<'a>> {
    if let Some(s) = series {
        return s
            .iter()
            .map(|s| NormSeries {
                label: &s.label,
                color: s.color,
                points: &s.points,
            })
            .collect();
    }
    if let Some(d) = data {
        return vec![NormSeries {
            label: "",
            color: None,
            points: d,
        }];
    }
    Vec::new()
}

fn series_color(series_color: Option<SemColor>, idx: usize) -> &'static str {
    let c = series_color.unwrap_or_else(|| cycle_color(idx));
    c.hex()
}

/// Default palette for multi-series charts when the author hasn't set colors.
/// Skips the `Default` alias (which is the same hex as `Teal`) so four
/// consecutive series land on four distinct tones.
fn cycle_color(idx: usize) -> SemColor {
    match idx % 4 {
        0 => SemColor::Teal,
        1 => SemColor::Green,
        2 => SemColor::Yellow,
        _ => SemColor::Red,
    }
}

// ── Pie ──────────────────────────────────────────────

fn render_pie(series: &[NormSeries], height: u32) -> String {
    // Pie is always single-series. If the user accidentally passed `series:`
    // with multiple entries, flatten the first one — matches the "pie = one
    // ring of slices" mental model rather than silently dropping data.
    let Some(first) = series.first() else {
        return empty_svg(height);
    };
    let slices = first.points;
    let total: f64 = slices.iter().map(|p| p.value.max(0.0)).sum();
    if total <= 0.0 || slices.is_empty() {
        return empty_svg(height);
    }

    let h = height as f64;
    let cx = h / 2.0 + 20.0;
    let cy = h / 2.0;
    let r = (h / 2.0) - 16.0;

    let mut out = format!(
        r#"<svg viewBox="0 0 {vb_w} {h}" preserveAspectRatio="xMidYMid meet" class="c-chart-svg">"#,
        vb_w = VB_W,
        h = h,
    );

    // Single 100% slice can't be drawn with an arc (start==end). Draw a
    // circle instead so the fill shows up.
    if slices.len() == 1 {
        let p = &slices[0];
        let fill = series_color(p.color.or(first.color), 0);
        out.push_str(&format!(
            r#"<circle cx="{cx}" cy="{cy}" r="{r}" fill="{fill}"><title>{t}</title></circle>"#,
            cx = cx,
            cy = cy,
            r = r,
            fill = fill,
            t = esc(&format!("{}: {}", p.label, fmt_num(p.value))),
        ));
        out.push_str("</svg>");
        return out;
    }

    let mut angle_acc = 0.0_f64;
    for (i, p) in slices.iter().enumerate() {
        let v = p.value.max(0.0);
        if v <= 0.0 {
            continue;
        }
        let frac = v / total;
        let angle = frac * std::f64::consts::TAU;
        let a0 = angle_acc;
        let a1 = angle_acc + angle;
        let (x0, y0) = polar(cx, cy, r, a0);
        let (x1, y1) = polar(cx, cy, r, a1);
        let large = if angle > std::f64::consts::PI { 1 } else { 0 };
        let fill = series_color(p.color.or(first.color), i);
        let title = format!("{}: {} ({:.1}%)", p.label, fmt_num(v), frac * 100.0);
        out.push_str(&format!(
            r#"<path d="M {cx} {cy} L {x0:.2} {y0:.2} A {r} {r} 0 {large} 1 {x1:.2} {y1:.2} Z" fill="{fill}" class="c-chart-slice"><title>{title}</title></path>"#,
            cx = cx,
            cy = cy,
            r = r,
            x0 = x0,
            y0 = y0,
            x1 = x1,
            y1 = y1,
            large = large,
            fill = fill,
            title = esc(&title),
        ));
        angle_acc = a1;
    }

    out.push_str("</svg>");
    out
}

/// Convert (angle from 12 o'clock, clockwise) to (x, y) on the circle.
fn polar(cx: f64, cy: f64, r: f64, theta: f64) -> (f64, f64) {
    (cx + r * theta.sin(), cy - r * theta.cos())
}

// ── Bar ──────────────────────────────────────────────

fn render_bar(
    series: &[NormSeries],
    height: u32,
    orientation: ChartOrientation,
    x_label: &Option<String>,
    y_label: &Option<String>,
) -> String {
    if series.is_empty() || series.iter().all(|s| s.points.is_empty()) {
        return empty_svg(height);
    }
    match orientation {
        ChartOrientation::Vertical => render_bar_vertical(series, height, x_label, y_label),
        ChartOrientation::Horizontal => render_bar_horizontal(series, height, x_label, y_label),
    }
}

fn render_bar_vertical(
    series: &[NormSeries],
    height: u32,
    _x_label: &Option<String>,
    _y_label: &Option<String>,
) -> String {
    let h = height as f64;
    let left = 56.0;
    let right = 20.0;
    let top = 16.0;
    let bottom = 40.0;
    let plot_w = VB_W - left - right;
    let plot_h = h - top - bottom;

    let buckets = collect_buckets(series);
    if buckets.is_empty() {
        return empty_svg(height);
    }

    // Max value across stacked sums per bucket.
    let max_val = buckets
        .iter()
        .map(|b| stacked_total(series, b))
        .fold(0.0_f64, f64::max);
    if max_val <= 0.0 {
        return empty_svg(height);
    }
    let (_nmin, nmax, step) = nice_scale(0.0, max_val, 5);
    let axis_max = nmax.max(step);

    let mut out = format!(
        r#"<svg viewBox="0 0 {vb_w} {h}" preserveAspectRatio="xMidYMid meet" class="c-chart-svg">"#,
        vb_w = VB_W,
        h = h,
    );

    // Gridlines + y tick labels
    let mut v = 0.0_f64;
    while v <= axis_max + 1e-9 {
        let y = top + plot_h - (v / axis_max) * plot_h;
        out.push_str(&format!(
            r#"<line x1="{x1}" y1="{y:.2}" x2="{x2}" y2="{y:.2}" class="c-chart-grid"/>"#,
            x1 = left,
            x2 = left + plot_w,
            y = y,
        ));
        out.push_str(&format!(
            r#"<text x="{x:.2}" y="{y:.2}" class="c-chart-axis c-chart-axis-y">{t}</text>"#,
            x = left - 8.0,
            y = y + 3.5,
            t = esc(&fmt_num(v)),
        ));
        v += step;
    }

    // Bars per bucket
    let n = buckets.len() as f64;
    let bucket_w = plot_w / n;
    let bar_w = (bucket_w * 0.62).min(60.0);

    for (i, bucket) in buckets.iter().enumerate() {
        let cx = left + bucket_w * (i as f64 + 0.5);
        let x = cx - bar_w / 2.0;
        // Stack from bottom → up.
        let mut stacked = 0.0_f64;
        for (s_idx, s) in series.iter().enumerate() {
            let v = s
                .points
                .iter()
                .find(|p| p.label == *bucket)
                .map(|p| p.value.max(0.0))
                .unwrap_or(0.0);
            if v <= 0.0 {
                continue;
            }
            let seg_h = (v / axis_max) * plot_h;
            let y = top + plot_h - ((stacked + v) / axis_max) * plot_h;
            let fill = series_color(s.color, s_idx);
            let title = if s.label.is_empty() {
                format!("{}: {}", bucket, fmt_num(v))
            } else {
                format!("{} — {}: {}", s.label, bucket, fmt_num(v))
            };
            out.push_str(&format!(
                r#"<rect x="{x:.2}" y="{y:.2}" width="{w:.2}" height="{seg_h:.2}" fill="{fill}" class="c-chart-bar"><title>{title}</title></rect>"#,
                x = x,
                y = y,
                w = bar_w,
                seg_h = seg_h,
                fill = fill,
                title = esc(&title),
            ));
            stacked += v;
        }
        // X tick label
        out.push_str(&format!(
            r#"<text x="{x:.2}" y="{y:.2}" class="c-chart-axis c-chart-axis-x">{t}</text>"#,
            x = cx,
            y = top + plot_h + 20.0,
            t = esc(bucket),
        ));
    }

    out.push_str("</svg>");
    out
}

fn render_bar_horizontal(
    series: &[NormSeries],
    height: u32,
    _x_label: &Option<String>,
    _y_label: &Option<String>,
) -> String {
    let h = height as f64;
    let left = 120.0;
    let right = 24.0;
    let top = 16.0;
    let bottom = 32.0;
    let plot_w = VB_W - left - right;
    let plot_h = h - top - bottom;

    let buckets = collect_buckets(series);
    if buckets.is_empty() {
        return empty_svg(height);
    }

    let max_val = buckets
        .iter()
        .map(|b| stacked_total(series, b))
        .fold(0.0_f64, f64::max);
    if max_val <= 0.0 {
        return empty_svg(height);
    }
    let (_nmin, nmax, step) = nice_scale(0.0, max_val, 5);
    let axis_max = nmax.max(step);

    let mut out = format!(
        r#"<svg viewBox="0 0 {vb_w} {h}" preserveAspectRatio="xMidYMid meet" class="c-chart-svg">"#,
        vb_w = VB_W,
        h = h,
    );

    // Gridlines + x-axis labels (values on the bottom)
    let mut v = 0.0_f64;
    while v <= axis_max + 1e-9 {
        let x = left + (v / axis_max) * plot_w;
        out.push_str(&format!(
            r#"<line x1="{x:.2}" y1="{y1:.2}" x2="{x:.2}" y2="{y2:.2}" class="c-chart-grid"/>"#,
            x = x,
            y1 = top,
            y2 = top + plot_h,
        ));
        out.push_str(&format!(
            r#"<text x="{x:.2}" y="{y:.2}" class="c-chart-axis c-chart-axis-x">{t}</text>"#,
            x = x,
            y = top + plot_h + 18.0,
            t = esc(&fmt_num(v)),
        ));
        v += step;
    }

    let n = buckets.len() as f64;
    let bucket_h = plot_h / n;
    let bar_h = (bucket_h * 0.62).min(38.0);

    for (i, bucket) in buckets.iter().enumerate() {
        let cy = top + bucket_h * (i as f64 + 0.5);
        let y = cy - bar_h / 2.0;
        let mut stacked = 0.0_f64;
        for (s_idx, s) in series.iter().enumerate() {
            let val = s
                .points
                .iter()
                .find(|p| p.label == *bucket)
                .map(|p| p.value.max(0.0))
                .unwrap_or(0.0);
            if val <= 0.0 {
                continue;
            }
            let seg_w = (val / axis_max) * plot_w;
            let x = left + (stacked / axis_max) * plot_w;
            let fill = series_color(s.color, s_idx);
            let title = if s.label.is_empty() {
                format!("{}: {}", bucket, fmt_num(val))
            } else {
                format!("{} — {}: {}", s.label, bucket, fmt_num(val))
            };
            out.push_str(&format!(
                r#"<rect x="{x:.2}" y="{y:.2}" width="{w:.2}" height="{seg_h:.2}" fill="{fill}" class="c-chart-bar"><title>{title}</title></rect>"#,
                x = x,
                y = y,
                w = seg_w,
                seg_h = bar_h,
                fill = fill,
                title = esc(&title),
            ));
            stacked += val;
        }
        out.push_str(&format!(
            r#"<text x="{x:.2}" y="{y:.2}" class="c-chart-axis c-chart-axis-y-right">{t}</text>"#,
            x = left - 10.0,
            y = cy + 3.5,
            t = esc(bucket),
        ));
    }

    out.push_str("</svg>");
    out
}

// ── Timeseries ───────────────────────────────────────

fn render_timeseries(
    series: &[NormSeries],
    height: u32,
    _x_label: &Option<String>,
    _y_label: &Option<String>,
) -> String {
    if series.is_empty() || series.iter().all(|s| s.points.is_empty()) {
        return empty_svg(height);
    }
    let h = height as f64;
    let left = 56.0;
    let right = 20.0;
    let top = 16.0;
    let bottom = 40.0;
    let plot_w = VB_W - left - right;
    let plot_h = h - top - bottom;

    let buckets = collect_buckets(series);
    if buckets.is_empty() {
        return empty_svg(height);
    }

    // Timeseries = multi-line (not stacked). Max is the largest single value
    // across all series — each line needs its own y-space, not a summed one.
    let max_val = series
        .iter()
        .flat_map(|s| s.points.iter())
        .map(|p| p.value)
        .fold(0.0_f64, f64::max);
    if max_val <= 0.0 {
        return empty_svg(height);
    }
    let (_nmin, nmax, step) = nice_scale(0.0, max_val, 5);
    let axis_max = nmax.max(step);

    let mut out = format!(
        r#"<svg viewBox="0 0 {vb_w} {h}" preserveAspectRatio="xMidYMid meet" class="c-chart-svg">"#,
        vb_w = VB_W,
        h = h,
    );

    // Gridlines + y tick labels
    let mut v = 0.0_f64;
    while v <= axis_max + 1e-9 {
        let y = top + plot_h - (v / axis_max) * plot_h;
        out.push_str(&format!(
            r#"<line x1="{x1}" y1="{y:.2}" x2="{x2}" y2="{y:.2}" class="c-chart-grid"/>"#,
            x1 = left,
            x2 = left + plot_w,
            y = y,
        ));
        out.push_str(&format!(
            r#"<text x="{x:.2}" y="{y:.2}" class="c-chart-axis c-chart-axis-y">{t}</text>"#,
            x = left - 8.0,
            y = y + 3.5,
            t = esc(&fmt_num(v)),
        ));
        v += step;
    }

    // X-axis labels (one per bucket). If there are many buckets, thin them
    // out so labels don't collide.
    let n = buckets.len();
    let stride = (n as f64 / 10.0).ceil() as usize;
    let stride = stride.max(1);
    let x_of = |i: usize| -> f64 {
        if n == 1 {
            left + plot_w / 2.0
        } else {
            left + plot_w * (i as f64) / ((n - 1) as f64)
        }
    };
    for (i, bucket) in buckets.iter().enumerate() {
        if i % stride != 0 && i != n - 1 {
            continue;
        }
        out.push_str(&format!(
            r#"<text x="{x:.2}" y="{y:.2}" class="c-chart-axis c-chart-axis-x">{t}</text>"#,
            x = x_of(i),
            y = top + plot_h + 20.0,
            t = esc(bucket),
        ));
    }

    // One polyline per series, plus point markers with tooltips.
    for (s_idx, s) in series.iter().enumerate() {
        let stroke = series_color(s.color, s_idx);
        let mut points_attr = String::new();
        let mut dots = String::new();
        for (i, bucket) in buckets.iter().enumerate() {
            let Some(p) = s.points.iter().find(|p| p.label == *bucket) else {
                continue;
            };
            let x = x_of(i);
            let y = top + plot_h - (p.value / axis_max) * plot_h;
            if !points_attr.is_empty() {
                points_attr.push(' ');
            }
            points_attr.push_str(&format!("{:.2},{:.2}", x, y));
            let title = if s.label.is_empty() {
                format!("{}: {}", bucket, fmt_num(p.value))
            } else {
                format!("{} — {}: {}", s.label, bucket, fmt_num(p.value))
            };
            dots.push_str(&format!(
                r#"<circle cx="{x:.2}" cy="{y:.2}" r="3" fill="{stroke}" class="c-chart-dot"><title>{title}</title></circle>"#,
                x = x,
                y = y,
                stroke = stroke,
                title = esc(&title),
            ));
        }
        if !points_attr.is_empty() {
            out.push_str(&format!(
                r#"<polyline points="{pts}" fill="none" stroke="{stroke}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" class="c-chart-line"/>"#,
                pts = points_attr,
                stroke = stroke,
            ));
        }
        out.push_str(&dots);
    }

    out.push_str("</svg>");
    out
}

// ── Shared helpers ───────────────────────────────────

/// Union of bucket labels across all series, preserving first-seen order so
/// months stay in January→December even when one series has holes.
fn collect_buckets(series: &[NormSeries]) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    for s in series {
        for p in s.points {
            if !out.iter().any(|b| b == &p.label) {
                out.push(p.label.clone());
            }
        }
    }
    out
}

fn stacked_total(series: &[NormSeries], bucket: &str) -> f64 {
    series
        .iter()
        .flat_map(|s| s.points.iter())
        .filter(|p| p.label == bucket)
        .map(|p| p.value.max(0.0))
        .sum()
}

fn render_legend(kind: ChartKind, series: &[NormSeries]) -> String {
    // Pie legend = slice labels. Bar/timeseries legend = series labels, but
    // only when there's more than one (single-series charts don't need one).
    let items: Vec<(String, String)> = match kind {
        ChartKind::Pie => {
            let Some(first) = series.first() else {
                return String::new();
            };
            first
                .points
                .iter()
                .enumerate()
                .map(|(i, p)| {
                    let color = series_color(p.color.or(first.color), i).to_string();
                    (p.label.clone(), color)
                })
                .collect()
        }
        _ => {
            if series.len() < 2 {
                return String::new();
            }
            series
                .iter()
                .enumerate()
                .map(|(i, s)| (s.label.to_string(), series_color(s.color, i).to_string()))
                .collect()
        }
    };
    if items.is_empty() {
        return String::new();
    }
    let mut out = String::from(r#"<ul class="c-chart-legend">"#);
    for (label, color) in items {
        out.push_str(&format!(
            r#"<li class="c-chart-legend-item"><span class="c-chart-swatch" style="background:{c}"></span><span>{l}</span></li>"#,
            c = color,
            l = esc(&label),
        ));
    }
    out.push_str("</ul>");
    out
}

fn empty_svg(height: u32) -> String {
    format!(
        r#"<svg viewBox="0 0 {vb_w} {h}" preserveAspectRatio="xMidYMid meet" class="c-chart-svg"><text x="50%" y="50%" class="c-chart-empty" text-anchor="middle">No data</text></svg>"#,
        vb_w = VB_W,
        h = height,
    )
}

// ── Numeric helpers ──────────────────────────────────

fn fmt_num(v: f64) -> String {
    if v.is_nan() || v.is_infinite() {
        return "—".into();
    }
    if v.fract().abs() < 1e-9 {
        return format!("{}", v as i64);
    }
    let s = format!("{:.2}", v);
    let trimmed = s.trim_end_matches('0').trim_end_matches('.');
    trimmed.to_string()
}

/// Round `raw` to a "nice" number — one of {1,2,5} * 10^n. `round=true` picks
/// the nearest nice step for tick spacing; `round=false` picks the next nice
/// number ≥ raw for the axis extent.
fn nice_number(raw: f64, round: bool) -> f64 {
    if raw <= 0.0 {
        return 1.0;
    }
    let exp = raw.log10().floor();
    let f = raw / 10_f64.powf(exp);
    let nf = if round {
        if f < 1.5 {
            1.0
        } else if f < 3.0 {
            2.0
        } else if f < 7.0 {
            5.0
        } else {
            10.0
        }
    } else if f <= 1.0 {
        1.0
    } else if f <= 2.0 {
        2.0
    } else if f <= 5.0 {
        5.0
    } else {
        10.0
    };
    nf * 10_f64.powf(exp)
}

fn nice_scale(min: f64, max: f64, target_ticks: usize) -> (f64, f64, f64) {
    let range = nice_number((max - min).max(1e-9), false);
    let ticks = target_ticks.max(2);
    let step = nice_number(range / (ticks as f64 - 1.0), true);
    let nice_min = (min / step).floor() * step;
    let nice_max = (max / step).ceil() * step;
    (nice_min, nice_max, step)
}

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

    #[test]
    fn fmt_num_trims_integer_and_decimal() {
        assert_eq!(fmt_num(42.0), "42");
        assert_eq!(fmt_num(42.5), "42.5");
        assert_eq!(fmt_num(0.0), "0");
        assert_eq!(fmt_num(1.10), "1.1");
    }

    #[test]
    fn nice_scale_produces_round_steps() {
        let (_, max, step) = nice_scale(0.0, 125.0, 5);
        assert!(max >= 125.0);
        assert!(step > 0.0);
        assert!((max / step).round() * step - max < 1e-6);
    }

    #[test]
    fn polar_places_zero_angle_at_twelve_oclock() {
        let (x, y) = polar(100.0, 100.0, 50.0, 0.0);
        assert!((x - 100.0).abs() < 1e-6);
        assert!((y - 50.0).abs() < 1e-6);
    }

    #[test]
    fn collect_buckets_preserves_first_seen_order() {
        let a_points = vec![
            ChartPoint {
                label: "Jan".into(),
                value: 1.0,
                color: None,
            },
            ChartPoint {
                label: "Feb".into(),
                value: 2.0,
                color: None,
            },
        ];
        let b_points = vec![
            ChartPoint {
                label: "Feb".into(),
                value: 3.0,
                color: None,
            },
            ChartPoint {
                label: "Mar".into(),
                value: 4.0,
                color: None,
            },
        ];
        let series = vec![
            NormSeries {
                label: "A",
                color: None,
                points: &a_points,
            },
            NormSeries {
                label: "B",
                color: None,
                points: &b_points,
            },
        ];
        let buckets = collect_buckets(&series);
        assert_eq!(buckets, vec!["Jan", "Feb", "Mar"]);
    }
}