diff --git a/crates/chart/src/lib.rs b/crates/chart/src/lib.rs index f4e2895fe..9092ef2c3 100644 --- a/crates/chart/src/lib.rs +++ b/crates/chart/src/lib.rs @@ -26,7 +26,7 @@ use serde::{Deserialize, Serialize}; pub use axis::{Scale, format_number, nice_scale}; pub use raster::rasterize; pub use render::{Swatch, legend_entries, render, supports_trendline}; -pub use resolve::{default_palette, has_volatile_series, resolve, series_color, series_plot_kind}; +pub use resolve::{default_palette, has_volatile_series, resolve, series_color}; pub use sparkline::render_sparkline; /// Straight (non-premultiplied) RGBA colour. @@ -143,7 +143,9 @@ pub struct SeriesData { /// Bubble sizes. pub sizes: Option>>, pub color: Rgba, - /// Per-series kind (combo charts). + /// The kind this series is drawn as. `resolve` sets it from `Chart::series_kind`. `render` + /// reads it for every series of a vertical cartesian or scatter chart, so a hand-built + /// `ChartData` sets it too (`SeriesData::default()` gives `ColumnClustered`). pub kind: ChartKind, /// Plotted against the secondary (right) value axis. pub secondary: bool, diff --git a/crates/chart/src/render.rs b/crates/chart/src/render.rs index c3f284bd9..48259d4c2 100644 --- a/crates/chart/src/render.rs +++ b/crates/chart/src/render.rs @@ -141,13 +141,20 @@ pub(crate) fn sanitize(d: &ChartData) -> ChartData { .series .iter() .take(MAX_SERIES) - .map(|s| SeriesData { + .enumerate() + .map(|(i, s)| SeriesData { name: s.name.clone(), values: sanitize_vals(&s.values), x: s.x.as_deref().map(sanitize_vals), sizes: s.sizes.as_deref().map(sanitize_vals), color: s.color, - kind: s.kind, + // `resolve` gives each series the kind it is drawn as (`Chart::series_kind`); a + // caller's combo kind is drawn as a combo's defaults: a column first, then lines. + kind: match s.kind { + ChartKind::Combo if i == 0 => ChartKind::ColumnClustered, + ChartKind::Combo => ChartKind::Line, + k => k, + }, secondary: s.secondary, smooth: s.smooth, trendlines: s.trendlines.iter().take(MAX_TRENDLINES).cloned().collect(), @@ -174,7 +181,8 @@ fn needs_sanitizing(d: &ChartData) -> bool { || d.series.len() > MAX_SERIES || d.series.iter().any(|s| { trendlines += s.trendlines.len(); - long(s.values.len()) + s.kind == ChartKind::Combo + || long(s.values.len()) || !s.values.iter().all(is_clean) || s.x.as_ref().is_some_and(|x| long(x.len()) || !x.iter().all(is_clean)) || s.sizes.as_ref().is_some_and(|x| long(x.len()) || !x.iter().all(is_clean)) diff --git a/crates/chart/src/render/cartesian.rs b/crates/chart/src/render/cartesian.rs index 8639409e4..fd4c44224 100644 --- a/crates/chart/src/render/cartesian.rs +++ b/crates/chart/src/render/cartesian.rs @@ -1,5 +1,5 @@ use super::frame::{Bx, CatAxis, ValAxis, frame, on, value_range}; -use super::legend::{cat_label, plot_kind}; +use super::legend::cat_label; use super::lines::{decimate_area, draw_markers, draw_runs}; use super::trend::{draw_trend_labels, draw_trendlines, max_backward, max_forward, max_forward_slots, supports_trendline}; use super::{ @@ -292,7 +292,7 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx if ncat == 0 { return; } - let kinds: Vec = data.series.iter().enumerate().map(|(i, s)| if horizontal { chart.kind } else { plot_kind(chart, s, i) }).collect(); + let kinds: Vec = data.series.iter().map(|s| if horizontal { chart.kind } else { s.kind }).collect(); let fams: Vec = kinds.iter().map(|k| family(*k)).collect(); let any_primary = data.series.iter().any(|s| !s.secondary); let sec: Vec = data.series.iter().map(|s| s.secondary && any_primary && !horizontal).collect(); @@ -528,7 +528,7 @@ pub(super) fn scatter(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) ctx.out.push(Prim::Circle { cx: p[0], cy: p[1], r, fill: Some(fill), stroke: Some((WHITE, 0.75)) }); } } else { - let lines = chart.kind == ChartKind::ScatterLines || s.kind == ChartKind::ScatterLines; + let lines = s.kind == ChartKind::ScatterLines; if lines { draw_runs(ctx, &px, s.color, 2.0, s.smooth.then_some(plot)); } diff --git a/crates/chart/src/render/legend.rs b/crates/chart/src/render/legend.rs index a9c7cfac0..d2456ef13 100644 --- a/crates/chart/src/render/legend.rs +++ b/crates/chart/src/render/legend.rs @@ -1,8 +1,8 @@ use super::frame::Bx; use super::trend::supports_trendline; use super::{ - Chart, ChartData, ChartKind, Ctx, DOWN, HAlign, LABEL_SIZE, MAX_CATS, MAX_SERIES, MAX_TRENDLINES, Prim, Rgba, SeriesData, TEXT, Theme, UP, - VAlign, auto_name, series_color, + Chart, ChartData, ChartKind, Ctx, DOWN, HAlign, LABEL_SIZE, MAX_CATS, MAX_SERIES, MAX_TRENDLINES, Prim, Rgba, TEXT, Theme, UP, VAlign, auto_name, + series_color, }; use gridcraft_model::LegendPos; @@ -15,12 +15,6 @@ pub enum Swatch { Marker, } -/// The kind series `i` is drawn as (per-series kinds only apply to combo charts); the same rule -/// as `series_plot_kind`, applied to the already resolved series kind. -pub(super) fn plot_kind(chart: &Chart, s: &SeriesData, i: usize) -> ChartKind { - crate::resolve::plot_kind(chart.kind, Some(s.kind), i) -} - /// Colour of point `j` for charts that colour by point (pie, doughnut, treemap, sunburst). pub(super) fn point_color(data: &ChartData, j: usize) -> Rgba { match (j, data.series.first()) { @@ -61,9 +55,8 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa let series = data.series.iter().take(MAX_SERIES); let mut out: Vec<(String, Rgba, Swatch)> = series .clone() - .enumerate() - .map(|(i, s)| { - let sw = match plot_kind(chart, s, i) { + .map(|s| { + let sw = match s.kind { ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line, ChartKind::LineMarkers => Swatch::LineMarker, ChartKind::Scatter | ChartKind::Bubble => Swatch::Marker, @@ -73,7 +66,7 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa }) .collect(); // Trendlines follow the series, named "Linear (Sales)" unless given a name. - for (_, s) in series.enumerate().filter(|(i, s)| supports_trendline(plot_kind(chart, s, *i))) { + for s in series.filter(|s| supports_trendline(s.kind)) { for t in s.trendlines.iter().take(MAX_TRENDLINES) { out.push((t.spec.name.clone().unwrap_or_else(|| auto_name(t.spec.kind, &s.name)), t.color, Swatch::Line)); } diff --git a/crates/chart/src/render/table.rs b/crates/chart/src/render/table.rs index 4f641afd2..9047e0c31 100644 --- a/crates/chart/src/render/table.rs +++ b/crates/chart/src/render/table.rs @@ -1,7 +1,7 @@ //! The chart data table uses the same primitives as the plot, including in print/PDF output. use super::frame::{Bx, CatAxis, level_groups}; -use super::legend::{Swatch, cat_label, draw_swatch, plot_kind}; +use super::legend::{Swatch, cat_label, draw_swatch}; use super::{AXIS, Chart, ChartData, ChartKind, Ctx, Fmt, HAlign, LABEL_SIZE, TEXT, VAlign}; pub(super) struct Layout { @@ -70,7 +70,7 @@ pub(super) fn draw(ctx: &mut Ctx, chart: &Chart, data: &ChartData, plot: Bx, lay let y = top + (layout.headers as f32 + i as f32 + 0.5) * layout.row_height; let name_x = if settings.show_keys { x0 + 25.0 } else { x0 + 4.0 }; if settings.show_keys { - let swatch = match plot_kind(chart, series, i) { + let swatch = match series.kind { ChartKind::Line | ChartKind::LineStacked => Swatch::Line, ChartKind::LineMarkers => Swatch::LineMarker, _ => Swatch::Box, diff --git a/crates/chart/src/resolve.rs b/crates/chart/src/resolve.rs index e7663e0d9..5852f6c89 100644 --- a/crates/chart/src/resolve.rs +++ b/crates/chart/src/resolve.rs @@ -448,32 +448,6 @@ fn series_name(wb: &Workbook, sheet: usize, name: &str) -> String { t.to_string() } -pub(crate) fn effective_kind(chart_kind: ChartKind, series_kind: Option, i: usize) -> ChartKind { - match (chart_kind, series_kind) { - (ChartKind::Combo, Some(k)) if k != ChartKind::Combo => k, - (ChartKind::Combo, _) => { - if i == 0 { - ChartKind::ColumnClustered - } else { - ChartKind::Line - } - } - (_, Some(k)) if k != ChartKind::Combo => k, - (k, _) => k, - } -} - -/// The kind series `i` is drawn as: its own kind in a combo chart (first series a column, the -/// rest lines when it has none), else the chart's. The one rule shared by resolving and drawing. -pub(crate) fn plot_kind(chart_kind: ChartKind, series_kind: Option, i: usize) -> ChartKind { - if chart_kind == ChartKind::Combo { effective_kind(chart_kind, series_kind, i) } else { chart_kind } -} - -/// The kind series `i` of `chart` is drawn as: its own kind in a combo chart, else the chart's. -pub fn series_plot_kind(chart: &Chart, i: usize) -> ChartKind { - plot_kind(chart.kind, chart.series.get(i).and_then(|s| s.kind), i) -} - /// Evaluates a chart's series formulas: names, values, categories (default "1", "2", …), X /// values (scatter/bubble), bubble sizes, number formats and colours (explicit, else the /// default palette derived from the workbook theme accents). @@ -489,7 +463,7 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData { let name = s.name.as_deref().map(|n| series_name(wb, sheet, n)).filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series{}", i + 1)); let color = s.color.as_ref().and_then(|c| c.resolve(&wb.theme)).map(|[r, g, b]| [r, g, b, 0xFF]).unwrap_or_else(|| series_color(&wb.theme, i)); - let kind = effective_kind(chart.kind, s.kind, i); + let kind = chart.series_kind(i); let x = match (&s.categories, numeric_x || matches!(kind, ChartKind::Scatter | ChartKind::ScatterLines | ChartKind::Bubble)) { // X values with text in them (labels) are ignored: the points are numbered 1..n. (Some(f), true) => { diff --git a/crates/chart/src/tests.rs b/crates/chart/src/tests.rs index a6d845387..aa261ab36 100644 --- a/crates/chart/src/tests.rs +++ b/crates/chart/src/tests.rs @@ -1421,21 +1421,22 @@ fn area_charts_draw_source_value_labels_only_when_enabled() { #[test] fn drawing_and_resolving_agree_on_the_combo_plot_kind() { - // Resolved series carry `effective_kind`; drawing re-derives the kind from it. Both paths - // must give the same kind for every chart kind, series kind (or none) and series index. + // Resolved series carry `Chart::series_kind`, the kind drawing uses: for every chart kind, + // series kind (or none) and series index it is never a combo, and outside a combo it is the + // chart's kind or one of its family. + let wb = Workbook::new(); let series_kinds = std::iter::once(None).chain(ALL_KINDS.iter().map(|k| Some(*k))); for ck in ALL_KINDS { for sk in series_kinds.clone() { for i in 0..3 { let mut c = chart(ck); c.series = (0..3).map(|j| Series { kind: if j == i { sk } else { None }, ..Default::default() }).collect(); - let from_chart = series_plot_kind(&c, i); - let resolved = crate::resolve::effective_kind(ck, sk, i); - assert_eq!(crate::resolve::plot_kind(ck, Some(resolved), i), from_chart, "{ck:?} {sk:?} {i}"); + let resolved: Vec = resolve(&wb, 0, &c).series.iter().map(|s| s.kind).collect(); + assert_eq!(resolved, c.series_kinds(), "{ck:?} {sk:?} {i}"); if ck != ChartKind::Combo { - assert_eq!(from_chart, ck); + assert!(gridcraft_model::same_family(ck, resolved[i]), "{ck:?} {sk:?} {i}"); } else { - assert_ne!(from_chart, ChartKind::Combo); + assert_ne!(resolved[i], ChartKind::Combo); } } } diff --git a/crates/chart/src/tests/budget.rs b/crates/chart/src/tests/budget.rs index fad349ba6..cc779f13b 100644 --- a/crates/chart/src/tests/budget.rs +++ b/crates/chart/src/tests/budget.rs @@ -166,6 +166,10 @@ fn stacked_hairline_bars_do_not_fill_the_gap_between_disjoint_spans() { c.data_labels = false; c.legend = LegendPos::None; let mut d = data_of(2, 20_000); + // Resolved series carry the kind they are drawn as (`Chart::series_kind`): stacked columns. + for s in &mut d.series { + s.kind = ChartKind::ColumnStacked; + } for v in d.series[0].values.iter_mut() { *v = Some(100.0); } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index f06e3b8d6..21f6b6dcc 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -31,4 +31,5 @@ unicode-segmentation = "=1.13.3" [dev-dependencies] gridcraft-xlsx = { workspace = true, features = ["test-support"] } +gridcraft-model = { workspace = true, features = ["test-support"] } zip = { workspace = true } diff --git a/crates/engine/src/cmd/extra/chart.rs b/crates/engine/src/cmd/extra/chart.rs index b6ed184ed..42ed5af75 100644 --- a/crates/engine/src/cmd/extra/chart.rs +++ b/crates/engine/src/cmd/extra/chart.rs @@ -69,8 +69,11 @@ pub(super) fn add_element(s: &mut Session, p: &Json) -> Result { return Ok(()); } let t = trendline_param(p)?; + // Every series' kind in one pass: a combo series' kind looks back for its group's + // first series, so asking per series is quadratic in a chart with many. + let kinds = c.series_kinds(); let eligible: Vec = - targets.into_iter().filter(|i| gridcraft_chart::supports_trendline(gridcraft_chart::series_plot_kind(c, *i))).collect(); + targets.into_iter().filter(|i| kinds.get(*i).is_some_and(|k| gridcraft_chart::supports_trendline(*k))).collect(); if eligible.is_empty() { return Err(bad("chart.addElement", "trendlines need a 2-D column, bar, line, area, scatter or bubble series")); } diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index 686fca6f5..41310782c 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -337,6 +337,74 @@ mod tests { assert_eq!(serde_json::from_value::(json).unwrap().data_table, None); } + #[test] + fn chart_type_change_drops_series_kinds_it_does_not_draw() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Q", "A", "B"], ["Q1", 10, 1], ["Q2", 20, 2]]})).unwrap(); + s.execute("insert.chart", json!({"range": "A1:C3", "type": "combo"})).unwrap(); + let chart = |s: &Session| s.active().unwrap().wb.active().unwrap().charts[0].clone(); + let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb); + let active = wb.active_sheet(); + if let Some(c) = wb.sheet_mut(active).unwrap().charts.get_mut(0) { + c.series[0].kind = Some(ChartKind::Area); + c.series[1].kind = Some(ChartKind::LineMarkers); + } + // A new type applies to every series: neither the area nor the markers stay. + s.execute("chart.set", json!({"type": "line"})).unwrap(); + let c = chart(&s); + assert_eq!(c.series.iter().map(|x| x.kind).collect::>(), vec![None, None]); + assert_eq!((c.series_kind(0), c.series_kind(1)), (ChartKind::Line, ChartKind::Line)); + // Setting the type a chart already has keeps a series' own markers (a file's). + let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb); + if let Some(c) = wb.sheet_mut(active).unwrap().charts.get_mut(0) { + c.series[1].kind = Some(ChartKind::LineMarkers); + } + s.execute("chart.set", json!({"type": "line", "subtype": ""})).unwrap(); + assert_eq!(chart(&s).series_kinds(), vec![ChartKind::Line, ChartKind::LineMarkers]); + // Trendlines go by the kind each series is drawn as. + s.execute("chart.set", json!({"type": "pie"})).unwrap(); + assert!(s.execute("chart.addElement", json!({"element": "trendline"})).is_err()); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(chart(&s).series[1].kind, Some(ChartKind::LineMarkers)); + } + + /// Adding a trendline to every series of a combo chart works out the series' kinds in one + /// pass, however many series it holds (a stored chart isn't held to the renderer's limit): + /// eight times the series is about eight times the work, not sixty-four. + #[test] + fn trendlines_for_every_series_are_checked_in_linear_time() { + let visits = |n: usize| { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Q", "A"], ["Q1", 10], ["Q2", 20]]})).unwrap(); + s.execute("insert.chart", json!({"range": "A1:B3", "type": "combo"})).unwrap(); + // Line series, then as many column series: asked one at a time, each column series + // looks back past every line series for the first column series of its group. + let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb); + let active = wb.active_sheet(); + if let Some(c) = wb.sheet_mut(active).unwrap().charts.get_mut(0) { + let one = c.series[0].clone(); + c.series = (0..2 * n) + .map(|i| { + let mut se = one.clone(); + se.kind = Some(if i < n { ChartKind::Line } else { ChartKind::ColumnClustered }); + se + }) + .collect(); + } + gridcraft_model::features::work::take_series_visits(); + s.execute("chart.addElement", json!({"element": "trendline"})).unwrap(); + let visits = gridcraft_model::features::work::take_series_visits(); + let c = s.active().unwrap().wb.active().unwrap().charts[0].clone(); + assert!(c.series.iter().all(|se| se.trendlines.len() == 1)); + visits + }; + let (small, large) = (visits(200), visits(1_600)); + assert!(small >= 400, "every series' kind is worked out: {small}"); + assert!(large < 16 * small, "eight times the series took {large} visits against {small}"); + } + #[test] fn chart_data_table_refuses_unsupported_types_without_changing_history() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/insert/chart.rs b/crates/engine/src/cmd/insert/chart.rs index 69425ca79..66c99414f 100644 --- a/crates/engine/src/cmd/insert/chart.rs +++ b/crates/engine/src/cmd/insert/chart.rs @@ -330,7 +330,15 @@ pub(super) fn chart_set(s: &mut Session, p: &Json) -> Result { let sh = cx.sheet_mut(si)?; let Some(c) = sh.charts.get_mut(ci) else { return Ok(Json::Null) }; if let Some(t) = str_param(p, "type") { - c.kind = chart_kind(t, str_param(p, "subtype").unwrap_or("")); + let kind = chart_kind(t, str_param(p, "subtype").unwrap_or("")); + // A new type (other than a combo) applies to every series, as choosing it did before + // series kept their own: their markers or lines from a file go with the old type. + if kind != c.kind && kind != ChartKind::Combo { + for series in &mut c.series { + series.kind = None; + } + } + c.kind = kind; if !c.supports_data_table() { c.data_table = None; } diff --git a/crates/model/Cargo.toml b/crates/model/Cargo.toml index ff15c6795..d658ae739 100644 --- a/crates/model/Cargo.toml +++ b/crates/model/Cargo.toml @@ -8,6 +8,11 @@ description = "GridCraft document model: workbooks, sheets, cells, styles, table [lints] workspace = true +[features] +# Counts work for other crates' growth tests (a dev-dependency feature; never enabled in a +# shipped build). +test-support = [] + [dependencies] gridcraft-core = { workspace = true } sha2 = { workspace = true } diff --git a/crates/model/src/features.rs b/crates/model/src/features.rs index d8bad07bc..bba75dce2 100644 --- a/crates/model/src/features.rs +++ b/crates/model/src/features.rs @@ -620,7 +620,155 @@ pub struct Chart { pub pivot: Option, } +/// Whether a series of kind `b` can be drawn in a chart of kind `a` without making it a combo: +/// the same kind, or a line with or without markers, or a scatter with or without lines. +pub fn same_family(a: ChartKind, b: ChartKind) -> bool { + use ChartKind::*; + a == b || matches!((a, b), (Line | LineMarkers, Line | LineMarkers) | (Scatter | ScatterLines, Scatter | ScatterLines)) +} + +/// The kind a combo chart's series `i` with its own kind `own` is drawn as. +fn combo_series_kind(own: Option, i: usize) -> ChartKind { + match own { + // A combination chart's bars stand upright: its categories run across. + Some(ChartKind::BarClustered) => ChartKind::ColumnClustered, + Some(ChartKind::BarStacked) => ChartKind::ColumnStacked, + Some(ChartKind::BarStacked100) => ChartKind::ColumnStacked100, + // A combination chart is drawn on category axes: its pies, doughnuts, bubbles and chartex + // kinds (histogram, waterfall, funnel, treemap, sunburst, box & whisker) as clustered + // columns, its scatter and radar series as lines (a markers-only scatter with markers). + Some( + ChartKind::Pie + | ChartKind::Doughnut + | ChartKind::Bubble + | ChartKind::Histogram + | ChartKind::Waterfall + | ChartKind::Funnel + | ChartKind::Treemap + | ChartKind::Sunburst + | ChartKind::BoxWhisker, + ) => ChartKind::ColumnClustered, + Some(ChartKind::Scatter) => ChartKind::LineMarkers, + Some(ChartKind::ScatterLines | ChartKind::Radar) => ChartKind::Line, + Some(k) if k != ChartKind::Combo => k, + _ if i == 0 => ChartKind::ColumnClustered, + _ => ChartKind::Line, + } +} + +/// The types whose series on one pair of axes share one grouping (clustered or stacked). +#[derive(Clone, Copy, PartialEq, Eq)] +enum Grouped { + Column, + Line, + Area, +} + +fn grouped(k: ChartKind) -> Option { + use ChartKind::*; + match k { + ColumnClustered | ColumnStacked | ColumnStacked100 => Some(Grouped::Column), + Line | LineMarkers | LineStacked => Some(Grouped::Line), + Area | AreaStacked | AreaStacked100 => Some(Grouped::Area), + _ => None, + } +} + +/// Kind `k` drawn in the grouping of `first`, the first series of its type on its axes: columns +/// and areas take its kind; a line is stacked when it is, and unstacked (keeping its own +/// markers) when it isn't. +fn regroup(k: ChartKind, first: ChartKind) -> ChartKind { + match (grouped(k), first) { + (Some(Grouped::Line), ChartKind::LineStacked) => ChartKind::LineStacked, + (Some(Grouped::Line), _) if k == ChartKind::LineStacked => ChartKind::Line, + (Some(Grouped::Line), _) => k, + _ => first, + } +} + impl Chart { + /// The kind series `i` is drawn as, and saved as (the one rule the renderer and every file + /// format share). + /// + /// In a combo chart: the series' own kind, else a column for the first series and a line + /// for the rest. A combo is drawn on category axes, so bars stand upright as columns; pies, + /// doughnuts, bubbles and chartex kinds are clustered columns; scatter series are lines with + /// markers, and scatter-with-lines and radar series plain lines. The series of one type on + /// one pair of axes share the first one's grouping (as Excel keeps them): a stacked column + /// after a clustered one is clustered. + /// + /// In any other chart: the chart's kind, or the series' own kind where it is of the same + /// family ([`same_family`]: a line's own markers, a scatter's own lines). + pub fn series_kind(&self, i: usize) -> ChartKind { + let own = self.series.get(i).and_then(|s| s.kind).filter(|k| *k != ChartKind::Combo); + match (self.kind, own) { + (ChartKind::Combo, own) => { + let k = combo_series_kind(own, i); + let Some(t) = grouped(k) else { return k }; + let secondary = self.series.get(i).is_some_and(|s| s.secondary); + let first = self.series.iter().enumerate().take(i).find_map(|(j, s)| { + #[cfg(any(test, feature = "test-support"))] + work::visit(); + let kj = combo_series_kind(s.kind, j); + (s.secondary == secondary && grouped(kj) == Some(t)).then_some(kj) + }); + first.map_or(k, |f| regroup(k, f)) + } + (k, Some(own)) if same_family(k, own) => own, + (k, _) => k, + } + } + + /// The kind every series is drawn as ([`Chart::series_kind`]), in one pass. + pub fn series_kinds(&self) -> Vec { + if self.kind != ChartKind::Combo { + return (0..self.series.len()).map(|i| self.series_kind(i)).collect(); + } + let mut firsts: Vec<(Grouped, bool, ChartKind)> = Vec::new(); + self.series + .iter() + .enumerate() + .map(|(i, s)| { + #[cfg(any(test, feature = "test-support"))] + work::visit(); + let k = combo_series_kind(s.kind, i); + let Some(t) = grouped(k) else { return k }; + match firsts.iter().find(|(ft, sec, _)| *ft == t && *sec == s.secondary) { + Some((_, _, f)) => regroup(k, *f), + None => { + firsts.push((t, s.secondary, k)); + k + } + } + }) + .collect() + } + + /// Sets the chart's kind and each series' own kind from the kinds a file draws its series + /// as (XLSX chart groups, ODS `chart:class`), one per series in order; `empty` is the + /// chart's kind when it has no series. Series of one family make a chart of the first's + /// kind, a series keeping its own kind only where it differs (a line's own markers, a + /// scatter's own lines); series of other families make a combination chart, every series + /// keeping its kind, except that the series of one type on one pair of axes share the first + /// one's grouping, as [`Chart::series_kinds`] draws and every format saves them (a stacked + /// column after a clustered one on the same axes is kept clustered; on the other axes it + /// stays stacked). Each series' own kind is then the kind it is drawn as. Set the series' + /// axes (`secondary`) first. + pub fn set_drawn_kinds(&mut self, drawn: &[ChartKind], empty: ChartKind) { + let first = drawn.first().copied().unwrap_or(empty); + let combo = drawn.iter().any(|k| !same_family(*k, first)); + self.kind = if combo { ChartKind::Combo } else { first }; + for (s, k) in self.series.iter_mut().zip(drawn) { + s.kind = (combo || *k != first).then_some(*k); + } + if combo { + let kinds = self.series_kinds(); + for (s, k) in self.series.iter_mut().zip(kinds) { + s.kind = Some(k); + } + } + } + /// Data tables belong to category-axis column, bar, line and area charts. pub fn supports_data_table(&self) -> bool { let eligible = |kind| { @@ -640,7 +788,7 @@ impl Chart { | ChartKind::AreaStacked100 ) }; - eligible(self.kind) || (self.kind == ChartKind::Combo && self.series.iter().all(|s| eligible(s.kind.unwrap_or(ChartKind::Line)))) + eligible(self.kind) || (self.kind == ChartKind::Combo && self.series_kinds().into_iter().all(eligible)) } } @@ -1120,6 +1268,158 @@ pub struct Slicer { pub columns: u32, } +/// Work counters for growth tests here and in other crates (`test-support`; never in a shipped +/// build): a test compares the counts at two input sizes instead of timing the work. +#[cfg(any(test, feature = "test-support"))] +pub mod work { + thread_local! { + /// Series a combo chart's kind lookups have visited on this thread. + static SERIES_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + pub(crate) fn visit() { + SERIES_VISITS.with(|n| n.set(n.get().saturating_add(1))); + } + + /// The series visited since the last call, and starts counting again. + pub fn take_series_visits() -> usize { + SERIES_VISITS.with(|n| n.replace(0)) + } +} + +#[cfg(test)] +mod series_kind_tests { + use super::{Chart, ChartKind, Series}; + + fn chart(kind: ChartKind, own: &[Option]) -> Chart { + Chart { + id: 1, + kind, + anchor: Default::default(), + title: None, + series: own.iter().map(|k| Series { kind: *k, ..Series::default() }).collect(), + legend: Default::default(), + data_labels: false, + data_table: None, + gridlines: true, + style: 2, + hole_size: 75, + first_slice_angle: 0, + x_title: None, + y_title: None, + source: None, + by_rows: false, + pivot: None, + } + } + + fn drawn(c: &Chart) -> Vec { + (0..c.series.len()).map(|i| c.series_kind(i)).collect() + } + + #[test] + fn combo_series_default_to_a_column_then_lines_and_bars_and_pies_stand_upright() { + use ChartKind::*; + let c = chart(Combo, &[None, None, Some(Combo), Some(Area), Some(BarClustered), Some(Doughnut)]); + assert_eq!(drawn(&c), vec![ColumnClustered, Line, Line, Area, ColumnClustered, ColumnClustered]); + for (bar, column) in [(BarStacked, ColumnStacked), (BarStacked100, ColumnStacked100)] { + assert_eq!(drawn(&chart(Combo, &[Some(bar), Some(Line)])), vec![column, Line]); + } + // On a combo's category axes scatter and radar series are lines (a markers-only scatter + // keeps its markers) and bubbles are columns. + let c = chart(Combo, &[Some(Scatter), Some(ScatterLines), Some(Radar), Some(Bubble)]); + assert_eq!(drawn(&c), vec![LineMarkers, Line, Line, ColumnClustered]); + // Out of range: the default for that position, never a panic. + assert_eq!(c.series_kind(usize::MAX), Line); + } + + #[test] + fn outside_a_combo_a_series_keeps_only_its_own_markers_or_lines() { + use ChartKind::*; + assert_eq!(drawn(&chart(Line, &[None, Some(LineMarkers), Some(Area)])), vec![Line, LineMarkers, Line]); + assert_eq!(drawn(&chart(ScatterLines, &[Some(Scatter), Some(Line)])), vec![Scatter, ScatterLines]); + assert_eq!(drawn(&chart(ColumnClustered, &[Some(Line)])), vec![ColumnClustered]); + } + + #[test] + fn combo_series_of_one_type_on_one_axis_share_the_first_grouping() { + use ChartKind::*; + let c = chart( + Combo, + &[Some(ColumnStacked), Some(ColumnClustered), Some(Pie), Some(LineStacked), Some(LineMarkers), Some(Area), Some(AreaStacked100)], + ); + assert_eq!(drawn(&c), vec![ColumnStacked, ColumnStacked, ColumnStacked, LineStacked, LineStacked, Area, Area]); + assert_eq!(c.series_kinds(), drawn(&c)); + // An unstacked line keeps its own markers; a stacked one after it is unstacked. + let c = chart(Combo, &[Some(Line), Some(LineMarkers), Some(LineStacked)]); + assert_eq!(drawn(&c), vec![Line, LineMarkers, Line]); + // Each pair of axes has its own first. + let mut c = chart(Combo, &[Some(ColumnClustered), Some(ColumnStacked)]); + c.series[1].secondary = true; + assert_eq!(drawn(&c), vec![ColumnClustered, ColumnStacked]); + assert_eq!(c.series_kinds(), drawn(&c)); + } + + /// A series' own markers or lines outside a combo are honoured wherever they come from: an + /// XLSX file's per-series markers, or a kind left in an older GridCraft JSON workbook by a + /// type change made before `chart.set` cleared series kinds on a change of type (not + /// migrated: the two can't be told apart). + /// A file's per-series kinds make a chart of one family, or a combo, that draws them so. + #[test] + fn drawn_kinds_set_the_chart_and_its_series() { + use ChartKind::*; + let mut c = chart(ColumnClustered, &[None, None, None]); + c.set_drawn_kinds(&[Line, LineMarkers, Line], ColumnClustered); + assert_eq!((c.kind, c.series.iter().map(|s| s.kind).collect::>()), (Line, vec![None, Some(LineMarkers), None])); + assert_eq!(c.series_kinds(), vec![Line, LineMarkers, Line]); + c.set_drawn_kinds(&[ColumnStacked, Line, Area], ColumnClustered); + assert_eq!(c.kind, Combo); + assert_eq!(c.series_kinds(), vec![ColumnStacked, Line, Area]); + let mut empty = chart(ColumnClustered, &[]); + empty.set_drawn_kinds(&[], Radar); + assert_eq!(empty.kind, Radar); + } + + /// Series of one type on one pair of axes keep the first one's grouping, so the kinds a + /// file gives them are stored as they are drawn and saved; on the other axes they keep their + /// own. + #[test] + fn drawn_kinds_of_one_type_share_a_grouping_per_pair_of_axes() { + use ChartKind::*; + let mut c = chart(ColumnClustered, &[None, None, None, None]); + c.set_drawn_kinds(&[ColumnClustered, ColumnStacked, ColumnStacked, Line], ColumnClustered); + assert_eq!( + c.series.iter().map(|s| s.kind).collect::>(), + vec![Some(ColumnClustered); 3].into_iter().chain([Some(Line)]).collect::>() + ); + assert_eq!(c.series.iter().map(|s| s.kind).collect::>(), c.series_kinds().into_iter().map(Some).collect::>()); + let mut c = chart(ColumnClustered, &[None, None, None, None]); + c.series[1].secondary = true; + c.series[2].secondary = true; + c.set_drawn_kinds(&[ColumnClustered, ColumnStacked, ColumnStacked, Line], ColumnClustered); + assert_eq!(c.series_kinds(), vec![ColumnClustered, ColumnStacked, ColumnStacked, Line]); + assert_eq!(c.series.iter().map(|s| s.kind).collect::>(), c.series_kinds().into_iter().map(Some).collect::>()); + } + + #[test] + fn a_leftover_kind_in_the_same_family_is_drawn() { + use ChartKind::*; + let json = serde_json::to_value(chart(Line, &[None, Some(LineMarkers)])).unwrap(); + let c: Chart = serde_json::from_value(json).unwrap(); + assert_eq!(drawn(&c), vec![Line, LineMarkers]); + assert_eq!(drawn(&chart(ScatterLines, &[Some(Scatter)])), vec![Scatter]); + } + + #[test] + fn a_combo_supports_a_data_table_by_its_drawn_kinds() { + use ChartKind::*; + assert!(chart(Combo, &[None, None]).supports_data_table()); + // Its scatter series are drawn as lines on its category axes; stock series have no table. + assert!(chart(Combo, &[None, Some(Scatter)]).supports_data_table()); + assert!(!chart(Combo, &[None, Some(Stock)]).supports_data_table()); + } +} + #[cfg(test)] mod trendline_forecast_tests { use super::Trendline; diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index eb1d22087..f8511d623 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -1,6 +1,7 @@ //! DrawingML charts (`xl/charts/chartN.xml`): reading the common 2-D/3-D chart groups into the //! model, and writing model charts (with cached series values) from scratch. +use std::collections::HashMap; use std::fmt::Write as _; use craft_drawingml::chart::{Chart as DmlChart, ChartType, Trendline as DmlTrendline, TrendlineType}; @@ -196,34 +197,176 @@ const DASHES: [(LineDash, &str); 11] = [ const EMU_PER_PT: f64 = 12_700.0; +fn group_kind(g: &El) -> Option { + let grouping = g.child_val("grouping").unwrap_or("standard"); + let stacked = grouping == "stacked"; + let pct = grouping == "percentStacked"; + Some(match g.name.as_str() { + "barChart" | "bar3DChart" => { + let bar = g.child_val("barDir") == Some("bar"); + match (bar, stacked, pct) { + (false, true, _) => ChartKind::ColumnStacked, + (false, _, true) => ChartKind::ColumnStacked100, + (false, _, _) => ChartKind::ColumnClustered, + (true, true, _) => ChartKind::BarStacked, + (true, _, true) => ChartKind::BarStacked100, + (true, _, _) => ChartKind::BarClustered, + } + } + "lineChart" | "line3DChart" => { + if stacked || pct { + ChartKind::LineStacked + } else { + // The group's kind is its first series' (each series may differ; see + // `series_kind_in`). + match g.kids("ser").next() { + Some(first) => series_kind_in(g, ChartKind::LineMarkers, first), + None if g.child_val("marker").is_some_and(|v| v == "0" || v == "false") => ChartKind::Line, + None => ChartKind::LineMarkers, + } + } + } + "pieChart" | "pie3DChart" | "ofPieChart" => ChartKind::Pie, + "doughnutChart" => ChartKind::Doughnut, + "areaChart" | "area3DChart" => { + if pct { + ChartKind::AreaStacked100 + } else if stacked { + ChartKind::AreaStacked + } else { + ChartKind::Area + } + } + "scatterChart" => match g.kids("ser").next() { + _ if g.child_val("scatterStyle") == Some("marker") => ChartKind::Scatter, + Some(first) => series_kind_in(g, ChartKind::ScatterLines, first), + None => ChartKind::ScatterLines, + }, + "bubbleChart" => ChartKind::Bubble, + "radarChart" => ChartKind::Radar, + "stockChart" => ChartKind::Stock, + _ => return None, + }) +} + +/// The kind series `s` of group `g` (of kind `k`) is drawn as: in a line group its own markers +/// (none when it says so), in a scatter group its own lines; otherwise the group's. +fn series_kind_in(g: &El, k: ChartKind, s: &El) -> ChartKind { + match k { + ChartKind::Line | ChartKind::LineMarkers => { + let group_markers = g.child_val("marker").is_none_or(|v| v == "1" || v == "true"); + let none = s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none"); + if group_markers && !none { ChartKind::LineMarkers } else { ChartKind::Line } + } + ChartKind::Scatter | ChartKind::ScatterLines if g.child_val("scatterStyle") != Some("marker") => { + if s.path(&["spPr", "ln"]).is_some_and(|l| l.child("noFill").is_some()) { ChartKind::Scatter } else { ChartKind::ScatterLines } + } + k => k, + } +} + +fn rich_title(t: &El) -> Option { + let tx = t.child("tx")?; + if let Some(rich) = tx.child("rich") { + let paras: Vec = + rich.kids("p").map(|p| p.kids("r").filter_map(|r| r.child("t")).map(|t| t.text.as_str()).collect::()).collect(); + let s = paras.join("\n"); + return if s.is_empty() { None } else { Some(s) }; + } + if let Some(sr) = tx.child("strRef") { + if let Some(v) = sr.path(&["strCache", "pt", "v"]) { + return Some(v.text.clone()); + } + return sr.child("f").map(|f| f.text.trim().to_string()); + } + None +} + +/// The text of an axis title (`c:title`): its rich text or cached reference, else Excel's default. +fn axis_title(t: &El) -> String { + rich_title(t).unwrap_or_else(|| "Axis Title".into()) +} + +// Value axes looked at (and looked up) while finding a chart's primary axes, so a test can check +// the work grows with the file, not with its square. +#[cfg(test)] +thread_local! { + pub(crate) static VAL_AXIS_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { let plot = root.and_then(|r| r.path(&["chart", "plotArea"])); let groups: Vec<&El> = plot.map(|p| p.children.iter().filter(|g| g.name.ends_with("Chart")).collect()).unwrap_or_default(); fn ax_ids(g: &El) -> Vec<&str> { g.kids("axId").filter_map(|a| a.attr("val")).collect() } - let first_axes = groups.first().map(|g| ax_ids(g)).unwrap_or_default(); - let ser_els: Vec<(&El, bool)> = groups + // An empty group draws nothing: the chart's kind and axes come from the groups with series + // (a chart without series from its first group). + let kinded: Vec<(&El, ChartKind)> = groups.iter().filter_map(|g| group_kind(g).map(|k| (*g, k))).collect(); + let with_series = kinded.iter().any(|(g, _)| g.child("ser").is_some()); + let drawing: Vec<(&El, ChartKind)> = kinded.iter().copied().filter(|(g, _)| !with_series || g.child("ser").is_some()).collect(); + let first_kind = drawing.first().map_or_else(|| map_chart_type(dc.kind, plot), |(_, k)| *k); + // The primary axes are the pair whose value axis sits left or bottom (a secondary pair is on + // the right or top), else the first group's; series on other axes are secondary. + let mut val_sides: HashMap<&str, &str> = HashMap::new(); + for a in plot.into_iter().flat_map(|p| p.kids("valAx")) { + #[cfg(test)] + VAL_AXIS_VISITS.with(|n| n.set(n.get().saturating_add(1))); + if let (Some(id), Some(pos)) = (a.child_val("axId"), a.child_val("axPos")) { + val_sides.entry(id).or_insert(pos); + } + } + let pairs: Vec> = drawing.iter().map(|(g, _)| ax_ids(g)).collect(); + let primary_axes: Vec<&str> = pairs .iter() - .enumerate() - .flat_map(|(gi, g)| { - let sec = gi > 0 && ax_ids(g) != first_axes; - g.kids("ser").map(move |s| (s, sec)) + .find(|ids| { + #[cfg(test)] + VAL_AXIS_VISITS.with(|n| n.set(n.get().saturating_add(1))); + ids.get(1).is_some_and(|id| matches!(val_sides.get(id).copied(), Some("l" | "b"))) + }) + .or_else(|| pairs.iter().find(|ids| !ids.is_empty())) + .cloned() + .unwrap_or_default(); + // The axis titles are the primary pair's (an axis of another pair, or of an empty group, holds + // another scale's titles), else the first of their kind in the file; a shown axis before a + // deleted one. + let primary = |a: &El| a.child_val("axId").is_some_and(|id| primary_axes.contains(&id)); + let shown = |a: &El| !a.child("delete").is_some_and(|c| c.flag("val", true)); + let first_of = |tags: &[&str], pos: &[&str]| -> Option<&El> { + let fits = |a: &&El| tags.contains(&a.name.as_str()) && (pos.is_empty() || a.child_val("axPos").is_some_and(|p| pos.contains(&p))); + let axes = plot.into_iter().flat_map(|p| p.children.iter()).filter(fits); + let ranked: [&dyn Fn(&El) -> bool; 4] = [&|a| primary(a) && shown(a), &shown, &primary, &|_| true]; + ranked.into_iter().find_map(|r| axes.clone().find(|a| r(a))) + }; + // The primary pair's group says whether its axes are both value axes (a scatter's). + let primary_kind = drawing.iter().zip(&pairs).find(|(_, ids)| **ids == primary_axes).map_or(first_kind, |((_, k), _)| *k); + let (x_ax, y_ax) = if matches!(primary_kind, ChartKind::Scatter | ChartKind::ScatterLines | ChartKind::Bubble) { + (first_of(&["valAx"], &["b", "t"]), first_of(&["valAx"], &["l", "r"])) + } else { + (first_of(&["catAx", "dateAx"], &[]), first_of(&["valAx"], &[])) + }; + let title_of = |a: Option<&El>| a.and_then(|a| a.child("title")).map(axis_title); + let axis_titles = if plot.is_some() { (title_of(x_ax), title_of(y_ax)) } else { dc.axis_titles.clone() }; + // Each series element with its axes and the kind its group draws it as (a line's markers and + // a scatter's lines are the series' own), in the order the shared reader lists them. + let ser_els: Vec<(&El, bool, ChartKind)> = groups + .iter() + .flat_map(|g| { + let ids = ax_ids(g); + let sec = !ids.is_empty() && ids != primary_axes; + let k = group_kind(g); + g.kids("ser").map(move |s| (s, sec, k.map_or(first_kind, |k| series_kind_in(g, k, s)))) }) .collect(); - let multi_axis = ser_els.iter().any(|(_, sec)| *sec); - let is_combo = dc.kind == ChartType::Combo || multi_axis; - let base_kind = map_chart_type(dc.kind, plot); - let kind = if is_combo { ChartKind::Combo } else { base_kind }; let series_labels = dc.series.iter().any(|s| s.data_labels == Some(true)); let series = dc .series .into_iter() .enumerate() .map(|(i, s)| { - let (sel, fallback_sec) = match ser_els.get(i).copied() { - Some((el, sec)) => (Some(el), sec), - None => (None, false), + let (sel, sec, drawn) = match ser_els.get(i).copied() { + Some((el, sec, k)) => (Some(el), sec, k), + None => (None, s.secondary_axis, s.kind.map_or(first_kind, |k| map_chart_type(k, plot))), }; let color = s .fill @@ -243,7 +386,7 @@ pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { .into_iter() .flat_map(|e| e.kids("trendline").take(16)) .filter(|e| e.child("trendlineType").and_then(|c| c.attr("val")).and_then(TrendlineType::from_xml).is_some()); - Series { + let series = Series { name: s.refs.name.as_deref().map(chart_ref_from_file).or_else(|| (!s.name.is_empty()).then_some(s.name)), categories: s .refs @@ -260,20 +403,22 @@ pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { .unwrap_or_default(), bubble_sizes: s.refs.sizes.as_deref().map(chart_ref_from_file).or_else(|| literal_array(sel.and_then(|e| e.child("bubbleSize")))), color, - secondary: is_combo && (s.secondary_axis || fallback_sec), - kind: if dc.kind == ChartType::Combo { - s.kind.map(|k| map_chart_type(k, plot)) - } else if multi_axis { - Some(s.kind.map(|k| map_chart_type(k, plot)).unwrap_or(base_kind)) - } else { - None - }, + secondary: sec, + kind: None, quartiles: Default::default(), smooth: sel.map_or(s.smooth, |e| e.child("smooth").is_some_and(|c| c.flag("val", true))), trendlines: s.trendlines.iter().map(|t| map_trendline(t, trendline_els.next())).collect(), - } + }; + (series, drawn, sel) }) - .collect(); + .collect::>(); + // Series in the order the file gives them (`c:order`), whichever group holds them. + let order = |e: Option<&El>| e.and_then(|s| s.child_val("order")).and_then(|v| v.parse::().ok()); + let mut series = series; + if series.iter().all(|(_, _, e)| order(*e).is_some()) { + series.sort_by_key(|(_, _, e)| order(*e)); + } + let (series, drawn): (Vec, Vec) = series.into_iter().map(|(s, k, _)| (s, k)).unzip(); let legend = match dc.legend.as_deref() { None => LegendPos::None, Some("b") => LegendPos::Bottom, @@ -283,9 +428,9 @@ pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { }; let hole_size = if plot.is_some_and(|p| p.child("doughnutChart").is_some()) { (dc.hole_size * 100.0).round().clamp(10.0, 90.0) as u8 } else { 75 }; - Chart { + let mut ch = Chart { id: 0, - kind, + kind: first_kind, anchor: Default::default(), title: dc.title, series, @@ -301,12 +446,15 @@ pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { style: dc.style, hole_size, first_slice_angle: dc.first_slice_angle, - x_title: dc.axis_titles.0, - y_title: dc.axis_titles.1, + x_title: axis_titles.0, + y_title: axis_titles.1, source: None, by_rows: false, pivot: dc.pivot_source.as_deref().map(strip_book).filter(|n| !n.is_empty()).map(str::to_string), - } + }; + // Series of one family are one chart; series of other families make a combination chart. + ch.set_drawn_kinds(&drawn, first_kind); + ch } pub fn read_chart(root: &El) -> Option { @@ -330,6 +478,45 @@ enum G { Stock, } +/// The kind of axes a group is drawn on. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Axes { + /// None: pie and doughnut. + None, + /// Categories across, values up: columns, lines, areas, stock, radar. + Category, + /// Categories down, values across: horizontal bars. + Horizontal, + /// Values both ways: scatter and bubble. + Values, +} + +fn axes_of(g: G) -> Axes { + match g { + G::Pie | G::Doughnut => Axes::None, + G::Bar { bar: true, .. } => Axes::Horizontal, + G::Scatter { .. } | G::Bubble => Axes::Values, + _ => Axes::Category, + } +} + +/// Group `g` drawn on axes of kind `family`: itself where it fits, else the nearest group that +/// does (a line-like series as lines, others as columns, bars or scatter). +fn fit_axes(g: G, family: Axes) -> G { + let own = axes_of(g); + if own == family || family == Axes::None { + return g; + } + let line_like = matches!(g, G::Line { .. } | G::Area { .. } | G::Radar | G::Scatter { .. }); + match family { + Axes::None => g, + Axes::Category if line_like => G::Line { stacked: false, markers: false }, + Axes::Category => G::Bar { bar: false, grouping: "clustered" }, + Axes::Horizontal => G::Bar { bar: true, grouping: "clustered" }, + Axes::Values => G::Scatter { lines: true }, + } +} + fn group_for(k: ChartKind) -> G { match k { ChartKind::ColumnStacked => G::Bar { bar: false, grouping: "stacked" }, @@ -561,7 +748,14 @@ fn multi_level_cat(f: &str, values: &str, wb: &Workbook, si: usize) -> Option String { +/// Series `s` in group `g`, drawn as kind `own`: a line or scatter series keeps its own markers +/// or lines within its group. +fn series_xml(s: &Series, idx: usize, g: G, own: ChartKind, wb: &Workbook, si: usize) -> String { + let g = match (g, group_for(own)) { + (G::Line { stacked, .. }, G::Line { markers, .. }) => G::Line { stacked, markers }, + (G::Scatter { .. }, mine @ G::Scatter { .. }) => mine, + _ => g, + }; let mut x = format!(""); if let Some(n) = &s.name { if is_ref(n) || is_defined_name(wb, si, n) { @@ -693,8 +887,10 @@ fn dlbls(show: bool) -> String { ) } -fn group_xml(g: G, series: &[(usize, &Series)], ch: &Chart, axes: (u32, u32), wb: &Workbook, si: usize) -> String { - let sers: String = series.iter().map(|(i, s)| series_xml(s, *i, g, wb, si)).collect(); +/// Group `g` of `series`, each drawn as its kind in `kinds` (by series index). +fn group_xml(g: G, series: &[(usize, &Series)], kinds: &[ChartKind], ch: &Chart, axes: (u32, u32), wb: &Workbook, si: usize) -> String { + let sers: String = + series.iter().map(|(i, s)| series_xml(s, *i, g, kinds.get(*i).copied().unwrap_or(ChartKind::ColumnClustered), wb, si)).collect(); let dl = dlbls(ch.data_labels); let ax = format!("", axes.0, axes.1); match g { @@ -705,9 +901,11 @@ fn group_xml(g: G, series: &[(usize, &Series)], ch: &Chart, axes: (u32, u32), wb if bar { "bar" } else { "col" } ) } - G::Line { stacked, .. } => format!( - "{sers}{dl}{ax}", - if stacked { "stacked" } else { "standard" } + // Each series states its own markers; an empty group's say whether the chart has them. + G::Line { stacked, markers } => format!( + "{sers}{dl}{ax}", + if stacked { "stacked" } else { "standard" }, + u8::from(markers || !series.is_empty()) ), G::Pie => format!("{sers}{dl}", ch.first_slice_angle % 360), G::Doughnut => format!( @@ -716,7 +914,11 @@ fn group_xml(g: G, series: &[(usize, &Series)], ch: &Chart, axes: (u32, u32), wb ch.hole_size.clamp(10, 90) ), G::Area { grouping } => format!("{sers}{dl}{ax}"), - G::Scatter { .. } => format!("{sers}{dl}{ax}"), + // Each series states its own lines; an empty group's style says whether the chart has them. + G::Scatter { lines } => { + let style = if lines || !series.is_empty() { "lineMarker" } else { "marker" }; + format!("{sers}{dl}{ax}") + } G::Bubble => { format!("{sers}{dl}{ax}") } @@ -802,110 +1004,119 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> Str } s.push_str(""); let all: Vec<(usize, &Series)> = ch.series.iter().enumerate().collect(); - let primary_g; - let mut secondary: Option = None; - if ch.kind == ChartKind::Combo { - // Series without a kind of their own: the first is a column, the others lines (as drawn). - let kind = |i: usize, x: &Series| x.kind.filter(|k| *k != ChartKind::Combo).or((i > 0).then_some(ChartKind::Line)); - let is_line = |k: Option| matches!(k.map(group_for), Some(G::Line { .. } | G::Area { .. } | G::Radar | G::Scatter { .. })); - let bars: Vec<(usize, &Series)> = all.iter().filter(|(i, x)| !x.secondary && !is_line(kind(*i, x))).copied().collect(); - let lines: Vec<(usize, &Series)> = all.iter().filter(|(i, x)| !x.secondary && is_line(kind(*i, x))).copied().collect(); - let sec: Vec<(usize, &Series)> = all.iter().filter(|(_, x)| x.secondary).copied().collect(); - primary_g = G::Bar { bar: false, grouping: "clustered" }; - if !bars.is_empty() || (lines.is_empty() && sec.is_empty()) { - s.push_str(&group_xml(primary_g, &bars, ch, (1, 2), wb, si)); + // A stock chart is one group of its 3 or 4 series (high-low-close, open-high-low-close); + // other charts get one group per kind their series are drawn as, on each axis, in the order + // they first appear (a line's markers and a scatter's lines are the series' own). + let stock = ch.kind == ChartKind::Stock; + let kinds = ch.series_kinds(); + let group_of = |i: usize| match group_for(kinds.get(i).copied().unwrap_or(ChartKind::ColumnClustered)) { + G::Line { stacked, .. } => G::Line { stacked, markers: false }, + G::Scatter { .. } => G::Scatter { lines: true }, + g => g, + }; + // A chart without axes (a pie or doughnut chart) has no secondary axes either: its series + // are all one group. (A combination chart's pies are drawn as columns, on axes.) + let has_axes = (0..all.len()).any(|i| axes_of(group_of(i)) != Axes::None); + let groups = |secondary: bool| { + let mut out: Vec<(G, Vec<(usize, &Series)>)> = Vec::new(); + for &(i, x) in all.iter().filter(|(_, x)| stock || (x.secondary && has_axes) == secondary) { + let g = group_of(i); + match out.iter_mut().find(|(k, _)| *k == g) { + Some((_, members)) => members.push((i, x)), + None => out.push((g, vec![(i, x)])), + } } - if !lines.is_empty() { - s.push_str(&group_xml(G::Line { stacked: false, markers: false }, &lines, ch, (1, 2), wb, si)); + // The groups on one pair of axes share its kind of axes; one that can't (a pie beside + // columns, a scatter beside lines) is drawn in the nearest group that can. + // A combination chart is drawn on category axes (its series' kinds say how). + let family = if ch.kind == ChartKind::Combo { + Axes::Category + } else { + out.iter().map(|(g, _)| axes_of(*g)).find(|a| *a != Axes::None).unwrap_or(Axes::None) + }; + // A stock group holds 3 or 4 series (high-low-close, open-high-low-close); others are + // lines, which join a line group already there rather than setting its grouping. + let (out, stock_lines): (Vec<_>, Vec<_>) = out.into_iter().partition(|(g, m)| *g != G::Stock || (3..=4).contains(&m.len())); + let stock_lines = stock_lines.into_iter().map(|(_, m)| (G::Line { stacked: false, markers: false }, m)); + // One group per type on a pair of axes (as Excel keeps them; `Chart::series_kind` gives + // the series of one type one grouping). Groups that fit the axes come first, so a group + // moved onto them joins one of its type there rather than setting its grouping. + let (fits, moved): (Vec<_>, Vec<_>) = out.into_iter().partition(|(g, _)| fit_axes(*g, family) == *g); + let mut fitted: Vec<(G, Vec<(usize, &Series)>)> = Vec::new(); + let moved = moved.into_iter().chain(stock_lines).map(|(g, m)| (fit_axes(g, family), m)); + for (g, members) in fits.into_iter().chain(moved) { + match fitted.iter_mut().find(|(k, _)| std::mem::discriminant(k) == std::mem::discriminant(&g)) { + Some((_, m)) => m.extend(members), + None => fitted.push((g, members)), + } } - if !sec.is_empty() { - let g = match sec.first().and_then(|(_, x)| x.kind).map(group_for) { - Some(b @ G::Bar { .. }) => b, - _ => G::Line { stacked: false, markers: false }, - }; - s.push_str(&group_xml(g, &sec, ch, (3, 4), wb, si)); - secondary = Some(g); + // Each group's series in their own order. + for (_, members) in &mut fitted { + members.sort_by_key(|(i, _)| *i); } - } else { - primary_g = match group_for(ch.kind) { - // A stock chart has 3 or 4 series (high-low-close, open-high-low-close). - G::Stock if !(3..=4).contains(&ch.series.len()) => G::Line { stacked: false, markers: false }, + fitted + }; + let (mut primary, mut sec) = if stock { (groups(false), Vec::new()) } else { (groups(false), groups(true)) }; + // With every series on the secondary axis, that axis is the only one. + if primary.is_empty() { + std::mem::swap(&mut primary, &mut sec); + } + // A chart without series still has a group of its kind, or it would not be read back (a + // stock group must hold series, so an empty stock chart has a line group). + if primary.is_empty() { + let g = match group_for(ch.kind) { + G::Stock => G::Line { stacked: false, markers: false }, g => g, }; - s.push_str(&group_xml(primary_g, &all, ch, (1, 2), wb, si)); + primary.push((g, Vec::new())); } - match primary_g { - G::Pie | G::Doughnut => {} - G::Scatter { .. } | G::Bubble => { - s.push_str(&axis_xml(&Ax { - cat: false, - id: 1, - cross: 2, - pos: "b", - delete: false, - grid: false, - title: ch.x_title.as_deref(), - crosses_max: false, - })); - s.push_str(&axis_xml(&Ax { - cat: false, - id: 2, - cross: 1, - pos: "l", - delete: false, - grid: ch.gridlines, - title: ch.y_title.as_deref(), - crosses_max: false, - })); - } - G::Bar { bar: true, .. } => { - s.push_str(&axis_xml(&Ax { - cat: true, - id: 1, - cross: 2, - pos: "l", - delete: false, - grid: false, - title: ch.x_title.as_deref(), - crosses_max: false, - })); - s.push_str(&axis_xml(&Ax { - cat: false, - id: 2, - cross: 1, - pos: "b", - delete: false, - grid: ch.gridlines, - title: ch.y_title.as_deref(), - crosses_max: false, - })); - } - _ => { - s.push_str(&axis_xml(&Ax { - cat: true, - id: 1, - cross: 2, - pos: "b", - delete: false, - grid: false, - title: ch.x_title.as_deref(), - crosses_max: false, - })); - s.push_str(&axis_xml(&Ax { - cat: false, - id: 2, - cross: 1, - pos: "l", - delete: false, - grid: ch.gridlines, - title: ch.y_title.as_deref(), - crosses_max: false, - })); - } + for (g, members) in &primary { + s.push_str(&group_xml(*g, members, &kinds, ch, (1, 2), wb, si)); } - if secondary.is_some() { - s.push_str(&axis_xml(&Ax { cat: true, id: 3, cross: 4, pos: "b", delete: true, grid: false, title: None, crosses_max: false })); - s.push_str(&axis_xml(&Ax { cat: false, id: 4, cross: 3, pos: "r", delete: false, grid: false, title: None, crosses_max: true })); + for (g, members) in &sec { + s.push_str(&group_xml(*g, members, &kinds, ch, (3, 4), wb, si)); + } + let family = |gs: &[(G, Vec<(usize, &Series)>)]| gs.iter().map(|(g, _)| axes_of(*g)).find(|a| *a != Axes::None).unwrap_or(Axes::None); + let primary_axes = family(&primary); + // The primary axes, placed by their kind. + let (cat, cat_pos, val_pos) = match primary_axes { + Axes::None => (true, "", ""), + Axes::Values => (false, "b", "l"), + Axes::Horizontal => (true, "l", "b"), + Axes::Category => (true, "b", "l"), + }; + if primary_axes != Axes::None { + s.push_str(&axis_xml(&Ax { + cat, + id: 1, + cross: 2, + pos: cat_pos, + delete: false, + grid: false, + title: ch.x_title.as_deref(), + crosses_max: false, + })); + s.push_str(&axis_xml(&Ax { + cat: false, + id: 2, + cross: 1, + pos: val_pos, + delete: false, + grid: ch.gridlines, + title: ch.y_title.as_deref(), + crosses_max: false, + })); + } + // The secondary axes: their categories (or x values) hidden, their values on the far side. + let (cat, cat_pos, val_pos) = match family(&sec) { + Axes::None => (true, "", ""), + Axes::Values => (false, "b", "r"), + Axes::Horizontal => (true, "l", "t"), + Axes::Category => (true, "b", "r"), + }; + if !cat_pos.is_empty() { + s.push_str(&axis_xml(&Ax { cat, id: 3, cross: 4, pos: cat_pos, delete: true, grid: false, title: None, crosses_max: false })); + s.push_str(&axis_xml(&Ax { cat: false, id: 4, cross: 3, pos: val_pos, delete: false, grid: false, title: None, crosses_max: true })); } if let Some(t) = &ch.data_table { let _ = write!( diff --git a/crates/xlsx/src/tests/chart_combo_kinds.rs b/crates/xlsx/src/tests/chart_combo_kinds.rs index 6857683ad..04890de53 100644 --- a/crates/xlsx/src/tests/chart_combo_kinds.rs +++ b/crates/xlsx/src/tests/chart_combo_kinds.rs @@ -44,3 +44,423 @@ fn line_first_group_stays_a_line() { assert!(matches!(k[0], Some(ChartKind::Line | ChartKind::LineMarkers))); assert_eq!(k[1], Some(ChartKind::ColumnClustered)); } + +/// Outside a combo, a series keeps its own markers or lines where they differ from its chart's, +/// read and written. The chart's kind is its first series'. +#[test] +fn series_keep_their_own_markers_and_lines() { + use gridcraft_model::{Chart, Series, Workbook}; + let no_marker = "Data!$A$1:$A$5"; + let xml = format!( + "{}", + line(&(no_marker.to_string() + &ser(1))) + ); + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert_eq!((ch.kind, ch.series.iter().map(|s| s.kind).collect::>()), (ChartKind::Line, vec![None, Some(ChartKind::LineMarkers)])); + let series = |kind| Series { values: "Sheet1!$A$1:$A$3".into(), kind, ..Series::default() }; + for (kind, kinds) in + [(ChartKind::Line, vec![None, Some(ChartKind::LineMarkers)]), (ChartKind::ScatterLines, vec![Some(ChartKind::Scatter), None])] + { + let chart = Chart { kind, series: kinds.iter().map(|k| series(*k)).collect(), ..ch.clone() }; + let written = crate::chart::write_chart(&Workbook::new(), 0, &chart, "Book1"); + let back = read_chart(&parse(written.as_bytes()).unwrap()).unwrap(); + // XLSX has no chart-wide kind besides its series': each series is drawn as it was. + let drawn = |c: &Chart| (0..c.series.len()).map(|i| c.series_kind(i)).collect::>(); + assert_eq!(drawn(&back), drawn(&chart), "{kind:?}"); + } +} + +/// A combo chart is written with one group per kind its series are drawn as, and read back in +/// the series' own order. +#[test] +fn combo_series_keep_their_kinds_and_order() { + use gridcraft_model::{Chart, Series, Workbook}; + let xml = format!( + "{}{}", + bar(&ser(0)), + line(&ser(1)) + ); + let base = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + for kinds in [ + vec![ChartKind::ColumnClustered, ChartKind::Area], + vec![ChartKind::ColumnStacked, ChartKind::LineMarkers], + vec![ChartKind::LineMarkers, ChartKind::ColumnClustered], + ] { + let series: Vec = kinds + .iter() + .enumerate() + .map(|(i, k)| Series { values: format!("Sheet1!${}$1:${}$3", ["B", "C"][i], ["B", "C"][i]), kind: Some(*k), ..Series::default() }) + .collect(); + let chart = Chart { kind: ChartKind::Combo, series, ..base.clone() }; + let back = read_chart(&parse(crate::chart::write_chart(&Workbook::new(), 0, &chart, "Book1").as_bytes()).unwrap()).unwrap(); + let drawn = |c: &Chart| (0..c.series.len()).map(|i| (c.series_kind(i), c.series[i].values.clone())).collect::>(); + assert_eq!(drawn(&back), drawn(&chart), "{kinds:?}"); + } + // Groups that can't share one pair of axes are drawn in the first one's kind: a pie beside + // columns as columns, its axes all present. (A combination's bars are drawn as columns.) + { + let (kinds, want) = (vec![ChartKind::Pie, ChartKind::ColumnClustered], ChartKind::ColumnClustered); + let series: Vec = kinds.iter().map(|k| Series { values: "Sheet1!$B$1:$B$3".into(), kind: Some(*k), ..Series::default() }).collect(); + let chart = Chart { kind: ChartKind::Combo, series, ..base.clone() }; + let xml = crate::chart::write_chart(&Workbook::new(), 0, &chart, "Book1"); + let back = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert!((0..2).all(|i| back.series_kind(i) == want), "{kinds:?}: {xml}"); + assert!(back.series.iter().all(|s| !s.secondary), "{kinds:?}"); + assert!(xml.contains(""), "{kinds:?}: {xml}"); + } +} + +/// A chart of one kind with a series on the secondary axis keeps it, and reads back as that +/// kind, not a combination. +#[test] +fn one_kind_on_two_axes_stays_one_kind() { + use gridcraft_model::{Chart, Series, Workbook}; + let xml = format!( + "{}", + bar(&ser(0)) + ); + let base = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + let series = vec![ + Series { values: "Sheet1!$B$1:$B$3".into(), ..Series::default() }, + Series { values: "Sheet1!$C$1:$C$3".into(), secondary: true, ..Series::default() }, + ]; + let chart = Chart { kind: ChartKind::ColumnClustered, series, ..base }; + let back = read_chart(&parse(crate::chart::write_chart(&Workbook::new(), 0, &chart, "Book1").as_bytes()).unwrap()).unwrap(); + assert_eq!(back.kind, ChartKind::ColumnClustered); + assert_eq!(back.series.iter().map(|s| (s.kind, s.secondary)).collect::>(), vec![(None, false), (None, true)]); +} + +/// A stock chart with volume: the stock group of 4 series stays a stock group beside the +/// volume columns. +#[test] +fn stock_with_volume_keeps_its_stock_group() { + use gridcraft_model::{Chart, Series, Workbook}; + let xml = format!( + "{}", + bar(&ser(0)) + ); + let base = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + let mut series = vec![Series { values: "Sheet1!$B$1:$B$3".into(), kind: Some(ChartKind::ColumnClustered), ..Series::default() }]; + series.extend((0..4).map(|_| Series { values: "Sheet1!$C$1:$C$3".into(), kind: Some(ChartKind::Stock), secondary: true, ..Series::default() })); + let chart = Chart { kind: ChartKind::Combo, series, ..base }; + let written = crate::chart::write_chart(&Workbook::new(), 0, &chart, "Book1"); + assert!(written.contains(""), "{written}"); + let back = read_chart(&parse(written.as_bytes()).unwrap()).unwrap(); + assert_eq!((1..5).map(|i| back.series_kind(i)).collect::>(), vec![ChartKind::Stock; 4]); +} + +/// A stock series too few for a stock group is saved as a line in the line group already on its +/// axes: the stacked lines after it stay stacked. +#[test] +fn a_lone_stock_series_does_not_unstack_the_lines_beside_it() { + use ChartKind::*; + let chart = chart_of(Combo, &[(Some(Stock), false), (Some(LineStacked), false), (Some(LineStacked), false)]); + let (xml, back) = round_trip(&chart); + assert_eq!(xml.matches("").count(), 1, "{xml}"); + assert!(xml.contains(""), "{xml}"); + assert_eq!((back.series_kind(1), back.series_kind(2)), (LineStacked, LineStacked), "{xml}"); +} + +/// The primary axes are the pair whose value axis is on the left, whichever group the file +/// lists first. +#[test] +fn a_secondary_scatter_listed_first_stays_secondary() { + let sc = |s: &str, a: u32, b: u32| { + format!("{s}") + }; + let ax = + |id: u32, cross: u32, pos: &str| format!(""); + let xml = format!( + "{}{}{}{}{}{}", + sc(&ser(0), 30, 40), + sc(&ser(1), 10, 20), + ax(10, 20, "b"), + ax(20, 10, "l"), + ax(30, 40, "b"), + ax(40, 30, "r") + ); + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert_eq!(ch.series.iter().map(|s| s.secondary).collect::>(), vec![true, false]); +} + +/// A chart of `kind` whose series have `kinds` (and secondary flags). +fn chart_of(kind: ChartKind, kinds: &[(Option, bool)]) -> gridcraft_model::Chart { + use gridcraft_model::{Chart, Series}; + let xml = format!( + "{}", + bar(&ser(0)) + ); + let base = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + let series = kinds + .iter() + .enumerate() + .map(|(i, (k, secondary))| Series { values: format!("Sheet1!$B${0}:$B${0}", i + 1), kind: *k, secondary: *secondary, ..Series::default() }) + .collect(); + Chart { kind, series, ..base } +} + +/// The chart written to XLSX, and read back. +fn round_trip(chart: &gridcraft_model::Chart) -> (String, gridcraft_model::Chart) { + let xml = crate::chart::write_chart(&gridcraft_model::Workbook::new(), 0, chart, "Book1"); + let back = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + (xml, back) +} + +/// What a chart draws: each series' values, kind and axis. +fn drawn(c: &gridcraft_model::Chart) -> Vec<(String, ChartKind, bool)> { + let any_primary = c.series.iter().any(|s| !s.secondary); + (0..c.series.len()).map(|i| c.series_kind(i)).zip(&c.series).map(|(k, s)| (s.values.clone(), k, s.secondary && any_primary)).collect() +} + +/// A chart written to XLSX and read back draws the same series, kinds and axes. +fn assert_round_trips(kind: ChartKind, kinds: &[(Option, bool)]) -> String { + let chart = chart_of(kind, kinds); + let (xml, back) = round_trip(&chart); + assert_eq!(drawn(&back), drawn(&chart), "{kinds:?}: {xml}"); + xml +} + +/// Pies and doughnuts have no axes: a series marked secondary (left from a combo before the +/// type changed) stays in the one group, so Excel draws one pie, not two on top of each other. +#[test] +fn pies_and_doughnuts_are_one_group_whatever_the_secondary_flags() { + for (kind, tag) in [(ChartKind::Pie, ""), (ChartKind::Doughnut, "")] { + let (xml, back) = round_trip(&chart_of(kind, &[(None, false), (None, true)])); + assert_eq!(xml.matches(tag).count(), 1, "{xml}"); + assert!(!xml.contains(""), "{xml}"); + assert_eq!((back.kind, back.series.len()), (kind, 2)); + } +} + +/// A combination chart's pies and doughnuts are drawn as columns, on axes: on the secondary +/// axis beside other secondary series, with primary axes always written, and a combo of only +/// pies and doughnuts is one group of columns. +#[test] +fn combo_pies_are_columns_on_their_own_axes() { + use ChartKind::*; + let xml = assert_round_trips(Combo, &[(Some(Pie), true), (Some(ColumnClustered), true)]); + assert!(xml.contains("") && !xml.contains(""), "{xml}"); + let xml = assert_round_trips(Combo, &[(Some(ColumnClustered), false), (Some(Line), true), (Some(Pie), true)]); + assert_eq!(xml.matches("").count(), 2, "{xml}"); + let xml = assert_round_trips(Combo, &[(Some(Pie), false), (Some(Doughnut), false)]); + assert!(!xml.contains("") && !xml.contains(""), "{xml}"); + assert_eq!(xml.matches("").count(), 1, "{xml}"); +} + +/// Excel keeps one group per type on a pair of axes: clustered and stacked columns (lines and +/// stacked lines, areas and stacked areas) on the same axes are written as one group, drawn +/// alike before saving and after reopening. +#[test] +fn one_group_per_type_on_a_pair_of_axes() { + use ChartKind::*; + for (kinds, tag) in [ + (vec![(Some(ColumnStacked), false), (Some(Pie), false), (Some(Line), false)], ""), + (vec![(Some(Pie), false), (Some(ColumnStacked), false), (Some(Line), false)], ""), + (vec![(Some(ColumnClustered), false), (Some(ColumnStacked), false)], ""), + (vec![(Some(ColumnStacked), false), (Some(ColumnClustered), false), (Some(Line), false)], ""), + (vec![(Some(Line), false), (Some(LineStacked), false), (Some(ColumnClustered), false)], ""), + (vec![(Some(LineStacked), false), (Some(LineMarkers), false), (Some(ColumnClustered), false)], ""), + (vec![(Some(Area), false), (Some(AreaStacked), false), (Some(ColumnClustered), false)], ""), + ] { + let xml = assert_round_trips(Combo, &kinds); + assert_eq!(xml.matches(tag).count(), 1, "{kinds:?}: {xml}"); + } + // A stacked column after a clustered one is drawn clustered, as it is saved. + let chart = chart_of(Combo, &[(Some(ColumnClustered), false), (Some(ColumnStacked), false)]); + assert_eq!((chart.series_kind(0), chart.series_kind(1)), (ColumnClustered, ColumnClustered)); + // On separate axes each keeps its own grouping. + let xml = assert_round_trips(Combo, &[(Some(ColumnClustered), false), (Some(ColumnStacked), true), (Some(Line), false)]); + assert_eq!(xml.matches("").count(), 2, "{xml}"); +} + +/// A merged group writes its series in their own order: a bubble series drawn as a column joins +/// the columns where it stands. +#[test] +fn a_merged_group_keeps_its_series_in_order() { + use ChartKind::*; + let (xml, back) = round_trip(&chart_of(Combo, &[(Some(ColumnClustered), false), (Some(Bubble), false), (Some(ColumnClustered), false)])); + assert_eq!(back.series.iter().map(|s| s.values.as_str()).collect::>(), vec!["Sheet1!$B$1:$B$1", "Sheet1!$B$2:$B$2", "Sheet1!$B$3:$B$3"]); + let orders: Vec<&str> = xml.match_indices("") && !xml.contains(""), "{kinds:?}: {xml}"); + assert!(xml.contains(""), "{kinds:?}: {xml}"); + } +} + +/// A combination chart's chartex series (histogram, waterfall, funnel, treemap, sunburst, box & +/// whisker) are drawn and saved as clustered columns, sharing the first column's grouping. +#[test] +fn combo_chartex_series_are_columns() { + use ChartKind::*; + for k in [Histogram, Waterfall, Funnel, Treemap, Sunburst, BoxWhisker] { + let xml = assert_round_trips(Combo, &[(Some(ColumnStacked), false), (Some(k), false), (None, false)]); + assert_eq!(xml.matches("").count(), 1, "{k:?}: {xml}"); + assert_round_trips(Combo, &[(Some(k), false), (Some(ColumnStacked), false), (Some(Line), false)]); + let chart = chart_of(Combo, &[(Some(Bubble), false), (Some(k), false)]); + assert_eq!(round_trip(&chart).1.supports_data_table(), chart.supports_data_table(), "{k:?}"); + } +} + +/// A chart without series keeps a group of its kind, so it is read back as that kind rather +/// than dropped (an empty combo as clustered columns, an empty stock chart as a line chart: a +/// stock group must hold series). +#[test] +fn a_chart_without_series_survives_a_round_trip() { + use ChartKind::*; + let kinds = [ + ColumnClustered, + ColumnStacked100, + BarStacked, + Line, + LineMarkers, + LineStacked, + Pie, + Doughnut, + Area, + AreaStacked, + Scatter, + ScatterLines, + Bubble, + Radar, + Stock, + Combo, + ]; + for kind in kinds { + let (xml, back) = round_trip(&chart_of(kind, &[])); + let want = match kind { + Combo => ColumnClustered, + Stock => Line, + k => k, + }; + assert_eq!((back.kind, back.series.len()), (want, 0), "{kind:?}: {xml}"); + } +} + +/// The primary axes are found in one pass over the value axes, however many groups a file has: +/// eight times the groups is about eight times the work, not sixty-four. +#[test] +fn many_groups_are_read_in_linear_time() { + // Every group has a series and its own value axis on the right, so no group is the primary + // pair and every group's value axis is looked up among all the others. + let visits = |n: usize| { + let groups: String = (0..n) + .map(|i| { + format!( + "{}", + ser(i), + 2 * i + 1, + 2 * i + 2 + ) + }) + .collect(); + let axes: String = (0..n).map(|i| format!("", 2 * i + 2)).collect(); + let xml = format!( + "{groups}{axes}" + ); + let doc = parse(xml.as_bytes()).unwrap(); + crate::chart::VAL_AXIS_VISITS.with(|v| v.set(0)); + let ch = read_chart(&doc).unwrap(); + assert_eq!(ch.series.len(), n); + crate::chart::VAL_AXIS_VISITS.with(|v| v.get()) + }; + let (small, large) = (visits(300), visits(2_400)); + assert!(small >= 300, "every value axis is looked at: {small}"); + assert!(large < 16 * small, "eight times the groups took {large} visits against {small}"); +} + +/// An empty group of another kind before the groups with series (as another writer may leave) +/// sets neither the chart's axes nor which series are secondary. +#[test] +fn an_empty_group_sets_neither_axes_nor_secondary() { + let ax = |tag: &str, id: u32, cross: u32, pos: &str, title: &str| { + format!( + "{title}" + ) + }; + let xml = format!( + "\ + {AX}\ + {}\ + {}{}{}{}", + ser(0), + ax("catAx", 1, 2, "b", "BARCAT"), + ax("valAx", 2, 1, "l", "BARVAL"), + ax("valAx", 3, 4, "b", "SCX"), + ax("valAx", 4, 3, "l", "SCY"), + ); + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert_eq!(ch.kind, ChartKind::ScatterLines); + assert!(!ch.series[0].secondary); + assert_eq!((ch.x_title.as_deref(), ch.y_title.as_deref()), (Some("SCX"), Some("SCY"))); +} + +/// An axis element (`tag` with id, crossing axis, side, title, and whether it is deleted). +fn axis(tag: &str, id: u32, cross: u32, pos: &str, title: Option<&str>, deleted: bool) -> String { + let title = title.map_or(String::new(), |t| format!("{t}")); + format!( + "{title}", + u8::from(deleted) + ) +} + +fn titles_of(plot: &str) -> (Option, Option) { + let xml = format!( + "{plot}" + ); + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + (ch.x_title, ch.y_title) +} + +/// Axis titles come from shown axes before deleted ones, and the primary pair's group says +/// whether they are a scatter's two value axes. +#[test] +fn titles_come_from_shown_axes_of_the_primary_pair() { + let some = |x: &str, y: &str| (Some(x.to_string()), Some(y.to_string())); + // Series only on axes 3/4 (whose category axis is deleted), beside an empty group on 1/2. + let plot = format!( + "{AX}\ + {}{}{}{}{}", + ser(0), + axis("catAx", 1, 2, "b", Some("PCAT"), false), + axis("valAx", 2, 1, "l", Some("PVAL"), false), + axis("catAx", 3, 4, "b", None, true), + axis("valAx", 4, 3, "r", Some("SVAL"), false), + ); + assert_eq!(titles_of(&plot), some("PCAT", "SVAL")); + // A secondary line group before the primary scatter group. + let plot = format!( + "{}\ + {}{AX}{}{}{}{}", + ser(0), + ser(1), + axis("catAx", 3, 4, "b", Some("SCAT"), true), + axis("valAx", 4, 3, "r", Some("SVAL"), false), + axis("valAx", 1, 2, "b", Some("X"), false), + axis("valAx", 2, 1, "l", Some("Y"), false), + ); + assert_eq!(titles_of(&plot), some("X", "Y")); +} diff --git a/crates/xlsx/src/tests/fixtures.rs b/crates/xlsx/src/tests/fixtures.rs index 46a953bc1..b40be2b15 100644 --- a/crates/xlsx/src/tests/fixtures.rs +++ b/crates/xlsx/src/tests/fixtures.rs @@ -909,18 +909,17 @@ fn two_column_groups_on_different_axes_preserve_secondary_and_kind() { ); let (wb, _) = read_xlsx(&bytes).unwrap(); let ch = &wb.sheet(0).unwrap().charts[0]; - assert_eq!(ch.kind, gridcraft_model::ChartKind::Combo); + // Series of one kind are one chart, a column chart with a secondary-axis series. + assert_eq!(ch.kind, gridcraft_model::ChartKind::ColumnClustered); assert!(!ch.series[0].secondary); assert!(ch.series[1].secondary); - assert_eq!(ch.series[0].kind, Some(gridcraft_model::ChartKind::ColumnClustered)); - assert_eq!(ch.series[1].kind, Some(gridcraft_model::ChartKind::ColumnClustered)); + assert_eq!(ch.series_kinds(), vec![gridcraft_model::ChartKind::ColumnClustered; 2]); let out = crate::write_xlsx(&wb).unwrap(); let (wb2, _) = read_xlsx(&out).unwrap(); let ch2 = &wb2.sheet(0).unwrap().charts[0]; - assert_eq!(ch2.kind, gridcraft_model::ChartKind::Combo); + assert_eq!(ch2.kind, gridcraft_model::ChartKind::ColumnClustered); assert!(!ch2.series[0].secondary); assert!(ch2.series[1].secondary); - assert_eq!(ch2.series[0].kind, Some(gridcraft_model::ChartKind::ColumnClustered)); - assert_eq!(ch2.series[1].kind, Some(gridcraft_model::ChartKind::ColumnClustered)); + assert_eq!(ch2.series_kinds(), vec![gridcraft_model::ChartKind::ColumnClustered; 2]); } diff --git a/docs/chart-parity.md b/docs/chart-parity.md index 4967b0020..37f482eeb 100644 --- a/docs/chart-parity.md +++ b/docs/chart-parity.md @@ -1,6 +1,6 @@ # Chart parity -> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-11-16 · **Change:** minor (a selected chart outlines its series names, category labels and values in Excel's colours, and dragging a corner of the values outline changes the plotted block, #4389, #4390; earlier: chart-data-table keys pass the series index to the shared combo plot-kind rule, restoring compilation after #1150; earlier: doughnut charts: every series is a concentric ring, the first series innermost; hole size and first slice angle kept; rotated slices cover their own sweep; legend names categories; earlier: charts resize from eight handles, chart data tables, legend keys and borders, native XLSX round-trip and print/PDF; earlier: selected chart source outlines stay beneath floating objects) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-11-16 · **Change:** minor (a selected chart outlines its series names, category labels and values in Excel's colours, and dragging a corner of the values outline changes the plotted block, #4389, #4390; earlier: combo series drawn and saved by their own kind; earlier: chart-data-table keys pass the series index to the shared combo plot-kind rule, restoring compilation after #1150; earlier: doughnut charts: every series is a concentric ring, the first series innermost; hole size and first slice angle kept; rotated slices cover their own sweep; legend names categories; earlier: charts resize from eight handles, chart data tables, legend keys and borders, native XLSX round-trip and print/PDF; earlier: selected chart source outlines stay beneath floating objects) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Excel's chart types and chart elements against GridCraft. Part of [target-app-parity.md](target-app-parity.md). **Breadth ~50%, ready ~30%, 40–60 h** (estimated). @@ -32,7 +32,7 @@ Sources: `crates/model/src/features.rs` (`ChartKind`, `Chart`, `Series`), `crate | Box & Whisker | 1 | 1 of 1 | | | Waterfall, Funnel | 2 | 2 of 2 | | | Filled map | 1 | 0 | needs geographic boundary data (licensing decision) | -| Combo | custom combinations, secondary axis | yes (line on secondary axis) | | +| Combo | custom combinations, secondary axis | yes: each series drawn as its own kind (column, stacked column, line, line with markers, area; bars stand upright as columns, pies, doughnuts, bubbles and chartex kinds are clustered columns, scatter series lines with markers, scatter-with-lines and radar series lines), secondary axis | | | **Total** | ~60 subtypes | **26 (~43%)** | usage-weighted breadth higher (~65%): column, bar, line, pie and scatter dominate | ## Chart elements and formatting @@ -49,7 +49,7 @@ Sources: `crates/model/src/features.rs` (`ChartKind`, `Chart`, `Series`), `crate | Axis options | min/max/units, log scale, reverse order, crossing point, display units, date axis, number format | **missing** (auto only) | | Multi-level category axis (a category range two or more columns wide beside the values: year beside month) | the outer levels grouped under the labels with separators | read (`multiLvlStrRef`), drawn (rows under the labels; columns beside them in bar charts; up to three outer levels), written back with Excel's level caches | | Doughnut hole size, first slice angle | 10–90% hole (Excel default 75%), 0–359° first slice | Format Chart pane sliders; read from and written to `c:holeSize` / `c:firstSliceAng`; documents saved before the setting existed keep their old 50% hole | -| Secondary axis | any series | line series in combo charts | +| Secondary axis | any series | any combo series; a one-kind chart's secondary series keep their axis in XLSX | | Trendlines | linear, exponential, logarithmic, polynomial, power, moving average, equation and R² | all six types, several per series, name, forward/backward forecast, set intercept, equation and R² label, line colour/width/dash; read, written and drawn on 2-D column, bar, line, area, scatter and bubble series; `chart.addElement` `trendline` adds/removes them. No Format Trendline pane, label position/number format not kept | | Error bars | fixed, %, standard deviation/error, custom | **missing** | | Up/down bars, high-low lines, drop lines, series lines | yes | **missing** | @@ -95,6 +95,37 @@ qualifier: with a bare name in `` it draws the whole chart blank, without a (observed in Excel for Windows, Microsoft 365). External books (`[1]Sheet1!…`) are kept as they are (#1686). Such series get no `numCache`/`strCache` on save (#1690). +Each series is drawn and saved as the kind `Chart::series_kind` gives it: in a combo chart its +own kind (by default the first a column and the rest lines), elsewhere the chart's kind, with a +line's own markers or a scatter's own lines kept. A combo chart is drawn on category axes: its +bars as columns, its pies, doughnuts, bubbles and chartex kinds (histogram, waterfall, funnel, +treemap, sunburst, box & whisker) as clustered columns, its scatter and radar series as lines (a +markers-only scatter with markers). In +a combo chart the series of one type on one pair of axes share the first one's grouping, as Excel +keeps them: a stacked column after a clustered one is drawn clustered, and a stacked line after +an unstacked one unstacked. Changing the chart type (to any type but a combo) applies it to every +series, dropping their own kinds; setting the type a chart already has keeps them. + +The XLSX writer writes one chart group per type on each pair of axes, with axes of the kind those +groups need (category axes for a combo; category, horizontal-bar or value axes otherwise), a secondary pair whenever a series is on it, and a stock group only for 3 +or 4 series. A pie or doughnut chart has no axes, so its series are one group whatever their +secondary flags. A chart without series is written with one empty group of its kind, so it +reopens as that kind (an empty combo as clustered columns, an empty stock chart as a line chart) +rather than vanishing; chartex charts (histogram, waterfall and the rest) without series are +still not kept. The reader takes the primary axes from the value axis on the left or bottom, and +orders series by `c:order`, then sets the chart's kind and each series' own kind with +`Chart::set_drawn_kinds`, the rule any reader of per-series kinds shares. A combo whose series all draw as one type reopens as a chart of +that type (it draws the same). + +Known gaps: a one-kind bar chart's secondary series get secondary axes in XLSX, which the +renderer does not yet draw for horizontal charts; a stock series in a combo +beside stacked lines is saved in the stacked line group but drawn unstacked; a stock series +beside columns (other than a 3- or 4-series stock group) is saved as a line and reopens as one; +a per-series line or scatter kind left in an older GridCraft JSON workbook by a type change is +honoured (markers gained or lines lost) rather than migrated, since it can't be told from a +file's own per-series kind; the Forecast Sheet's +column chart draws and saves its forecast series as columns, not lines. + ## Work (40–60 h) 1. Preserve unmodelled chart XML on round-trip (keep the original part, patch only edited fields): 6–10 h. @@ -109,6 +140,7 @@ are (#1686). Such series get no `numCache`/`strCache` on save (#1690). | Date | Change | Summary | |---|---|---| | 2026-11-16 | minor | A selected chart outlines its series names (red), category labels (purple) and values (one blue block), and the values outline has corner handles: dragging one changes the block the series plot through the new `chart.setValuesRange` command, keeping each series' formatting (#4389, #4390). Engine and real-input UI tests cover growing, shrinking, adding series, undo and Esc. No readiness score change. | +| 2026-11-14 | minor | Combo series drawn and saved by their own kind (`Chart::series_kind`): areas, stacked columns and marker lines in combos round-trip XLSX; the series of one type on one pair of axes share the first one's grouping on screen and in the file (as Excel keeps them); combo charts are drawn and saved on category axes (pies, doughnuts, bubbles and chartex kinds as columns, scatter and radar as lines); one-kind charts keep secondary-axis series (pie and doughnut charts stay one group); changing the type applies it to every series; charts without series survive XLSX. No readiness score change. | | 2026-11-07 | minor | Chart-data-table keys use the shared plot-kind helper with their series index after #1150. A focused regression checks the first combo series uses a column key and later series use line keys. No readiness score change. | | 2026-11-02 | minor | Charts move and resize from eight handles, each moving only its own edges (#190); resizing leaves the work list (1–2 h, within the 40–60 h rounding) | | 2026-11-01 | minor | Chart data tables for column, bar, line, area and compatible combo charts: command/UI controls, formatted source values, blanks, grouped category headers, legend keys, independent borders, shared print/PDF rendering and native c:dTable import/export. Dense tables show a space notice; no readiness score change. |