From bf15f965aea77593876e210114841409a980ca8d Mon Sep 17 00:00:00 2001 From: neilcawse <8085959+neilcawse@users.noreply.github.com> Date: Mon, 12 Oct 2026 11:54:09 -0400 Subject: [PATCH 01/20] PivotTables: refresh keeps sort by value, captions, item order and layout settings A refreshed PivotTable read from an Excel file now lays out like Excel's: - Sort by a value field (autoSortScope on data field n): PivotField.sort_by, applied within each parent; pivot.sort takes `by: "Sum of X"`. - Captions: rowHeaderCaption, colHeaderCaption, dataCaption, grandTotalCaption and missingCaption (For empty cells show), field custom names and renamed items (item n). - Manual item order of fields that aren't auto-sorted. - Per-field subtotals (defaultSubtotal, with the table default in pivotTableDefinition16), Repeat Item Labels (fillDownLabels), field number formats, the Values row (hideValuesRow) and the classic layout (gridDropZones). - rowGrandTotals/colGrandTotals were read and written the wrong way round. - Date items sort after text, as in Excel. All settings are written back to XLSX. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/pivot.rs | 190 +++++++++++++- crates/engine/src/pivot.rs | 356 ++++++++++++++++++--------- crates/model/src/features.rs | 48 ++++ crates/xlsx/src/pivot.rs | 186 ++++++++++++-- crates/xlsx/src/tests/pivot_tests.rs | 34 ++- docs/gaps.md | 5 +- docs/target-app-parity.md | 5 +- 7 files changed, 668 insertions(+), 156 deletions(-) diff --git a/crates/engine/src/cmd/pivot.rs b/crates/engine/src/cmd/pivot.rs index 8a441fa1b4..804eacea64 100644 --- a/crates/engine/src/cmd/pivot.rs +++ b/crates/engine/src/cmd/pivot.rs @@ -101,7 +101,15 @@ pub fn specs() -> Vec { value_settings ), cmd!("pivot.filter", "Filter Items", [], None, "{pivot?, field, selected: [\"East\", ..] | null (all), replace?}", has_doc, filter), - cmd!("pivot.sort", "Sort Field", [], None, "{pivot?, field, order: asc|desc|none, replace?}", has_doc, sort), + cmd!( + "pivot.sort", + "Sort Field", + [], + None, + "{pivot?, field, order: asc|desc|none, by?: \"Sum of Sales\" (sort by a value field), replace?}", + has_doc, + sort + ), cmd!( "pivot.group", "Group Field", @@ -736,6 +744,18 @@ fn summarize_table(s: &mut Session, p: &Json) -> Result { // ---------------------------------------------------------------- queries +fn field_json(f: &PivotField) -> Json { + json!({ + "field": f.source_col, + "caption": f.caption, + "sort": sort_name(f.sort), + "sortBy": f.sort_by, + "group": group_name(f.date_group), + "numberFormat": f.number_format, + "collapsed": f.collapsed_items, + }) +} + fn pivot_json(wb: &Workbook, si: usize, pt: &PivotTable) -> Json { json!({ "id": pt.id, @@ -744,8 +764,8 @@ fn pivot_json(wb: &Workbook, si: usize, pt: &PivotTable) -> Json { "anchor": pt.anchor.a1(), "range": pt.last_range.map(|r| r.a1()), "source": pt.source, - "rows": pt.rows.iter().map(|f| json!({"field": f.source_col, "sort": sort_name(f.sort), "group": group_name(f.date_group), "collapsed": f.collapsed_items})).collect::>(), - "columns": pt.columns.iter().map(|f| json!({"field": f.source_col, "sort": sort_name(f.sort), "group": group_name(f.date_group), "collapsed": f.collapsed_items})).collect::>(), + "rows": pt.rows.iter().map(field_json).collect::>(), + "columns": pt.columns.iter().map(field_json).collect::>(), "values": pt.values.iter().map(|v| json!({"field": v.source_col, "func": func_name(v.func), "name": v.name, "showAs": show_as_name(v.show_as), "numberFormat": v.number_format})).collect::>(), "filters": pt.filters.iter().map(|f| json!({"field": f.source_col, "selected": f.selected, "report": !in_axes(pt, &f.source_col)})).collect::>(), "layout": layout_name(pt.layout), @@ -1074,6 +1094,12 @@ fn value_settings(s: &mut Session, p: &Json) -> Result { None => {} } let name = v.name.clone(); + // Fields sorted by this value field follow its new caption. + for f in pt.rows.iter_mut().chain(pt.columns.iter_mut()) { + if f.sort_by.as_deref().is_some_and(|b| b.eq_ignore_ascii_case(&cur.name)) { + f.sort_by = Some(name.clone()); + } + } if let Some(slot) = pt.values.get_mut(i) { *slot = v; } @@ -1146,8 +1172,23 @@ fn sort(s: &mut Session, p: &Json) -> Result { "none" | "manual" | "source" => PivotSort::None, o => return Err(bad(C, format!("unknown order `{o}` (asc|desc|none)"))), }; + // Sort by a value field (its caption or source field) instead of by the item labels. + let by = str_param(p, "by").map(str::to_string); update(s, p, |pt, _, _| { - axis_field(C, pt, &field)?.sort = order; + let by = match by { + Some(b) => Some( + pt.values + .iter() + .find(|v| v.name.eq_ignore_ascii_case(&b)) + .or_else(|| pt.values.iter().find(|v| v.source_col.eq_ignore_ascii_case(&b))) + .map(|v| v.name.clone()) + .ok_or_else(|| bad(C, format!("`{b}` isn't in the values area")))?, + ), + None => None, + }; + let f = axis_field(C, pt, &field)?; + f.sort = order; + f.sort_by = by; Ok(json!({})) }) } @@ -1552,6 +1593,7 @@ fn recommended(s: &mut Session, p: &Json) -> Result { #[cfg(test)] mod tests { use gridcraft_core::{CellError, CellRef, Value}; + use gridcraft_model::{PivotLayout, PivotSort}; use serde_json::{Value as Json, json}; use crate::Session; @@ -1982,6 +2024,146 @@ mod tests { s.execute("pivot.refresh", json!({"pivot": "PivotTable1"})).unwrap(); } + /// Edits the active sheet's last PivotTable in the model (settings only a file sets) and + /// refreshes it. + fn edit_pt(s: &mut Session, f: impl FnOnce(&mut gridcraft_model::PivotTable)) { + let d = s.doc_mut().unwrap(); + let wb = std::sync::Arc::make_mut(&mut d.wb); + let si = wb.active_sheet; + f(wb.sheet_mut(si).unwrap().pivots.last_mut().unwrap()); + s.execute("pivot.refresh", json!({})).unwrap(); + } + + #[test] + fn sort_by_value_within_each_parent() { + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": ["Sales"]})).unwrap(); + // East 415, West 285, North 135. + s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap(); + assert_eq!(pt(&s).rows[0].sort_by.as_deref(), Some("Sum of Sales")); + assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6")], ["East", "West", "North"]); + s.execute("pivot.sort", json!({"field": "Region", "order": "asc", "by": "Sales"})).unwrap(); + assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6")], ["North", "West", "East"]); + assert!(s.execute("pivot.sort", json!({"field": "Region", "order": "asc", "by": "Nope"})).is_err()); + // The sort follows a renamed value field; sorting without `by` sorts by label again. + s.execute("pivot.valueSettings", json!({"field": "Sum of Sales", "name": "Revenue"})).unwrap(); + assert_eq!(pt(&s).rows[0].sort_by.as_deref(), Some("Revenue")); + assert_eq!(text(&s, "A4"), "North"); + s.execute("pivot.sort", json!({"field": "Region", "order": "desc"})).unwrap(); + assert_eq!(pt(&s).rows[0].sort_by, None); + assert_eq!(text(&s, "A4"), "West"); + // Inner items sort within their parent; subtotals stay with their group. + s.execute("pivot.addField", json!({"field": "Product", "area": "rows"})).unwrap(); + s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap(); + s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Revenue"})).unwrap(); + s.execute("pivot.sort", json!({"field": "Product", "order": "desc", "by": "Revenue"})).unwrap(); + // East: Pears 195, Apples 160, Plums 60. + assert_eq!( + [text(&s, "A4"), text(&s, "B4"), text(&s, "B5"), text(&s, "B6"), text(&s, "A7")], + ["East", "Pears", "Apples", "Plums", "East Total"] + ); + assert_eq!(val(&s, "C4"), Value::Number(195.0)); + // West: Apples 170, Plums 70, Pears 45. + assert_eq!([text(&s, "A8"), text(&s, "B8"), text(&s, "B9"), text(&s, "B10")], ["West", "Apples", "Plums", "Pears"]); + // Columns sort by their row totals. + s.execute("pivot.moveField", json!({"field": "Region", "from": "rows", "to": "columns"})).unwrap(); + assert_eq!([text(&s, "B4"), text(&s, "C4"), text(&s, "D4")], ["East", "West", "North"]); + } + + #[test] + fn captions_renamed_items_and_manual_order() { + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap(); + edit_pt(&mut s, |p| { + p.row_header_caption = Some("Area".into()); + p.col_header_caption = Some("Fruit".into()); + p.grand_total_caption = Some("Everything".into()); + p.rows[0].item_captions = vec![("East".into(), "Eastern".into())]; + p.columns[0].sort = PivotSort::None; + p.columns[0].item_order = vec!["Plums".into(), "Pears".into()]; + }); + assert_eq!(text(&s, "A4"), "Area"); + assert_eq!(text(&s, "B3"), "Fruit"); + // Listed items first, the rest after. + assert_eq!([text(&s, "B4"), text(&s, "C4"), text(&s, "D4"), text(&s, "E4")], ["Plums", "Pears", "Apples", "Everything"]); + assert_eq!(text(&s, "A5"), "Eastern"); + assert_eq!(text(&s, "A8"), "Everything"); + // A renamed item sorts by its label still, and a filter still names it by its label. + s.execute("pivot.filter", json!({"field": "Region", "selected": ["East"]})).unwrap(); + assert_eq!(text(&s, "A5"), "Eastern"); + assert_eq!(val(&s, "E5"), Value::Number(415.0)); + // Outline layout: the field's custom name heads its column. + edit_pt(&mut s, |p| { + p.layout = PivotLayout::Outline; + p.rows[0].caption = Some("Sales area".into()); + p.columns[0].caption = Some("Kind".into()); + }); + assert_eq!(text(&s, "A4"), "Sales area"); + assert_eq!(text(&s, "B3"), "Kind"); + } + + #[test] + fn field_subtotals_repeat_labels_and_values_row() { + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Sales"]})).unwrap(); + s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap(); + assert_eq!(text(&s, "A7"), "East Total"); + // Region without subtotals although the table has them; labels repeated on every row. + edit_pt(&mut s, |p| { + p.rows[0].subtotal = Some(false); + p.rows[0].repeat_labels = true; + }); + assert_eq!(pt(&s).last_range.unwrap().height(), 1 + 9 + 1); + assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6"), text(&s, "A7")], ["East", "East", "East", "North"]); + assert_eq!(text(&s, "B7"), "Apples"); + // Outline repeats the labels too. + s.execute("pivot.layout", json!({"layout": "outline"})).unwrap(); + assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "A5"), text(&s, "B5")], ["East", "", "East", "Apples"]); + // Two values without a column field: the Values row (Outline/Tabular) holds the caption. + s.execute("pivot.removeField", json!({"field": "Product"})).unwrap(); + s.execute("pivot.addField", json!({"field": "Units", "area": "values"})).unwrap(); + assert_eq!(text(&s, "B3"), "Values"); + assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "C4")], ["Region", "Sum of Sales", "Sum of Units"]); + edit_pt(&mut s, |p| p.data_caption = Some("Data".into())); + assert_eq!(text(&s, "B3"), "Data"); + edit_pt(&mut s, |p| p.show_values_row = false); + assert_eq!([text(&s, "A3"), text(&s, "B3")], ["Region", "Sum of Sales"]); + // Compact layout never shows it. + edit_pt(&mut s, |p| { + p.show_values_row = true; + p.layout = PivotLayout::Compact; + }); + assert_eq!([text(&s, "A3"), text(&s, "B3")], ["Row Labels", "Sum of Sales"]); + } + + #[test] + fn empty_cell_caption_classic_layout_and_date_order() { + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Units"], "values": ["Sales"]})).unwrap(); + // East has no record with 1 unit: blank, or the "For empty cells show" caption. + assert_eq!([text(&s, "A5"), text(&s, "B4"), text(&s, "B5")], ["East", "1", ""]); + edit_pt(&mut s, |p| p.empty_caption = Some("0".into())); + assert_eq!(text(&s, "B5"), "0"); + // Classic layout, one value and no column field: the value caption above the row + // headers and a "Total" column. + s.execute("pivot.removeField", json!({"field": "Units"})).unwrap(); + edit_pt(&mut s, |p| { + p.layout = PivotLayout::Tabular; + p.classic_layout = true; + }); + assert_eq!([text(&s, "A3"), text(&s, "A4"), text(&s, "B4"), text(&s, "A5")], ["Sum of Sales", "Region", "Total", "East"]); + assert_eq!(pt(&s).last_range.unwrap().height(), 2 + 3 + 1); + // A field number format applies to the item labels; date items sort after text, as in + // Excel. + s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap(); + s.execute("cell.set", json!({"cell": "C13", "input": "NA"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap(); + s.execute("pivot.removeField", json!({"field": "Region"})).unwrap(); + s.execute("pivot.addField", json!({"field": "Date", "area": "rows"})).unwrap(); + edit_pt(&mut s, |p| p.rows[0].number_format = Some("m/d/yyyy".into())); + assert_eq!(text(&s, "A5"), "NA"); + } + fn pivot_chart(s: &Session) -> gridcraft_model::Chart { s.doc().unwrap().wb.active().unwrap().charts.last().unwrap().clone() } diff --git a/crates/engine/src/pivot.rs b/crates/engine/src/pivot.rs index 6146bd4f91..29dbb3f6f0 100644 --- a/crates/engine/src/pivot.rs +++ b/crates/engine/src/pivot.rs @@ -9,7 +9,7 @@ use std::cmp::Ordering; use std::collections::{HashMap, HashSet}; use gridcraft_core::date::datetime_from_serial; -use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value}; +use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value, number_to_text}; use gridcraft_model::*; use crate::pivot_calc::CalcSet; @@ -199,6 +199,20 @@ struct Item { first: usize, /// The value is a number shown with the source format. formatted: bool, + /// The item's custom name (a renamed item). + caption: Option, + /// Position in the field's manual item order. + rank: Option, +} + +impl Item { + /// The value shown: the custom name, else the item's value. + fn shown_value(&self) -> Value { + self.caption.as_deref().map(Value::text).unwrap_or_else(|| self.value.clone()) + } + fn shown_label(&self) -> &str { + self.caption.as_deref().unwrap_or(&self.label) + } } #[derive(Default)] @@ -207,6 +221,8 @@ struct FieldItems { index: HashMap, } +/// Sort classes: numbers, text, dates (a number shown with a date format; Excel sorts these +/// after text), logicals, errors, blanks. fn cmp_items(a: &Item, b: &Item) -> Ordering { a.class.cmp(&b.class).then(a.num.total_cmp(&b.num)).then_with(|| a.text.cmp(&b.text)) } @@ -221,9 +237,11 @@ fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: num, first, formatted, + caption: None, + rank: None, }; match v { - Value::Empty => ("b".into(), it(Value::text("(blank)"), "(blank)".into(), 4, 0.0, false)), + Value::Empty => ("b".into(), it(Value::text("(blank)"), "(blank)".into(), 5, 0.0, false)), Value::Number(n) => { if group != PivotDateGroup::None && let Some(dt) = datetime_from_serial(wb.date_system, *n) @@ -240,15 +258,16 @@ fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: }; return (format!("g{key}"), it(Value::text(label.as_str()), label, 0, key, false)); } - let label = crate::display::format(v, fmt, wb).text; - (format!("n{}", n.to_bits()), it(v.clone(), label, 0, *n, true)) + let shown = crate::display::format(v, fmt, wb); + let class = if crate::display::number_format(fmt).is_date() { 2 } else { 0 }; + (format!("n{}", n.to_bits()), it(v.clone(), shown.text, class, *n, true)) } Value::Text(t) => (format!("t{}", t.to_lowercase()), it(v.clone(), t.to_string(), 1, 0.0, false)), Value::Bool(b) => { let l = if *b { "TRUE" } else { "FALSE" }; - (format!("l{l}"), it(Value::Bool(*b), l.into(), 2, *b as u8 as f64, false)) + (format!("l{l}"), it(Value::Bool(*b), l.into(), 3, *b as u8 as f64, false)) } - Value::Error(e) => (format!("e{}", e.as_str()), it(v.clone(), e.as_str().into(), 3, 0.0, false)), + Value::Error(e) => (format!("e{}", e.as_str()), it(v.clone(), e.as_str().into(), 4, 0.0, false)), Value::Array(_) => make_item(wb, &v.scalar(), group, fmt, first), } } @@ -270,6 +289,29 @@ impl FieldItems { fn label(&self, i: u32) -> String { self.get(i).map(|x| x.label.clone()).unwrap_or_default() } + fn shown_label(&self, i: u32) -> String { + self.get(i).map(|x| x.shown_label().to_string()).unwrap_or_default() + } + /// Applies a field's renamed items and manual item order. Settings name items by label; a + /// number item also matches its unformatted number text (how a file's cache names it). + fn apply(&mut self, f: &PivotField) { + if f.item_captions.is_empty() && f.item_order.is_empty() { + return; + } + let mut order: HashMap = HashMap::new(); + for (i, l) in f.item_order.iter().enumerate() { + order.entry(l.to_lowercase()).or_insert(i); + } + let mut captions: HashMap = HashMap::new(); + for (l, c) in &f.item_captions { + captions.entry(l.to_lowercase()).or_insert(c.as_str()); + } + for it in &mut self.items { + let raw = if it.formatted { Some(number_to_text(it.num).to_lowercase()) } else { None }; + it.rank = order.get(&it.text).or_else(|| raw.as_ref().and_then(|r| order.get(r))).copied(); + it.caption = captions.get(&it.text).or_else(|| raw.as_ref().and_then(|r| captions.get(r))).map(|c| c.to_string()); + } + } } /// The label of a source value under a date grouping (for filters and field lists). @@ -409,7 +451,14 @@ struct Node { children: Vec, } -fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], items: &[FieldItems]) -> Vec { +/// Sorting of an axis by value fields: the value field each axis field sorts by, and the value +/// of an axis path (a row path with the column total, or a column path with the row total). +struct ByValue<'a> { + fields: Vec>, + value: &'a dyn Fn(&[u32], usize) -> Option, +} + +fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], items: &[FieldItems], by_value: &ByValue) -> Vec { let (Some(field), Some(fi)) = (fields.get(depth), items.get(depth)) else { return vec![] }; let mut order: Vec = Vec::new(); let mut groups: HashMap> = HashMap::new(); @@ -422,23 +471,33 @@ fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], items: &[F g.push(p); } } - let mut nodes: Vec = order + let vi = by_value.fields.get(depth).copied().flatten().filter(|_| field.sort != PivotSort::None); + let mut nodes: Vec<(Option, Node)> = order .into_iter() .map(|it| { let ps = groups.remove(&it).unwrap_or_default(); - Node { item: it, children: build_tree(&ps, depth + 1, fields, items) } + let key = vi.and_then(|vi| ps.first().and_then(|p| p.get(..=depth)).and_then(|p| (by_value.value)(p, vi))); + (key, Node { item: it, children: build_tree(&ps, depth + 1, fields, items, by_value) }) }) .collect(); - let by = |a: &Node, b: &Node| match (fi.get(a.item), fi.get(b.item)) { + let by_label = |a: &Node, b: &Node| match (fi.get(a.item), fi.get(b.item)) { (Some(x), Some(y)) => match field.sort { PivotSort::Asc => cmp_items(x, y), PivotSort::Desc => cmp_items(y, x), - PivotSort::None => x.first.cmp(&y.first), + PivotSort::None => x.rank.unwrap_or(usize::MAX).cmp(&y.rank.unwrap_or(usize::MAX)).then(x.first.cmp(&y.first)), }, _ => Ordering::Equal, }; - nodes.sort_by(by); - nodes + // By value: numbers in the sort direction, then items without a number; ties by label. + let by_key = |a: &Option, b: &Option| match (a, b) { + (Some(x), Some(y)) if field.sort == PivotSort::Desc => y.total_cmp(x), + (Some(x), Some(y)) => x.total_cmp(y), + (Some(_), None) => Ordering::Less, + (None, Some(_)) => Ordering::Greater, + (None, None) => Ordering::Equal, + }; + nodes.sort_by(|(ka, a), (kb, b)| by_key(ka, kb).then_with(|| by_label(a, b))); + nodes.into_iter().map(|(_, n)| n).collect() } fn is_collapsed(field: &PivotField, label: &str) -> bool { @@ -587,11 +646,22 @@ struct Ctx<'a> { val_names: Vec, } +/// A label cell of a report line: (column, value, indent, number format). +type Label = (usize, Value, u8, Option); + +/// Whether an axis field shows subtotals (its own setting, else the table's). +fn shows_subtotals(pt: &PivotTable, f: Option<&&PivotField>) -> bool { + f.and_then(|f| f.subtotal).unwrap_or(pt.subtotals) +} + impl Ctx<'_> { - fn label_cell(&self, depth: usize, item: u32) -> (Value, Option, String) { - let Some(it) = self.row_items.get(depth).and_then(|fi| fi.get(item)) else { return (Value::Empty, None, String::new()) }; - let fmt = if it.formatted { self.row_fmts.get(depth).cloned() } else { None }; - (it.value.clone(), fmt, it.label.clone()) + /// (shown value, number format, item label, shown label) of a row item. + fn label_cell(&self, depth: usize, item: u32) -> (Value, Option, String, String) { + let Some(it) = self.row_items.get(depth).and_then(|fi| fi.get(item)) else { + return (Value::Empty, None, String::new(), String::new()); + }; + let fmt = if it.formatted && it.caption.is_none() { self.row_fmts.get(depth).cloned() } else { None }; + (it.shown_value(), fmt, it.label.clone(), it.shown_label().to_string()) } /// (column, indent) of a row level (Σ Values counts as a level) in Compact/Outline form. @@ -620,86 +690,79 @@ impl Ctx<'_> { /// The Σ Values level at row field depth `depth`: one item per value field, each followed by /// the row fields below it (`nodes`) or, innermost, holding that value. - fn flatten_values(&self, nodes: &[Node], depth: usize, prefix: &mut Vec, out: &mut Vec) { + fn flatten_values(&self, nodes: &[Node], depth: usize, prefix: &mut Vec, repeat: &mut Vec