Skip to main content

byob_types/
chart.rs

1//! Charts byob draws itself: `ChartSpec` v1, the same JSON hob saves as `<title>.chart.json`,
2//! so chart files move between the two apps.
3//!
4//! [`validate`] ports hob's `validateChart` (`app/src/shared/chart.ts`): it coerces
5//! numbers written as text ("1,234.5", "€12", "40%"), puts timelines in date order, caps
6//! rows and series, and fails with one plain sentence the model can act on.
7
8use serde::{Deserialize, Serialize};
9use serde_json::{Map, Value};
10
11/// Most rows one chart may hold.
12pub const MAX_ROWS: usize = 2000;
13/// Most series (number columns) one chart may hold.
14pub const MAX_SERIES: usize = 8;
15/// Longest title kept, in characters.
16pub const MAX_TITLE_CHARS: usize = 120;
17/// Longest unit kept, in characters.
18pub const MAX_UNIT_CHARS: usize = 12;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
21#[serde(rename_all = "lowercase")]
22pub enum ChartType {
23    Bar,
24    Line,
25    Area,
26    Pie,
27    Scatter,
28}
29
30impl ChartType {
31    pub const ALL: [ChartType; 5] = [ChartType::Bar, ChartType::Line, ChartType::Area, ChartType::Pie, ChartType::Scatter];
32
33    pub fn name(self) -> &'static str {
34        match self {
35            ChartType::Bar => "bar",
36            ChartType::Line => "line",
37            ChartType::Area => "area",
38            ChartType::Pie => "pie",
39            ChartType::Scatter => "scatter",
40        }
41    }
42
43    pub fn from_name(s: &str) -> Option<Self> {
44        Self::ALL.into_iter().find(|t| t.name() == s)
45    }
46}
47
48/// One number column and how the legend names it.
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50pub struct ChartSeries {
51    pub key: String,
52    pub label: String,
53}
54
55/// A validated chart. Build it with [`validate`]; a spec read from disk or the wire should
56/// be passed through [`validate`] again (see [`ChartSpec::from_json`]).
57#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
58pub struct ChartSpec {
59    /// Always 1.
60    pub version: u32,
61    #[serde(rename = "type")]
62    pub kind: ChartType,
63    pub title: String,
64    /// The column along the bottom (pie: the slice names).
65    pub x: String,
66    pub series: Vec<ChartSeries>,
67    /// Rows: `x` holds a string or number (scatter: a number or null); each series key a
68    /// number or null.
69    pub data: Vec<Map<String, Value>>,
70    /// Shown with numbers, e.g. "€" or "kg".
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub unit: Option<String>,
73    /// Bars or areas on top of each other.
74    #[serde(default, skip_serializing_if = "is_false")]
75    pub stacked: bool,
76    /// Where the rows come from when the chart is drawn from a spreadsheet: it is drawn again
77    /// from there whenever the sheet changes (the sheets plugin's `chart_sheet`).
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub source: Option<Box<ChartSource>>,
80}
81
82/// A chart's spreadsheet: artifact `sheet`, tab `tab`, the row with the column names
83/// (`header_row`, 1-based) and the columns (letters) of `x` and each series; the rows run from
84/// under the header to the last one with an `x`.
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86pub struct ChartSource {
87    pub sheet: String,
88    #[serde(default, skip_serializing_if = "String::is_empty")]
89    pub tab: String,
90    pub header_row: u32,
91    pub x: String,
92    pub series: Vec<String>,
93    /// The last row charted (a selection's bottom); without it, down to the first row with an
94    /// empty `x`.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub last_row: Option<u32>,
97}
98
99/// Longest artifact id or tab name kept in a [`ChartSource`].
100const MAX_SOURCE_NAME: usize = 128;
101
102impl ChartSource {
103    /// From untrusted JSON: `None` unless it names a sheet and plain column letters.
104    fn from_value(v: &Value) -> Option<Self> {
105        let o = v.as_object()?;
106        let text = |k: &str| o.get(k).and_then(Value::as_str).map(str::trim).filter(|t| t.chars().count() <= MAX_SOURCE_NAME).map(str::to_owned);
107        let column = |c: &str| (1..=3).contains(&c.len()) && c.bytes().all(|b| b.is_ascii_uppercase());
108        let sheet = text("sheet").filter(|s| !s.is_empty())?;
109        let x = text("x").filter(|x| column(x))?;
110        let series: Vec<String> =
111            o.get("series")?.as_array()?.iter().filter_map(Value::as_str).filter(|c| column(c)).take(MAX_SERIES).map(str::to_owned).collect();
112        let header_row = o.get("header_row").and_then(Value::as_u64).filter(|r| (1..=1_048_576).contains(r)).and_then(|r| u32::try_from(r).ok())?;
113        let last_row = o.get("last_row").and_then(Value::as_u64).and_then(|r| u32::try_from(r).ok()).filter(|r| *r > header_row);
114        (!series.is_empty()).then(|| Self { sheet, tab: text("tab").unwrap_or_default(), header_row, x, series, last_row })
115    }
116}
117
118fn is_false(b: &bool) -> bool {
119    !*b
120}
121
122impl ChartSpec {
123    /// Parse and re-validate an untrusted `.chart.json` (from disk, hob, or a peer).
124    pub fn from_json(text: &str) -> Result<Self, String> {
125        let v: Value = serde_json::from_str(text).map_err(|e| format!("not a chart file: {e}"))?;
126        validate(&v)
127    }
128
129    pub fn to_json(&self) -> String {
130        serde_json::to_string(self).unwrap_or_default()
131    }
132
133    /// A number cell (`None` for null, missing or non-numbers).
134    pub fn number(row: &Map<String, Value>, key: &str) -> Option<f64> {
135        row.get(key).and_then(Value::as_f64).filter(|n| n.is_finite())
136    }
137
138    /// The `x` cell of a row as text, for labels.
139    pub fn label(&self, row: &Map<String, Value>) -> String {
140        match row.get(&self.x) {
141            Some(Value::String(s)) => s.clone(),
142            Some(Value::Null) | None => String::new(),
143            Some(v) => js_string(v),
144        }
145    }
146}
147
148/// `String(v)` as JavaScript would write it, for the values the model sends.
149fn js_string(v: &Value) -> String {
150    match v {
151        Value::Null => "null".into(),
152        Value::Bool(b) => b.to_string(),
153        Value::Number(n) => match n.as_f64() {
154            Some(f) if f.fract() == 0.0 && f.abs() < 1e15 => format!("{f:.0}"),
155            _ => n.to_string(),
156        },
157        Value::String(s) => s.clone(),
158        Value::Array(a) => a.iter().map(|x| if x.is_null() { String::new() } else { js_string(x) }).collect::<Vec<_>>().join(","),
159        Value::Object(_) => "[object Object]".into(),
160    }
161}
162
163/// A chart cell that should hold a number but doesn't.
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub struct NotANumber;
166
167/// A cell as a number: `Ok(None)` for empty, `Err` for something that isn't a number.
168/// "1,234.5" → 1234.5; currency, percent signs and spaces are dropped.
169pub fn to_number(v: Option<&Value>) -> Result<Option<f64>, NotANumber> {
170    match v {
171        None | Some(Value::Null) => Ok(None),
172        Some(Value::String(s)) if s.is_empty() => Ok(None),
173        Some(Value::Number(n)) => n.as_f64().filter(|f| f.is_finite()).map(Some).ok_or(NotANumber),
174        Some(Value::String(s)) => parse_number(s).map(Some).ok_or(NotANumber),
175        Some(_) => Err(NotANumber),
176    }
177}
178
179fn is_word(c: char) -> bool {
180    c.is_ascii_alphanumeric() || c == '_'
181}
182
183/// JavaScript `Number(...)` after hob's clean-up: thousands separators (a comma followed by
184/// exactly three digits) and `%€$£¥` and whitespace removed.
185fn parse_number(s: &str) -> Option<f64> {
186    let chars: Vec<char> = s.trim().chars().collect();
187    let mut cleaned = String::with_capacity(chars.len());
188    for (i, &c) in chars.iter().enumerate() {
189        if c == ',' {
190            let three = (1..=3).all(|k| chars.get(i + k).is_some_and(char::is_ascii_digit));
191            let boundary = !chars.get(i + 4).is_some_and(|&n| is_word(n));
192            if three && boundary {
193                continue;
194            }
195        }
196        if matches!(c, '%' | '€' | '$' | '£' | '¥') || c.is_whitespace() {
197            continue;
198        }
199        cleaned.push(c);
200    }
201    if cleaned.is_empty() {
202        // Number("") is 0 in JavaScript.
203        return Some(0.0);
204    }
205    // Rust accepts "inf"/"nan" spellings JavaScript doesn't; neither is finite anyway.
206    let lower = cleaned.to_ascii_lowercase();
207    if lower.contains("inf") || lower.contains("nan") {
208        return None;
209    }
210    cleaned.parse::<f64>().ok().filter(|f| f.is_finite())
211}
212
213const MONTHS: [&str; 12] = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
214
215fn month_of(word: &str) -> Option<u32> {
216    let w = word.trim_end_matches('.').to_ascii_lowercase();
217    if w.len() < 3 {
218        return None;
219    }
220    let pos = MONTHS.iter().position(|m| w.starts_with(m))?;
221    // Accept "mar", "march", "sept"; refuse e.g. "marble".
222    const FULL: [&str; 12] = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
223    let full = FULL.get(pos)?;
224    (full.starts_with(&w) || w == "sept").then(|| u32::try_from(pos).unwrap_or(0) + 1)
225}
226
227/// Days since 1970-01-01 (proleptic Gregorian).
228fn days_from_civil(y: i64, m: u32, d: u32) -> Option<i64> {
229    if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
230        return None;
231    }
232    let dim = [31, if (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 { 29 } else { 28 }, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
233    if d > *dim.get(usize::try_from(m - 1).ok()?)? {
234        return None;
235    }
236    let y = if m <= 2 { y - 1 } else { y };
237    let era = y.div_euclid(400);
238    let yoe = y - era * 400;
239    let mp = i64::from((m + 9) % 12);
240    let doy = (153 * mp + 2) / 5 + i64::from(d) - 1;
241    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
242    Some(era * 146_097 + doe - 719_468)
243}
244
245/// Seconds into the day for "HH:MM[:SS]" (after a `T` or a space), if present.
246fn time_of(rest: &str) -> Option<i64> {
247    let rest = rest.trim().trim_end_matches('Z');
248    if rest.is_empty() {
249        return Some(0);
250    }
251    let main = rest.split(['+', 'Z', ' ']).next().unwrap_or_default();
252    let mut parts = main.split(':');
253    let h: i64 = parts.next()?.trim().parse().ok()?;
254    let m: i64 = parts.next().map_or(Some(0), |p| p.trim().parse().ok())?;
255    let s: f64 = parts.next().map_or(Some(0.0), |p| p.trim().parse().ok())?;
256    if !(0..24).contains(&h) || !(0..60).contains(&m) || !(0.0..61.0).contains(&s) {
257        return None;
258    }
259    #[allow(clippy::cast_possible_truncation)] // checked range above
260    Some(h * 3600 + m * 60 + s as i64)
261}
262
263/// A sortable time (seconds since 1970) for strings that look like dates — "2026-03-05",
264/// "3/5/2026", "Mar 5, 2026", "5 March 2026", "March 2026", "2026-03". Bare names ("Mar",
265/// "North") and plain numbers are not dates, as in hob.
266pub fn date_of(v: &Value) -> Option<i64> {
267    let s = v.as_str()?.trim();
268    if !s.chars().any(|c| c.is_ascii_digit()) || !s.chars().any(|c| matches!(c, '-' | '/' | '.') || c.is_whitespace()) {
269        return None;
270    }
271    let (date, time) = match s.find(['T', ' ']) {
272        Some(i) if s.as_bytes().first().is_some_and(u8::is_ascii_digit) && s.get(..i).is_some_and(|d| d.contains(['-', '/'])) => {
273            (s.get(..i).unwrap_or(s), s.get(i + 1..).unwrap_or(""))
274        }
275        _ => (s, ""),
276    };
277    let secs = time_of(time)?;
278    let day = numeric_date(date).or_else(|| worded_date(s))?;
279    day.checked_mul(86_400)?.checked_add(secs)
280}
281
282/// "2026-03-05", "2026/3/5", "2026-03", "3/5/2026" (US month first, like JavaScript).
283fn numeric_date(s: &str) -> Option<i64> {
284    let sep = if s.contains('-') {
285        '-'
286    } else if s.contains('/') {
287        '/'
288    } else {
289        return None;
290    };
291    let parts: Vec<&str> = s.split(sep).collect();
292    if parts.iter().any(|p| p.is_empty() || !p.chars().all(|c| c.is_ascii_digit()) || p.len() > 4) {
293        return None;
294    }
295    let n = |i: usize| parts.get(i).and_then(|p| p.parse::<i64>().ok());
296    match parts.as_slice() {
297        [y, _, _] if y.len() == 4 => days_from_civil(n(0)?, u32::try_from(n(1)?).ok()?, u32::try_from(n(2)?).ok()?),
298        [y, _] if y.len() == 4 => days_from_civil(n(0)?, u32::try_from(n(1)?).ok()?, 1),
299        [_, _, y] if sep == '/' && (y.len() == 4 || y.len() == 2) => {
300            let year = if y.len() == 2 { 2000 + n(2)? } else { n(2)? };
301            days_from_civil(year, u32::try_from(n(0)?).ok()?, u32::try_from(n(1)?).ok()?)
302        }
303        _ => None,
304    }
305}
306
307/// "Mar 5, 2026", "5 March 2026", "March 2026", "Tue, 5 Mar 2026".
308fn worded_date(s: &str) -> Option<i64> {
309    let words: Vec<&str> = s.split(|c: char| c.is_whitespace() || c == ',' || c == '-' || c == '/').filter(|w| !w.is_empty()).collect();
310    let mut month = None;
311    let mut year = None;
312    let mut day = None;
313    for w in &words {
314        if let Some(m) = month_of(w) {
315            if month.is_some() {
316                return None;
317            }
318            month = Some(m);
319        } else if let Ok(n) = w.trim_end_matches(['.', 's', 't', 'n', 'd', 'r', 'h']).parse::<i64>() {
320            if w.len() == 4 && year.is_none() {
321                year = Some(n);
322            } else if day.is_none() && (1..=31).contains(&n) {
323                day = Some(n);
324            } else {
325                return None;
326            }
327        } else if w.len() >= 3 && ["mon", "tue", "wed", "thu", "fri", "sat", "sun"].iter().any(|d| w.to_ascii_lowercase().starts_with(d)) {
328            // weekday names are ignored
329        } else {
330            return None;
331        }
332    }
333    days_from_civil(year?, month?, u32::try_from(day.unwrap_or(1)).ok()?)
334}
335
336fn columns(row: Option<&Map<String, Value>>) -> String {
337    row.map(|r| r.keys().cloned().collect::<Vec<_>>().join(", ")).unwrap_or_default()
338}
339
340fn fail(why: impl std::fmt::Display) -> String {
341    format!("Can't draw this chart: {why}")
342}
343
344fn series_of(v: Option<&Value>) -> Vec<ChartSeries> {
345    let raw: Vec<Value> = match v {
346        Some(Value::Array(a)) => a.clone(),
347        Some(Value::String(s)) => vec![Value::String(s.clone())],
348        _ => Vec::new(),
349    };
350    raw.iter()
351        .map(|s| match s {
352            Value::String(k) => ChartSeries { key: k.clone(), label: k.clone() },
353            Value::Object(o) => {
354                let key = o.get("key").filter(|k| !k.is_null()).map(js_string).unwrap_or_default();
355                let label = o.get("label").filter(|l| !l.is_null()).map(js_string).unwrap_or_else(|| key.clone());
356                ChartSeries { key, label }
357            }
358            _ => ChartSeries { key: String::new(), label: String::new() },
359        })
360        .collect()
361}
362
363/// Check a chart the model (or a file) asked for; the error says plainly what to fix.
364pub fn validate(input: &Value) -> Result<ChartSpec, String> {
365    let empty = Map::new();
366    let o = input.as_object().unwrap_or(&empty);
367    let type_name = o.get("type").filter(|t| !t.is_null()).map(js_string).unwrap_or_default();
368    let kind = ChartType::from_name(&type_name).ok_or_else(|| fail(format!("type must be one of {}.", ChartType::ALL.map(ChartType::name).join(", "))))?;
369    let data: Vec<&Map<String, Value>> = match o.get("data") {
370        Some(Value::Array(a)) => a.iter().filter_map(Value::as_object).collect(),
371        _ => Vec::new(),
372    };
373    if data.is_empty() {
374        return Err(fail(r#"there is no data. Give data as a list of rows, like [{"month": "Jan", "sales": 10}]."#));
375    }
376    if data.len() > MAX_ROWS {
377        return Err(fail(format!("{} rows is too many; at most {MAX_ROWS}. Group or sum the data first.", data.len())));
378    }
379    let first = data.first().copied();
380    let x = o.get("x").filter(|x| !x.is_null()).map(js_string).unwrap_or_default();
381    if x.is_empty() || !data.iter().any(|r| r.contains_key(&x)) {
382        return Err(fail(format!("the rows have no column \"{x}\" for x. Columns: {}.", columns(first))));
383    }
384    let series = series_of(o.get("series"));
385    if series.is_empty() {
386        return Err(fail("give at least one series: the column(s) with the numbers."));
387    }
388    if series.len() > MAX_SERIES {
389        return Err(fail(format!("at most {MAX_SERIES} series.")));
390    }
391    if kind == ChartType::Pie && series.len() != 1 {
392        return Err(fail("a pie chart shows one series."));
393    }
394    for s in &series {
395        if !data.iter().any(|r| r.contains_key(&s.key)) {
396            return Err(fail(format!("the rows have no column \"{}\". Columns: {}.", s.key, columns(first))));
397        }
398    }
399    let mut out: Vec<Map<String, Value>> = Vec::with_capacity(data.len());
400    for r in &data {
401        let mut row = Map::new();
402        let xv = r.get(&x);
403        if kind == ChartType::Scatter {
404            let n = to_number(xv)
405                .map_err(|NotANumber| fail(format!("a scatter chart needs numbers in \"{x}\"; found \"{}\".", xv.map(js_string).unwrap_or_default())))?;
406            row.insert(x.clone(), num(n));
407        } else {
408            let v = match xv {
409                None | Some(Value::Null) => Value::String(String::new()),
410                Some(n @ Value::Number(_)) => n.clone(),
411                Some(other) => Value::String(js_string(other)),
412            };
413            row.insert(x.clone(), v);
414        }
415        for s in &series {
416            let cell = r.get(&s.key);
417            let n = to_number(cell).map_err(|NotANumber| {
418                fail(format!("\"{}\" must hold numbers; found \"{}\".", s.key, cell.map(js_string).unwrap_or_else(|| "undefined".into())))
419            })?;
420            row.insert(s.key.clone(), num(n));
421        }
422        out.push(row);
423    }
424    // A timeline in the wrong order draws a zig-zag; put dates in order (pie slices aren't one).
425    if kind != ChartType::Pie && kind != ChartType::Scatter {
426        let times: Option<Vec<i64>> = out.iter().map(|r| r.get(&x).and_then(date_of)).collect();
427        if let Some(times) = times {
428            let mut order: Vec<(i64, Map<String, Value>)> = times.into_iter().zip(out).collect();
429            order.sort_by_key(|(t, _)| *t);
430            out = order.into_iter().map(|(_, r)| r).collect();
431        }
432    }
433    let title = o.get("title").filter(|t| !t.is_null()).map(js_string).unwrap_or_default();
434    let mut title: String = title.trim().chars().take(MAX_TITLE_CHARS).collect();
435    if title.is_empty() {
436        title = series.iter().map(|s| s.label.as_str()).collect::<Vec<_>>().join(" and ");
437    }
438    let unit = o.get("unit").and_then(Value::as_str).map(str::trim).filter(|u| !u.is_empty()).map(|u| u.chars().take(MAX_UNIT_CHARS).collect());
439    let stacked = o.get("stacked") == Some(&Value::Bool(true));
440    let source = o.get("source").and_then(ChartSource::from_value).map(Box::new);
441    Ok(ChartSpec { version: 1, kind, title, x, series, data: out, unit, stacked, source })
442}
443
444fn num(n: Option<f64>) -> Value {
445    n.and_then(serde_json::Number::from_f64).map_or(Value::Null, Value::Number)
446}
447
448/// Plain CSV as hob reads it: a header row, commas, `"quoted, values"` with `""` escapes.
449/// Blank lines are skipped; missing cells are empty.
450pub fn parse_csv(text: &str) -> Vec<Map<String, Value>> {
451    let rows = csv_rows(text);
452    let Some((head, body)) = rows.split_first() else { return Vec::new() };
453    body.iter().map(|r| head.iter().enumerate().map(|(i, h)| (h.trim().to_owned(), Value::String(r.get(i).cloned().unwrap_or_default()))).collect()).collect()
454}
455
456/// CSV records (hob's tokenizer), header included.
457pub fn csv_rows(text: &str) -> Vec<Vec<String>> {
458    let mut rows = Vec::new();
459    let mut row: Vec<String> = Vec::new();
460    let mut cell = String::new();
461    let mut quoted = false;
462    let mut it = text.chars().peekable();
463    while let Some(c) = it.next() {
464        if quoted {
465            if c == '"' && it.peek() == Some(&'"') {
466                cell.push('"');
467                it.next();
468            } else if c == '"' {
469                quoted = false;
470            } else {
471                cell.push(c);
472            }
473        } else if c == '"' {
474            quoted = true;
475        } else if c == ',' {
476            row.push(std::mem::take(&mut cell));
477        } else if c == '\n' || c == '\r' {
478            if c == '\r' && it.peek() == Some(&'\n') {
479                it.next();
480            }
481            row.push(std::mem::take(&mut cell));
482            if row.iter().any(|v| !v.is_empty()) {
483                rows.push(std::mem::take(&mut row));
484            } else {
485                row.clear();
486            }
487        } else {
488            cell.push(c);
489        }
490    }
491    row.push(cell);
492    if row.iter().any(|v| !v.is_empty()) {
493        rows.push(row);
494    }
495    // A UTF-8 BOM would otherwise end up in the first column name.
496    if let Some(first) = rows.first_mut().and_then(|r| r.first_mut())
497        && let Some(stripped) = first.strip_prefix('\u{feff}')
498    {
499        *first = stripped.to_owned();
500    }
501    rows
502}
503
504#[cfg(test)]
505mod tests {
506    use super::*;
507    use serde_json::json;
508
509    fn rows() -> Value {
510        json!([{ "month": "Jan", "sales": 10, "costs": "4" }, { "month": "Feb", "sales": 30, "costs": 8 }])
511    }
512
513    fn err(v: Value) -> String {
514        validate(&v).unwrap_err()
515    }
516
517    #[test]
518    fn a_good_chart_coerces_numbers_and_takes_plain_keys() {
519        let spec =
520            validate(&json!({"type": "bar", "title": "Sales", "x": "month", "series": ["sales", {"key": "costs", "label": "Costs"}], "data": rows()})).unwrap();
521        assert_eq!(spec.kind, ChartType::Bar);
522        assert_eq!(spec.title, "Sales");
523        assert_eq!(spec.series, vec![ChartSeries { key: "sales".into(), label: "sales".into() }, ChartSeries { key: "costs".into(), label: "Costs".into() }]);
524        assert_eq!(
525            serde_json::to_value(&spec.data).unwrap(),
526            json!([{ "month": "Jan", "sales": 10.0, "costs": 4.0 }, { "month": "Feb", "sales": 30.0, "costs": 8.0 }])
527        );
528        // Same JSON as hob: version 1, "type", no unit/stacked when unset.
529        let v: Value = serde_json::from_str(&spec.to_json()).unwrap();
530        assert_eq!(v["version"], 1);
531        assert_eq!(v["type"], "bar");
532        assert!(v.get("unit").is_none() && v.get("stacked").is_none());
533        assert_eq!(ChartSpec::from_json(&spec.to_json()).unwrap(), spec);
534    }
535
536    #[test]
537    fn says_plainly_what_is_wrong() {
538        assert!(err(json!({"type": "radar", "x": "month", "series": ["sales"], "data": rows()})).contains("type must be one of bar, line, area, pie, scatter"));
539        assert!(err(json!({"type": "bar", "x": "month", "series": ["sales"], "data": []})).contains("no data"));
540        assert!(err(json!({"type": "bar", "x": "week", "series": ["sales"], "data": rows()})).contains("\"week\""));
541        assert!(err(json!({"type": "bar", "x": "month", "series": ["profit"], "data": rows()})).contains("\"profit\""));
542        assert!(err(json!({"type": "bar", "x": "month", "series": ["month"], "data": rows()})).contains("numbers"));
543        assert!(err(json!({"type": "pie", "x": "month", "series": ["sales", "costs"], "data": rows()})).contains("one series"));
544        let nine: Vec<String> = (0..9).map(|i| format!("s{i}")).collect();
545        assert!(err(json!({"type": "bar", "x": "month", "series": nine, "data": rows()})).contains("at most 8"));
546        let many: Vec<Value> = (0..2001).map(|i| json!({"i": i, "v": i})).collect();
547        assert!(err(json!({"type": "bar", "x": "i", "series": ["v"], "data": many})).contains("2000"));
548        assert!(err(json!({"type": "bar", "x": "month", "series": [], "data": rows()})).contains("at least one series"));
549        assert!(err(json!({"type": "scatter", "x": "month", "series": ["sales"], "data": rows()})).contains("scatter chart needs numbers in \"month\""));
550        assert!(err(json!("garbage")).starts_with("Can't draw this chart"));
551        assert!(err(json!({"type": "bar", "x": "week", "series": ["sales"], "data": rows()})).contains("Columns: costs, month, sales"));
552    }
553
554    #[test]
555    fn number_coercion_matches_hob() {
556        let n = |s: &str| to_number(Some(&json!(s)));
557        assert_eq!(n("1,234.5"), Ok(Some(1234.5)));
558        assert_eq!(n("€1,234"), Ok(Some(1234.0)));
559        assert_eq!(n(" 40 % "), Ok(Some(40.0)));
560        assert_eq!(n("$ 1 000"), Ok(Some(1000.0)));
561        assert_eq!(n("1,23"), Err(NotANumber));
562        assert_eq!(n("1,2345"), Err(NotANumber));
563        assert_eq!(n("-3.5e2"), Ok(Some(-350.0)));
564        assert_eq!(n(""), Ok(None));
565        assert_eq!(n("€"), Ok(Some(0.0)));
566        assert_eq!(n("abc"), Err(NotANumber));
567        assert_eq!(n("Infinity"), Err(NotANumber));
568        assert_eq!(n("NaN"), Err(NotANumber));
569        assert_eq!(to_number(None), Ok(None));
570        assert_eq!(to_number(Some(&Value::Null)), Ok(None));
571        assert_eq!(to_number(Some(&json!(true))), Err(NotANumber));
572        assert_eq!(to_number(Some(&json!([1]))), Err(NotANumber));
573        // nulls are kept as gaps
574        let spec = validate(&json!({"type": "line", "x": "m", "series": ["v"], "data": [{"m": "a", "v": null}, {"m": "b", "v": ""}, {"m": "c"}]})).unwrap();
575        assert!(spec.data.iter().all(|r| r["v"].is_null()));
576    }
577
578    #[test]
579    fn dates_along_the_bottom_are_sorted() {
580        let sorted = |data: Value, kind: &str| -> Vec<Value> {
581            validate(&json!({"type": kind, "x": "d", "series": ["v"], "data": data})).unwrap().data.into_iter().map(|r| r["d"].clone()).collect()
582        };
583        assert_eq!(
584            sorted(json!([{"d": "5/18/2026", "v": 1}, {"d": "5/6/2026", "v": 2}, {"d": "4/29/2026", "v": 3}]), "line"),
585            vec![json!("4/29/2026"), json!("5/6/2026"), json!("5/18/2026")]
586        );
587        assert_eq!(sorted(json!([{"d": "2026-03-02", "v": 1}, {"d": "2026-02-27", "v": 2}]), "bar"), vec![json!("2026-02-27"), json!("2026-03-02")]);
588        assert_eq!(sorted(json!([{"d": "Mar", "v": 1}, {"d": "Jan", "v": 2}]), "line"), vec![json!("Mar"), json!("Jan")]);
589        assert_eq!(sorted(json!([{"d": "North", "v": 1}, {"d": "2026-01-01", "v": 2}]), "line"), vec![json!("North"), json!("2026-01-01")]);
590        assert_eq!(sorted(json!([{"d": "2026-03-02", "v": 1}, {"d": "2026-02-27", "v": 2}]), "pie"), vec![json!("2026-03-02"), json!("2026-02-27")]);
591        assert_eq!(
592            sorted(json!([{"d": "Mar 2026", "v": 1}, {"d": "Jan 5, 2026", "v": 2}, {"d": "2025-12", "v": 3}]), "bar"),
593            vec![json!("2025-12"), json!("Jan 5, 2026"), json!("Mar 2026")]
594        );
595    }
596
597    #[test]
598    fn date_parsing() {
599        let d = |s: &str| date_of(&json!(s));
600        assert_eq!(d("1970-01-02"), Some(86_400));
601        assert_eq!(d("1970-01-01T01:00:00Z"), Some(3600));
602        assert_eq!(d("1970-01-01 00:01"), Some(60));
603        assert_eq!(d("2026-02-30"), None);
604        assert_eq!(d("5 March 2026"), d("2026-03-05"));
605        assert_eq!(d("Thu, 5 Mar 2026"), d("2026-03-05"));
606        assert_eq!(d("3/5/26"), d("2026-03-05"));
607        assert_eq!(d("Mar"), None);
608        assert_eq!(d("2026"), None);
609        assert_eq!(d("North 5"), None);
610        assert_eq!(d("Marble 5 2026"), None);
611        assert_eq!(date_of(&json!(5)), None);
612    }
613
614    #[test]
615    fn title_unit_and_stacked() {
616        let spec =
617            validate(&json!({"type": "area", "x": "month", "series": ["sales", "costs"], "data": rows(), "unit": "  € ", "stacked": true, "title": "  "}))
618                .unwrap();
619        assert_eq!(spec.title, "sales and costs");
620        assert_eq!(spec.unit.as_deref(), Some("€"));
621        assert!(spec.stacked);
622        let long = validate(
623            &json!({"type": "bar", "x": "month", "series": "sales", "data": rows(), "title": "t".repeat(500), "unit": "u".repeat(50), "stacked": "yes"}),
624        )
625        .unwrap();
626        assert_eq!(long.title.chars().count(), MAX_TITLE_CHARS);
627        assert_eq!(long.unit.map(|u| u.chars().count()), Some(MAX_UNIT_CHARS));
628        assert!(!long.stacked);
629    }
630
631    #[test]
632    fn x_values_become_strings_or_stay_numbers() {
633        let spec =
634            validate(&json!({"type": "bar", "x": "k", "series": ["v"], "data": [{"k": 2024, "v": 1}, {"k": true, "v": 2}, {"k": null, "v": 3}, {"v": 4}]}))
635                .unwrap();
636        let xs: Vec<Value> = spec.data.iter().map(|r| r["k"].clone()).collect();
637        assert_eq!(xs, vec![json!(2024), json!("true"), json!(""), json!("")]);
638        assert_eq!(spec.label(&spec.data[0]), "2024");
639    }
640
641    #[test]
642    fn reads_simple_csv() {
643        let rows = parse_csv("month,sales\nJan,10\n\"Feb, late\",30\n");
644        assert_eq!(serde_json::to_value(rows).unwrap(), json!([{"month": "Jan", "sales": "10"}, {"month": "Feb, late", "sales": "30"}]));
645        let rows = parse_csv("\u{feff}a,b\r\n\r\n1,\"x \"\"y\"\"\"\r\n2\r\n");
646        assert_eq!(serde_json::to_value(rows).unwrap(), json!([{"a": "1", "b": "x \"y\""}, {"a": "2", "b": ""}]));
647        assert!(parse_csv("").is_empty());
648        assert!(parse_csv("only,header").is_empty());
649    }
650
651    #[test]
652    fn hostile_input_never_panics() {
653        for v in [json!(null), json!([]), json!({"type": "bar", "data": "x"}), json!({"type": "bar", "x": {}, "series": [1, null, {}], "data": [1, "a", {}]})] {
654            assert!(validate(&v).is_err());
655        }
656    }
657}