zenith-scene 0.0.3

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

use zenith_core::{ChartNode, Diagnostic, FontStyle};
use zenith_layout::{ShapeRequest, TextDirection, TextLayoutEngine};

use crate::ir::{Color, Paint, SceneCommand};

use super::super::NodeCtx;
use super::super::paint::resolve_property_color;
use super::super::text::run_to_scene_glyphs;
use super::axis::format_tick_label;
use super::frame::PlotArea;
use super::palette::series_color;
use super::scale::LinearScale;

// ── Constants ─────────────────────────────────────────────────────────────────

/// Fraction of a category slot that is padding (split equally on each side).
const CATEGORY_PAD_FRAC: f64 = 0.20;
/// Gap between adjacent bars within a grouped category, as a fraction of
/// `bar_w` (applied once between each pair).
const BAR_GAP_FRAC: f64 = 0.15;

/// Color for value labels drawn above (or inside) each bar.
pub(super) const VALUE_LABEL_COLOR: Color = Color::srgb(60, 60, 60, 255);

// ── BarMode ───────────────────────────────────────────────────────────────────

/// Layout mode for a bar chart.
#[derive(Clone, Copy, PartialEq, Debug)]
pub(super) enum BarMode {
    /// Series bars are placed side-by-side within each category slot.
    Grouped,
    /// Series bars are stacked vertically within each category slot.
    Stacked,
}

impl BarMode {
    /// Derive the bar mode from the optional `bar_mode` string property.
    ///
    /// `Some("stacked")` → `Stacked`; everything else (including `None`,
    /// `Some("grouped")`, or any unrecognised string) → `Grouped`.
    pub(super) fn from_opt(s: Option<&str>) -> BarMode {
        match s {
            Some("stacked") => BarMode::Stacked,
            _ => BarMode::Grouped,
        }
    }
}

// ── BarRect ───────────────────────────────────────────────────────────────────

/// Pixel rectangle for a single bar.
///
/// A `w == 0.0` or `h < 0.5` sentinel means "nothing to draw here" — the
/// emitter skips these.
#[derive(Clone, Copy)]
pub(super) struct BarRect {
    pub(super) x: f64,
    pub(super) y: f64,
    pub(super) w: f64,
    pub(super) h: f64,
}

// ── bar_rects ─────────────────────────────────────────────────────────────────

/// Compute pixel rectangles for every bar.
///
/// Returns `rects[series_idx][category_idx]`. The outer `Vec` has one entry
/// per series; the inner `Vec` has one entry per category (padded to
/// `n_categories` with zero-size sentinels when a series has fewer values).
///
/// Returns an empty `Vec` when `n_categories == 0` (no data) or when the
/// plot area is degenerate (`w <= 0`).
///
/// This function is PURE — no engine, no I/O, no side effects beyond the
/// returned `Vec`.
pub(super) fn bar_rects(
    plot: &PlotArea,
    y_scale: &LinearScale,
    series_values: &[&[f64]],
    mode: BarMode,
) -> Vec<Vec<BarRect>> {
    let n_categories = series_values.iter().map(|s| s.len()).max().unwrap_or(0);
    if n_categories == 0 || plot.w <= 0.0 {
        return Vec::new();
    }

    let n_series = series_values.len();
    if n_series == 0 {
        return Vec::new();
    }

    // Snap the value baseline to a whole device pixel. Bar segment edges are
    // rounded to integers (below) so abutting stacked segments share an exact
    // pixel boundary — without this, two fills meeting at a fractional y leave a
    // 1px anti-aliased seam (background hairline) between them.
    let baseline_px = y_scale.map(0.0).round();
    let slot_w = plot.w / n_categories as f64;
    let usable_w = slot_w * (1.0 - CATEGORY_PAD_FRAC);
    let left_pad = (slot_w - usable_w) / 2.0;

    match mode {
        BarMode::Grouped => {
            // bar_w accounts for gaps between bars within a slot.
            // Formula: n_series * bar_w + (n_series - 1) * bar_w * BAR_GAP_FRAC = usable_w
            //   => bar_w * (n_series + (n_series-1)*BAR_GAP_FRAC) = usable_w
            //   => bar_w * (n_series * (1+BAR_GAP_FRAC) - BAR_GAP_FRAC) = usable_w
            let bar_w = usable_w / (n_series as f64 * (1.0 + BAR_GAP_FRAC) - BAR_GAP_FRAC).max(1.0);

            if bar_w <= 0.0 {
                return Vec::new();
            }

            let step = bar_w * (1.0 + BAR_GAP_FRAC);

            series_values
                .iter()
                .enumerate()
                .map(|(s, sv)| {
                    (0..n_categories)
                        .map(|c| match sv.get(c) {
                            None => BarRect {
                                x: 0.0,
                                y: 0.0,
                                w: 0.0,
                                h: 0.0,
                            },
                            Some(&value) => {
                                let bar_x = plot.x + c as f64 * slot_w + left_pad + s as f64 * step;
                                let top = y_scale.map(value).round();
                                let h = (baseline_px - top).abs();
                                let y = top.min(baseline_px);
                                BarRect {
                                    x: bar_x,
                                    y,
                                    w: bar_w,
                                    h,
                                }
                            }
                        })
                        .collect()
                })
                .collect()
        }

        BarMode::Stacked => {
            let bar_w = usable_w;
            // Per-category running cumulative (one accumulator per category).
            let mut cumulative = vec![0.0f64; n_categories];

            series_values
                .iter()
                .map(|sv| {
                    (0..n_categories)
                        .map(|c| match sv.get(c) {
                            None => BarRect {
                                x: 0.0,
                                y: 0.0,
                                w: 0.0,
                                h: 0.0,
                            },
                            Some(&value) => {
                                let bar_x = plot.x + c as f64 * slot_w + left_pad;
                                let lower = cumulative.get(c).copied().unwrap_or(0.0);
                                let upper = lower + value;
                                if let Some(slot) = cumulative.get_mut(c) {
                                    *slot = upper;
                                }
                                let top = y_scale.map(upper).round();
                                let bottom = y_scale.map(lower).round();
                                let y = top.min(bottom);
                                let h = (bottom - top).abs();
                                BarRect {
                                    x: bar_x,
                                    y,
                                    w: bar_w,
                                    h,
                                }
                            }
                        })
                        .collect()
                })
                .collect()
        }
    }
}

/// Largest per-category cumulative total across all series — the height a
/// stacked column reaches. Used to size the value axis so stacked bars fit
/// inside the plot area (a grouped chart sizes to the max single value instead).
///
/// Returns `0.0` when there are no series/values. Negative values are summed
/// too, matching the stacking model.
pub(super) fn stacked_max(chart: &ChartNode) -> f64 {
    let n_categories = chart
        .series
        .iter()
        .map(|s| s.values.len())
        .max()
        .unwrap_or(0);
    let mut max = 0.0_f64;
    for c in 0..n_categories {
        let sum: f64 = chart.series.iter().filter_map(|s| s.values.get(c)).sum();
        if sum > max {
            max = sum;
        }
    }
    max
}

// ── Value-label placement ──────────────────────────────────────────────────────

/// Where (and whether) per-bar value labels are drawn.
#[derive(Clone, Copy, PartialEq, Debug)]
pub(super) enum ValueLabelMode {
    /// No value labels.
    Off,
    /// Above each bar (good for grouped/single; stacked lower segments hide).
    Top,
    /// Centered inside each bar/segment (every stacked segment stays visible).
    Center,
}

impl ValueLabelMode {
    /// Resolve the mode from the optional `value-labels` property.
    ///
    /// `"none"` → Off, `"top"` → Top, `"center"` → Center. `"auto"`, `None`, and
    /// any unrecognised value resolve to the smart default: stacked bars center
    /// (so each segment shows its own value), everything else labels on top.
    pub(super) fn resolve(value_labels: Option<&str>, is_stacked: bool) -> ValueLabelMode {
        match value_labels {
            Some("none") => ValueLabelMode::Off,
            Some("top") => ValueLabelMode::Top,
            Some("center") => ValueLabelMode::Center,
            _ => {
                if is_stacked {
                    ValueLabelMode::Center
                } else {
                    ValueLabelMode::Top
                }
            }
        }
    }
}

/// Default color for value labels drawn ON a bar/slice fill. White by default
/// (consistent across slices); overridable via the chart's `value-color` or a
/// per-label color. Labels drawn ABOVE a bar (on the plot background) use
/// [`VALUE_LABEL_COLOR`] instead so they stay legible on a light page.
pub(super) const ON_FILL_LABEL_COLOR: Color = Color::srgb(255, 255, 255, 255);

// ── emit_bars ─────────────────────────────────────────────────────────────────

/// Resolve series colors and emit `FillRect` commands for every bar, followed
/// by a value label placed per the chart's `value-labels` mode.
///
/// Bars with `w <= 0` or `h < 0.5` are skipped. An empty series list or an
/// empty series produces no commands.
pub(super) fn emit_bars(
    chart: &ChartNode,
    plot: &PlotArea,
    y_scale: &LinearScale,
    cx: NodeCtx,
    commands: &mut Vec<SceneCommand>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let series_values: Vec<&[f64]> = chart.series.iter().map(|s| s.values.as_slice()).collect();
    let mode = BarMode::from_opt(chart.bar_mode.as_deref());
    let rects = bar_rects(plot, y_scale, &series_values, mode);

    if rects.is_empty() {
        return;
    }

    // Value-label mode + optional explicit color override (a (token) ref);
    // when absent the color is derived per-bar (contrast inside / dark on top).
    let label_mode =
        ValueLabelMode::resolve(chart.value_labels.as_deref(), mode == BarMode::Stacked);
    let explicit_label_color = chart
        .value_color
        .as_ref()
        .and_then(|p| resolve_property_color(p, cx.resolved, diagnostics, &chart.id));

    // Hoisted outside the per-series/per-bar loops: one allocation for all
    // value-label shape requests in this chart.
    let value_label_families = [String::from("Noto Sans")];

    for s in 0..chart.series.len() {
        // Resolve color: explicit series color → palette fallback.
        // Shared resolver lives in palette::series_color so all chart kinds
        // (bar, line, area, sparkline) produce identical color semantics.
        let color = match chart.series.get(s) {
            Some(series) => series_color(series, s, cx.resolved, diagnostics, &chart.id),
            None => continue,
        };

        let paint = Paint::solid(color);

        // Per-series label color overrides the chart value-color; either, when
        // absent, leaves `explicit` None so the placement default applies.
        let label_explicit = chart
            .series
            .get(s)
            .and_then(|sr| sr.label_color.as_ref())
            .and_then(|p| resolve_property_color(p, cx.resolved, diagnostics, &chart.id))
            .or(explicit_label_color);

        if let Some(series_rects) = rects.get(s) {
            for (c, rect) in series_rects.iter().enumerate() {
                if rect.w <= 0.0 || rect.h < 0.5 {
                    continue;
                }

                commands.push(SceneCommand::FillRect {
                    x: rect.x,
                    y: rect.y,
                    w: rect.w,
                    h: rect.h,
                    paint: paint.clone(),
                });

                if label_mode == ValueLabelMode::Off {
                    continue;
                }

                // Value label: the raw data value for this bar.
                let value = match chart.series.get(s).and_then(|sr| sr.values.get(c)) {
                    Some(v) => *v,
                    None => continue,
                };

                emit_value_label(
                    value,
                    *rect,
                    LabelCtx {
                        plot,
                        families: &value_label_families,
                        chart_id: &chart.id,
                        placement: label_mode,
                        explicit: label_explicit,
                    },
                    cx,
                    commands,
                    diagnostics,
                );
            }
        }
    }
}

// ── emit_value_label ──────────────────────────────────────────────────────────

/// Per-chart context shared by every bar's value label — bundled so the
/// font-family allocation is hoisted once and the emitter's argument list stays
/// within bounds.
#[derive(Clone, Copy)]
struct LabelCtx<'a> {
    plot: &'a PlotArea,
    families: &'a [String],
    chart_id: &'a str,
    placement: ValueLabelMode,
    /// Resolved label-color override (per-label or chart `value-color`); when
    /// `None` the color is the placement default (white on a fill, dark above).
    explicit: Option<Color>,
}

/// Shape and emit a numeric value label for one bar.
///
/// Placement follows `lc.placement`:
/// - `Top`: 3 px above the bar; if that clips the plot top it falls inside.
/// - `Center`: vertically centered inside the bar/segment. Segments shorter than
///   the label height are skipped so text never overflows its segment.
///
/// Color: `lc.explicit` wins if set; otherwise a label that ends up ON the bar
/// fill (centered, or a top label that fell inside) uses the white on-fill
/// default, while a label above the bar uses the dark plot-background color.
///
/// `lc` bundles the per-chart context shared across every bar so the allocation
/// stays out of the per-bar loop and the argument list stays bounded.
fn emit_value_label(
    value: f64,
    rect: BarRect,
    lc: LabelCtx,
    cx: NodeCtx,
    commands: &mut Vec<SceneCommand>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let plot = lc.plot;
    // A centered label must fit inside its segment — skip tiny segments.
    if lc.placement == ValueLabelMode::Center && rect.h < 12.0 {
        return;
    }
    let label = format_tick_label(value);
    let req = ShapeRequest {
        text: &label,
        families: lc.families,
        weight: 400,
        style: FontStyle::Normal,
        font_size: 9.0,
        direction: TextDirection::Ltr,
    };

    match cx.engine.shape_with_fallback(&req, cx.fonts) {
        Err(e) => {
            diagnostics.push(Diagnostic::advisory(
                "scene.text_unshaped",
                format!(
                    "chart '{}' bar value label '{}' could not be shaped: {}",
                    lc.chart_id, label, e.message
                ),
                None,
                Some(lc.chart_id.to_owned()),
            ));
        }
        Ok(result) => {
            let total_advance: f64 = result.runs.iter().map(|r| r.advance_width as f64).sum();
            let ascent: f64 = result.runs.first().map(|r| r.ascent as f64).unwrap_or(7.0);

            // Determine baseline + whether the label lands ON the bar fill.
            let (baseline_y, on_fill) = match lc.placement {
                // Centered: cap height in the middle of the segment, on the fill.
                ValueLabelMode::Center => (rect.y + rect.h / 2.0 + ascent * 0.35, true),
                // Top: above the bar; if it would clip the plot top, fall inside.
                // Off is unreachable here (emit_bars skips labels when mode is Off),
                // but must be listed to avoid a wildcard over a Zenith enum.
                ValueLabelMode::Top | ValueLabelMode::Off => {
                    if rect.y - 3.0 - ascent >= plot.y {
                        (rect.y - 3.0, false)
                    } else {
                        (rect.y + 12.0, true)
                    }
                }
            };

            // Color: explicit override wins; else the white on-fill default when
            // the label sits on the bar, dark on the plot background when above it.
            let color = lc.explicit.unwrap_or(if on_fill {
                ON_FILL_LABEL_COLOR
            } else {
                VALUE_LABEL_COLOR
            });

            // Centered horizontally over the bar.
            let mut label_x = rect.x + rect.w / 2.0 - total_advance / 2.0;

            for run in result.runs {
                let advance = run.advance_width as f64;
                let glyphs = run_to_scene_glyphs(&run);
                commands.push(SceneCommand::DrawGlyphRun {
                    x: label_x,
                    y: baseline_y,
                    font_id: run.font_id.clone(),
                    font_size: run.font_size,
                    color,
                    stroke_color: None,
                    stroke_width: None,
                    link: None,
                    selectable: true,
                    glyphs,
                });
                label_x += advance;
            }
        }
    }
}

// ── emit_category_labels ──────────────────────────────────────────────────────

/// Layout inputs for category labels, bundled to keep the emitter's argument
/// list within bounds.
#[derive(Clone, Copy)]
pub(super) struct CatLabels<'a> {
    /// Plot rectangle the labels sit beneath.
    pub plot: &'a PlotArea,
    /// Label text color.
    pub color: Color,
    /// `true` → labels under category-band centers (bars); `false` → under
    /// edge-to-edge vertex positions (line/area).
    pub slot_center: bool,
}

/// Emit X-axis category labels under each category.
///
/// When `slot_center` is true, each label is centered under its category band
/// (`plot.x + (c + 0.5) * slot_w`) — the placement bars use. When false, labels
/// sit at the edge-to-edge vertex positions (`plot.x + c * plot.w/(n-1)`, single
/// category centered) so they line up under line/area vertices.
///
/// When `categories` is shorter than `n_categories`, the remaining slots are
/// labelled by 1-based index (`"1"`, `"2"`, …). Empty label strings are
/// skipped.
pub(super) fn emit_category_labels(
    categories: &[String],
    n_categories: usize,
    layout: CatLabels,
    cx: NodeCtx,
    commands: &mut Vec<SceneCommand>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let plot = layout.plot;
    let label_color = layout.color;
    if n_categories == 0 || plot.w <= 0.0 {
        return;
    }

    let baseline_y = plot.y + plot.h + 14.0;
    let families = [String::from("Noto Sans")];

    for c in 0..n_categories {
        let label: String = categories
            .get(c)
            .cloned()
            .unwrap_or_else(|| (c + 1).to_string());

        if label.is_empty() {
            continue;
        }

        let req = ShapeRequest {
            text: &label,
            families: &families,
            weight: 400,
            style: FontStyle::Normal,
            font_size: 9.0,
            direction: TextDirection::Ltr,
        };

        match cx.engine.shape_with_fallback(&req, cx.fonts) {
            Err(e) => {
                diagnostics.push(Diagnostic::advisory(
                    "scene.text_unshaped",
                    format!(
                        "chart category label '{}' could not be shaped: {}",
                        label, e.message
                    ),
                    None,
                    None,
                ));
            }
            Ok(result) => {
                let total_advance: f64 = result.runs.iter().map(|r| r.advance_width as f64).sum();
                // Match line_points' X placement so labels sit under vertices.
                let center_x = if layout.slot_center {
                    plot.x + (c as f64 + 0.5) * (plot.w / n_categories as f64)
                } else if n_categories <= 1 {
                    plot.x + plot.w / 2.0
                } else {
                    plot.x + c as f64 * (plot.w / (n_categories - 1) as f64)
                };
                let mut label_x = center_x - total_advance / 2.0;

                for run in result.runs {
                    let advance = run.advance_width as f64;
                    let glyphs = run_to_scene_glyphs(&run);
                    commands.push(SceneCommand::DrawGlyphRun {
                        x: label_x,
                        y: baseline_y,
                        font_id: run.font_id.clone(),
                        font_size: run.font_size,
                        color: label_color,
                        stroke_color: None,
                        stroke_width: None,
                        link: None,
                        selectable: true,
                        glyphs,
                    });
                    label_x += advance;
                }
            }
        }
    }
}

// ── Unit tests ────────────────────────────────────────────────────────────────

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

    /// Build a simple PlotArea for testing.
    fn test_plot() -> PlotArea {
        PlotArea {
            x: 44.0,
            y: 10.0,
            w: 300.0,
            h: 200.0,
        }
    }

    /// Build a y_scale mapping data [0,100] onto pixels [210, 10] (inverted).
    fn test_scale() -> LinearScale {
        LinearScale {
            data_min: 0.0,
            data_max: 100.0,
            pixel_min: 210.0, // plot.y + plot.h = 10+200
            pixel_max: 10.0,  // plot.y
        }
    }

    #[test]
    fn bar_mode_from_opt_stacked() {
        assert_eq!(BarMode::from_opt(Some("stacked")), BarMode::Stacked);
    }

    #[test]
    fn bar_mode_from_opt_grouped_variants() {
        assert_eq!(BarMode::from_opt(None), BarMode::Grouped);
        assert_eq!(BarMode::from_opt(Some("grouped")), BarMode::Grouped);
        assert_eq!(BarMode::from_opt(Some("x")), BarMode::Grouped);
    }

    #[test]
    fn value_label_mode_resolve() {
        use ValueLabelMode::*;
        // Explicit values.
        assert_eq!(ValueLabelMode::resolve(Some("none"), false), Off);
        assert_eq!(ValueLabelMode::resolve(Some("top"), true), Top);
        assert_eq!(ValueLabelMode::resolve(Some("center"), false), Center);
        // auto / None / unknown → smart default by stacking.
        assert_eq!(ValueLabelMode::resolve(Some("auto"), true), Center);
        assert_eq!(ValueLabelMode::resolve(Some("auto"), false), Top);
        assert_eq!(ValueLabelMode::resolve(None, true), Center);
        assert_eq!(ValueLabelMode::resolve(None, false), Top);
        assert_eq!(ValueLabelMode::resolve(Some("???"), true), Center);
    }

    #[test]
    fn bar_rects_empty_series_returns_empty() {
        let plot = test_plot();
        let scale = test_scale();
        let result = bar_rects(&plot, &scale, &[], BarMode::Grouped);
        assert!(result.is_empty());
    }

    #[test]
    fn bar_rects_zero_categories_returns_empty() {
        let plot = test_plot();
        let scale = test_scale();
        // Series with no values => n_categories == 0
        let empty: &[f64] = &[];
        let result = bar_rects(&plot, &scale, &[empty], BarMode::Grouped);
        assert!(result.is_empty());
    }

    #[test]
    fn bar_rects_single_series_grouped_geometry() {
        let plot = test_plot();
        let scale = test_scale();
        let values: &[f64] = &[25.0, 50.0, 75.0];
        let rects = bar_rects(&plot, &scale, &[values], BarMode::Grouped);

        assert_eq!(rects.len(), 1, "one series");
        assert_eq!(rects[0].len(), 3, "three categories");

        let eps = 0.5;

        for r in &rects[0] {
            // All bars within the horizontal extent of the plot.
            assert!(r.x >= plot.x - eps, "bar left of plot.x");
            assert!(
                r.x + r.w <= plot.x + plot.w + eps,
                "bar right of plot right"
            );
            // Bar bottom is at the baseline (pixel for value 0).
            let baseline = scale.map(0.0);
            assert!(
                (r.y + r.h - baseline).abs() < eps,
                "bar bottom not at baseline"
            );
        }

        // A larger data value → taller bar → smaller y (higher up on screen).
        let r0 = rects[0][0]; // value 25
        let r1 = rects[0][1]; // value 50
        let r2 = rects[0][2]; // value 75
        assert!(r0.h < r1.h, "25 bar shorter than 50 bar");
        assert!(r1.h < r2.h, "50 bar shorter than 75 bar");
        assert!(
            r2.y < r0.y,
            "75 bar top is higher (smaller y) than 25 bar top"
        );
    }

    #[test]
    fn bar_rects_grouped_two_series_no_overlap() {
        let plot = test_plot();
        let scale = test_scale();
        let s0: &[f64] = &[30.0, 60.0, 90.0];
        let s1: &[f64] = &[10.0, 20.0, 30.0];
        let rects = bar_rects(&plot, &scale, &[s0, s1], BarMode::Grouped);

        assert_eq!(rects.len(), 2);
        assert_eq!(rects[0].len(), 3);
        assert_eq!(rects[1].len(), 3);

        for (c, (r0, r1)) in rects[0].iter().zip(rects[1].iter()).enumerate() {
            // Series 0 is to the left of series 1 within each slot.
            assert!(
                r0.x < r1.x,
                "series 0 bar not left of series 1 bar at category {}",
                c
            );
            // No horizontal overlap: s0 right edge <= s1 left edge.
            assert!(
                r0.x + r0.w <= r1.x + 0.5,
                "bars overlap at category {}: s0 right={} s1 left={}",
                c,
                r0.x + r0.w,
                r1.x
            );
        }
    }

    #[test]
    fn bar_rects_stacked_same_x_stacked_heights() {
        let plot = test_plot();
        let scale = test_scale();
        let s0: &[f64] = &[20.0, 40.0];
        let s1: &[f64] = &[30.0, 10.0];
        let rects = bar_rects(&plot, &scale, &[s0, s1], BarMode::Stacked);

        assert_eq!(rects.len(), 2);
        assert_eq!(rects[0].len(), 2);
        assert_eq!(rects[1].len(), 2);

        let eps = 0.5;
        for c in 0..2 {
            let r0 = rects[0][c];
            let r1 = rects[1][c];

            // Same x and w (stacked, same slot).
            assert!(
                (r0.x - r1.x).abs() < eps,
                "stacked bars differ in x at cat {}",
                c
            );
            assert!(
                (r0.w - r1.w).abs() < eps,
                "stacked bars differ in w at cat {}",
                c
            );

            // Series 1 is stacked above series 0: its top pixel is smaller (higher).
            assert!(r1.y < r0.y, "series 1 not above series 0 at cat {}", c);

            // Combined pixel height equals height for the summed value.
            let combined_value = s0[c] + s1[c];
            let expected_h = (scale.map(0.0) - scale.map(combined_value)).abs();
            let actual_h = r0.h + r1.h;
            assert!(
                (actual_h - expected_h).abs() < eps,
                "stacked heights don't sum at cat {}: got {} expected {}",
                c,
                actual_h,
                expected_h
            );
        }
    }
}