fulgur-chart 0.8.0

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
//! scatter チャート: 線形 x × 線形 y 軸に点(円)を描く。
//! カテゴリ系の `common::compute` は x をカテゴリ前提にするため、ここでは
//! 線形フレームを自前で組む。共有できる凡例/定数/テーマは `common` を再利用する。

use super::common::{
    LEGEND_BAND, OUTER_PAD, TEXT_BASELINE_RATIO, TITLE_BAND, TITLE_FONT, X_LABEL_BAND,
    X_LABEL_CENTER_RATIO, draw_vertical_legend, legend_band_width_vertical, legend_entry_width,
};
use crate::ir::{AxisSpec, ChartKind, ChartSpec, Color, LegendPos, Point};
use crate::num::fmt_num;
use crate::scale::{LinearScale, nice_ticks};
use crate::scene::{Anchor, Prim, Scene};
use crate::text::TextMeasurer;

/// scatter のマーカー既定半径。chart.js scatter の pointRadius 既定値 ~3.0。
const DEFAULT_POINT_R: f64 = 3.0;

/// bubble で `point.r` が無い場合の既定半径。bubble は通常 r を持つが保険。
const DEFAULT_BUBBLE_R: f64 = 5.0;

/// 1 点の半径を返す。bubble はデータの第3次元 `point.r` を優先し、無ければ
/// dataset の `pointRadius`、それも無ければ既定値。scatter は dataset の `pointRadius`
/// (chart.js の指定)を使い、無指定なら既定値。非有限/負の半径は不正な SVG を避けるため
/// それぞれの既定値にフォールバックする。
fn point_radius(kind: &ChartKind, point: &Point, dataset_radius: Option<f64>) -> f64 {
    let valid = |r: f64, fallback: f64| {
        if r.is_finite() && r >= 0.0 {
            r
        } else {
            fallback
        }
    };
    match kind {
        ChartKind::Bubble => {
            let r = point.r.or(dataset_radius).unwrap_or(DEFAULT_BUBBLE_R);
            valid(r, DEFAULT_BUBBLE_R)
        }
        _ => valid(dataset_radius.unwrap_or(DEFAULT_POINT_R), DEFAULT_POINT_R),
    }
}

/// 凡例の有無(Top/Bottom/Left/Right かつ名前付き系列が 1 つ以上)。
fn has_legend(spec: &ChartSpec) -> bool {
    matches!(
        spec.legend,
        LegendPos::Top | LegendPos::Bottom | LegendPos::Left | LegendPos::Right
    ) && spec.series.iter().any(|s| !s.name.is_empty())
}

/// 全系列の全点から 1 軸ぶんのドメインを求める。`select` で x/y を選ぶ。
/// 非有限値は無視し、有限値が無ければ 0.0..1.0 にフォールバックする(NaN/panic 回避)。
/// nice_ticks 側が min==max(縮退)を吸収するため、ここでは追加の拡張はしない。
/// `axis_spec` の suggested_min/suggested_max はドメインを広げるだけ(データが優先)。
pub(crate) fn axis_domain(
    spec: &ChartSpec,
    axis_spec: &AxisSpec,
    select: impl Fn(&Point) -> f64,
) -> (f64, f64) {
    let mut lo = f64::INFINITY;
    let mut hi = f64::NEG_INFINITY;
    for s in &spec.series {
        for p in &s.points {
            let v = select(p);
            if v.is_finite() {
                if v < lo {
                    lo = v;
                }
                if v > hi {
                    hi = v;
                }
            }
        }
    }
    // データなし: suggested を初期シードとして使う(chart.js 互換)。suggested もなければ 0..1。
    if !lo.is_finite() || !hi.is_finite() {
        lo = axis_spec
            .suggested_min
            .filter(|s| s.is_finite())
            .unwrap_or(0.0);
        hi = axis_spec
            .suggested_max
            .filter(|s| s.is_finite())
            .unwrap_or(if lo == 0.0 { 1.0 } else { lo + 1.0 });
        if axis_spec.begin_at_zero {
            lo = lo.min(0.0);
            hi = hi.max(0.0);
        }
        return (lo, if hi > lo { hi } else { lo + 1.0 });
    }
    // begin_at_zero でドメインに 0 を含める。
    if axis_spec.begin_at_zero {
        lo = lo.min(0.0);
        hi = hi.max(0.0);
    }
    // suggestedMin/suggestedMax: データが優先、suggested はドメインを広げるだけ。
    // 非有限値(Infinity/NaN)は nice_ticks で無限 range を生じさせるため無視する。
    if let Some(s) = axis_spec.suggested_min {
        if s.is_finite() && s < lo {
            lo = s;
        }
    }
    if let Some(s) = axis_spec.suggested_max {
        if s.is_finite() && s > hi {
            hi = s;
        }
    }
    (lo, hi)
}

pub fn build(spec: &ChartSpec, m: &TextMeasurer) -> Scene {
    let ink = spec.theme.text_color;
    let label_font = spec.theme.font_size;

    // x/y ドメイン → nice ticks。
    let (xmin, xmax) = axis_domain(spec, &spec.x_axis, |p| p.x);
    let (ymin, ymax) = axis_domain(spec, &spec.y_axis, |p| p.y);
    let x_ticks = nice_ticks(xmin, xmax, 10);
    let y_ticks = nice_ticks(ymin, ymax, 10);

    // y 軸ラベル幅(目盛りラベルの最大幅 + 余白)。
    let mut max_y_w = 0.0_f32;
    for &t in &y_ticks.ticks {
        let w = m.width(&fmt_num(t), label_font as f32);
        if w > max_y_w {
            max_y_w = w;
        }
    }
    let y_axis_w = max_y_w as f64 + 10.0;

    // 凡例帯(カテゴリ系 common と同じロジック)。
    let legend = has_legend(spec);
    let title_band = if spec.title.is_some() {
        TITLE_BAND
    } else {
        0.0
    };
    let legend_top = if legend && spec.legend == LegendPos::Top {
        LEGEND_BAND
    } else {
        0.0
    };
    let legend_bottom = if legend && spec.legend == LegendPos::Bottom {
        LEGEND_BAND
    } else {
        0.0
    };
    let series_names: Vec<String> = spec.series.iter().map(|s| s.name.clone()).collect();
    let legend_left = if legend && spec.legend == LegendPos::Left {
        legend_band_width_vertical(m, &series_names, label_font)
    } else {
        0.0
    };
    let legend_right = if legend && spec.legend == LegendPos::Right {
        legend_band_width_vertical(m, &series_names, label_font)
    } else {
        0.0
    };

    let plot_left = OUTER_PAD + y_axis_w + legend_left;
    let plot_right = spec.width - OUTER_PAD - legend_right;
    let plot_top = OUTER_PAD + title_band + legend_top;
    let plot_bottom = spec.height - OUTER_PAD - X_LABEL_BAND - legend_bottom;

    // 線形スケール: x は左→右(非反転)、y は下→上(反転)。
    let xs = LinearScale::new(x_ticks.min, x_ticks.max, plot_left, plot_right);
    let ys = LinearScale::new(y_ticks.min, y_ticks.max, plot_bottom, plot_top);

    let mut items: Vec<Prim> = Vec::new();

    // 1. タイトル。
    if let Some(title) = &spec.title {
        items.push(Prim::Text {
            x: spec.width / 2.0,
            y: OUTER_PAD + TITLE_FONT,
            size: TITLE_FONT,
            anchor: Anchor::Middle,
            fill: ink,
            content: title.clone(),
        });
    }

    // 2. 横グリッド + y 目盛りラベル(右寄せ)。
    for &t in &y_ticks.ticks {
        let y = ys.map(t);
        items.push(Prim::Line {
            x1: plot_left,
            y1: y,
            x2: plot_right,
            y2: y,
            stroke: spec.theme.grid_color,
            stroke_width: 1.0,
        });
        items.push(Prim::Text {
            x: plot_left - 6.0,
            y: y + label_font * TEXT_BASELINE_RATIO,
            size: label_font,
            anchor: Anchor::End,
            fill: ink,
            content: fmt_num(t),
        });
    }

    // 3. 縦グリッド + x 目盛りラベル(軸下に中央寄せ)。
    for &t in &x_ticks.ticks {
        let x = xs.map(t);
        items.push(Prim::Line {
            x1: x,
            y1: plot_top,
            x2: x,
            y2: plot_bottom,
            stroke: spec.theme.grid_color,
            stroke_width: 1.0,
        });
        items.push(Prim::Text {
            x,
            y: plot_bottom + X_LABEL_BAND * X_LABEL_CENTER_RATIO,
            size: label_font,
            anchor: Anchor::Middle,
            fill: ink,
            content: fmt_num(t),
        });
    }

    // 4. 軸ベースライン(x 下辺 + y 左辺)。
    items.push(Prim::Line {
        x1: plot_left,
        y1: plot_bottom,
        x2: plot_right,
        y2: plot_bottom,
        stroke: ink,
        stroke_width: 1.0,
    });
    items.push(Prim::Line {
        x1: plot_left,
        y1: plot_top,
        x2: plot_left,
        y2: plot_bottom,
        stroke: ink,
        stroke_width: 1.0,
    });

    // 5. 点(円)。系列・点とも入力順。非有限座標はスキップ。
    for ser in &spec.series {
        for (i, p) in ser.points.iter().enumerate() {
            if !p.x.is_finite() || !p.y.is_finite() {
                continue;
            }
            items.push(Prim::Circle {
                cx: xs.map(p.x),
                cy: ys.map(p.y),
                r: point_radius(&spec.kind, p, ser.point_radius),
                fill: ser.fill_at(i),
                stroke: ser.stroke_at(i),
                stroke_width: ser.stroke_width,
            });
        }
    }

    // 6. 凡例(Top/Bottom: 横並び。draw_frame と同じ配置)。
    if legend && matches!(spec.legend, LegendPos::Top | LegendPos::Bottom) {
        let mut total = 0.0_f64;
        for (k, ser) in spec.series.iter().enumerate() {
            let ew = legend_entry_width(m, &ser.name, label_font);
            total += ew;
            if k == spec.series.len() - 1 {
                total -= 16.0;
            }
        }
        let start_x = (spec.width - total) / 2.0;
        let legend_cy = if spec.legend == LegendPos::Top {
            OUTER_PAD + title_band + LEGEND_BAND / 2.0
        } else {
            spec.height - OUTER_PAD - LEGEND_BAND / 2.0
        };
        let mut cursor = start_x;
        for ser in &spec.series {
            items.push(Prim::Rect {
                x: cursor,
                y: legend_cy - 6.0,
                w: 12.0,
                h: 12.0,
                fill: ser.fill_at(0),
            });
            items.push(Prim::Text {
                x: cursor + 16.0,
                y: legend_cy + label_font * TEXT_BASELINE_RATIO,
                size: label_font,
                anchor: Anchor::Start,
                fill: ink,
                content: ser.name.clone(),
            });
            cursor += legend_entry_width(m, &ser.name, label_font);
        }
    }

    // 6b. 凡例(Left/Right: 縦並び)。
    if legend && matches!(spec.legend, LegendPos::Left | LegendPos::Right) {
        let entries: Vec<(String, Color)> = spec
            .series
            .iter()
            .map(|s| (s.name.clone(), s.fill_at(0)))
            .collect();
        let band_x = if spec.legend == LegendPos::Left {
            OUTER_PAD
        } else {
            spec.width - OUTER_PAD - legend_right
        };
        draw_vertical_legend(
            &mut items,
            &entries,
            band_x,
            plot_top,
            plot_bottom,
            ink,
            label_font,
        );
    }

    Scene {
        width: spec.width,
        height: spec.height,
        items,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ir::{AxisSpec, ChartKind, ChartSpec, LegendPos, Point, Series, SeriesType};

    fn make_scatter_spec(points: &[(f64, f64)]) -> ChartSpec {
        let palette = crate::palette::PALETTE.to_vec();
        ChartSpec {
            kind: ChartKind::Scatter,
            categories: vec![],
            series: vec![Series {
                name: String::new(),
                values: vec![],
                points: points
                    .iter()
                    .map(|&(x, y)| Point { x, y, r: None })
                    .collect(),
                fill: vec![palette[0]],
                stroke: vec![],
                stroke_width: 1.0,
                area: false,
                tension: 0.0,
                series_type: SeriesType::Bar,
                point_radius: None,
                box_points: vec![],
            }],
            x_axis: AxisSpec {
                title: None,
                min: None,
                max: None,
                suggested_min: None,
                suggested_max: None,
                begin_at_zero: false,
                grid: true,
            },
            y_axis: AxisSpec {
                title: None,
                min: None,
                max: None,
                suggested_min: None,
                suggested_max: None,
                begin_at_zero: false,
                grid: true,
            },
            legend: LegendPos::None,
            title: None,
            width: 600.0,
            height: 400.0,
            data_labels: false,
            theme: crate::ir::Theme::default(),
        }
    }

    #[test]
    fn axis_domain_suggested_min_expands_below_data() {
        // x データが [1.0, 10.0]、suggested_min=-5.0 → ドメインが -5.0 まで広がる。
        let mut spec = make_scatter_spec(&[(1.0, 0.0), (10.0, 0.0)]);
        spec.x_axis.suggested_min = Some(-5.0);
        let (lo, _hi) = axis_domain(&spec, &spec.x_axis, |p| p.x);
        assert_eq!(
            lo, -5.0,
            "suggested_min=-5 はドメインを正確に -5.0 に設定すべき: 実際 lo={lo}"
        );
    }

    #[test]
    fn axis_domain_suggested_min_noop_when_data_lower() {
        // x データが [1.0, 10.0]、suggested_min=5.0 → データ(1.0)が優先されるので no-op。
        let mut spec = make_scatter_spec(&[(1.0, 0.0), (10.0, 0.0)]);
        spec.x_axis.suggested_min = Some(5.0);
        let (lo, _hi) = axis_domain(&spec, &spec.x_axis, |p| p.x);
        assert_eq!(
            lo, 1.0,
            "suggested_min=5 はデータの下端(1.0)を維持すべき: 実際 lo={lo}"
        );
    }

    #[test]
    fn axis_domain_suggested_max_expands_above_data() {
        // x データが [1.0, 10.0]、suggested_max=15.0 → ドメインが 15.0 まで広がる。
        let mut spec = make_scatter_spec(&[(1.0, 0.0), (10.0, 0.0)]);
        spec.x_axis.suggested_max = Some(15.0);
        let (_lo, hi) = axis_domain(&spec, &spec.x_axis, |p| p.x);
        assert_eq!(
            hi, 15.0,
            "suggested_max=15 はドメインを正確に 15.0 に設定すべき: 実際 hi={hi}"
        );
    }

    #[test]
    fn axis_domain_suggested_max_noop_when_data_higher() {
        // x データが [1.0, 10.0]、suggested_max=5.0 → データ(10.0)が優先されるので no-op。
        let mut spec = make_scatter_spec(&[(1.0, 0.0), (10.0, 0.0)]);
        spec.x_axis.suggested_max = Some(5.0);
        let (_lo, hi) = axis_domain(&spec, &spec.x_axis, |p| p.x);
        assert_eq!(
            hi, 10.0,
            "suggested_max=5 はデータの上端(10.0)を縮小してはいけない: 実際 hi={hi}"
        );
    }
}