From 9777459eb6b52e5c52d532a860c57caacd2d3a68 Mon Sep 17 00:00:00 2001 From: AnhNgoo <110978888+AnhNgoo@users.noreply.github.com> Date: Thu, 29 Oct 2026 13:23:50 +0700 Subject: [PATCH 1/7] fix(chart): render explicit Excel chart styles --- crates/chart/src/render/cartesian.rs | 4 +- crates/chart/src/resolve.rs | 72 ++++++++++- crates/chart/src/tests.rs | 182 +++++++++++++++++++++++++++ 3 files changed, 253 insertions(+), 5 deletions(-) diff --git a/crates/chart/src/render/cartesian.rs b/crates/chart/src/render/cartesian.rs index d449498e7..28f8bf791 100644 --- a/crates/chart/src/render/cartesian.rs +++ b/crates/chart/src/render/cartesian.rs @@ -284,10 +284,10 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx let len = (pb - pt).abs(); if horizontal { let y = c + nslots * bw / 2.0 - (k + 1.0) * bw; - ctx.rect(lo, y, len, bw, s.color, None); + ctx.rect(lo, y, len, bw, s.color, (chart.style == 9).then_some((WHITE, 1.0))); } else { let x = c - nslots * bw / 2.0 + k * bw; - ctx.rect(x, lo, bw, len, s.color, None); + ctx.rect(x, lo, bw, len, s.color, (chart.style == 9).then_some((WHITE, 1.0))); } if labels_on && let Some(v) = s.values.get(j).copied().flatten() { let t = fmt.format(v, None); diff --git a/crates/chart/src/resolve.rs b/crates/chart/src/resolve.rs index 6eee201ae..1d74eaf6a 100644 --- a/crates/chart/src/resolve.rs +++ b/crates/chart/src/resolve.rs @@ -30,6 +30,28 @@ pub fn series_color(theme: &Theme, i: usize) -> Rgba { [r, g, b, 0xFF] } +/// Excel reference colours for explicit styles 1 and 9. +/// +/// These palettes cover measured default-theme examples. +/// Other counts still use the existing theme-based fallback. +fn chart_style_series_color(theme: &Theme, style: u32, index: usize, count: usize) -> Rgba { + if !matches!(style, 1 | 9) { + return series_color(theme, index); + } + + const SMALL: [u8; 4] = [0x61, 0xB3, 0x81, 0x50]; + const MEDIUM: [u8; 8] = [0x55, 0x9E, 0x72, 0x46, 0x83, 0xC1, 0x9A, 0xC8]; + const LARGE: [u8; 16] = [0x4F, 0x93, 0x6A, 0x40, 0x7A, 0xB4, 0x61, 0xB3, 0x81, 0x50, 0x95, 0xDA, 0xAF, 0xD2, 0xBA, 0xAA]; + + let shades: &[u8] = match count { + 1..=4 => &SMALL, + 5..=8 => &MEDIUM, + 9..=16 => &LARGE, + _ => return series_color(theme, index), + }; + + shades.get(index).map_or_else(|| series_color(theme, index), |shade| [*shade, *shade, *shade, 0xFF]) +} /// The first `n` series colours for `theme`. pub fn default_palette(theme: &Theme, n: usize) -> Vec { (0..n.min(4096)).map(|i| series_color(theme, i)).collect() @@ -231,8 +253,12 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData { for (i, s) in chart.series.iter().take(MAX_SERIES).enumerate() { let values = nums(wb, sheet, &s.values); 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 color = s + .color + .as_ref() + .and_then(|c| c.resolve(&wb.theme)) + .map(|[r, g, b]| [r, g, b, 0xFF]) + .unwrap_or_else(|| chart_style_series_color(&wb.theme, chart.style, i, chart.series.len().min(MAX_SERIES))); let kind = effective_kind(chart.kind, s.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. @@ -273,6 +299,46 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData { } let n = series.iter().map(|s| s.values.len()).max().unwrap_or(0); let categories = categories.unwrap_or_else(|| (1..=n).map(|i| i.to_string()).collect()); - let palette = default_palette(&wb.theme, n.min(PALETTE_CYCLE)); + let palette = if matches!(chart.style, 1 | 9) { + (0..n.min(PALETTE_CYCLE)).map(|i| chart_style_series_color(&wb.theme, chart.style, i, n)).collect() + } else { + default_palette(&wb.theme, n.min(PALETTE_CYCLE)) + }; ChartData { categories, category_levels, series, palette } } + +#[cfg(test)] +mod explicit_style_palette_tests { + use super::*; + + #[test] + fn explicit_style_palette_boundaries() { + let theme = Workbook::default().theme; + + for style in [1, 9] { + for count in [0, 17, 255] { + for index in [0, 1, 4, 8, 16] { + assert_eq!(chart_style_series_color(&theme, style, index, count), series_color(&theme, index),); + } + } + + for (count, expected_first) in [(1, 0x61), (4, 0x61), (5, 0x55), (8, 0x55), (9, 0x4F), (16, 0x4F)] { + assert_eq!( + chart_style_series_color(&theme, style, 0, count), + [expected_first, expected_first, expected_first, 255], + "style {style}, count {count}", + ); + + assert_eq!( + chart_style_series_color(&theme, style, 16, count), + series_color(&theme, 16), + "out-of-range index for style {style}, count {count}", + ); + } + } + + for style in [0, 2, 10, 48] { + assert_eq!(chart_style_series_color(&theme, style, 0, 4), series_color(&theme, 0),); + } + } +} diff --git a/crates/chart/src/tests.rs b/crates/chart/src/tests.rs index 3f1a068a2..9a463d9f2 100644 --- a/crates/chart/src/tests.rs +++ b/crates/chart/src/tests.rs @@ -1255,3 +1255,185 @@ fn box_whisker_draws_each_series_quartile_method() { // The boxes span 3.5 and 2.5 data units on the same value axis. assert!((heights[0] / heights[1] - 1.4).abs() < 0.001); } + +/// Explicit Excel chart styles should affect default series colours, +/// without changing the workbook theme. +#[test] +fn explicit_chart_styles_use_distinct_default_colors() { + let wb = Workbook::default(); + + let mut c = chart(ChartKind::ColumnClustered); + c.series.push(Series { + name: None, + categories: None, + values: "{10,20,30}".into(), + bubble_sizes: None, + color: None, + secondary: false, + kind: None, + quartiles: Default::default(), + smooth: false, + trendlines: Vec::new(), + }); + + c.style = 2; + let style2 = resolve(&wb, 0, &c).series[0].color; + assert_eq!(style2, series_color(&wb.theme, 0)); + + c.style = 1; + let style1 = resolve(&wb, 0, &c).series[0].color; + + c.style = 9; + let style9 = resolve(&wb, 0, &c).series[0].color; + + assert_ne!(style1, style2, "style 1 should differ from style 2"); + assert_ne!(style9, style2, "style 9 should differ from style 2"); +} + +/// Excel chart styles must not override explicitly assigned series colours. +#[test] +fn explicit_chart_styles_preserve_custom_series_colors() { + let wb = Workbook::default(); + let mut c = chart(ChartKind::ColumnClustered); + + c.series.push(Series { + name: None, + categories: None, + values: "{10,20,30}".into(), + bubble_sizes: None, + color: Some(Color::rgb(12, 34, 56)), + secondary: false, + kind: None, + quartiles: Default::default(), + smooth: false, + trendlines: Vec::new(), + }); + + for style in [1, 2, 9] { + c.style = style; + let data = resolve(&wb, 0, &c); + + assert_eq!(data.series[0].color, [12, 34, 56, 255], "explicit series colour changed under chart style {style}"); + } +} + +/// Check the first four point colours measured in Excel for styles 1 and 9. +#[test] +fn excel_chart_styles_use_measured_point_palette() { + let wb = Workbook::default(); + let mut c = chart(ChartKind::Pie); + + c.series.push(Series { + name: None, + categories: None, + values: "{10,20,30,40}".into(), + bubble_sizes: None, + color: None, + secondary: false, + kind: None, + quartiles: Default::default(), + smooth: false, + trendlines: Vec::new(), + }); + + let expected = [[0x61, 0x61, 0x61, 0xFF], [0xB3, 0xB3, 0xB3, 0xFF], [0x81, 0x81, 0x81, 0xFF], [0x50, 0x50, 0x50, 0xFF]]; + + for style in [1, 9] { + c.style = style; + let data = resolve(&wb, 0, &c); + + assert_eq!(&data.palette[..4], &expected); + assert_eq!(data.series[0].color, expected[0]); + } +} + +/// Excel's default-theme chart colours depend on the total series count. +#[test] +fn excel_chart_styles_depend_on_series_count() { + let wb = Workbook::default(); + + let base_series = Series { + name: None, + categories: None, + values: "{10,20,30,40}".into(), + bubble_sizes: None, + color: None, + secondary: false, + kind: None, + quartiles: Default::default(), + smooth: false, + trendlines: Vec::new(), + }; + + let cases: &[(usize, [[u8; 4]; 3])] = &[ + (6, [[0x55, 0x55, 0x55, 0xFF], [0x9E, 0x9E, 0x9E, 0xFF], [0x72, 0x72, 0x72, 0xFF]]), + (12, [[0x4F, 0x4F, 0x4F, 0xFF], [0x93, 0x93, 0x93, 0xFF], [0x6A, 0x6A, 0x6A, 0xFF]]), + ]; + + for (count, expected) in cases { + for style in [1, 9] { + let mut c = chart(ChartKind::ColumnClustered); + c.style = style; + c.series = vec![base_series.clone(); *count]; + + let data = resolve(&wb, 0, &c); + + assert_eq!(data.series.len(), *count); + + for (i, color) in expected.iter().enumerate() { + assert_eq!(data.series[i].color, *color, "style {style}, {count} series, index {i}"); + } + } + } +} + +/// Style 9 uses white outlines on column and bar data rectangles. +#[test] +fn explicit_style_nine_draws_white_column_outlines() { + let wb = Workbook::default(); + + for kind in [ + ChartKind::ColumnClustered, + ChartKind::BarClustered, + ChartKind::ColumnStacked, + ChartKind::BarStacked, + ChartKind::ColumnStacked100, + ChartKind::BarStacked100, + ] { + let mut c = chart(kind); + c.legend = LegendPos::None; + c.series.push(Series { + name: None, + categories: None, + values: "{10,20,30,40}".into(), + bubble_sizes: None, + color: None, + secondary: false, + kind: None, + quartiles: Default::default(), + smooth: false, + trendlines: Vec::new(), + }); + + for style in [1, 2, 9] { + c.style = style; + let data = resolve(&wb, 0, &c); + let color = data.series[0].color; + let prims = render(&c, &data, 640.0, 400.0, &ApproxMeasure); + + let outlines: Vec<_> = prims + .iter() + .filter_map(|p| match p { + Prim::Rect { fill: Some(fill), stroke, .. } if *fill == color => Some(*stroke), + _ => None, + }) + .collect(); + + assert!(!outlines.is_empty(), "No data rectangles for {kind:?}, style {style}"); + + let expected = if style == 9 { Some(([255, 255, 255, 255], 1.0)) } else { None }; + + assert!(outlines.iter().all(|stroke| *stroke == expected), "Unexpected outline for {kind:?}, style {style}: {outlines:?}"); + } + } +} From 47c5e3b8160b72eb4fcd44aa7d44c10027ff41d0 Mon Sep 17 00:00:00 2001 From: AnhNgoo <110978888+AnhNgoo@users.noreply.github.com> Date: Thu, 29 Oct 2026 13:54:59 +0700 Subject: [PATCH 2/7] docs(chart): document Cartesian chart rendering --- crates/chart/src/render/cartesian.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/chart/src/render/cartesian.rs b/crates/chart/src/render/cartesian.rs index 28f8bf791..6e6f70286 100644 --- a/crates/chart/src/render/cartesian.rs +++ b/crates/chart/src/render/cartesian.rs @@ -179,6 +179,12 @@ fn column_slots(fams: &[Fam], sec: &[bool]) -> (Vec, f32) { (slot_of, slot_keys.len().max(1) as f32) } +/// Renders Cartesian column, bar, line, area, and combination charts. +/// +/// Resolves series families and their axes, calculates stacking and +/// category positions, and draws the corresponding primitives. +/// Explicit chart style 9 adds white outlines to column and bar +/// rectangles, including stacked and 100%-stacked variants. pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizontal: bool) { let ncat = data.categories.len().max(data.series.iter().map(|s| s.values.len()).max().unwrap_or(0)).min(MAX_CATS); if ncat == 0 { From 8e0d621a0f25982a9520a81fdf1aea0d037d8687 Mon Sep 17 00:00:00 2001 From: AnhNgoo <110978888+AnhNgoo@users.noreply.github.com> Date: Mon, 2 Nov 2026 16:31:31 +0700 Subject: [PATCH 3/7] fix(chart): preserve Excel styles and line weights --- crates/chart/src/render/cartesian.rs | 11 +- crates/chart/src/tests.rs | 36 ++++++ crates/xlsx/src/chart.rs | 8 +- crates/xlsx/src/tests.rs | 1 + crates/xlsx/src/tests/chart_combo_kinds.rs | 36 ++++++ .../xlsx/src/tests/chart_style_roundtrip.rs | 118 ++++++++++++++++++ 6 files changed, 208 insertions(+), 2 deletions(-) create mode 100644 crates/xlsx/src/tests/chart_style_roundtrip.rs diff --git a/crates/chart/src/render/cartesian.rs b/crates/chart/src/render/cartesian.rs index 6e6f70286..e4dc2f95d 100644 --- a/crates/chart/src/render/cartesian.rs +++ b/crates/chart/src/render/cartesian.rs @@ -51,6 +51,15 @@ fn is_line(f: Fam) -> bool { matches!(f, Fam::Line | Fam::LineStack) } +/// Stroke widths for explicitly selected Excel chart styles. +fn line_style_width(style: u32) -> f32 { + match style { + 1 => 3.0, + 9 => 5.0, + _ => 2.25, + } +} + fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Vec>> { // Totals for 100% stacking, per axis and family (100% columns and 100% areas stack apart). let mut totals: Vec<((bool, Fam), Vec)> = Vec::new(); @@ -323,7 +332,7 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx } _ => { let pts: Vec> = row.iter().enumerate().map(|(j, sp)| sp.map(|(_, t)| [center(j), vpos(t, &sc)])).collect(); - draw_runs(ctx, &pts, s.color, 2.25, s.smooth.then_some(plot)); + draw_runs(ctx, &pts, s.color, line_style_width(chart.style), s.smooth.then_some(plot)); let k = kinds.get(i).copied().unwrap_or(ChartKind::Line); if k == ChartKind::LineMarkers && cw >= 3.0 { draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color); diff --git a/crates/chart/src/tests.rs b/crates/chart/src/tests.rs index 9a463d9f2..9183f3206 100644 --- a/crates/chart/src/tests.rs +++ b/crates/chart/src/tests.rs @@ -1437,3 +1437,39 @@ fn explicit_style_nine_draws_white_column_outlines() { } } } + +/// Excel's default line weights are 3 pt for style 1 and 5 pt for style 9. +/// Other styles retain GridCraft's existing stroke width. +#[test] +fn explicit_excel_styles_set_line_stroke_width() { + let color: Rgba = [17, 73, 131, 255]; + + for kind in [ChartKind::Line, ChartKind::LineMarkers, ChartKind::LineStacked] { + let data = ChartData { + categories: ["Jan", "Feb", "Mar", "Apr"].map(String::from).to_vec(), + category_levels: vec![], + palette: vec![], + series: vec![series("North", &[12.0, 19.0, 25.0, 30.0], color, kind)], + }; + + let mut c = chart(kind); + c.legend = LegendPos::None; + c.data_labels = false; + + for (style, expected_width) in [(0, 2.25_f32), (1, 3.0), (2, 2.25), (9, 5.0), (48, 2.25)] { + c.style = style; + + let prims = render(&c, &data, 640.0, 400.0, &ApproxMeasure); + + let widths: Vec = prims + .iter() + .filter_map(|primitive| match primitive { + Prim::Line { color: line_color, width, .. } if *line_color == color => Some(*width), + _ => None, + }) + .collect(); + + assert_eq!(widths, vec![expected_width], "Unexpected stroke width for {kind:?}, style {style}"); + } + } +} diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index 37bcf91b0..17207c00e 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -269,7 +269,13 @@ pub fn read_chart(root: &El) -> Option { legend, data_labels, gridlines: val_axes.iter().any(|a| a.child("majorGridlines").is_some()), - style: root.child_val("style").and_then(|v| v.parse().ok()).unwrap_or(2), + // Excel can wrap the legacy chart style in mc:AlternateContent. + // The c14 Choice uses different IDs, so read the c:style Fallback. + style: root + .child_val("style") + .and_then(|v| v.parse().ok()) + .or_else(|| root.path(&["AlternateContent", "Fallback"]).and_then(|fallback| fallback.child_val("style")).and_then(|v| v.parse().ok())) + .unwrap_or(2), x_title: x_ax.and_then(|a| a.child("title")).and_then(rich_title), y_title: y_ax.and_then(|a| a.child("title")).and_then(rich_title), source: None, diff --git a/crates/xlsx/src/tests.rs b/crates/xlsx/src/tests.rs index 73be1a064..f2651115b 100644 --- a/crates/xlsx/src/tests.rs +++ b/crates/xlsx/src/tests.rs @@ -6,6 +6,7 @@ mod chart_book_names; mod chart_bool_default; mod chart_combo_kinds; mod chart_ref_offsets; +mod chart_style_roundtrip; mod csv_tests; mod encrypted_tests; mod fixtures; diff --git a/crates/xlsx/src/tests/chart_combo_kinds.rs b/crates/xlsx/src/tests/chart_combo_kinds.rs index 6857683ad..980594bcb 100644 --- a/crates/xlsx/src/tests/chart_combo_kinds.rs +++ b/crates/xlsx/src/tests/chart_combo_kinds.rs @@ -44,3 +44,39 @@ fn line_first_group_stays_a_line() { assert!(matches!(k[0], Some(ChartKind::Line | ChartKind::LineMarkers))); assert_eq!(k[1], Some(ChartKind::ColumnClustered)); } + +#[test] +fn explicit_chart_style_survives_xml_roundtrip() { + use gridcraft_model::Workbook; + + for kind in [ChartKind::ColumnClustered, ChartKind::BarClustered, ChartKind::Line] { + for style in [1, 9, 48] { + let mut chart = crate::chart::read_chart( + &parse( + format!( + "\ + \ + \ + \ + \ + \ + " + ) + .as_bytes(), + ) + .unwrap(), + ) + .unwrap(); + + chart.kind = kind; + assert_eq!(chart.style, style); + + let wb = Workbook::default(); + let xml = crate::chart::write_chart(&wb, 0, &chart, "Book.xlsx"); + let root = parse(xml.as_bytes()).unwrap(); + let restored = crate::chart::read_chart(&root).unwrap(); + + assert_eq!(restored.style, style, "chart style changed for {kind:?}"); + } + } +} diff --git a/crates/xlsx/src/tests/chart_style_roundtrip.rs b/crates/xlsx/src/tests/chart_style_roundtrip.rs new file mode 100644 index 000000000..0120784bf --- /dev/null +++ b/crates/xlsx/src/tests/chart_style_roundtrip.rs @@ -0,0 +1,118 @@ +//! Explicit chart styles survive complete XLSX serialization. + +use std::sync::Arc; + +use gridcraft_core::CellRef; +use gridcraft_model::{Anchor, Chart, ChartKind, LegendPos, Series, Sheet, Workbook}; + +use crate::{read_xlsx, write_xlsx}; + +#[test] +fn explicit_styles_survive_xlsx_save_and_reload() { + for kind in [ChartKind::ColumnClustered, ChartKind::BarClustered, ChartKind::Line] { + for style in [1, 9, 48] { + let mut wb = Workbook::default(); + let mut sheet = Sheet::new("Data"); + + sheet.charts.push(Chart { + id: 1, + kind, + anchor: Anchor { cell: CellRef::new(0, 3), width: 480.0, height: 300.0, ..Anchor::default() }, + title: Some("Style roundtrip".into()), + series: vec![Series { + name: Some("Series 1".into()), + categories: Some(r#"{"A","B","C"}"#.into()), + values: "{10,20,30}".into(), + bubble_sizes: None, + color: None, + secondary: false, + kind: None, + quartiles: Default::default(), + smooth: false, + trendlines: Vec::new(), + }], + legend: LegendPos::Bottom, + data_labels: false, + gridlines: true, + style, + x_title: None, + y_title: None, + source: None, + by_rows: false, + pivot: None, + }); + + wb.sheets = vec![Arc::new(sheet)]; + + let bytes = write_xlsx(&wb).unwrap(); + let (reloaded, _) = read_xlsx(&bytes).unwrap(); + + assert_eq!(reloaded.sheets[0].charts.len(), 1); + assert_eq!(reloaded.sheets[0].charts[0].kind, kind); + assert_eq!(reloaded.sheets[0].charts[0].style, style); + + let bytes2 = write_xlsx(&reloaded).unwrap(); + let (reloaded2, _) = read_xlsx(&bytes2).unwrap(); + + assert_eq!(reloaded2.sheets[0].charts.len(), 1); + assert_eq!(reloaded2.sheets[0].charts[0].kind, kind); + assert_eq!(reloaded2.sheets[0].charts[0].style, style, "XLSX round-trip changed style {style} for {kind:?}"); + } + } +} + +/// Excel stores legacy styles 1 and 9 in mc:Fallback, +/// alongside c14 Choice values 101 and 109. +#[test] +fn excel_alternate_content_chart_styles_roundtrip() { + use crate::chart::{read_chart, write_chart}; + use crate::xml::parse; + + for (kind, group) in [ + ( + ChartKind::ColumnClustered, + r#""#, + ), + ( + ChartKind::BarClustered, + r#""#, + ), + ( + ChartKind::Line, + r#""#, + ), + ] { + for (legacy_style, modern_style) in [(1, 101), (9, 109)] { + let xml = format!( + r#" + + + + + + + + + + {group} + + "# + ); + + let root = parse(xml.as_bytes()).unwrap(); + let chart = read_chart(&root).unwrap(); + + assert_eq!(chart.kind, kind); + assert_eq!(chart.style, legacy_style, "Excel AlternateContent style for {kind:?}"); + + let saved = write_chart(&Workbook::default(), 0, &chart, "Book.xlsx"); + + let reopened = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap(); + + assert_eq!(reopened.style, legacy_style, "Style changed when re-exporting {kind:?}"); + } + } +} From a1fc98213204202a03ccaf5a665f33cd844e2563 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ng=C3=B4=20Qu=E1=BB=91c=20Anh?= Date: Mon, 2 Nov 2026 16:55:15 +0700 Subject: [PATCH 4/7] test(chart): make XLSX roundtrip fixture compatible with newer Chart fields --- .../xlsx/src/tests/chart_style_roundtrip.rs | 70 ++++++++++++------- 1 file changed, 43 insertions(+), 27 deletions(-) diff --git a/crates/xlsx/src/tests/chart_style_roundtrip.rs b/crates/xlsx/src/tests/chart_style_roundtrip.rs index 0120784bf..3e3052b1c 100644 --- a/crates/xlsx/src/tests/chart_style_roundtrip.rs +++ b/crates/xlsx/src/tests/chart_style_roundtrip.rs @@ -9,38 +9,54 @@ use crate::{read_xlsx, write_xlsx}; #[test] fn explicit_styles_survive_xlsx_save_and_reload() { + // Start from the XLSX reader so this fixture follows new optional Chart fields. + let template: Chart = crate::chart::read_chart( + &crate::xml::parse( + concat!( + r#""#, + "", + r#""#, + r#""#, + "", + ) + .as_bytes(), + ) + .unwrap(), + ) + .unwrap(); + for kind in [ChartKind::ColumnClustered, ChartKind::BarClustered, ChartKind::Line] { for style in [1, 9, 48] { let mut wb = Workbook::default(); let mut sheet = Sheet::new("Data"); - sheet.charts.push(Chart { - id: 1, - kind, - anchor: Anchor { cell: CellRef::new(0, 3), width: 480.0, height: 300.0, ..Anchor::default() }, - title: Some("Style roundtrip".into()), - series: vec![Series { - name: Some("Series 1".into()), - categories: Some(r#"{"A","B","C"}"#.into()), - values: "{10,20,30}".into(), - bubble_sizes: None, - color: None, - secondary: false, - kind: None, - quartiles: Default::default(), - smooth: false, - trendlines: Vec::new(), - }], - legend: LegendPos::Bottom, - data_labels: false, - gridlines: true, - style, - x_title: None, - y_title: None, - source: None, - by_rows: false, - pivot: None, - }); + let mut chart = template.clone(); + chart.id = 1; + chart.kind = kind; + chart.anchor = Anchor { cell: CellRef::new(0, 3), width: 480.0, height: 300.0, ..Anchor::default() }; + chart.title = Some("Style roundtrip".into()); + chart.series = vec![Series { + name: Some("Series 1".into()), + categories: Some(r#"{"A","B","C"}"#.into()), + values: "{10,20,30}".into(), + bubble_sizes: None, + color: None, + secondary: false, + kind: None, + quartiles: Default::default(), + smooth: false, + trendlines: Vec::new(), + }]; + chart.legend = LegendPos::Bottom; + chart.data_labels = false; + chart.gridlines = true; + chart.style = style; + chart.x_title = None; + chart.y_title = None; + chart.source = None; + chart.by_rows = false; + chart.pivot = None; + sheet.charts.push(chart); wb.sheets = vec![Arc::new(sheet)]; From 14bc6757784dcc33d999f8590f2e5616f1721889 Mon Sep 17 00:00:00 2001 From: AnhNgoo <110978888+AnhNgoo@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:47:28 +0700 Subject: [PATCH 5/7] fix(chart): preserve narrow style 9 bar fill and validate fallback style (#2865) --- crates/chart/src/render/cartesian.rs | 9 +++-- crates/chart/src/tests.rs | 36 +++++++++++++++++++ crates/xlsx/src/chart.rs | 9 +++-- .../xlsx/src/tests/chart_style_roundtrip.rs | 28 +++++++++++++++ 4 files changed, 75 insertions(+), 7 deletions(-) diff --git a/crates/chart/src/render/cartesian.rs b/crates/chart/src/render/cartesian.rs index b71f7a28d..8f979bbbb 100644 --- a/crates/chart/src/render/cartesian.rs +++ b/crates/chart/src/render/cartesian.rs @@ -144,11 +144,10 @@ impl BarSink { let pos = self.pos(c); let band = self.band(); if !merge { - if self.horizontal { - ctx.rect(lo, pos, len, self.bw, self.color, self.stroke); - } else { - ctx.rect(pos, lo, self.bw, len, self.color, self.stroke); - } + let (x, y, w, h) = if self.horizontal { (lo, pos, len, self.bw) } else { (pos, lo, self.bw, len) }; + // Omit the outline when a bar is no wider/taller than the stroke, so the inner fill never disappears. + let stroke = self.stroke.filter(|(_, sw)| w > *sw && h > *sw); + ctx.rect(x, y, w, h, self.color, stroke); return; } match &mut self.run { diff --git a/crates/chart/src/tests.rs b/crates/chart/src/tests.rs index dbbcd67a8..638a0a2d4 100644 --- a/crates/chart/src/tests.rs +++ b/crates/chart/src/tests.rs @@ -1995,3 +1995,39 @@ fn explicit_excel_styles_set_line_stroke_width() { } } } + +/// Narrow style 9 bars (at or below the 1 px outline width) omit the white stroke so their gray fill stays visible. +#[test] +fn narrow_style_9_bars_retain_visible_fill() { + let fill_color: Rgba = [0x61, 0x61, 0x61, 0xFF]; + let count = 240usize; + let categories: Vec = (0..count).map(|i| format!("C{i}")).collect(); + let values = vec![50.0; count]; + + for kind in [ChartKind::ColumnClustered, ChartKind::BarClustered] { + let data = ChartData { + categories: categories.clone(), + category_levels: vec![], + palette: vec![], + series: vec![series("S1", &values, fill_color, kind)], + }; + let mut c = chart(kind); + c.legend = LegendPos::None; + // Data labels keep bars on the unmerged direct path even when narrower than 1 px. + c.data_labels = true; + c.gridlines = false; + c.style = 9; + + let prims = render(&c, &data, 220.0, 220.0, &ApproxMeasure); + let narrow_bars: Vec<_> = prims + .iter() + .filter_map(|p| match p { + Prim::Rect { w, h, fill: Some(fill), stroke, .. } if *fill == fill_color && (*w <= 1.0 || *h <= 1.0) => Some(*stroke), + _ => None, + }) + .collect(); + + assert!(!narrow_bars.is_empty(), "Expected narrow unmerged bars for {kind:?}"); + assert!(narrow_bars.iter().all(Option::is_none), "Narrow style 9 bars must omit the 1 px white outline: {narrow_bars:?}"); + } +} diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index aca80f6f0..e27ded068 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -218,6 +218,11 @@ fn axis_ids(g: &El) -> Vec { g.kids("axId").filter_map(|a| a.attr("val")).map(str::to_string).collect() } +/// Parses a legacy OOXML `` index (`1..=48`), trimming surrounding spaces. +fn parse_chart_style(val: &str) -> Option { + val.trim().parse::().ok().filter(|s| (1..=48).contains(s)) +} + /// Parses a DrawingML `` element into a [`Chart`] model. pub fn read_chart(root: &El) -> Option { let chart = root.child("chart")?; @@ -284,8 +289,8 @@ pub fn read_chart(root: &El) -> Option { // The c14 Choice uses different IDs, so read the c:style Fallback. style: root .child_val("style") - .and_then(|v| v.parse().ok()) - .or_else(|| root.path(&["AlternateContent", "Fallback"]).and_then(|fallback| fallback.child_val("style")).and_then(|v| v.parse().ok())) + .and_then(parse_chart_style) + .or_else(|| root.path(&["AlternateContent", "Fallback"]).and_then(|fallback| fallback.child_val("style")).and_then(parse_chart_style)) .unwrap_or(2), hole_size, first_slice_angle, diff --git a/crates/xlsx/src/tests/chart_style_roundtrip.rs b/crates/xlsx/src/tests/chart_style_roundtrip.rs index 9792b1589..9b4f05e3e 100644 --- a/crates/xlsx/src/tests/chart_style_roundtrip.rs +++ b/crates/xlsx/src/tests/chart_style_roundtrip.rs @@ -133,3 +133,31 @@ fn excel_alternate_content_chart_styles_roundtrip() { } } } + +/// Surrounding whitespace on `` trims cleanly, while out-of-range fallback values default to style 2. +#[test] +fn alternate_content_fallback_style_trims_and_validates_range() { + use crate::chart::read_chart; + use crate::xml::parse; + + for (raw_val, expected) in [(" 9 ", 9), ("\t1\n", 1), ("0", 2), ("49", 2), ("200", 2)] { + let xml = format!( + r#" + + + + + + + + + + "# + ); + let chart = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert_eq!(chart.style, expected, "raw fallback style {raw_val:?}"); + } +} From e86b2ef0efa181fb464c7fb08755872053845ca8 Mon Sep 17 00:00:00 2001 From: AnhNgoo <110978888+AnhNgoo@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:56:43 +0700 Subject: [PATCH 6/7] fix(xlsx): remove duplicate closing braces in chart reader --- crates/xlsx/src/chart.rs | 21 +++++---------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index 7af0dee7a..8611c0733 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -307,13 +307,11 @@ pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { // The c14 Choice uses different IDs, so read the c:style Fallback. style: root .and_then(|r| { - r.child_val("style") - .and_then(parse_chart_style) - .or_else(|| { - r.kids("AlternateContent") - .filter_map(|wrapper| wrapper.child("Fallback")) - .find_map(|fallback| fallback.child_val("style").and_then(parse_chart_style)) - }) + r.child_val("style").and_then(parse_chart_style).or_else(|| { + r.kids("AlternateContent") + .filter_map(|wrapper| wrapper.child("Fallback")) + .find_map(|fallback| fallback.child_val("style").and_then(parse_chart_style)) + }) }) .or_else(|| (1..=48).contains(&dc.style).then_some(dc.style)) .unwrap_or(2), @@ -326,15 +324,6 @@ pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { pivot: dc.pivot_source.as_deref().map(strip_book).filter(|n| !n.is_empty()).map(str::to_string), } } - hole_size, - first_slice_angle: dc.first_slice_angle, - x_title: dc.axis_titles.0, - y_title: dc.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), - } -} pub fn read_chart(root: &El) -> Option { let craft = to_craft_el(root); From 86a0c41e8fb7359256d7f85deef8d90b14545f84 Mon Sep 17 00:00:00 2001 From: AnhNgoo <110978888+AnhNgoo@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:39:42 +0700 Subject: [PATCH 7/7] test(chart): use Series::default() for new upstream fields --- crates/chart/src/tests.rs | 65 +++------------------------------------ 1 file changed, 5 insertions(+), 60 deletions(-) diff --git a/crates/chart/src/tests.rs b/crates/chart/src/tests.rs index a066c0273..60a11ef19 100644 --- a/crates/chart/src/tests.rs +++ b/crates/chart/src/tests.rs @@ -1925,18 +1925,7 @@ fn explicit_chart_styles_use_distinct_default_colors() { let wb = Workbook::default(); let mut c = chart(ChartKind::ColumnClustered); - c.series.push(Series { - name: None, - categories: None, - values: "{10,20,30}".into(), - bubble_sizes: None, - color: None, - secondary: false, - kind: None, - quartiles: Default::default(), - smooth: false, - trendlines: Vec::new(), - }); + c.series.push(Series { values: "{10,20,30}".into(), ..Series::default() }); c.style = 2; let style2 = resolve(&wb, 0, &c).series[0].color; @@ -1958,18 +1947,7 @@ fn explicit_chart_styles_preserve_custom_series_colors() { let wb = Workbook::default(); let mut c = chart(ChartKind::ColumnClustered); - c.series.push(Series { - name: None, - categories: None, - values: "{10,20,30}".into(), - bubble_sizes: None, - color: Some(Color::rgb(12, 34, 56)), - secondary: false, - kind: None, - quartiles: Default::default(), - smooth: false, - trendlines: Vec::new(), - }); + c.series.push(Series { values: "{10,20,30}".into(), color: Some(Color::rgb(12, 34, 56)), ..Series::default() }); for style in [1, 2, 9] { c.style = style; @@ -1985,18 +1963,7 @@ fn excel_chart_styles_use_measured_point_palette() { let wb = Workbook::default(); let mut c = chart(ChartKind::Pie); - c.series.push(Series { - name: None, - categories: None, - values: "{10,20,30,40}".into(), - bubble_sizes: None, - color: None, - secondary: false, - kind: None, - quartiles: Default::default(), - smooth: false, - trendlines: Vec::new(), - }); + c.series.push(Series { values: "{10,20,30,40}".into(), ..Series::default() }); let expected = [[0x61, 0x61, 0x61, 0xFF], [0xB3, 0xB3, 0xB3, 0xFF], [0x81, 0x81, 0x81, 0xFF], [0x50, 0x50, 0x50, 0xFF]]; @@ -2014,18 +1981,7 @@ fn excel_chart_styles_use_measured_point_palette() { fn excel_chart_styles_depend_on_series_count() { let wb = Workbook::default(); - let base_series = Series { - name: None, - categories: None, - values: "{10,20,30,40}".into(), - bubble_sizes: None, - color: None, - secondary: false, - kind: None, - quartiles: Default::default(), - smooth: false, - trendlines: Vec::new(), - }; + let base_series = Series { values: "{10,20,30,40}".into(), ..Series::default() }; let cases: &[(usize, [[u8; 4]; 3])] = &[ (6, [[0x55, 0x55, 0x55, 0xFF], [0x9E, 0x9E, 0x9E, 0xFF], [0x72, 0x72, 0x72, 0xFF]]), @@ -2064,18 +2020,7 @@ fn explicit_style_nine_draws_white_column_outlines() { ] { let mut c = chart(kind); c.legend = LegendPos::None; - c.series.push(Series { - name: None, - categories: None, - values: "{10,20,30,40}".into(), - bubble_sizes: None, - color: None, - secondary: false, - kind: None, - quartiles: Default::default(), - smooth: false, - trendlines: Vec::new(), - }); + c.series.push(Series { values: "{10,20,30,40}".into(), ..Series::default() }); for style in [1, 2, 9] { c.style = style;