Skip to main content

plotting/
spec.rs

1//! Chart intermediate representation.
2//!
3//! This is the one contract that adapters, renderers (SVG, canvas,
4//! ratatui), and the JSON wire format all share. Serialises cleanly so
5//! the WASM canvas renderer can consume the same bytes the server
6//! produces.
7
8use serde::{Deserialize, Serialize};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
11#[serde(rename_all = "lowercase")]
12pub enum ChartKind {
13    Bar,
14    /// Bars grow right from a left axis of x labels, one row per label.
15    HBar,
16    StackedBar,
17    Line,
18}
19
20/// One x/y datum. `y` is carried as a `num`/`denom` pair so the exact
21/// Rational64 crosses the wire without float drift; each renderer
22/// converts to `f64` for display.
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24pub struct SeriesPoint {
25    pub x: String,
26    pub y_num: i64,
27    pub y_denom: i64,
28}
29
30impl SeriesPoint {
31    /// Best-effort conversion to an `f64` for the renderer. A zero
32    /// denominator falls back to 0.0 rather than panicking — an
33    /// invariant violation in the IR shouldn't take down the renderer.
34    #[must_use]
35    pub fn y_f64(&self) -> f64 {
36        if self.y_denom == 0 {
37            return 0.0;
38        }
39        self.y_num as f64 / self.y_denom as f64
40    }
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct Series {
45    pub label: String,
46    /// Commodity symbol (e.g. "USD"). Empty when the series is unitless.
47    pub commodity_symbol: String,
48    pub points: Vec<SeriesPoint>,
49}
50
51/// A chart the server has already prepared. Renderers read this
52/// directly; none of them compute totals, pick top-N, or negate
53/// signs. All of that lives in the adapters.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55pub struct ChartSpec {
56    pub title: String,
57    pub kind: ChartKind,
58    pub x_label: String,
59    pub y_label: String,
60    pub series: Vec<Series>,
61    /// Display-time notes (e.g. "Showing USD; 2 other commodities
62    /// hidden"). Rendered as an info line under the chart.
63    pub notes: Vec<String>,
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    fn sample() -> ChartSpec {
71        ChartSpec {
72            title: "Income vs Expense".to_string(),
73            kind: ChartKind::StackedBar,
74            x_label: "Month".to_string(),
75            y_label: "Amount".to_string(),
76            series: vec![
77                Series {
78                    label: "Income".to_string(),
79                    commodity_symbol: "USD".to_string(),
80                    points: vec![
81                        SeriesPoint {
82                            x: "2026-01".to_string(),
83                            y_num: 3200,
84                            y_denom: 1,
85                        },
86                        SeriesPoint {
87                            x: "2026-02".to_string(),
88                            y_num: 2800,
89                            y_denom: 1,
90                        },
91                    ],
92                },
93                Series {
94                    label: "Expense".to_string(),
95                    commodity_symbol: "USD".to_string(),
96                    points: vec![
97                        SeriesPoint {
98                            x: "2026-01".to_string(),
99                            y_num: 2100,
100                            y_denom: 1,
101                        },
102                        SeriesPoint {
103                            x: "2026-02".to_string(),
104                            y_num: 1900,
105                            y_denom: 1,
106                        },
107                    ],
108                },
109            ],
110            notes: vec!["Showing USD only; 1 other commodity hidden".to_string()],
111        }
112    }
113
114    #[test]
115    fn spec_round_trips_through_json() {
116        let original = sample();
117        let encoded = serde_json::to_string(&original).expect("serialise");
118        let decoded: ChartSpec = serde_json::from_str(&encoded).expect("deserialise");
119        assert_eq!(decoded, original, "wire format must be lossless");
120    }
121
122    #[test]
123    fn chart_kind_serialises_as_lowercase() {
124        let s = serde_json::to_string(&ChartKind::StackedBar).expect("serialise");
125        assert_eq!(s, "\"stackedbar\"");
126    }
127
128    #[test]
129    fn series_point_converts_to_f64() {
130        let p = SeriesPoint {
131            x: "x".to_string(),
132            y_num: 3,
133            y_denom: 2,
134        };
135        assert!((p.y_f64() - 1.5).abs() < f64::EPSILON);
136    }
137
138    #[test]
139    fn series_point_zero_denominator_is_safe() {
140        let p = SeriesPoint {
141            x: "x".to_string(),
142            y_num: 42,
143            y_denom: 0,
144        };
145        assert_eq!(p.y_f64(), 0.0);
146    }
147}