fulgur-chart 0.13.1

Render chart.js-compatible JSON specs to deterministic static SVG/PNG
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
//! チャート意味モデル: chart.js と数値照合するための、解決済み色・軸目盛り・
//! counts を持つシリアライズ可能な中間表現。描画はせず IR + layout から構築する。

use serde::Serialize;

use crate::ir::{ChartKind, ChartSpec, Color};
use crate::text::TextMeasurer;

/// 解決済み色を正規化 rgba 文字列にする(plan の正規化規約に従う)。
pub fn rgba_string(c: &Color) -> String {
    format!("rgba({},{},{},{})", c.r, c.g, c.b, fmt_alpha(c.a))
}

/// alpha を正規化整形する(>=1→"1", <=0→"0", それ以外は 3 桁丸め・末尾ゼロ除去)。
fn fmt_alpha(a: f32) -> String {
    if a >= 1.0 {
        return "1".to_string();
    }
    if a <= 0.0 {
        return "0".to_string();
    }
    let r = (a as f64 * 1000.0).round() / 1000.0;
    // f64 の Display は最短往復表現を出すため n/1000 に末尾ゼロは付かない。
    format!("{r}")
}

#[derive(Debug, Serialize, PartialEq)]
pub struct ChartModel {
    pub meta: Meta,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub axes: Option<Axes>,
    pub series: Vec<SeriesModel>,
    pub counts: Counts,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub geometry: Option<Geometry>,
}

#[derive(Debug, Serialize, PartialEq)]
pub struct Meta {
    pub r#type: String,
    pub width: f64,
    pub height: f64,
}

#[derive(Debug, Serialize, PartialEq)]
pub struct Axes {
    pub x: AxisModel,
    pub y: AxisModel,
}

#[derive(Debug, Serialize, PartialEq)]
pub struct AxisModel {
    pub kind: String, // "linear" | "category"
    #[serde(skip_serializing_if = "Option::is_none")]
    pub labels: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub step: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ticks: Option<Vec<f64>>,
}

#[derive(Debug, Serialize, PartialEq)]
pub struct SeriesModel {
    pub label: String,
    pub fill: Vec<String>,
    pub stroke: Vec<String>,
    pub values: Vec<f64>,
}

#[derive(Debug, Serialize, PartialEq)]
pub struct Counts {
    pub datasets: usize,
    /// ラベル非空のデータセット数。描画される凡例エントリ数ではない
    /// (pie/doughnut はスライスごとに 1 エントリを描画する)。
    pub legend_items: usize,
    pub x_ticks: usize,
    pub y_ticks: usize,
}

/// 矩形/プロット領域の正規化座標(チャート間ジオメトリ照合用)。
#[derive(Debug, Serialize, PartialEq)]
pub struct RectN {
    pub x: f64,
    pub y: f64,
    pub w: f64,
    pub h: f64,
}

/// 単一データ要素の正規化ジオメトリ。n* はプロット領域基準 [0,1]。
#[derive(Debug, Serialize, PartialEq)]
pub struct ElemN {
    pub series: usize,
    pub index: usize,
    pub kind: String,
    pub nx: f64,
    pub ny: f64,
    pub nw: f64,
    pub nh: f64,
}

/// チャートのジオメトリ。plot_area はキャンバス基準 [0,1]、elements はプロット領域基準。
#[derive(Debug, Serialize, PartialEq)]
pub struct Geometry {
    pub plot_area: RectN,
    pub elements: Vec<ElemN>,
}

/// 縦棒のジオメトリを共有 `vertical_bar_boxes` から構築する(描画と単一真実源)。
/// 縦棒以外、または退化プロット領域(幅/高さ<=0)は None。
fn compute_geometry(spec: &ChartSpec, m: &TextMeasurer) -> Option<Geometry> {
    match &spec.kind {
        ChartKind::Bar {
            horizontal: false, ..
        } => {
            let frame = crate::layout::common::compute(spec, m);
            let pw = frame.plot_right - frame.plot_left;
            let ph = frame.plot_bottom - frame.plot_top;
            if pw <= 0.0 || ph <= 0.0 {
                return None;
            }
            let plot_area = RectN {
                x: frame.plot_left / spec.width,
                y: frame.plot_top / spec.height,
                w: pw / spec.width,
                h: ph / spec.height,
            };
            let elements = crate::layout::bar::vertical_bar_boxes(spec, &frame)
                .iter()
                .map(|b| ElemN {
                    series: b.series,
                    index: b.index,
                    kind: "bar".to_string(),
                    nx: (b.x - frame.plot_left) / pw,
                    ny: (b.y - frame.plot_top) / ph,
                    nw: b.w / pw,
                    nh: b.h / ph,
                })
                .collect();
            Some(Geometry {
                plot_area,
                elements,
            })
        }
        ChartKind::Scatter | ChartKind::Bubble => {
            let layout = crate::layout::scatter::compute_scatter_layout(spec, m);
            let pw = layout.plot_right - layout.plot_left;
            let ph = layout.plot_bottom - layout.plot_top;
            if pw <= 0.0 || ph <= 0.0 || spec.width <= 0.0 || spec.height <= 0.0 {
                return None;
            }
            let plot_area = RectN {
                x: layout.plot_left / spec.width,
                y: layout.plot_top / spec.height,
                w: pw / spec.width,
                h: ph / spec.height,
            };
            let elements = crate::layout::scatter::scatter_points(spec, &layout)
                .iter()
                .map(|b| ElemN {
                    series: b.series,
                    index: b.index,
                    kind: b.kind.to_string(),
                    nx: (b.cx - layout.plot_left) / pw,
                    ny: (b.cy - layout.plot_top) / ph,
                    nw: if b.kind == "bubble" { b.r / pw } else { 0.0 },
                    nh: 0.0,
                })
                .collect();
            Some(Geometry {
                plot_area,
                elements,
            })
        }
        ChartKind::Line => {
            let frame = crate::layout::common::compute(spec, m);
            let pw = frame.plot_right - frame.plot_left;
            let ph = frame.plot_bottom - frame.plot_top;
            if pw <= 0.0 || ph <= 0.0 || spec.width <= 0.0 || spec.height <= 0.0 {
                return None;
            }
            let plot_area = RectN {
                x: frame.plot_left / spec.width,
                y: frame.plot_top / spec.height,
                w: pw / spec.width,
                h: ph / spec.height,
            };
            let elements = crate::layout::line::line_points(spec, &frame)
                .iter()
                .map(|b| ElemN {
                    series: b.series,
                    index: b.index,
                    kind: b.kind.to_string(),
                    nx: (b.cx - frame.plot_left) / pw,
                    ny: (b.cy - frame.plot_top) / ph,
                    nw: 0.0,
                    nh: 0.0,
                })
                .collect();
            Some(Geometry {
                plot_area,
                elements,
            })
        }
        _ => None,
    }
}

/// 描画要素数(scatter/bubble は points、boxplot は box_points、その他は values)。
fn element_count(s: &crate::ir::Series) -> usize {
    if !s.box_points.is_empty() {
        s.box_points.len()
    } else if s.points.is_empty() {
        s.values.len()
    } else {
        s.points.len()
    }
}

/// 色ベクタを「要素ごと rgba」に展開しつつ、全要素同色なら長さ1へ畳む。
/// 色解決はレンダラと共有する `ir::color_at` を使い、モデルと描画の差異を防ぐ。
/// 要素数 0(空データセット)では描画マークが無いため空ベクタを返す
/// (chart.js 抽出器も `meta.data.length`=0 で空配列を返すため、これに揃える)。
fn colors_to_strings(colors: &[Color], n: usize) -> Vec<String> {
    if n == 0 {
        return Vec::new();
    }
    let all: Vec<String> = (0..n)
        .map(|i| rgba_string(&crate::ir::color_at(colors, i)))
        .collect();
    if all.iter().all(|x| x == &all[0]) {
        vec![all[0].clone()]
    } else {
        all
    }
}

fn chart_type_name(kind: &ChartKind) -> &'static str {
    match kind {
        ChartKind::Bar {
            horizontal: true, ..
        } => "bar-horizontal",
        ChartKind::Bar { .. } => "bar",
        ChartKind::Line => "line",
        ChartKind::Pie { donut_ratio } if *donut_ratio > 0.0 => "doughnut",
        ChartKind::Pie { .. } => "pie",
        ChartKind::Scatter => "scatter",
        ChartKind::Bubble => "bubble",
        ChartKind::Radar => "radar",
        ChartKind::Mixed => "mixed",
        ChartKind::Matrix { .. } => "matrix",
        ChartKind::VegaRect { .. } => "vegaRect",
        ChartKind::Progress => "progress",
        ChartKind::BoxPlot => "boxplot",
        ChartKind::Sparkline => "sparkline",
        ChartKind::PolarArea => "polarArea",
        ChartKind::RadialGauge { .. } => "radialGauge",
        ChartKind::Gauge { .. } => "gauge",
        ChartKind::OutlabeledPie { donut_ratio, .. } if *donut_ratio > 0.0 => "outlabeledDoughnut",
        ChartKind::OutlabeledPie { .. } => "outlabeledPie",
        ChartKind::Treemap => "treemap",
        ChartKind::WordCloud { .. } => "wordCloud",
        ChartKind::Sankey { .. } => "sankey",
    }
}

/// 軸抜き(meta/series/counts のみ)のコアモデル。Task 3 で軸を載せる。
pub fn build_model_core(spec: &ChartSpec) -> ChartModel {
    // pie/doughnut のスライス境界は renderer が白(pie::SLICE_STROKE)で固定描画し、
    // 解析済み borderColor を使わない。モデルも実描画に合わせて白を主張する
    // (spec が borderColor を指定しても fulgur はそれを無視して白を描く点を、
    // chart.js との diff で正しく顕在化させるため)。
    let is_pie = matches!(
        spec.kind,
        ChartKind::Pie { .. } | ChartKind::PolarArea | ChartKind::OutlabeledPie { .. }
    );
    let series: Vec<SeriesModel> = spec
        .series
        .iter()
        .map(|s| {
            let n = element_count(s);
            let stroke = if is_pie {
                colors_to_strings(&[crate::layout::pie::SLICE_STROKE], n)
            } else {
                colors_to_strings(&s.stroke, n)
            };
            SeriesModel {
                label: s.name.clone(),
                fill: colors_to_strings(&s.fill, n),
                stroke,
                values: s.values.clone(),
            }
        })
        .collect();
    let legend_items = spec.series.iter().filter(|s| !s.name.is_empty()).count();
    let mut counts = Counts {
        datasets: spec.series.len(),
        legend_items,
        x_ticks: spec.categories.len(),
        y_ticks: 0,
    };
    // VegaRect は series/categories が空で、ラベルは ChartKind::VegaRect の
    // x_labels/y_labels に直接持たれる。既存の counts 算出だと datasets=0, x_ticks=0
    // と誤報告になるため、rect 側の情報源で上書きする。build_model 側の compute_axes は
    // VegaRect で None を返すので y_ticks は clobber されない。
    if let ChartKind::VegaRect {
        x_labels, y_labels, ..
    } = &spec.kind
    {
        counts.datasets = 1;
        counts.legend_items = 0; // rect には legend なし
        counts.x_ticks = x_labels.len();
        counts.y_ticks = y_labels.len();
    }
    ChartModel {
        meta: Meta {
            r#type: chart_type_name(&spec.kind).to_string(),
            width: spec.width,
            height: spec.height,
        },
        axes: None,
        series,
        counts,
        geometry: None,
    }
}

/// NiceTicks を線形軸モデルへ変換する。
fn linear_axis(t: &crate::scale::NiceTicks) -> AxisModel {
    AxisModel {
        kind: "linear".to_string(),
        labels: None,
        min: Some(t.min),
        max: Some(t.max),
        step: Some(t.step),
        ticks: Some(t.ticks.clone()),
    }
}

/// カテゴリ軸モデル(ラベルのみ)。
fn category_axis(labels: &[String]) -> AxisModel {
    AxisModel {
        kind: "category".to_string(),
        labels: Some(labels.to_vec()),
        min: None,
        max: None,
        step: None,
        ticks: None,
    }
}

/// 直交チャートの (x 軸, y 軸, y 目盛り数) を計算する。値(線形)軸は描画上の向きに
/// 関わらず常に `y` に載せ、カテゴリ軸を `x` に載せる — JS 抽出器の正規化規約
/// (線形値軸→y・カテゴリ→x)と揃え、apples-to-apples 照合を可能にするため。
/// 値域・nice_ticks は renderer の各 layout と同じ関数を共有し、描画との乖離を防ぐ。
/// 軸を持たないチャート(pie/radar/matrix/progress)は None を返す。
fn compute_axes(spec: &ChartSpec, m: &TextMeasurer) -> Option<(AxisModel, AxisModel, usize)> {
    use crate::scale::nice_ticks;
    match &spec.kind {
        // 縦棒・線・mixed: 値軸=y(layout::common::compute と共有)、カテゴリ=x。
        ChartKind::Bar {
            horizontal: false, ..
        }
        | ChartKind::Line
        | ChartKind::Mixed => {
            let t = crate::layout::common::compute(spec, m).ticks;
            Some((
                category_axis(&spec.categories),
                linear_axis(&t),
                t.ticks.len(),
            ))
        }
        // 横棒: 値軸は描画上 x だが照合のため y に載せる。値域は build_horizontal と
        // 同じく x_axis から読む。カテゴリ=x。
        ChartKind::Bar {
            horizontal: true, ..
        } => {
            let (lo, hi) = crate::layout::common::value_domain(spec, &spec.x_axis);
            let t = nice_ticks(lo, hi, 10);
            Some((
                category_axis(&spec.categories),
                linear_axis(&t),
                t.ticks.len(),
            ))
        }
        // scatter/bubble: x・y とも線形。renderer (scatter::build) と同じ axis_domain を共有。
        ChartKind::Scatter | ChartKind::Bubble => {
            let (xlo, xhi) = crate::layout::scatter::axis_domain(spec, &spec.x_axis, |p| p.x);
            let (ylo, yhi) = crate::layout::scatter::axis_domain(spec, &spec.y_axis, |p| p.y);
            let xt = nice_ticks(xlo, xhi, 10);
            let yt = nice_ticks(ylo, yhi, 10);
            Some((linear_axis(&xt), linear_axis(&yt), yt.ticks.len()))
        }
        // boxplot: カテゴリ x、線形 y。ドメインは layout::boxplot と共有。
        ChartKind::BoxPlot => {
            let t = crate::layout::boxplot::compute_frame(spec, m).ticks;
            Some((
                category_axis(&spec.categories),
                linear_axis(&t),
                t.ticks.len(),
            ))
        }
        _ => None,
    }
}

/// IR + layout から完全な意味モデルを構築する。直交チャート(縦棒・横棒・線・
/// mixed・scatter・bubble)に軸を載せる。
pub fn build_model(spec: &ChartSpec, m: &TextMeasurer) -> ChartModel {
    let mut model = build_model_core(spec);
    if let Some((x, y, y_ticks)) = compute_axes(spec, m) {
        model.counts.y_ticks = y_ticks;
        model.axes = Some(Axes { x, y });
    }
    model.geometry = compute_geometry(spec, m);
    model
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::font::DEFAULT_FONT;
    use crate::frontend::chartjs;
    use crate::ir::Color;
    use crate::text::TextMeasurer;

    #[test]
    fn rgba_opaque_uses_1() {
        let c = Color {
            r: 54,
            g: 162,
            b: 235,
            a: 1.0,
        };
        assert_eq!(rgba_string(&c), "rgba(54,162,235,1)");
    }

    #[test]
    fn rgba_half_alpha() {
        let c = Color {
            r: 54,
            g: 162,
            b: 235,
            a: 0.5,
        };
        assert_eq!(rgba_string(&c), "rgba(54,162,235,0.5)");
    }

    #[test]
    fn rgba_transparent_uses_0() {
        let c = Color {
            r: 0,
            g: 0,
            b: 0,
            a: 0.0,
        };
        assert_eq!(rgba_string(&c), "rgba(0,0,0,0)");
    }

    #[test]
    fn rgba_trims_trailing_zeros() {
        let c = Color {
            r: 1,
            g: 2,
            b: 3,
            a: 0.25,
        };
        assert_eq!(rgba_string(&c), "rgba(1,2,3,0.25)");
    }

    #[test]
    fn builds_meta_series_counts_for_bar() {
        let json = r#"{"type":"bar","data":{"labels":["1月","2月","3月"],
          "datasets":[{"label":"売上","data":[120,200,150]}]}}"#;
        let spec = chartjs::parse(json, false).unwrap();
        let model = build_model_core(&spec);
        assert_eq!(model.meta.r#type, "bar");
        assert_eq!(model.series.len(), 1);
        assert_eq!(model.series[0].label, "売上");
        // 既定パレット先頭 #36A2EB、fill alpha=0.5 / stroke alpha=1.0(chart.js v4)
        assert_eq!(
            model.series[0].fill,
            vec!["rgba(54,162,235,0.5)".to_string()]
        );
        assert_eq!(
            model.series[0].stroke,
            vec!["rgba(54,162,235,1)".to_string()]
        );
        assert_eq!(model.series[0].values, vec![120.0, 200.0, 150.0]);
        assert_eq!(model.counts.datasets, 1);
        assert_eq!(model.counts.x_ticks, 3);
    }

    #[test]
    fn pie_emits_per_slice_fill() {
        let json = r##"{"type":"pie","data":{"labels":["a","b","c"],
          "datasets":[{"data":[1,2,3],
          "backgroundColor":["#ff0000","#00ff00","#0000ff"]}]}}"##;
        let spec = chartjs::parse(json, false).unwrap();
        let model = build_model_core(&spec);
        assert_eq!(model.series[0].fill.len(), 3);
        assert_eq!(model.series[0].fill[0], "rgba(255,0,0,1)");
    }

    #[test]
    fn bar_has_linear_y_and_category_x() {
        let json = r#"{"type":"bar","data":{"labels":["1月","2月","3月"],
          "datasets":[{"data":[0,100,50]}]}}"#;
        let spec = chartjs::parse(json, false).unwrap();
        let m = TextMeasurer::new(DEFAULT_FONT).unwrap();
        let model = build_model(&spec, &m);
        let axes = model.axes.expect("bar には軸があるべき");
        assert_eq!(axes.y.kind, "linear");
        assert_eq!(axes.y.min, Some(0.0));
        assert_eq!(axes.x.kind, "category");
        assert_eq!(
            axes.x.labels.as_deref(),
            Some(&["1月".to_string(), "2月".to_string(), "3月".to_string()][..])
        );
        // y_ticks は目盛り数に同期
        assert_eq!(model.counts.y_ticks, axes.y.ticks.unwrap().len());
    }

    #[test]
    fn pie_has_no_axes() {
        let json = r#"{"type":"pie","data":{"labels":["a","b"],"datasets":[{"data":[1,2]}]}}"#;
        let spec = chartjs::parse(json, false).unwrap();
        let m = TextMeasurer::new(DEFAULT_FONT).unwrap();
        let model = build_model(&spec, &m);
        assert!(model.axes.is_none());
    }

    #[test]
    fn horizontal_bar_puts_value_axis_on_y() {
        // 横棒でも値(線形)軸は y に、カテゴリは x に載る(JS 抽出器の規約に揃える)。
        let json = r#"{"type":"bar","data":{"labels":["a","b"],
          "datasets":[{"data":[10,90]}]},"options":{"indexAxis":"y"}}"#;
        let spec = chartjs::parse(json, false).unwrap();
        let m = TextMeasurer::new(DEFAULT_FONT).unwrap();
        let model = build_model(&spec, &m);
        let axes = model.axes.expect("横棒には軸があるべき");
        assert_eq!(axes.y.kind, "linear");
        assert_eq!(axes.y.min, Some(0.0));
        assert_eq!(axes.x.kind, "category");
        assert!(model.counts.y_ticks > 0);
        assert_eq!(model.counts.y_ticks, axes.y.ticks.unwrap().len());
    }

    #[test]
    fn scatter_has_linear_x_and_y_axes() {
        let json = r#"{"type":"scatter","data":{"datasets":[{"data":[
          {"x":1,"y":2},{"x":3,"y":8}]}]}}"#;
        let spec = chartjs::parse(json, false).unwrap();
        let m = TextMeasurer::new(DEFAULT_FONT).unwrap();
        let model = build_model(&spec, &m);
        let axes = model.axes.expect("scatter には軸があるべき");
        assert_eq!(axes.x.kind, "linear");
        assert_eq!(axes.y.kind, "linear");
        assert!(model.counts.y_ticks > 0);
        assert_eq!(model.counts.y_ticks, axes.y.ticks.unwrap().len());
    }

    #[test]
    fn pie_stroke_claims_rendered_white() {
        // renderer は borderColor を無視し白でスライス境界を描くので、モデルも白を主張する。
        let json = r##"{"type":"pie","data":{"labels":["a","b"],
          "datasets":[{"data":[1,2],"borderColor":"#ff0000"}]}}"##;
        let spec = chartjs::parse(json, false).unwrap();
        let model = build_model_core(&spec);
        assert_eq!(
            model.series[0].stroke,
            vec!["rgba(255,255,255,1)".to_string()]
        );
    }

    #[test]
    fn empty_dataset_emits_no_element_colors() {
        // 空データセットは描画マークが無いため fill/stroke とも空(chart.js と一致)。
        let json = r#"{"type":"bar","data":{"labels":[],"datasets":[{"data":[]}]}}"#;
        let spec = chartjs::parse(json, false).unwrap();
        let model = build_model_core(&spec);
        assert!(model.series[0].fill.is_empty());
        assert!(model.series[0].stroke.is_empty());
    }

    #[test]
    fn bar_has_normalized_geometry() {
        let json = r#"{"type":"bar","data":{"labels":["A","B","C"],
          "datasets":[{"data":[10,20,30]}]}}"#;
        let spec = chartjs::parse(json, false).unwrap();
        let m = TextMeasurer::new(DEFAULT_FONT).unwrap();
        let model = build_model(&spec, &m);
        let g = model.geometry.expect("縦棒には geometry があるべき");
        // plot_area はキャンバス [0,1] 内、要素はプロット領域 [0,1] 内。
        assert!(g.plot_area.x > 0.0 && g.plot_area.x < 1.0);
        assert!(g.plot_area.w > 0.0 && g.plot_area.w <= 1.0);
        assert_eq!(g.elements.len(), 3);
        for e in &g.elements {
            assert_eq!(e.kind, "bar");
            assert!(e.nx >= 0.0 && e.nx <= 1.0, "nx={}", e.nx);
            assert!(e.nw > 0.0 && e.nw <= 1.0, "nw={}", e.nw);
            assert!(e.nh >= 0.0 && e.nh <= 1.0, "nh={}", e.nh);
        }
        // 左→右にカテゴリが並ぶ。
        assert!(g.elements[0].nx < g.elements[1].nx);
        assert!(g.elements[1].nx < g.elements[2].nx);
        // 値が大きいほど高い。
        assert!(g.elements[2].nh > g.elements[0].nh);
    }

    #[test]
    fn pie_has_no_geometry() {
        let json = r#"{"type":"pie","data":{"labels":["a","b"],"datasets":[{"data":[1,2]}]}}"#;
        let spec = chartjs::parse(json, false).unwrap();
        let m = TextMeasurer::new(DEFAULT_FONT).unwrap();
        let model = build_model(&spec, &m);
        assert!(model.geometry.is_none());
    }

    #[test]
    fn horizontal_bar_has_no_geometry_yet() {
        // 横棒は今回スコープ外: geometry=None。
        let json = r#"{"type":"bar","data":{"labels":["a","b"],
          "datasets":[{"data":[10,90]}]},"options":{"indexAxis":"y"}}"#;
        let spec = chartjs::parse(json, false).unwrap();
        let m = TextMeasurer::new(DEFAULT_FONT).unwrap();
        let model = build_model(&spec, &m);
        assert!(model.geometry.is_none());
    }

    #[test]
    fn scatter_has_normalized_geometry() {
        let json = r#"{"type":"scatter","data":{"datasets":[
          {"data":[{"x":1,"y":2},{"x":3,"y":4},{"x":5,"y":6}]}]}}"#;
        let spec = chartjs::parse(json, false).unwrap();
        let m = TextMeasurer::new(DEFAULT_FONT).unwrap();
        let model = build_model(&spec, &m);
        let g = model.geometry.expect("scatter には geometry があるべき");
        assert_eq!(g.elements.len(), 3);
        for e in &g.elements {
            assert_eq!(e.kind, "scatter");
            assert_eq!(e.nw, 0.0);
            assert_eq!(e.nh, 0.0);
            assert!(e.nx >= 0.0 && e.nx <= 1.0, "nx={}", e.nx);
            assert!(e.ny >= 0.0 && e.ny <= 1.0, "ny={}", e.ny);
        }
        assert!(g.elements[0].nx < g.elements[1].nx);
        assert!(g.elements[1].nx < g.elements[2].nx);
    }

    #[test]
    fn bubble_has_normalized_geometry_with_radius() {
        let json = r#"{"type":"bubble","data":{"datasets":[
          {"data":[{"x":1,"y":2,"r":10},{"x":3,"y":4,"r":20}]}]}}"#;
        let spec = chartjs::parse(json, false).unwrap();
        let m = TextMeasurer::new(DEFAULT_FONT).unwrap();
        let model = build_model(&spec, &m);
        let g = model.geometry.expect("bubble には geometry があるべき");
        assert_eq!(g.elements.len(), 2);
        for e in &g.elements {
            assert_eq!(e.kind, "bubble");
            assert!(e.nw > 0.0, "bubble の nw(正規化半径)は正: nw={}", e.nw);
        }
        assert!(g.elements[1].nw > g.elements[0].nw, "大きい r は大きい nw");
    }

    #[test]
    fn line_has_normalized_geometry() {
        let json = r#"{"type":"line","data":{"labels":["a","b","c"],
          "datasets":[{"data":[10,20,30]}]}}"#;
        let spec = chartjs::parse(json, false).unwrap();
        let m = TextMeasurer::new(DEFAULT_FONT).unwrap();
        let model = build_model(&spec, &m);
        let g = model.geometry.expect("line には geometry があるべき");
        assert_eq!(g.elements.len(), 3);
        for e in &g.elements {
            assert_eq!(e.kind, "line");
            assert_eq!(e.nw, 0.0);
            assert_eq!(e.nh, 0.0);
        }
        assert!(g.elements[0].nx < g.elements[1].nx);
        assert!(
            g.elements[2].ny < g.elements[0].ny,
            "大きい値は小さい ny(上方向)"
        );
    }

    /// クロス言語フィクスチャ: ここの行は
    /// `tools/chartjs-compat/rgba-fixture.json` と同一でなければならない。
    /// Rust `rgba_string` と JS `fmtAlpha` の乖離をどちらか一方のテストで必ず捕捉する。
    #[test]
    fn rgba_string_matches_cross_language_fixture() {
        let rows: &[(u8, u8, u8, f32, &str)] = &[
            (0, 0, 0, 0.0, "rgba(0,0,0,0)"),
            (1, 2, 3, 1.0, "rgba(1,2,3,1)"),
            (54, 162, 235, 0.5, "rgba(54,162,235,0.5)"),
            (255, 99, 132, 0.25, "rgba(255,99,132,0.25)"),
            (10, 20, 30, 0.333, "rgba(10,20,30,0.333)"),
            (10, 20, 30, 0.3333333, "rgba(10,20,30,0.333)"),
            (10, 20, 30, 0.1, "rgba(10,20,30,0.1)"),
            (10, 20, 30, 0.999, "rgba(10,20,30,0.999)"),
            (10, 20, 30, 0.9999, "rgba(10,20,30,1)"),
            (10, 20, 30, 0.0004, "rgba(10,20,30,0)"),
        ];
        for &(r, g, b, a, expected) in rows {
            let c = Color { r, g, b, a };
            assert_eq!(rgba_string(&c), expected, "row r={r} g={g} b={b} a={a}");
        }
    }
}