hephaestus 0.2.0

Backend-agnostic 2D scene renderer for data visualization.
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
//! Axis rendering. Pre-shapes tick labels via [`crate::text::TextRun`],
//! reports their dimensions as a [`Measure`] for the composition solver,
//! and strokes the tick marks + labels at draw time.
//!
//! Conventions:
//!
//! - All tick labels are horizontal (no rotation). Wide labels on a
//!   vertical axis grow the axis chrome column.
//! - Tick mark length, label gap, and font size are pulled from the
//!   theme's resolved `AxisChromeStyle` — the same style the renderer
//!   uses at draw time, so the slot reservation matches the visible
//!   chrome.
//! - Tick labels use the scale's own [`Scale::format`], which renders
//!   numeric values via `{n}` Display and temporal values in calendar
//!   form (YYYY-MM-DD etc.).

use crate::geometry::{Point, Rect};
use crate::layout::{Measure, WidthHint};
use crate::plot::chrome::linear_axis::{draw_linear_axis_at, AxisChromeStyle};
use crate::plot::scale::Scale;
use crate::plot::theme::Theme;
use crate::scales::breaks::DEFAULT_BREAK_COUNT;
use crate::scales::value::Value;
use crate::scene::SceneBuilder;

use crate::scales::chrome::AxisSide;

// ─── Axis spec (high-level Plot surface) ─────────────────────────────────────

/// Stable identifier returned by [`crate::plot::Plot::add_axis`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct AxisId(u32);

impl AxisId {
    pub(crate) fn new(raw: u32) -> Self {
        Self(raw)
    }

    /// The raw handle value. Opaque — useful only as a key, and not
    /// comparable across plots.
    pub fn raw(self) -> u32 {
        self.0
    }
}

/// One axis attached to a [`Plot`](crate::plot::Plot). Built
/// manually by the caller — `Plot` doesn't infer any default axes
/// from its channel bindings.
///
/// Both the rail (`scale_name`) and the `title` are optional. A
/// title-only axis (rail = `None`, title = `Some`) reserves the
/// title slot for an axis whose rail has been suppressed.
#[derive(Clone, Debug)]
pub struct Axis {
    /// Scale that supplies the breaks + map for the rail. `None`
    /// means "no rail" — the title (if any) still renders.
    scale_name: Option<String>,
    placement: AxisPlacement,
    title: Option<String>,
}

/// Where an axis sits relative to its plot.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AxisPlacement {
    /// Standard rectilinear axis along one of the panel's four
    /// edges. Wired into the corresponding patch slot via
    /// [`measure`] + [`draw`].
    Cartesian(AxisSide),
    /// Radius axis along a spoke at `theta_frac ∈ [0, 1]` on a
    /// polar projection. The spoke direction is computed via the
    /// projection's `unit_position` so it follows the polygon edge
    /// on chord-style projections.
    PolarRadius { theta_frac: f64 },
    /// Angular axis along the projection's outer or inner ring.
    /// The inner variant is silently skipped when the projection
    /// has `inner_radius_frac == 0` (no hole, no inner ring), so a
    /// single axis definition works for both disk and ring layouts.
    PolarAngular(PolarRing),
}

/// Which ring an angular axis runs along.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PolarRing {
    Outer,
    Inner,
}

impl Axis {
    /// Axis with a rail driven by `scale_name`. Add a title via
    /// [`Self::title`].
    pub fn rail(scale_name: impl Into<String>, placement: AxisPlacement) -> Self {
        Self {
            scale_name: Some(scale_name.into()),
            placement,
            title: None,
        }
    }

    /// Title-only axis — reserves the matching title slot
    /// (cartesian) or renders an inline title (polar) without
    /// drawing a rail. Use when the rail would be visual noise but
    /// the slot still needs a label.
    pub fn title_only(title: impl Into<String>, placement: AxisPlacement) -> Self {
        Self {
            scale_name: None,
            placement,
            title: Some(title.into()),
        }
    }

    /// Attach a title to an existing axis. Cartesian axes draw the
    /// title into the matching patch
    /// [`Slot::AxisLeftTitle`](crate::composition::Slot) /
    /// `AxisBottomTitle` / etc.; polar axes render it inline.
    pub fn title(mut self, t: impl Into<String>) -> Self {
        self.title = Some(t.into());
        self
    }

    /// Name of the scale driving the rail, or `None` when the axis
    /// has no rail.
    pub fn scale_name(&self) -> Option<&str> {
        self.scale_name.as_deref()
    }

    /// Where the axis sits relative to its plot.
    pub fn placement(&self) -> AxisPlacement {
        self.placement
    }

    /// The axis title, or `None` when the axis carries no title.
    pub fn title_ref(&self) -> Option<&str> {
        self.title.as_deref()
    }
}

// ─── AxisMeasure ─────────────────────────────────────────────────────────────

/// Snapshot of an axis's chrome footprint. Holds shaped TextRuns for each
/// tick label so the layout solver can size the chrome track without
/// reshaping per query. The same labels are reshaped at draw time —
/// shaping is cheap, but a future per-channel cache (`Scale::generation`
/// hook) will eliminate the duplicate work.
pub(crate) struct AxisMeasure {
    side: AxisSide,
    /// (max label width across all ticks, in px at the dpi captured at
    /// construction). Computed once.
    max_label_w_px: f64,
    /// (max label height across all ticks, in px at the dpi captured at
    /// construction). Computed once.
    max_label_h_px: f64,
    /// Resolved tick length (px, absolute value — sign drives draw
    /// direction but not reservation magnitude).
    tick_length_px: f64,
    /// Resolved gap between tick end and label near-edge, px.
    gap_px: f64,
}

impl AxisMeasure {
    fn new(
        scale: &Scale,
        side: AxisSide,
        dpi: f64,
        chrome_style: &AxisChromeStyle,
        locale: &crate::scales::Locale,
    ) -> Self {
        let breaks = scale.breaks(DEFAULT_BREAK_COUNT);
        let mut max_w: f64 = 0.0;
        let mut max_h: f64 = 0.0;
        for v in &breaks {
            if matches!(v, Value::Null) {
                continue;
            }
            let label = scale.format(v, locale);
            // Shaped through whichever pipeline the draw pass uses,
            // so the reserved rail matches what lands in it.
            let run = crate::plot::chrome::text::ChromeRun::shape(
                &label,
                &chrome_style.text_style,
                dpi,
                chrome_style.rich.as_ref(),
            );
            let h = run.line_box_height();
            // Tick labels render unwrapped — the natural width is the
            // actual draw width. `width_hint` returns the longest-
            // unbreakable-cluster bound (one word), which undershoots
            // multi-word labels and clips them at draw.
            let w = run.width();
            max_w = max_w.max(w);
            max_h = max_h.max(h);
        }
        AxisMeasure {
            side,
            max_label_w_px: max_w,
            max_label_h_px: max_h,
            // Reservation uses the tick's magnitude — sign flips the
            // tick's draw direction but the slot still needs to fit
            // it either way.
            tick_length_px: chrome_style.tick_length_px.abs(),
            gap_px: chrome_style.gap_px,
        }
    }

    /// Total px contribution along the axis's perpendicular direction.
    /// For Left/Right axes this is the column width; for Bottom/Top it's
    /// the row height.
    fn chrome_thickness_px(&self) -> f64 {
        let label_dim = if self.side.is_vertical() {
            self.max_label_w_px
        } else {
            self.max_label_h_px
        };
        self.tick_length_px + self.gap_px + label_dim
    }
}

impl Measure for AxisMeasure {
    fn width_hint(&self, _dpi: f64) -> WidthHint {
        if self.side.is_vertical() {
            WidthHint::Min(self.chrome_thickness_px())
        } else {
            // Horizontal axes don't constrain column width.
            WidthHint::Min(0.0)
        }
    }

    fn height_at(&self, _width: f64, _dpi: f64) -> f64 {
        if self.side.is_horizontal() {
            self.chrome_thickness_px()
        } else {
            // Vertical axes inherit panel height; their cell doesn't
            // contribute to row sizing.
            0.0
        }
    }
}

// ─── Measure + draw ──────────────────────────────────────────────────────────

/// Pre-shape `scale`'s tick labels into a [`Measure`] cell suitable for
/// dropping into a [`composition::Patch`](crate::composition::Patch)
/// slot. The chrome style (label text style, tick / gap pixel sizes) is
/// resolved from `theme` against the channel + side derived from
/// `side`, so the slot reservation matches what [`draw`] emits.
pub fn measure(scale: &Scale, side: AxisSide, dpi: f64, theme: &Theme) -> Box<dyn Measure> {
    let (ch, side_idx) = axis_side_to_channel_side(side);
    let resolved = theme.resolved_axis(ch, side_idx);
    let chrome_style = AxisChromeStyle::from_resolved(
        &resolved,
        theme,
        dpi,
        crate::plot::chrome::root_text_pt(theme),
    );
    Box::new(AxisMeasure::new(
        scale,
        side,
        dpi,
        &chrome_style,
        &theme.locale,
    ))
}

/// Stroke tick marks and draw tick labels into `slot_rect`, mapping
/// the scale's breaks into panel-space pixels via `panel_rect`.
///
/// Conventions:
/// - For position scales (no output range), `scale.map_break(value)`
///   returns a `Value::Number` in `[0, 1]`; the geom-side convention
///   `px = panel.x0 + frac * panel_w` (and `panel.y1 - frac * panel_h`
///   for y, to flip pixels-grow-downward) applies here too.
/// - Tick marks stroke outward from the panel edge into `slot_rect`.
/// - Labels are anchored toward `slot_rect`'s far edge from the panel.
///
/// Silently does nothing if the scale has no input range, has empty
/// breaks, or the slot rect is degenerate.
#[allow(clippy::too_many_arguments)]
pub fn draw(
    scale: &Scale,
    scene: &mut dyn SceneBuilder,
    slot_rect: Rect,
    panel_rect: Rect,
    side: AxisSide,
    dpi: f64,
    theme: &Theme,
) {
    let breaks = scale.breaks(DEFAULT_BREAK_COUNT);
    if breaks.is_empty() {
        return;
    }
    let panel_w = panel_rect.x1 - panel_rect.x0;
    let panel_h = panel_rect.y1 - panel_rect.y0;
    if panel_w <= 0.0 || panel_h <= 0.0 {
        return;
    }

    // Translate the side + slot/panel layout into the linear-axis
    // primitives: baseline endpoints and the perpendicular tick
    // direction. `frac=0` corresponds to `start`; `frac=1` to
    // `end`. y axes flip so `frac=0` is at the panel BOTTOM.
    let (start, end, tick_direction) = match side {
        AxisSide::Bottom => (
            Point::new(panel_rect.x0, slot_rect.y0),
            Point::new(panel_rect.x1, slot_rect.y0),
            (0.0, 1.0),
        ),
        AxisSide::Top => (
            Point::new(panel_rect.x0, slot_rect.y1),
            Point::new(panel_rect.x1, slot_rect.y1),
            (0.0, -1.0),
        ),
        AxisSide::Left => (
            Point::new(slot_rect.x1, panel_rect.y1),
            Point::new(slot_rect.x1, panel_rect.y0),
            (-1.0, 0.0),
        ),
        AxisSide::Right => (
            Point::new(slot_rect.x0, panel_rect.y1),
            Point::new(slot_rect.x0, panel_rect.y0),
            (1.0, 0.0),
        ),
    };

    let majors: Vec<(f64, String)> = breaks
        .iter()
        .filter(|v| !matches!(v, Value::Null))
        .filter_map(|v| {
            scale
                .map_break(v)
                .as_number()
                .map(|f| (f, scale.format(v, &theme.locale)))
        })
        .filter(|(f, _)| f.is_finite())
        .collect();
    let minors: Vec<f64> = scale
        .minor_breaks(DEFAULT_BREAK_COUNT)
        .into_iter()
        .filter(|v| !matches!(v, Value::Null))
        .filter_map(|v| scale.map_break(&v).as_number())
        .filter(|f| f.is_finite())
        .collect();

    // Resolve the (channel, side) axis from the theme. Channel
    // is determined by which axis side this is — Bottom/Top
    // belong to channel 0 (x), Left/Right to channel 1 (y).
    // Side 0 / 1 within the channel selects between the two
    // possible axes for that channel.
    let (ch, side_idx) = axis_side_to_channel_side(side);
    let resolved = theme.resolved_axis(ch, side_idx);
    let style = AxisChromeStyle::from_resolved(
        &resolved,
        theme,
        dpi,
        crate::plot::chrome::root_text_pt(theme),
    );
    draw_linear_axis_at(
        scene,
        start,
        end,
        tick_direction,
        &majors,
        &minors,
        &style,
        dpi,
    );
}

/// Map an `AxisSide` to the projection-agnostic `(channel, side)`
/// indices the theme stores axis chrome under.
///
/// - `Bottom` → (0, 0): x-axis, primary side.
/// - `Top`    → (0, 1): x-axis, secondary side.
/// - `Left`   → (1, 0): y-axis, primary side.
/// - `Right`  → (1, 1): y-axis, secondary side.
pub(crate) fn axis_side_to_channel_side(side: AxisSide) -> (u8, u8) {
    match side {
        AxisSide::Bottom => (0, 0),
        AxisSide::Top => (0, 1),
        AxisSide::Left => (1, 0),
        AxisSide::Right => (1, 1),
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plot::scale;
    use crate::scales::value::Value;
    use crate::scene::recording::{Op, RecordingScene};

    fn dpi_96() -> f64 {
        96.0
    }

    fn panel_400_300() -> Rect {
        Rect::new(50.0, 20.0, 450.0, 320.0)
    }

    // ── Axis spec ──

    #[test]
    fn axis_builders_round_trip_through_the_accessors() {
        let rail = Axis::rail("x", AxisPlacement::Cartesian(AxisSide::Bottom)).title("Time");
        assert_eq!(rail.scale_name(), Some("x"));
        assert_eq!(rail.placement(), AxisPlacement::Cartesian(AxisSide::Bottom));
        assert_eq!(rail.title_ref(), Some("Time"));

        let title_only = Axis::title_only("Depth", AxisPlacement::PolarAngular(PolarRing::Outer));
        assert_eq!(title_only.scale_name(), None);
        assert_eq!(title_only.title_ref(), Some("Depth"));
    }

    /// A theme whose root text element reads markdown, the way a host
    /// that wants rich chrome sets it.
    fn markdown_theme() -> Theme {
        let mut t = Theme::default();
        t.text.markdown = Some(true);
        t
    }

    /// A discrete x scale whose categories spell markdown.
    fn italic_labels() -> crate::plot::scale::Scale {
        scale::discrete([
            Value::String(std::sync::Arc::from("*a*")),
            Value::String(std::sync::Arc::from("*b*")),
        ])
    }

    fn glyph_count(scene: &RecordingScene) -> usize {
        scene
            .ops
            .iter()
            .filter_map(|op| match op {
                Op::DrawGlyphs(run) => Some(run.glyphs.len()),
                _ => None,
            })
            .sum()
    }

    fn draw_axis(theme: &Theme) -> RecordingScene {
        let mut scene = RecordingScene::default();
        draw(
            &italic_labels(),
            &mut scene,
            Rect::new(50.0, 320.0, 450.0, 360.0),
            panel_400_300(),
            AxisSide::Bottom,
            dpi_96(),
            theme,
        );
        scene
    }

    /// The theme's root `markdown` reaches cartesian tick labels, so
    /// a category spelling markdown renders as styled text.
    #[test]
    fn markdown_reaches_cartesian_tick_labels() {
        let plain = glyph_count(&draw_axis(&Theme::default()));
        let md = glyph_count(&draw_axis(&markdown_theme()));
        assert_eq!(
            plain - md,
            4,
            "two italic labels drop two asterisks each (plain {plain}, markdown {md})"
        );
    }

    /// The rail reserves what it draws: a markdown label whose markers
    /// vanish needs less room than the same string drawn literally.
    #[test]
    fn a_markdown_axis_reserves_the_width_it_draws() {
        let s = italic_labels();
        let plain = measure(&s, AxisSide::Left, dpi_96(), &Theme::default());
        let md = measure(&s, AxisSide::Left, dpi_96(), &markdown_theme());
        let width = |m: &dyn Measure| match m.width_hint(dpi_96()) {
            WidthHint::Min(w) => w,
            WidthHint::NeedsHeight { seed } => seed,
        };
        assert!(
            width(md.as_ref()) < width(plain.as_ref()),
            "markdown labels lose their markers, so the rail narrows ({} → {})",
            width(plain.as_ref()),
            width(md.as_ref())
        );
    }

    // ── axis_measure ──

    #[test]
    fn bottom_axis_measure_reports_chrome_height() {
        let s = scale::continuous(0.0..=100.0);
        let theme = Theme::default();
        let m = measure(&s, AxisSide::Bottom, dpi_96(), &theme);
        // Bottom axis: width contribution = 0, height = tick + gap + label_h.
        assert_eq!(m.width_hint(dpi_96()), WidthHint::Min(0.0));
        let h = m.height_at(400.0, dpi_96());
        assert!(h > 0.0, "axis height should be positive");
        // Sanity: at least the tick length in px.
        assert!(h >= 1.0);
    }

    #[test]
    fn left_axis_measure_reports_chrome_width() {
        let s = scale::continuous(0.0..=100.0);
        let theme = Theme::default();
        let m = measure(&s, AxisSide::Left, dpi_96(), &theme);
        let w = match m.width_hint(dpi_96()) {
            WidthHint::Min(w) => w,
            WidthHint::NeedsHeight { seed } => seed,
        };
        assert!(w > 0.0, "axis width should be positive");
        // Left axis row contribution is zero (height is panel-driven).
        assert_eq!(m.height_at(w, dpi_96()), 0.0);
    }

    #[test]
    fn axis_chrome_grows_with_longer_labels() {
        // A scale whose labels are wider (8-digit numbers) should
        // produce a wider Left axis.
        let s_short = scale::continuous(0.0..=10.0);
        let s_long = scale::continuous(0.0..=100_000_000.0);
        let theme = Theme::default();
        let m_short = measure(&s_short, AxisSide::Left, dpi_96(), &theme);
        let m_long = measure(&s_long, AxisSide::Left, dpi_96(), &theme);
        let w_short = match m_short.width_hint(dpi_96()) {
            WidthHint::Min(w) => w,
            WidthHint::NeedsHeight { seed } => seed,
        };
        let w_long = match m_long.width_hint(dpi_96()) {
            WidthHint::Min(w) => w,
            WidthHint::NeedsHeight { seed } => seed,
        };
        assert!(
            w_long > w_short,
            "longer labels should grow the axis: short={w_short}, long={w_long}"
        );
    }

    // ── draw_axis op-emission ──

    fn count_strokes_and_glyph_runs(scene: &RecordingScene) -> (usize, usize) {
        let mut strokes = 0usize;
        let mut glyphs = 0usize;
        for op in &scene.ops {
            match op {
                Op::Stroke { .. } => strokes += 1,
                Op::DrawGlyphs(_) => glyphs += 1,
                _ => {}
            }
        }
        (strokes, glyphs)
    }

    #[test]
    fn bottom_axis_draws_ticks_and_labels() {
        let s = scale::continuous(0.0..=10.0);
        let panel = panel_400_300();
        // Place the slot directly below the panel — height = chrome.
        let theme = Theme::default();
        let m = measure(&s, AxisSide::Bottom, dpi_96(), &theme);
        let chrome_h = m.height_at(panel.x1 - panel.x0, dpi_96());
        let slot = Rect::new(panel.x0, panel.y1, panel.x1, panel.y1 + chrome_h);

        let mut scene = RecordingScene::default();
        draw(
            &s,
            &mut scene,
            slot,
            panel,
            AxisSide::Bottom,
            dpi_96(),
            &Theme::default(),
        );

        let (strokes, glyphs) = count_strokes_and_glyph_runs(&scene);
        let breaks = s.breaks(DEFAULT_BREAK_COUNT);
        let minors = s.minor_breaks(DEFAULT_BREAK_COUNT);
        let n_majors = breaks.iter().filter(|v| !matches!(v, Value::Null)).count();
        let n_minors = minors.iter().filter(|v| !matches!(v, Value::Null)).count();
        // Default theme has `axis.line = Blank` (ggplot2 theme_gray
        // style), so the baseline contributes no stroke — only ticks.
        let expected_strokes = n_majors + n_minors;
        assert_eq!(
            strokes, expected_strokes,
            "expected {expected_strokes} strokes ({n_majors} majors + {n_minors} minors, no baseline); got {strokes}"
        );
        assert!(
            glyphs >= n_majors,
            "expected at least one glyph-run per major label"
        );
    }

    #[test]
    fn left_axis_draws_ticks_and_labels() {
        let s = scale::continuous(0.0..=1.0);
        let panel = panel_400_300();
        let theme = Theme::default();
        let m = measure(&s, AxisSide::Left, dpi_96(), &theme);
        let chrome_w = match m.width_hint(dpi_96()) {
            WidthHint::Min(w) => w,
            WidthHint::NeedsHeight { seed } => seed,
        };
        let slot = Rect::new(panel.x0 - chrome_w, panel.y0, panel.x0, panel.y1);

        let mut scene = RecordingScene::default();
        draw(
            &s,
            &mut scene,
            slot,
            panel,
            AxisSide::Left,
            dpi_96(),
            &Theme::default(),
        );

        let (strokes, glyphs) = count_strokes_and_glyph_runs(&scene);
        let breaks = s.breaks(DEFAULT_BREAK_COUNT);
        let minors = s.minor_breaks(DEFAULT_BREAK_COUNT);
        let n_majors = breaks.iter().filter(|v| !matches!(v, Value::Null)).count();
        let n_minors = minors.iter().filter(|v| !matches!(v, Value::Null)).count();
        let expected_strokes = n_majors + n_minors;
        assert_eq!(strokes, expected_strokes);
        assert!(glyphs >= n_majors);
    }

    #[test]
    fn binned_axis_ticks_sit_on_their_own_bin_edges() {
        use crate::geometry::Shape as _;

        let edges = vec![2500.0, 3500.0, 4500.0, 5500.0, 6500.0];
        let s = scale::binned(2500.0..=6500.0, edges.clone());
        let panel = panel_400_300();
        let theme = Theme::default();
        let m = measure(&s, AxisSide::Bottom, dpi_96(), &theme);
        let chrome_h = m.height_at(panel.x1 - panel.x0, dpi_96());
        let slot = Rect::new(panel.x0, panel.y1, panel.x1, panel.y1 + chrome_h);

        let mut scene = RecordingScene::default();
        draw(
            &s,
            &mut scene,
            slot,
            panel,
            AxisSide::Bottom,
            dpi_96(),
            &theme,
        );

        let tick_xs: Vec<f64> = scene
            .ops
            .iter()
            .filter_map(|op| match op {
                Op::Stroke { path, .. } => Some(path.bounding_box().center().x),
                _ => None,
            })
            .collect();
        let panel_w = panel.x1 - panel.x0;
        let expected: Vec<f64> = edges
            .iter()
            .map(|e| panel.x0 + (e - 2500.0) / 4000.0 * panel_w)
            .collect();
        assert_eq!(tick_xs.len(), expected.len(), "one tick per bin edge");
        for (got, want) in tick_xs.iter().zip(&expected) {
            assert!(
                (got - want).abs() < 1e-6,
                "tick at {got}, expected {want} (ticks: {tick_xs:?})"
            );
        }
    }

    #[test]
    fn draw_axis_with_no_breaks_is_silent() {
        // Identity scale produces no breaks → no draws.
        let s = scale::identity();
        let panel = panel_400_300();
        let slot = Rect::new(panel.x0, panel.y1, panel.x1, panel.y1 + 30.0);

        let mut scene = RecordingScene::default();
        draw(
            &s,
            &mut scene,
            slot,
            panel,
            AxisSide::Bottom,
            dpi_96(),
            &Theme::default(),
        );
        assert!(
            scene.ops.is_empty(),
            "expected no ops for empty breaks; got {}",
            scene.ops.len()
        );
    }

    #[test]
    fn draw_axis_with_degenerate_panel_is_silent() {
        let s = scale::continuous(0.0..=10.0);
        // Zero-area panel.
        let panel = Rect::new(0.0, 0.0, 0.0, 0.0);
        let slot = Rect::new(0.0, 0.0, 10.0, 10.0);
        let mut scene = RecordingScene::default();
        draw(
            &s,
            &mut scene,
            slot,
            panel,
            AxisSide::Bottom,
            dpi_96(),
            &Theme::default(),
        );
        assert!(scene.ops.is_empty());
    }
}