From 6200c713044243780b4c31676eb09f302ceae231 Mon Sep 17 00:00:00 2001 From: FredApps Date: Fri, 20 Nov 2026 15:51:04 +0100 Subject: [PATCH] Keep category formats with their source and preserve literal slashes --- crates/drawingml/src/chart.rs | 5 ++-- crates/drawingml/src/chart/read.rs | 39 +++++++++++++++++++++-------- crates/drawingml/src/chart/write.rs | 21 ++++++++++++++-- crates/drawingml/src/numfmt.rs | 22 ++++++++++++++-- 4 files changed, 71 insertions(+), 16 deletions(-) diff --git a/crates/drawingml/src/chart.rs b/crates/drawingml/src/chart.rs index 984fc05e8..1dd92177a 100644 --- a/crates/drawingml/src/chart.rs +++ b/crates/drawingml/src/chart.rs @@ -833,8 +833,9 @@ impl Chart { } /// The label of category `i`: its number or date in the category format (`45292` with `mmm-yy` - /// is "Jan-24"), else the category text as it is. `categories` keeps the cached text, so a - /// chart written back keeps its source values. + /// is "Jan-24"), else the category text as it is. `categories` keeps the cached text in memory. + /// Rebuilding a mixed number/text cache writes the formatted labels as strings; a reload + /// preserves those labels but cannot recover the original numeric serials. pub fn category_label(&self, i: usize) -> String { let raw = self.categories.get(i).map_or("", String::as_str); match (&self.category_format, raw.trim().parse::()) { diff --git a/crates/drawingml/src/chart/read.rs b/crates/drawingml/src/chart/read.rs index 166d822d9..ead3fd297 100644 --- a/crates/drawingml/src/chart/read.rs +++ b/crates/drawingml/src/chart/read.rs @@ -174,7 +174,11 @@ fn chart_within(root: &El, mut budget: usize) -> Option { let val_axis = group_value_axis(&val_map, g); let secondary = val_axis.is_some() && val_axis != primary_val; for s in g.children(Local("ser")).take(1000) { + let needs_categories = c.categories.is_empty(); let ser = read_series(s, g, (kind, secondary, group_labels), &mut c.categories, &mut budget); + if needs_categories && !c.categories.is_empty() { + c.category_format = category_format(pa, g, s); + } c.series.push(ser); } } @@ -207,7 +211,6 @@ fn chart_within(root: &El, mut budget: usize) -> Option { } }); let (val_ax, cat_ax) = read_axes(&mut c, pa, &primary_val); - c.category_format = category_format(pa, cat_ax); read_text_styles(&mut c, root, ch, val_ax, cat_ax); Some(c) } @@ -504,16 +507,18 @@ fn read_axes<'a>(c: &mut Chart, pa: &'a El, primary_val: &Option) -> (Op /// axis' own format, unless it is linked to the source (`sourceLinked`, or no `c:numFmt`), in which /// case the format code of the category cells. `None` when the categories are text (their cached /// strings show as they are) or the file gives only General. -fn category_format(pa: &El, cat_ax: Option<&El>) -> Option { - // The first series with categories gives them, as in `read_series`: its cache is the one - // `strings_capped` reads, so a series whose categories are multi-level text or a bare value - // gives no number format, and no later series does. - let cat = pa +fn category_format(pa: &El, group: &El, series: &El) -> Option { + // Called only when the budgeted series read first supplies categories. Never rescan caches + // or take a format from a skipped series or another plot group's axis. + let cat = series.child(Local("cat")).or_else(|| series.child(Local("xVal")))?; + let ids: Vec<&str> = group.children(Local("axId")).filter_map(|id| id.attr_local("val")).collect(); + let cat_ax = pa .elements() - .filter(|g| g.local().ends_with("Chart") && group_chart_type(g.local(), g).is_some()) - .flat_map(|g| g.children(Local("ser"))) - .filter_map(|s| s.child(Local("cat")).or_else(|| s.child(Local("xVal")))) - .find(|c| !strings_capped(c, MAX_CACHE_POINTS).is_empty())?; + .find(|axis| { + matches!(axis.local(), "catAx" | "dateAx") + && axis.child(Local("axId")).and_then(|id| id.attr_local("val")).is_some_and(|id| ids.contains(&id)) + }) + .or_else(|| pa.children(Local("valAx")).find(|axis| axis.child(Local("axId")).and_then(|id| id.attr_local("val")) == ids.first().copied())); if cat.find(Local("strCache")).or_else(|| cat.find(Local("strLit"))).is_some() { return None; } @@ -1004,6 +1009,20 @@ mod tests { assert_eq!(c.category_label(0), "2024"); } + #[test] + fn category_formats_follow_the_retained_series_and_its_plot_axis() { + let skipped = format!(r#"{}"#, num_cat("m/d/yyyy")); + let over_budget = format!("{}{}", r#""#.repeat(1000), skipped); + let text = r#"2024"#; + for (first, second, expected) in [(String::new(), num_cat("m/d/yyyy"), "Jan-24"), (over_budget, text.to_string(), "2024")] { + let xml = format!( + r#"{first}{second}"# + ); + let c = read_chart_xml(xml.as_bytes()).unwrap(); + assert_eq!(c.category_label(0), expected); + } + } + #[test] fn text_categories_ignore_the_axis_number_format() { let strs = r#"2024Q2"#; diff --git a/crates/drawingml/src/chart/write.rs b/crates/drawingml/src/chart/write.rs index 0701c77d0..a0ea48e5a 100644 --- a/crates/drawingml/src/chart/write.rs +++ b/crates/drawingml/src/chart/write.rs @@ -494,7 +494,10 @@ fn axes(w: &mut Writer, c: &Chart, g: Group) { if let Some(t) = &c.axis_titles.0 { title(w, t, c); } - w.tag("c:numFmt").attr("formatCode", c.category_format.as_deref().unwrap_or("General")).attr("sourceLinked", 1).empty(); + w.tag("c:numFmt") + .attr("formatCode", c.category_format.as_deref().unwrap_or("General")) + .attr("sourceLinked", u8::from(c.category_format.is_none())) + .empty(); w.tag("c:majorTickMark").attr("val", "out").empty(); w.tag("c:minorTickMark").attr("val", "none").empty(); w.tag("c:tickLblPos").attr("val", "nextTo").empty(); @@ -514,7 +517,10 @@ fn axes(w: &mut Writer, c: &Chart, g: Group) { if let Some(t) = &c.axis_titles.0 { title(w, t, c); } - w.tag("c:numFmt").attr("formatCode", c.category_format.as_deref().unwrap_or("General")).attr("sourceLinked", 1).empty(); + w.tag("c:numFmt") + .attr("formatCode", c.category_format.as_deref().unwrap_or("General")) + .attr("sourceLinked", u8::from(c.category_format.is_none())) + .empty(); w.tag("c:majorTickMark").attr("val", "none").empty(); w.tag("c:minorTickMark").attr("val", "none").empty(); w.tag("c:tickLblPos").attr("val", "nextTo").empty(); @@ -1327,6 +1333,17 @@ mod cache_cap_tests { assert!(text.contains("") && text.contains(r#""#), "{text}"); } + #[test] + fn explicit_general_category_format_survives_a_rebuild() { + let mut c = + Chart { kind: ChartType::Bar, categories: vec!["12345678901.25".into()], category_format: Some("General".into()), ..Default::default() }; + c.series.push(Series { values: vec![Some(1.0)], ..Default::default() }); + let back = crate::chart::read::read_chart_xml(&super::chart_xml(&c).0).unwrap(); + assert_eq!(back.category_format, c.category_format); + assert_eq!(back.category_label(0), c.category_label(0)); + assert_eq!(back.categories, c.categories); + } + #[test] fn mixed_date_and_text_categories_keep_their_labels_through_a_write() { let mut c = Chart { diff --git a/crates/drawingml/src/numfmt.rs b/crates/drawingml/src/numfmt.rs index 1abd1ff12..bbc89aad8 100644 --- a/crates/drawingml/src/numfmt.rs +++ b/crates/drawingml/src/numfmt.rs @@ -25,6 +25,8 @@ enum Tok { Dot, Comma, Percent, + /// An unquoted, unescaped fraction separator. + Slash, } /// A section's tokens (`[$₽-419]` gives its symbol; colours, conditions and locales drop out). @@ -76,6 +78,7 @@ fn tokens(section: &str) -> Vec { '.' => out.push(Tok::Dot), ',' => out.push(Tok::Comma), '%' => out.push(Tok::Percent), + '/' => out.push(Tok::Slash), '@' => {} _ => out.push(Tok::Lit(c.to_string())), } @@ -386,7 +389,14 @@ pub fn format_dated(code: &str, v: f64, lang: Option<&str>, date_1904: bool) -> let last = toks.iter().rposition(|t| matches!(t, Tok::Digit(_))); let (Some(first), Some(last)) = (first, last) else { // No digits: just the section's text ("-" for zero, a label). - let s: String = toks.iter().filter_map(|t| if let Tok::Lit(s) = t { Some(s.as_str()) } else { None }).collect(); + let s: String = toks + .iter() + .filter_map(|t| match t { + Tok::Lit(s) => Some(s.as_str()), + Tok::Slash => Some("/"), + _ => None, + }) + .collect(); return s.trim().to_string(); }; // A percent sign scales the value before the fraction is picked, as in `fixed`. @@ -409,6 +419,7 @@ fn lits(ts: &[Tok]) -> String { .filter_map(|t| match t { Tok::Lit(s) => Some(s.clone()), Tok::Percent => Some("%".into()), + Tok::Slash => Some("/".into()), _ => None, }) .collect() @@ -545,7 +556,7 @@ fn fraction(toks: &[Tok], v: f64, sep: char) -> Option<(String, bool)> { if toks.contains(&Tok::Dot) { return None; } - let slash = toks.iter().position(|t| matches!(t, Tok::Lit(s) if s.as_str() == "/"))?; + let slash = toks.iter().position(|t| *t == Tok::Slash)?; let is_digit = |t: Option<&Tok>| matches!(t, Some(Tok::Digit(_))); // Numerator placeholders end at the slash. let mut ns = slash; @@ -1161,6 +1172,13 @@ mod tests { ]); } + #[test] + fn escaped_and_quoted_slashes_stay_literal() { + assert_eq!(format(r"0\/8", 2.0, None), "2/8"); + assert_eq!(format(r#"0"/"8"#, 2.0, None), "2/8"); + assert_eq!(format("# ?/8", 2.5, None), "2 4/8"); + } + #[test] fn fractions_show_the_closest_fraction() { check(&[