mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 20:22:39 +00:00
Keep category formats with their source and preserve literal slashes
This commit is contained in:
@@ -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::<f64>()) {
|
||||
|
||||
@@ -174,7 +174,11 @@ fn chart_within(root: &El, mut budget: usize) -> Option<Chart> {
|
||||
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<Chart> {
|
||||
}
|
||||
});
|
||||
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<String>) -> (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<String> {
|
||||
// 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<String> {
|
||||
// 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#"<c:ser><c:idx val="1000"/><c:cat>{}</c:cat></c:ser>"#, num_cat("m/d/yyyy"));
|
||||
let over_budget = format!("{}{}", r#"<c:ser><c:idx val="0"/></c:ser>"#.repeat(1000), skipped);
|
||||
let text = r#"<c:strLit><c:ptCount val="1"/><c:pt idx="0"><c:v>2024</c:v></c:pt></c:strLit>"#;
|
||||
for (first, second, expected) in [(String::new(), num_cat("m/d/yyyy"), "Jan-24"), (over_budget, text.to_string(), "2024")] {
|
||||
let xml = format!(
|
||||
r#"<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart"><c:chart><c:plotArea><c:barChart>{first}<c:axId val="1"/><c:axId val="2"/></c:barChart><c:lineChart><c:ser><c:idx val="0"/><c:cat>{second}</c:cat></c:ser><c:axId val="3"/><c:axId val="4"/></c:lineChart><c:catAx><c:axId val="1"/><c:numFmt formatCode="0.00" sourceLinked="0"/></c:catAx><c:valAx><c:axId val="2"/><c:axPos val="l"/></c:valAx><c:dateAx><c:axId val="3"/><c:numFmt formatCode="mmm-yy" sourceLinked="0"/></c:dateAx><c:valAx><c:axId val="4"/><c:axPos val="r"/></c:valAx></c:plotArea></c:chart></c:chartSpace>"#
|
||||
);
|
||||
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#"<c:strRef><c:strCache><c:ptCount val="2"/><c:pt idx="0"><c:v>2024</c:v></c:pt><c:pt idx="1"><c:v>Q2</c:v></c:pt></c:strCache></c:strRef>"#;
|
||||
|
||||
@@ -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("<c:strCache>") && text.contains(r#"<c:date1904 val="0"/>"#), "{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 {
|
||||
|
||||
@@ -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<Tok> {
|
||||
'.' => 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(&[
|
||||
|
||||
Reference in New Issue
Block a user