From e16b95eb821e9bb70f809eaad85e3cbcdac0f046 Mon Sep 17 00:00:00 2001 From: Local contributor Date: Wed, 14 Oct 2026 08:22:29 -0400 Subject: [PATCH] XLSX: Multi-level PivotChart categories plot one label per point; quoted series names survive a save A PivotChart whose multiLvlStrRef categories cover two levels (Graph!$A$4:$B$7 for 4 points) stayed live when the innermost column matched the cache. The renderer reads every cell of that block, so the chart drew 8 labels for 4 points, and a save flattened it into an 8-point strRef. Such a block is now compared cell for cell like any other reference: its cell count isn't the point count, so the innermost level is plotted from the cache, one label per point, and saved as a strLit. A one-level reference whose cells hold the cache still stays live. A literal series name is stored as a quoted formula literal with doubled quotes ("Sales ""East"""), which stale PivotChart series now always get. The chart and chartex writers only stripped the outer quotes, so the name came back as Sales ""East"" after a save. Both writers now unescape the literal through one helper. --- crates/xlsx/src/chart.rs | 38 +++++------ crates/xlsx/src/chartex.rs | 3 +- crates/xlsx/src/tests/chart_read_tests.rs | 78 +++++++++++++++-------- docs/chart-parity.md | 4 +- 4 files changed, 71 insertions(+), 52 deletions(-) diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index 198487c96b..f591fec93d 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -3,7 +3,7 @@ use std::fmt::Write as _; -use gridcraft_core::{CellRef, RangeRef, Value}; +use gridcraft_core::Value; use gridcraft_formula::{BinOp, Expr, Reference, SheetSel}; use gridcraft_model::{Chart, ChartKind, Color, LegendPos, LineDash, Series, Trendline, TrendlineKind, Workbook}; @@ -122,9 +122,6 @@ fn literal>(points: &[Option], numeric: bool) -> String { struct CachedPoints { points: Vec>, numeric: bool, - /// A `multiLvlStrRef`: one column (or row) of cells per level, the innermost last. The - /// cache holds the innermost level. - multi_level: bool, } /// What a PivotChart series saved with its references, plotted when the referenced cells don't @@ -139,16 +136,18 @@ pub(crate) struct PivotSeriesCache { } /// `numCache`, `strCache`, or the innermost level of a `multiLvlStrCache`, under `cat` or `val`. +/// A `multiLvlStrRef` block of more than one level has a cell per level for each point, so its +/// cell count isn't the point count and the innermost level is plotted from the cache. fn cached_points(e: Option<&El>) -> Option { let e = e?; let owned = |p: Vec>| p.into_iter().map(|v| v.map(str::to_string)).collect(); if let Some(c) = e.path(&["numRef", "numCache"]) { - Some(CachedPoints { points: owned(read_points(c, c)?), numeric: true, multi_level: false }) + Some(CachedPoints { points: owned(read_points(c, c)?), numeric: true }) } else if let Some(c) = e.path(&["strRef", "strCache"]) { - Some(CachedPoints { points: owned(read_points(c, c)?), numeric: false, multi_level: false }) + Some(CachedPoints { points: owned(read_points(c, c)?), numeric: false }) } else { let c = e.path(&["multiLvlStrRef", "multiLvlStrCache"])?; - Some(CachedPoints { points: owned(read_points(c, c.child("lvl")?)?), numeric: false, multi_level: true }) + Some(CachedPoints { points: owned(read_points(c, c.child("lvl")?)?), numeric: false }) } } @@ -213,19 +212,6 @@ fn live_matches(wb: &Workbook, home: usize, f: &str, p: &CachedPoints) -> bool { areas.push((sheet, r.range())); } let n = p.points.len(); - if p.multi_level { - // Only the innermost level is cached: the last column of a block with a row per point, - // or the last row of one with a column per point. - let [(sheet, r)] = areas[..] else { return false }; - let leaf = if r.height() as usize == n { - RangeRef::new(CellRef::new(r.start.row, r.end.col), r.end) - } else if r.width() as usize == n { - RangeRef::new(CellRef::new(r.end.row, r.start.col), r.end) - } else { - return false; - }; - areas = vec![(sheet, leaf)]; - } if areas.iter().try_fold(0u64, |t, (_, r)| t.checked_add(r.count())) != Some(n as u64) { return false; } @@ -626,14 +612,22 @@ fn str_data(tag: &str, f: &str, wb: &Workbook, si: usize) -> String { s } +/// The text of a literal series name: a quoted formula literal (`"Sales ""East"""`) without its +/// quotes and with `""` read as `"`; bare text as is. +pub(crate) fn literal_text(n: &str) -> std::borrow::Cow<'_, str> { + match n.trim().strip_prefix('"').and_then(|t| t.strip_suffix('"')) { + Some(t) => t.replace("\"\"", "\"").into(), + None => n.into(), + } +} + fn series_xml(s: &Series, idx: usize, g: G, wb: &Workbook, si: usize) -> String { let mut x = format!(""); if let Some(n) = &s.name { if is_ref(n) { x.push_str(&str_data("tx", n, wb, si)); } else { - let lit = n.trim().strip_prefix('"').and_then(|t| t.strip_suffix('"')).unwrap_or(n); - let _ = write!(x, "{}", esc(lit)); + let _ = write!(x, "{}", esc(&literal_text(n))); } } let color = s.color.as_ref().and_then(|c: &Color| srgb(c, &wb.theme)); diff --git a/crates/xlsx/src/chartex.rs b/crates/xlsx/src/chartex.rs index 2ab8c221bd..40f7d0956a 100644 --- a/crates/xlsx/src/chartex.rs +++ b/crates/xlsx/src/chartex.rs @@ -169,8 +169,7 @@ fn tx_xml(t: &str, wb: &Workbook, si: usize, names: &mut Vec) -> String let v = crate::chart::ref_values(wb, si, t).and_then(|v| v.into_iter().next()).map(|v| v.display()).unwrap_or_default(); format!("{}{}", f_xml(wb, si, t, names), esc(&v)) } else { - let lit = t.trim().strip_prefix('"').and_then(|x| x.strip_suffix('"')).unwrap_or(t); - format!("{}", esc(lit)) + format!("{}", esc(&crate::chart::literal_text(t))) } } diff --git a/crates/xlsx/src/tests/chart_read_tests.rs b/crates/xlsx/src/tests/chart_read_tests.rs index 3a139738a4..2b56ed6197 100644 --- a/crates/xlsx/src/tests/chart_read_tests.rs +++ b/crates/xlsx/src/tests/chart_read_tests.rs @@ -107,12 +107,7 @@ fn pivot_charts_plot_their_cached_points_when_the_references_do_not_cover_them() let c = read(&chart_xml(true, &plot, "")); let back = read(&crate::chart::write_chart(&Workbook::new(), 0, &c)); assert_eq!(back.pivot, c.pivot); - let parts = |c: &Chart| { - c.series - .iter() - .map(|s| (s.name.as_deref().map(|n| n.trim_matches('"').to_string()), s.categories.clone(), s.values.clone())) - .collect::>() - }; + let parts = |c: &Chart| c.series.iter().map(|s| (shown(s.name.as_deref()), s.categories.clone(), s.values.clone())).collect::>(); assert_eq!(parts(&back), parts(&c)); } @@ -142,41 +137,72 @@ fn a_one_point_pivot_chart_at_the_corner_cell_plots_its_cache() { } #[test] -fn multi_level_pivot_categories_stay_live_when_their_cells_hold_the_cache() { +fn multi_level_pivot_categories_plot_their_innermost_level() { // Two levels of row labels in A4:B7, the outer one (country) on the left; the cache keeps // the innermost level first. let cities = ["Ottawa", "Toronto", "Boston", "NYC"]; let leaf: String = cities.iter().enumerate().map(|(i, v)| format!(r#"{v}"#)).collect(); let outer = r#"CanadaUSA"#; - let cat = format!( - r#"Graph!$A$4:$B$7{leaf}{outer}"# - ); - let val = num_cache("Graph!$C$4:$C$7", 4, &[(0, "1"), (1, "2"), (2, "3"), (3, "4")]); - let xml = chart_xml( - true, - &format!( - r#"{}"#, - ser(&str_cache("Graph!$C$3", &["Total"]), &cat, &val) - ), - "", - ); + let xml = |f: &str, levels: &str| { + let cat = + format!(r#"{f}{levels}"#); + let val = num_cache("Graph!$C$4:$C$7", 4, &[(0, "1"), (1, "2"), (2, "3"), (3, "4")]); + chart_xml( + true, + &format!( + r#"{}"#, + ser(&str_cache("Graph!$C$3", &["Total"]), &cat, &val) + ), + "", + ) + }; let mut cells = vec![("A4", Value::text("Canada")), ("A6", Value::text("USA")), ("C3", Value::text("Total"))]; for (i, city) in cities.iter().enumerate() { cells.push((["B4", "B5", "B6", "B7"][i], Value::text(*city))); cells.push((["C4", "C5", "C6", "C7"][i], Value::Number(i as f64 + 1.0))); } let wb = book("Graph", &cells); - let c = read_in(&wb, &xml); + // The two-level block would draw both levels' cells (8 labels for 4 points): the innermost + // level is plotted from the cache, one label per point. The values' cells hold their cache. + let two_levels = xml("Graph!$A$4:$B$7", &format!("{leaf}{outer}")); + let c = read_in(&wb, &two_levels); let s = &c.series[0]; - assert_eq!((s.name.as_deref(), s.categories.as_deref(), s.values.as_str()), (Some("Graph!$C$3"), Some("Graph!$A$4:$B$7"), "Graph!$C$4:$C$7")); - // A save keeps the reference. + let labels = r#"{"Ottawa","Toronto","Boston","NYC"}"#; + assert_eq!((s.categories.as_deref(), s.values.as_str()), (Some(labels), "Graph!$C$4:$C$7")); + // A save keeps one label per point. let back = read_in(&wb, &crate::chart::write_chart(&wb, 0, &c)); - assert_eq!(back.series[0].categories.as_deref(), Some("Graph!$A$4:$B$7")); + assert_eq!(back.series[0].categories.as_deref(), Some(labels)); - // When the innermost level's cells show other labels, the cache is plotted. + // A one-level reference whose cells hold the cache stays live; when a cell shows another + // label, the cache is plotted. + let one_level = xml("Graph!$B$4:$B$7", &format!("{leaf}")); + assert_eq!(read_in(&wb, &one_level).series[0].categories.as_deref(), Some("Graph!$B$4:$B$7")); cells.push(("B5", Value::text("Montreal"))); - let c = read_in(&book("Graph", &cells), &xml); - assert_eq!(c.series[0].categories.as_deref(), Some(r#"{"Ottawa","Toronto","Boston","NYC"}"#)); + assert_eq!(read_in(&book("Graph", &cells), &one_level).series[0].categories.as_deref(), Some(labels)); +} + +/// A series name as the chart shows it: a quoted literal without its quotes, `""` read as `"`. +fn shown(name: Option<&str>) -> Option { + name.map(|n| n.strip_prefix('"').and_then(|q| q.strip_suffix('"')).map_or_else(|| n.to_string(), |q| q.replace("\"\"", "\""))) +} + +#[test] +fn series_names_with_quotes_survive_a_save() { + // A stale PivotChart series takes its cached name, quotes and all. + let s = + ser(&str_cache("Graph!$J$2", &["Sales \"East\""]), &str_cache("Graph!$J$2", &["a", "b"]), &num_cache("Graph!$J$2", 2, &[(0, "1"), (1, "2")])); + let c = read(&chart_xml(true, &format!("{s}"), "")); + assert_eq!(shown(c.series[0].name.as_deref()).as_deref(), Some("Sales \"East\"")); + let back = read(&crate::chart::write_chart(&Workbook::new(), 0, &c)); + assert_eq!(shown(back.series[0].name.as_deref()).as_deref(), Some("Sales \"East\"")); + + // So does a literal name on a chartex chart. + let mut c = Chart { kind: ChartKind::Waterfall, ..c }; + c.series[0].categories = None; + let mut names = Vec::new(); + let xml = crate::chartex::write_chartex(&Workbook::new(), 0, &c, &mut names); + let back = crate::chartex::read_chartex(&crate::xml::parse(xml.as_bytes()).unwrap()).unwrap(); + assert_eq!(shown(back.series[0].name.as_deref()).as_deref(), Some("Sales \"East\"")); } #[test] diff --git a/docs/chart-parity.md b/docs/chart-parity.md index 6c9743800a..3b0881141d 100644 --- a/docs/chart-parity.md +++ b/docs/chart-parity.md @@ -55,7 +55,7 @@ open PRs #158, #161, and issue #190. | Recommended Charts | yes | partial (Insert ▸ Recommended) | | Switch Row/Column, Select Data | yes | yes (Switch on charts read from files landed in #116); Select Data dialog: data range, remove series, Horizontal (Category) Axis Labels (#287). No series add/edit or hidden/empty cell options | | Sparklines (line, column, win/loss, markers, axis) | yes | line, column, win/loss | -| PivotCharts | yes | Insert ▸ PivotChart (`insert.pivotChart`): bound to a PivotTable's report, rebuilt on refresh and layout changes, `c:pivotSource` round trip; no field buttons, innermost category level only. Opened from a file, a series whose referenced cells don't hold its cached points (Excel often points them at the PivotTable's corner cell, or takes in the grand total row) plots the cached points until the PivotTable is refreshed; data labels and the value axis use the cache's number format, which is kept through a save | +| PivotCharts | yes | Insert ▸ PivotChart (`insert.pivotChart`): bound to a PivotTable's report, rebuilt on refresh and layout changes, `c:pivotSource` round trip; no field buttons, innermost category level only. Opened from a file, a series whose referenced cells don't hold its cached points (Excel often points them at the PivotTable's corner cell, or takes in the grand total row) plots the cached points until the PivotTable is refreshed, as does a multi-level category block (its innermost level, one label per point); data labels and the value axis use the cache's number format, which is kept through a save | | Animation on data change | yes (Windows) | no | ## XLSX round-trip @@ -80,7 +80,7 @@ back. | Date | Change | Summary | |---|---|---| -| 2026-10-13 | minor | XLSX: PivotChart series whose referenced cells don't hold their cached points plot the cached points (they drew empty or with the grand total), in the cache's number format; `autoTitleDeleted` keeps a deleted automatic title off; array-constant series keep quoted text, gaps and their number format through a save | +| 2026-10-13 | minor | XLSX: PivotChart series whose referenced cells don't hold their cached points plot the cached points (they drew empty or with the grand total), in the cache's number format, and multi-level category blocks plot their innermost level (they drew every level's cells); `autoTitleDeleted` keeps a deleted automatic title off; array-constant series keep quoted text, gaps and their number format through a save, and literal series names keep their quotes | | 2026-10-12 | trivial | chart sheets are kept on save, still not editable (#727) | | 2026-10-11 | minor | Trendlines: all six types modelled, round-tripped through `c:trendline`, drawn with forecast and equation/R² labels; `chart.addElement` `trendline` | | 2026-10-11 | minor | PivotCharts (`insert.pivotChart`) |