From e24a8631b448c42ca62d1c1a40d46c61e3fccbe0 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Thu, 15 Oct 2026 02:59:25 -0500 Subject: [PATCH 01/17] Filter: SUBTOTAL over filtered table rows keeps its value after save and reopen A sheet AutoFilter that overlaps a table can't be saved (the file only holds a table's own filter there), so the writer dropped it. Its criteria were lost and the rows it hid reopened as rows hidden by hand, which SUBTOTAL 1-11 counts. - Save a sheet AutoFilter that starts on a table's header row as that table's filter (columns mapped to the table), merged with the table's own criteria. - Filtering inside a table takes over the criteria the table already had, so a reopened filtered table filtered again saves both. - From a cell outside a table, the filter range keeps off the table like Excel (observed: table B4:C8, AutoFilter from A1 covers A1:A3, from A6 A5:A8, from B3 A1:B3); an explicit range over part of a table is refused. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/data.rs | 40 ++++- crates/engine/src/selection.rs | 36 ++++- .../engine/tests/subtotal-filter-roundtrip.rs | 153 ++++++++++++++++++ crates/xlsx/src/sheet_write.rs | 31 +++- crates/xlsx/src/tests/mod.rs | 1 + crates/xlsx/src/tests/tablefilter.rs | 102 ++++++++++++ 6 files changed, 352 insertions(+), 11 deletions(-) create mode 100644 crates/engine/tests/subtotal-filter-roundtrip.rs create mode 100644 crates/xlsx/src/tests/tablefilter.rs diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index 383624b70c..3fc27811ae 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -472,20 +472,48 @@ fn toggle_filter(s: &mut Session, p: &Json) -> Result { } /// Turn a sheet AutoFilter on over `p.range`, or over the data range of the selection. +/// +/// A sheet AutoFilter never overlaps a table, because a file can't hold one (Excel refuses +/// `Range("A1:C8").AutoFilter` over part of a table, and from a cell outside a table it leaves the +/// table's cells out of the region). Inside a table the filter covers the table from its header +/// row, which is saved as the table's own filter, and takes over the criteria the table already +/// had so there is one filter to save. fn install_filter(s: &mut Session, p: &Json) -> Result { let sheet = s.doc()?.wb.active_sheet; let mut r = data_range(s, p)?; - // A selected header row filters the data below it (#201). - if p.get("range").is_none() && r.height() == 1 { + { let d = s.doc()?; let sh = d.wb.active().ok_or(EngineError::NoDocument)?; - let below = current_region(sh, r.start).end.row; - if below > r.end.row { - r = RangeRef::new(r.start, CellRef::new(below, r.end.col)); + if p.get("range").is_none() && sh.table_at(d.selection.active).is_none() && d.selection.current().is_single() { + r = crate::selection::current_region_outside_tables(sh, d.selection.active); + } + // A selected header row filters the data below it (#201). + if p.get("range").is_none() && r.height() == 1 { + let region = if sh.table_at(r.start).is_some() { + current_region(sh, r.start) + } else { + crate::selection::current_region_outside_tables(sh, r.start) + }; + if region.end.row > r.end.row { + r = RangeRef::new(r.start, CellRef::new(region.end.row, r.end.col)); + } } } + let Some(sh) = s.doc()?.wb.sheet(sheet) else { return Err(EngineError::NoDocument) }; + // The table whose header row the filter starts on, when it lies inside that table. + let host = + sh.tables.iter().position(|t| t.header_row && t.range.start.row == r.start.row && t.range.contains(r.start) && t.range.contains(r.end)); + if host.is_none() && sh.tables.iter().any(|t| t.range.intersects(&r)) { + return Err(bad("data.filter", "a filter range can't overlap a table; filter inside the table instead")); + } edit(s, |cx| { - cx.sheet_mut(sheet)?.autofilter = Some(AutoFilter { range: r, criteria: vec![] }); + let sh = cx.sheet_mut(sheet)?; + let mut criteria = vec![]; + if let Some(t) = host.and_then(|i| sh.tables.get_mut(i)) { + let shift = r.start.col.saturating_sub(t.range.start.col); + criteria = std::mem::take(&mut t.filter).into_iter().filter_map(|(o, c)| Some((o.checked_sub(shift)?, c))).collect(); + } + sh.autofilter = Some(AutoFilter { range: r, criteria }); Ok(json!({"filter": true, "range": r.a1()})) }) } diff --git a/crates/engine/src/selection.rs b/crates/engine/src/selection.rs index 27418a21a1..9a8c0581b0 100644 --- a/crates/engine/src/selection.rs +++ b/crates/engine/src/selection.rs @@ -186,7 +186,41 @@ pub fn jump(sheet: &Sheet, from: CellRef, dr: i64, dc: i64) -> CellRef { /// The contiguous data region around `c` (Ctrl+A / Ctrl+Shift+8, AutoSum, sort, tables). pub fn current_region(sheet: &Sheet, c: CellRef) -> RangeRef { - let filled = |c: CellRef| sheet.cell(c).is_some_and(|x| !x.value.is_empty() || x.formula.is_some()) || sheet.spill.contains_key(&c); + region_where(sheet, c, |_| true) +} + +/// The data region a sheet AutoFilter takes from `c`, a cell outside any table: the current +/// region, kept off the tables it reaches. Observed in Windows Excel 16 (table B4:C8, text in +/// A1:A3, A5:A8 and B3; the current region of A1 is A1:C8): from A1 the filter covers A1:A3, from +/// A6 A5:A8, from B3 A1:B3. So the region is cut to the columns on the cell's side of the table +/// when the cell is left or right of it, else to the rows above or below, and grown again from +/// the cell inside that window. +pub fn current_region_outside_tables(sheet: &Sheet, c: CellRef) -> RangeRef { + let (mut c0, mut c1, mut r0, mut r1) = (0, MAX_COLS - 1, 0, MAX_ROWS - 1); + let mut region = current_region(sheet, c); + for _ in 0..=sheet.tables.len() { + let Some(t) = sheet.tables.iter().find(|t| t.range.intersects(®ion)) else { break }; + let t = t.range; + if c.col < t.start.col { + c1 = c1.min(t.start.col - 1); + } else if c.col > t.end.col { + c0 = c0.max(t.end.col + 1); + } else if c.row < t.start.row { + r1 = r1.min(t.start.row - 1); + } else if c.row > t.end.row { + r0 = r0.max(t.end.row + 1); + } else { + return RangeRef::cell(c); + } + region = region_where(sheet, c, |x| x.col >= c0 && x.col <= c1 && x.row >= r0 && x.row <= r1 && sheet.table_at(x).is_none()); + } + region +} + +/// The current region around `c`, counting only filled cells that `counts` accepts. +fn region_where(sheet: &Sheet, c: CellRef, counts: impl Fn(CellRef) -> bool) -> RangeRef { + let filled = + |c: CellRef| (sheet.cell(c).is_some_and(|x| !x.value.is_empty() || x.formula.is_some()) || sheet.spill.contains_key(&c)) && counts(c); // Whether a row (or column) has a filled cell between two columns (rows), inclusive. let row_has = |row: u32, a: u32, b: u32| (a..=b).any(|col| filled(CellRef::new(row, col))); let col_has = |col: u32, a: u32, b: u32| (a..=b).any(|row| filled(CellRef::new(row, col))); diff --git a/crates/engine/tests/subtotal-filter-roundtrip.rs b/crates/engine/tests/subtotal-filter-roundtrip.rs new file mode 100644 index 0000000000..f5e6b64805 --- /dev/null +++ b/crates/engine/tests/subtotal-filter-roundtrip.rs @@ -0,0 +1,153 @@ +//! SUBTOTAL over filtered rows keeps its value through an XLSX save and reopen (ft-3ir.10.24). +//! +//! Excel (observed in Windows Excel 16 with synthetic workbooks) saves rows a filter hides as plain +//! `hidden="1"` rows; a hidden row counts as filtered when it lies in an AutoFilter (sheet or table) +//! that has criteria. Excel can't hold a sheet AutoFilter that overlaps a table, so GridCraft saves +//! a table's filter in the table part and never creates a sheet AutoFilter over part of a table. + +use gridcraft_core::{CellRef, Value}; +use gridcraft_engine::calc::Calc; +use gridcraft_engine::model::Workbook; +use gridcraft_engine::{Session, io}; +use serde_json::{Value as Json, json}; + +fn reopened(wb: &Workbook) -> Workbook { + let bytes = io::save_bytes(wb, "t.xlsx").unwrap(); + let (mut back, _) = io::open_bytes("t.xlsx", &bytes).unwrap(); + Calc::new().recalc_all(&mut back); + back +} + +/// Every formula value in memory against the same cell after a save and reopen. +fn assert_values_survive(wb: &Workbook) { + let back = reopened(wb); + for (a, b) in wb.sheets.iter().zip(&back.sheets) { + for (c, cell) in a.cells.iter() { + if cell.formula.is_some() { + assert_eq!(cell.value, b.value(c), "{}!{} ({:?})", a.name, c.a1(), cell.formula.as_ref().map(|f| &f.text)); + } + } + } +} + +fn session(sample: &str, steps: &[(&str, Json)]) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"sample": sample})).unwrap(); + for (id, p) in steps { + let _ = s.execute(id, p.clone()); + } + s +} + +fn wb(s: &Session) -> &Workbook { + &s.doc().unwrap().wb +} + +#[test] +fn bead_repro_filter_then_replace_on_the_sales_sample() { + let s = + session("sales", &[("data.filterBy", json!({"column":"G","top":{"count":2}})), ("edit.replace", json!({"all":true,"what":"1","with":""}))]); + let sh = wb(&s).active().unwrap(); + assert!(sh.autofilter.as_ref().is_none_or(|af| !sh.tables.iter().any(|t| t.range.intersects(&af.range)))); + assert_values_survive(wb(&s)); +} + +#[test] +fn bead_repro_subtotal_then_filter_on_the_grades_sample() { + let s = session( + "grades", + &[ + ("home.insertColumns", json!({})), + ("data.subtotal", json!({"columns":["G"],"function":"sum","groupBy":"J"})), + ("data.filterBy", json!({"column":"B","values":["x"]})), + ], + ); + let sh = wb(&s).active().unwrap(); + assert!(sh.autofilter.as_ref().is_none_or(|af| !sh.tables.iter().any(|t| t.range.intersects(&af.range)))); + assert_values_survive(wb(&s)); +} + +/// A table A1:B7 (Name, Qty = 1, 10, 100...) with SUBTOTAL(9) and SUBTOTAL(109) beside it. +fn table_book() -> Session { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range":"A1","values":[["Name","Qty"],["a",1],["b",10],["c",100],["d",1000],["e",10000],["f",100000]]})) + .unwrap(); + s.execute("insert.table", json!({"range":"A1:B7","header":true})).unwrap(); + s.execute("cell.set", json!({"cell":"E1","input":"=SUBTOTAL(9,B2:B7)"})).unwrap(); + s.execute("cell.set", json!({"cell":"E2","input":"=SUBTOTAL(109,B2:B7)"})).unwrap(); + s.execute("selection.set", json!({"cell":"A2"})).unwrap(); + s +} + +fn e1_e2(wb: &Workbook) -> (Value, Value) { + let sh = wb.active().unwrap(); + (sh.value(CellRef::new(0, 4)), sh.value(CellRef::new(1, 4))) +} + +#[test] +fn table_filter_keeps_subtotal_and_criteria_through_save() { + let mut s = table_book(); + s.execute("data.filterBy", json!({"column":"A","values":["a","c","e","f"]})).unwrap(); + // Like Excel, a row hidden by hand inside an active filter range is left out by SUBTOTAL 9 too. + s.execute("home.hideRows", json!({"rows":"6:6"})).unwrap(); + assert_eq!(e1_e2(wb(&s)), (Value::Number(100101.0), Value::Number(100101.0))); + assert_values_survive(wb(&s)); + let back = reopened(wb(&s)); + assert_eq!(e1_e2(&back), (Value::Number(100101.0), Value::Number(100101.0))); + let t = &back.active().unwrap().tables[0]; + assert_eq!(t.filter.len(), 1, "the criteria are saved with the table: {:?}", t.filter); +} + +#[test] +fn rows_hidden_by_hand_without_a_filter_still_count_for_subtotal_9() { + let mut s = table_book(); + s.execute("home.hideRows", json!({"rows":"3:3"})).unwrap(); + s.execute("home.hideRows", json!({"rows":"5:5"})).unwrap(); + assert_eq!(e1_e2(wb(&s)), (Value::Number(111111.0), Value::Number(110101.0))); + let back = reopened(wb(&s)); + assert_eq!(e1_e2(&back), (Value::Number(111111.0), Value::Number(110101.0))); +} + +#[test] +fn filtering_a_reopened_table_again_keeps_both_criteria() { + let mut s = table_book(); + s.execute("data.filterBy", json!({"column":"A","values":["a","c","e","f"]})).unwrap(); + let back = reopened(wb(&s)); + let mut s = Session::new(); + s.add_document(gridcraft_engine::DocState::new(back, None, "t".into())); + s.execute("selection.set", json!({"cell":"A2"})).unwrap(); + s.execute("data.filterBy", json!({"column":"B","custom":{"op":">","value":"50"}})).unwrap(); + let sh = wb(&s).active().unwrap(); + assert!(sh.tables[0].filter.is_empty(), "the table's criteria moved into the live filter"); + assert_eq!(sh.autofilter.as_ref().map(|af| af.criteria.len()), Some(2)); + assert_eq!(e1_e2(wb(&s)), (Value::Number(110100.0), Value::Number(110100.0))); + assert_values_survive(wb(&s)); + assert_eq!(reopened(wb(&s)).active().unwrap().tables[0].filter.len(), 2); +} + +#[test] +fn a_sheet_filter_from_outside_a_table_leaves_the_table_out() { + // Excel: table B4:C8 with text in A1:A3, A5:A8 and B3. AutoFilter from A1 covers A1:A3, from + // A6 A5:A8, from B3 A1:B3; an explicit range over part of the table is refused. + let layout = || { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range":"A1","values":[["Title"],["x"],["y"]]})).unwrap(); + s.execute("cell.set", json!({"cell":"B3","input":"z"})).unwrap(); + s.execute("range.setValues", json!({"range":"B4","values":[["Name","Qty"],["n5","v5"],["n6","v6"],["n7","v7"],["n8","v8"]]})).unwrap(); + s.execute("range.setValues", json!({"range":"A5","values":[["a5"],["a6"],["a7"],["a8"]]})).unwrap(); + s.execute("insert.table", json!({"range":"B4:C8","header":true})).unwrap(); + s + }; + for (cell, want) in [("A1", "A1:A3"), ("A6", "A5:A8"), ("B3", "A1:B3")] { + let mut s = layout(); + s.execute("selection.set", json!({"cell": cell})).unwrap(); + s.execute("data.filter", json!({})).unwrap(); + let af = wb(&s).active().unwrap().autofilter.clone(); + assert_eq!(af.map(|a| a.range.a1()), Some(want.to_string()), "from {cell}"); + } + let mut s = layout(); + assert!(s.execute("data.filter", json!({"range":"A1:C8"})).is_err()); + assert!(wb(&s).active().unwrap().autofilter.is_none()); +} diff --git a/crates/xlsx/src/sheet_write.rs b/crates/xlsx/src/sheet_write.rs index 78e1afaaef..63ed2e7989 100644 --- a/crates/xlsx/src/sheet_write.rs +++ b/crates/xlsx/src/sheet_write.rs @@ -569,7 +569,8 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> ( out.table_id += 1; let n = out.tables; let name = table_name(&t.name, &mut used_names, out.table_id); - let xml = table_xml(t, cols, &name, out.table_id, out); + let filter = table_filter(sheet, t); + let xml = table_xml(t, cols, &name, out.table_id, &filter, out); out.part(&format!("xl/tables/table{n}.xml"), Some(CT_TABLE), xml.into_bytes()); let rid = rels.add("table", &format!("../tables/table{n}.xml")); let _ = write!(parts, ""); @@ -1021,7 +1022,29 @@ fn autofilter_xml(range: RangeRef, criteria: &[(u32, FilterCriterion)], out: &mu s } -fn table_xml(t: &Table, cols: &[String], name: &str, id: u32, out: &mut Out) -> String { +/// The criteria saved in a table's ``: its own, plus those of a sheet AutoFilter +/// that starts on the table's header row. GridCraft filters a table through the sheet +/// AutoFilter, but a file can't hold a sheet AutoFilter that overlaps a table (the sheet element +/// is left out), so without this the criteria would be lost and the rows they hide would reopen +/// as rows hidden by hand, which SUBTOTAL 1-11 counts. +fn table_filter(sheet: &Sheet, t: &Table) -> Vec<(u32, FilterCriterion)> { + let mut criteria = t.filter.clone(); + let Some(af) = sheet.autofilter.as_ref().filter(|af| t.header_row && af.range.start.row == t.range.start.row && af.range.intersects(&t.range)) + else { + return criteria; + }; + for (off, c) in &af.criteria { + let Some(col) = af.range.start.col.checked_add(*off).and_then(|abs| abs.checked_sub(t.range.start.col)) else { continue }; + if col < t.range.width() { + criteria.retain(|(o, _)| *o != col); + criteria.push((col, c.clone())); + } + } + criteria.sort_by_key(|(o, _)| *o); + criteria +} + +fn table_xml(t: &Table, cols: &[String], name: &str, id: u32, filter: &[(u32, FilterCriterion)], out: &mut Out) -> String { let mut s = format!("{XML_DECL} let _ = write!(s, " connectionId=\"{c}\""); } s.push('>'); - if t.header_row && t.filter_button { + if t.header_row && (t.filter_button || !filter.is_empty()) { let end_row = if t.totals_row { t.range.end.row.saturating_sub(1).max(t.range.start.row) } else { t.range.end.row }; let r = RangeRef::new(t.range.start, CellRef::new(end_row, t.range.end.col)); - s.push_str(&autofilter_xml(r, &t.filter, out)); + s.push_str(&autofilter_xml(r, filter, out)); } let _ = write!(s, "", cols.len()); for (i, name) in cols.iter().enumerate() { diff --git a/crates/xlsx/src/tests/mod.rs b/crates/xlsx/src/tests/mod.rs index 517113d0f6..b9f7b8ca34 100644 --- a/crates/xlsx/src/tests/mod.rs +++ b/crates/xlsx/src/tests/mod.rs @@ -15,6 +15,7 @@ mod richdata_tests; mod roundtrip; mod sheet_names; mod smooth_roundtrip; +mod tablefilter; mod trendline_roundtrip; mod xls_tests; mod xlsb_tests; diff --git a/crates/xlsx/src/tests/tablefilter.rs b/crates/xlsx/src/tests/tablefilter.rs new file mode 100644 index 0000000000..784361b7fd --- /dev/null +++ b/crates/xlsx/src/tests/tablefilter.rs @@ -0,0 +1,102 @@ +//! A sheet AutoFilter that filters a table is saved as the table's own filter (a file can't hold +//! a sheet AutoFilter that overlaps a table), so the rows it hides reopen as filtered rows. + +use gridcraft_core::{CellRef, RangeRef, Value}; +use gridcraft_model::*; + +use crate::{read_xlsx, write_xlsx}; + +fn rr(a: &str) -> RangeRef { + RangeRef::parse(a).unwrap() +} + +fn table(range: &str, cols: &[&str]) -> Table { + Table { + id: 1, + name: "T".into(), + range: rr(range), + header_row: true, + totals_row: false, + columns: cols + .iter() + .map(|n| TableColumn { name: (*n).into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None }) + .collect(), + style: String::new(), + banded_rows: true, + banded_cols: false, + first_col: false, + last_col: false, + filter_button: true, + filter: vec![], + table_type: None, + connection_id: None, + } +} + +/// Table B2:C6 (Name, Qty) with rows 4 and 6 hidden by a filter on Name. +fn filtered(af_range: &str, af_col: u32) -> Workbook { + let mut wb = Workbook::new(); + let s = wb.sheet_mut(0).unwrap(); + s.set_value(CellRef::new(1, 1), Value::text("Name")); + s.set_value(CellRef::new(1, 2), Value::text("Qty")); + for (i, n) in ["a", "b", "c", "d"].iter().enumerate() { + let row = 2 + i as u32; + s.set_value(CellRef::new(row, 1), Value::text(*n)); + s.set_value(CellRef::new(row, 2), Value::Number(10f64.powi(i as i32))); + } + let mut t = table("B2:C6", &["Name", "Qty"]); + // A criterion the table already had (from the file it was opened from) on the Qty column. + t.filter = vec![(1, FilterCriterion::Custom { a: (">".into(), "0".into()), b: None, and: true })]; + s.tables.push(t); + s.autofilter = Some(AutoFilter { + range: rr(af_range), + criteria: vec![(af_col, FilterCriterion::Values { values: vec!["a".into(), "c".into()], blanks: false })], + }); + for row in [3, 5] { + s.rows.entry(row).or_default().hidden = true; + } + wb +} + +#[test] +fn table_filter_through_the_sheet_autofilter_is_saved_with_the_table() { + let wb = filtered("B2:C6", 0); + assert!(wb.sheets[0].is_row_filtered(3)); + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + let s = back.sheet(0).unwrap(); + assert!(s.autofilter.is_none(), "no sheet AutoFilter over a table"); + let t = &s.tables[0]; + assert_eq!(t.filter.len(), 2, "{:?}", t.filter); + assert_eq!(t.filter[0].0, 0); + assert!(matches!(&t.filter[0].1, FilterCriterion::Values { values, .. } if values == &["a".to_string(), "c".to_string()])); + assert!(matches!(&t.filter[1].1, FilterCriterion::Custom { .. }), "the table's own criterion is kept"); + for row in [3, 5] { + assert!(s.is_row_filtered(row), "row {} reopens as filtered", row + 1); + } + assert!(!s.is_row_hidden(2) && !s.is_row_hidden(4)); +} + +#[test] +fn sheet_autofilter_starting_left_of_the_table_maps_its_columns() { + // The filter starts one column left of the table on its header row: Name is column 1 of the + // filter and column 0 of the table; a criterion on the column outside the table is dropped. + let mut wb = filtered("A2:C6", 1); + if let Some(af) = wb.sheet_mut(0).unwrap().autofilter.as_mut() { + af.criteria.push((0, FilterCriterion::Values { values: vec!["zz".into()], blanks: true })); + } + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + let t = &back.sheet(0).unwrap().tables[0]; + let cols: Vec = t.filter.iter().map(|(c, _)| *c).collect(); + assert_eq!(cols, [0, 1]); + assert!(matches!(&t.filter[0].1, FilterCriterion::Values { values, .. } if values == &["a".to_string(), "c".to_string()])); +} + +#[test] +fn sheet_autofilter_not_on_the_header_row_is_not_folded() { + let wb = filtered("B1:C6", 0); + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + let s = back.sheet(0).unwrap(); + assert!(s.autofilter.is_none()); + let cols: Vec = s.tables[0].filter.iter().map(|(c, _)| *c).collect(); + assert_eq!(cols, [1], "only the table's own criterion"); +} From 937634a31a6c1c6384c86e45053c478655d9bcf4 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:38:52 -0500 Subject: [PATCH 02/17] Test: drop internal tracker id from subtotal filter test header --- crates/engine/tests/subtotal-filter-roundtrip.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/subtotal-filter-roundtrip.rs b/crates/engine/tests/subtotal-filter-roundtrip.rs index f5e6b64805..6fcc09fd07 100644 --- a/crates/engine/tests/subtotal-filter-roundtrip.rs +++ b/crates/engine/tests/subtotal-filter-roundtrip.rs @@ -1,4 +1,4 @@ -//! SUBTOTAL over filtered rows keeps its value through an XLSX save and reopen (ft-3ir.10.24). +//! SUBTOTAL over filtered rows keeps its value through an XLSX save and reopen. //! //! Excel (observed in Windows Excel 16 with synthetic workbooks) saves rows a filter hides as plain //! `hidden="1"` rows; a hidden row counts as filtered when it lies in an AutoFilter (sheet or table) From 46bdd416bbc8878238404ee27fefa4e9f59cd105 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:48:11 -0500 Subject: [PATCH 03/17] Test: pass the trust level to DocState::new in the subtotal filter test --- crates/engine/tests/subtotal-filter-roundtrip.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/subtotal-filter-roundtrip.rs b/crates/engine/tests/subtotal-filter-roundtrip.rs index 6fcc09fd07..83987f8268 100644 --- a/crates/engine/tests/subtotal-filter-roundtrip.rs +++ b/crates/engine/tests/subtotal-filter-roundtrip.rs @@ -115,7 +115,7 @@ fn filtering_a_reopened_table_again_keeps_both_criteria() { s.execute("data.filterBy", json!({"column":"A","values":["a","c","e","f"]})).unwrap(); let back = reopened(wb(&s)); let mut s = Session::new(); - s.add_document(gridcraft_engine::DocState::new(back, None, "t".into())); + s.add_document(gridcraft_engine::DocState::new(back, None, "t".into(), gridcraft_engine::Trust::FromFile)); s.execute("selection.set", json!({"cell":"A2"})).unwrap(); s.execute("data.filterBy", json!({"column":"B","custom":{"op":">","value":"50"}})).unwrap(); let sh = wb(&s).active().unwrap(); From 214ad973720ad58d42ada39a97f4f0c1c560d473 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:55:24 -0500 Subject: [PATCH 04/17] Test: a partial sheet filter folds into the table column it filters --- crates/xlsx/src/tests/roundtrip.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 5b79438dbb..bd53c22c85 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -1418,9 +1418,9 @@ fn a_table_filter_criteria_survive_a_round_trip() { assert!(b.autofilter.is_none(), "a table's filter belongs to the table part, not the sheet"); } -/// Stored `colId` offsets are relative to the filter range's first column, so criteria of a filter -/// that starts right of the table's first column must not be folded into the table part, where -/// they would apply to the wrong column. +/// Stored `colId` offsets are relative to the table's first column, so criteria of a sheet filter +/// that starts right of the table's first column are moved to the column they filter (Region), not +/// kept at the filter's own offset (which would be Id). #[test] fn a_partial_sheet_filter_is_not_folded_into_a_table() { let mut wb = Workbook::new(); @@ -1454,6 +1454,10 @@ fn a_partial_sheet_filter_is_not_folded_into_a_table() { assert!(rep.warnings.is_empty(), "{:?}", rep.warnings); let b = back.sheet(0).unwrap(); let t = b.tables.first().expect("the table survived"); - assert!(t.filter.is_empty(), "the criteria landed on the wrong table column: {:?}", t.filter); + assert!( + matches!(t.filter.as_slice(), [(1, FilterCriterion::Values { values, .. })] if values == &["East".to_string()]), + "the criteria landed on the wrong table column: {:?}", + t.filter + ); assert!(b.autofilter.is_none(), "a sheet filter inside a table would be invalid"); } From 2d65676f5d4375fa73e6169d05155fccc2b21846 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:04:44 -0500 Subject: [PATCH 05/17] Filter: bound a table-header filter by the table, refuse a narrower range that would drop criteria, fail the test helper on errors --- crates/engine/src/cmd/data.rs | 14 ++++++++++---- crates/engine/tests/subtotal-filter-roundtrip.rs | 14 +++++++++++++- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index 944323e41a..38c3f0ccad 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -552,10 +552,9 @@ fn install_filter(s: &mut Session, p: &Json) -> Result { } // A selected header row filters the data below it (#201). if p.get("range").is_none() && r.height() == 1 { - let region = if sh.table_at(r.start).is_some() { - current_region(sh, r.start) - } else { - crate::selection::current_region_outside_tables(sh, r.start) + let region = match sh.table_at(r.start) { + Some(t) => t.data_range().map(|dr| RangeRef::new(t.range.start, dr.end)).unwrap_or(t.range), + None => crate::selection::current_region_outside_tables(sh, r.start), }; if region.end.row > r.end.row { r = RangeRef::new(r.start, CellRef::new(region.end.row, r.end.col)); @@ -569,6 +568,13 @@ fn install_filter(s: &mut Session, p: &Json) -> Result { if host.is_none() && sh.tables.iter().any(|t| t.range.intersects(&r)) { return Err(bad("data.filter", "a filter range can't overlap a table; filter inside the table instead")); } + // A narrower range would leave out the table's criteria on the columns it doesn't cover, and saving would drop them. + if let Some(t) = host.and_then(|i| sh.tables.get(i)) { + let shift = r.start.col.saturating_sub(t.range.start.col); + if t.filter.iter().any(|(o, _)| o.checked_sub(shift).is_none_or(|c| c >= r.width())) { + return Err(bad("data.filter", "the table is filtered on a column this range leaves out; filter the table's full width")); + } + } edit(s, |cx| { let sh = cx.sheet_mut(sheet)?; let mut criteria = vec![]; diff --git a/crates/engine/tests/subtotal-filter-roundtrip.rs b/crates/engine/tests/subtotal-filter-roundtrip.rs index 83987f8268..3f02b7606e 100644 --- a/crates/engine/tests/subtotal-filter-roundtrip.rs +++ b/crates/engine/tests/subtotal-filter-roundtrip.rs @@ -34,7 +34,7 @@ fn session(sample: &str, steps: &[(&str, Json)]) -> Session { let mut s = Session::new(); s.execute("file.new", json!({"sample": sample})).unwrap(); for (id, p) in steps { - let _ = s.execute(id, p.clone()); + s.execute(id, p.clone()).unwrap(); } s } @@ -109,6 +109,18 @@ fn rows_hidden_by_hand_without_a_filter_still_count_for_subtotal_9() { assert_eq!(e1_e2(&back), (Value::Number(111111.0), Value::Number(110101.0))); } +#[test] +fn a_narrower_range_inside_a_filtered_table_is_refused_not_dropped() { + let mut s = table_book(); + s.execute("data.filterBy", json!({"column":"A","values":["a"]})).unwrap(); + let back = reopened(wb(&s)); + let mut s = Session::new(); + s.add_document(gridcraft_engine::DocState::new(back, None, "t".into(), gridcraft_engine::Trust::FromFile)); + s.execute("selection.set", json!({"cell":"D1"})).unwrap(); + assert!(s.execute("data.filter", json!({"range":"B1:B7"})).is_err()); + assert_eq!(wb(&s).active().unwrap().tables[0].filter.len(), 1, "the table's criteria are kept"); +} + #[test] fn filtering_a_reopened_table_again_keeps_both_criteria() { let mut s = table_book(); From b97c27f2b310851db54be7a44c76d757c9e13ca0 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:10:53 -0500 Subject: [PATCH 06/17] Test: the repro helper tolerates refused steps again, with the reason in a comment --- crates/engine/tests/subtotal-filter-roundtrip.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/tests/subtotal-filter-roundtrip.rs b/crates/engine/tests/subtotal-filter-roundtrip.rs index 3f02b7606e..4046713e17 100644 --- a/crates/engine/tests/subtotal-filter-roundtrip.rs +++ b/crates/engine/tests/subtotal-filter-roundtrip.rs @@ -34,7 +34,8 @@ fn session(sample: &str, steps: &[(&str, Json)]) -> Session { let mut s = Session::new(); s.execute("file.new", json!({"sample": sample})).unwrap(); for (id, p) in steps { - s.execute(id, p.clone()).unwrap(); + // A refused step leaves the book as it was; the asserts check what survives. + let _ = s.execute(id, p.clone()); } s } From 0b31398c0d359afc539cd28f2a2a2a3bda173ab0 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:20:32 -0500 Subject: [PATCH 07/17] Filter: a table filter must reach the table's last data row, and the table part keeps only such filters --- crates/engine/src/cmd/data/filter.rs | 3 +++ crates/xlsx/src/sheet_write/parts.rs | 8 ++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index 59643755b5..f56f9252b4 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -75,6 +75,9 @@ fn install_filter(s: &mut Session, p: &Json) -> Result { } // A narrower range would leave out the table's criteria on the columns it doesn't cover, and saving would drop them. if let Some(t) = host.and_then(|i| sh.tables.get(i)) { + if t.data_range().is_some_and(|data| r.end.row < data.end.row) { + return Err(bad("data.filter", "filter the table's full data range")); + } let shift = r.start.col.saturating_sub(t.range.start.col); if t.filter.iter().any(|(o, _)| o.checked_sub(shift).is_none_or(|c| c >= r.width())) { return Err(bad("data.filter", "the table is filtered on a column this range leaves out; filter the table's full width")); diff --git a/crates/xlsx/src/sheet_write/parts.rs b/crates/xlsx/src/sheet_write/parts.rs index 579733d6c3..87e0184655 100644 --- a/crates/xlsx/src/sheet_write/parts.rs +++ b/crates/xlsx/src/sheet_write/parts.rs @@ -107,8 +107,12 @@ pub(super) fn autofilter_xml(range: RangeRef, criteria: &[(u32, FilterCriterion) /// as rows hidden by hand, which SUBTOTAL 1-11 counts. pub(super) fn table_filter(sheet: &Sheet, t: &Table) -> Vec<(u32, FilterCriterion)> { let mut criteria = t.filter.clone(); - let Some(af) = sheet.autofilter.as_ref().filter(|af| t.header_row && af.range.start.row == t.range.start.row && af.range.intersects(&t.range)) - else { + let Some(af) = sheet.autofilter.as_ref().filter(|af| { + t.header_row + && af.range.start.row == t.range.start.row + && af.range.intersects(&t.range) + && t.data_range().is_some_and(|d| af.range.end.row >= d.end.row) + }) else { return criteria; }; for (off, c) in &af.criteria { From 2e1a744c6cfbbc4c7799a19727c0712390cd4d27 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:24:32 -0500 Subject: [PATCH 08/17] Filter: turning a table's filter buttons off also drops the sheet AutoFilter on it, and a disabled table filter saves no criteria --- crates/engine/src/cmd/data/filter.rs | 12 ++++++++++++ crates/xlsx/src/sheet_write/parts.rs | 3 ++- crates/xlsx/src/tests/tablefilter.rs | 12 ++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index f56f9252b4..6d8c6ea95f 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -13,10 +13,22 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result { if let Some(name) = in_table { return edit(s, |cx| { let sh = cx.sheet_mut(sheet)?; + let filtered: Vec = sh.rows.keys().copied().filter(|r| sh.is_row_filtered(*r)).collect(); + let mut cleared = false; if let Some(t) = sh.tables.iter_mut().find(|t| t.name == name) { t.filter_button = !t.filter_button; if !t.filter_button { t.filter.clear(); + // The sheet AutoFilter hosted on this table's header row is the table's filter too. + cleared = sh.autofilter.as_ref().is_some_and(|af| af.range.start.row == t.range.start.row && af.range.intersects(&t.range)); + } + } + if cleared { + sh.autofilter = None; + for r in filtered { + if let Some(info) = sh.rows.get_mut(&r) { + info.hidden = false; + } } } Ok(Json::Null) diff --git a/crates/xlsx/src/sheet_write/parts.rs b/crates/xlsx/src/sheet_write/parts.rs index 87e0184655..eb348df707 100644 --- a/crates/xlsx/src/sheet_write/parts.rs +++ b/crates/xlsx/src/sheet_write/parts.rs @@ -109,6 +109,7 @@ pub(super) fn table_filter(sheet: &Sheet, t: &Table) -> Vec<(u32, FilterCriterio let mut criteria = t.filter.clone(); let Some(af) = sheet.autofilter.as_ref().filter(|af| { t.header_row + && t.filter_button && af.range.start.row == t.range.start.row && af.range.intersects(&t.range) && t.data_range().is_some_and(|d| af.range.end.row >= d.end.row) @@ -144,7 +145,7 @@ pub(super) fn table_xml(t: &Table, cols: &[String], name: &str, id: u32, filter: let _ = write!(s, " connectionId=\"{c}\""); } s.push('>'); - if t.header_row && (t.filter_button || !filter.is_empty()) { + if t.header_row && t.filter_button { let end_row = if t.totals_row { t.range.end.row.saturating_sub(1).max(t.range.start.row) } else { t.range.end.row }; let r = RangeRef::new(t.range.start, CellRef::new(end_row, t.range.end.col)); s.push_str(&autofilter_xml(r, filter, out)); diff --git a/crates/xlsx/src/tests/tablefilter.rs b/crates/xlsx/src/tests/tablefilter.rs index 784361b7fd..e8e9ff906d 100644 --- a/crates/xlsx/src/tests/tablefilter.rs +++ b/crates/xlsx/src/tests/tablefilter.rs @@ -100,3 +100,15 @@ fn sheet_autofilter_not_on_the_header_row_is_not_folded() { let cols: Vec = s.tables[0].filter.iter().map(|(c, _)| *c).collect(); assert_eq!(cols, [1], "only the table's own criterion"); } + +#[test] +fn disabled_table_filter_saves_no_autofilter_criteria() { + let mut wb = filtered("B2:C6", 0); + if let Some(t) = wb.sheet_mut(0).unwrap().tables.first_mut() { + t.filter_button = false; + t.filter.clear(); + } + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + let t = &back.sheet(0).unwrap().tables[0]; + assert!(!t.filter_button && t.filter.is_empty(), "{:?}", t.filter); +} From be8efa6d0bb49abebacda982a0dbbf177f1cf7d9 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:46:18 -0500 Subject: [PATCH 09/17] Filter: turning a table's filter off keeps rows another table's criteria still hide --- crates/engine/src/cmd/data/filter.rs | 5 +++- .../tests/it/subtotal_filter_roundtrip.rs | 23 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index 6d8c6ea95f..abfc70cdce 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -26,7 +26,10 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result { if cleared { sh.autofilter = None; for r in filtered { - if let Some(info) = sh.rows.get_mut(&r) { + // Rows another table's criteria still hide stay hidden. + if !sh.is_row_filtered(r) + && let Some(info) = sh.rows.get_mut(&r) + { info.hidden = false; } } diff --git a/crates/engine/tests/it/subtotal_filter_roundtrip.rs b/crates/engine/tests/it/subtotal_filter_roundtrip.rs index 4046713e17..14faa27262 100644 --- a/crates/engine/tests/it/subtotal_filter_roundtrip.rs +++ b/crates/engine/tests/it/subtotal_filter_roundtrip.rs @@ -164,3 +164,26 @@ fn a_sheet_filter_from_outside_a_table_leaves_the_table_out() { assert!(s.execute("data.filter", json!({"range":"A1:C8"})).is_err()); assert!(wb(&s).active().unwrap().autofilter.is_none()); } + +#[test] +fn turning_a_table_filter_off_keeps_rows_another_table_still_hides() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range":"A1","values":[["K","V"],["k1",1],["k2",2],["k3",3],["k4",4],["k5",5]]})).unwrap(); + s.execute("range.setValues", json!({"range":"D1","values":[["X","Y"],["x1",1],["x2",2],["x3",3],["x4",4],["x5",5]]})).unwrap(); + s.execute("insert.table", json!({"range":"A1:B6","header":true})).unwrap(); + s.execute("insert.table", json!({"range":"D1:E6","header":true})).unwrap(); + // The second table's criteria are saved with it, so both tables hold a filter after reopening. + s.execute("selection.set", json!({"cell":"D2"})).unwrap(); + s.execute("data.filterBy", json!({"column":"D","values":["x1","x2"]})).unwrap(); + let mut s2 = Session::new(); + s2.add_document(gridcraft_engine::DocState::new(reopened(wb(&s)), None, "t".into(), gridcraft_engine::Trust::FromFile)); + s2.execute("selection.set", json!({"cell":"A2"})).unwrap(); + s2.execute("data.filterBy", json!({"column":"A","values":["k1"]})).unwrap(); + s2.execute("data.filter", json!({})).unwrap(); + let sh = wb(&s2).active().unwrap(); + assert!(!sh.is_row_hidden(2), "only the first table hid row 3"); + for row in 3..6 { + assert!(sh.is_row_hidden(row), "row {} is still filtered out of the second table", row + 1); + } +} From a2e3f265c0953b2f5b2048181d077172f363b222 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:12:04 -0500 Subject: [PATCH 10/17] Filter: turning a table's filter off re-evaluates the criteria of the tables that keep one --- crates/engine/src/cmd/data/filter.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index abfc70cdce..64cb958f7b 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -26,13 +26,23 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result { if cleared { sh.autofilter = None; for r in filtered { - // Rows another table's criteria still hide stay hidden. - if !sh.is_row_filtered(r) - && let Some(info) = sh.rows.get_mut(&r) - { + if let Some(info) = sh.rows.get_mut(&r) { info.hidden = false; } } + // Rows another table's criteria hide stay hidden: evaluate each such table's + // saved criteria through the live filter, then take the filter off again. + let others: Vec<(RangeRef, Vec<(u32, FilterCriterion)>)> = + sh.tables.iter().filter(|t| !t.filter.is_empty()).map(|t| (t.range, t.filter.clone())).collect(); + for (range, criteria) in others { + if let Some(sh) = cx.wb.sheet_mut(sheet) { + sh.autofilter = Some(AutoFilter { range, criteria }); + } + apply_filter(&mut cx.wb, sheet); + } + if let Some(sh) = cx.wb.sheet_mut(sheet) { + sh.autofilter = None; + } } Ok(Json::Null) }); From f3c214b2dd7d3a30363a91785127940a4d493ffb Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:23:24 -0500 Subject: [PATCH 11/17] Filter: turning a table's filter off hides the union of the other tables' excluded rows and recalculates --- crates/engine/src/cmd/data/filter.rs | 13 ++++++-- .../tests/it/subtotal_filter_roundtrip.rs | 31 +++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index 64cb958f7b..f1214d61b6 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -30,19 +30,28 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result { info.hidden = false; } } - // Rows another table's criteria hide stay hidden: evaluate each such table's - // saved criteria through the live filter, then take the filter off again. + // Rows another table's criteria hide stay hidden: evaluate each such table's saved + // criteria through the live filter, then hide the union once (a later table would + // unhide what an earlier one excluded) and take the filter off again. let others: Vec<(RangeRef, Vec<(u32, FilterCriterion)>)> = sh.tables.iter().filter(|t| !t.filter.is_empty()).map(|t| (t.range, t.filter.clone())).collect(); + let mut excluded: std::collections::HashSet = std::collections::HashSet::new(); for (range, criteria) in others { if let Some(sh) = cx.wb.sheet_mut(sheet) { sh.autofilter = Some(AutoFilter { range, criteria }); } apply_filter(&mut cx.wb, sheet); + if let Some(sh) = cx.wb.sheet(sheet) { + excluded.extend((range.start.row.saturating_add(1)..=range.end.row).filter(|r| sh.is_row_hidden(*r))); + } } if let Some(sh) = cx.wb.sheet_mut(sheet) { sh.autofilter = None; + for r in excluded { + sh.rows.entry(r).or_default().hidden = true; + } } + cx.structural = true; } Ok(Json::Null) }); diff --git a/crates/engine/tests/it/subtotal_filter_roundtrip.rs b/crates/engine/tests/it/subtotal_filter_roundtrip.rs index 14faa27262..54931640f9 100644 --- a/crates/engine/tests/it/subtotal_filter_roundtrip.rs +++ b/crates/engine/tests/it/subtotal_filter_roundtrip.rs @@ -187,3 +187,34 @@ fn turning_a_table_filter_off_keeps_rows_another_table_still_hides() { assert!(sh.is_row_hidden(row), "row {} is still filtered out of the second table", row + 1); } } + +#[test] +fn turning_a_table_filter_off_hides_the_rows_of_all_other_filtered_tables() { + let mut s = Session::new(); + s.new_workbook(); + for (col, keys) in [("A", "k"), ("D", "x"), ("G", "z")] { + let rows: Vec = (1..=5).map(|n| json!([format!("{keys}{n}"), n])).collect(); + s.execute("range.setValues", json!({"range": format!("{col}1"), "values": [json!(["K", "V"])].into_iter().chain(rows).collect::>()})) + .unwrap(); + } + for range in ["A1:B6", "D1:E6", "G1:H6"] { + s.execute("insert.table", json!({"range": range, "header": true})).unwrap(); + } + // Each filtered table's criteria are saved with it: reopening leaves both holding a filter. + s.execute("selection.set", json!({"cell":"D2"})).unwrap(); + s.execute("data.filterBy", json!({"column":"D","values":["x1","x2"]})).unwrap(); + let mut s2 = Session::new(); + s2.add_document(gridcraft_engine::DocState::new(reopened(wb(&s)), None, "t".into(), gridcraft_engine::Trust::FromFile)); + s2.execute("selection.set", json!({"cell":"G2"})).unwrap(); + s2.execute("data.filterBy", json!({"column":"G","values":["z1","z3"]})).unwrap(); + let mut s3 = Session::new(); + s3.add_document(gridcraft_engine::DocState::new(reopened(wb(&s2)), None, "t".into(), gridcraft_engine::Trust::FromFile)); + s3.execute("selection.set", json!({"cell":"A2"})).unwrap(); + s3.execute("data.filterBy", json!({"column":"A","values":["k1"]})).unwrap(); + s3.execute("data.filter", json!({})).unwrap(); + let sh = wb(&s3).active().unwrap(); + assert!(!sh.is_row_hidden(1)); + for row in 2..6 { + assert!(sh.is_row_hidden(row), "row {} is excluded by one of the two other tables", row + 1); + } +} From 7b83509a93b27c3efd4be44598545d3dbd8e741a Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:28:43 -0500 Subject: [PATCH 12/17] Filter test: build the table rows outside json! so the test compiles --- crates/engine/tests/it/subtotal_filter_roundtrip.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/tests/it/subtotal_filter_roundtrip.rs b/crates/engine/tests/it/subtotal_filter_roundtrip.rs index 54931640f9..ddc868701a 100644 --- a/crates/engine/tests/it/subtotal_filter_roundtrip.rs +++ b/crates/engine/tests/it/subtotal_filter_roundtrip.rs @@ -193,9 +193,9 @@ fn turning_a_table_filter_off_hides_the_rows_of_all_other_filtered_tables() { let mut s = Session::new(); s.new_workbook(); for (col, keys) in [("A", "k"), ("D", "x"), ("G", "z")] { - let rows: Vec = (1..=5).map(|n| json!([format!("{keys}{n}"), n])).collect(); - s.execute("range.setValues", json!({"range": format!("{col}1"), "values": [json!(["K", "V"])].into_iter().chain(rows).collect::>()})) - .unwrap(); + let mut values = vec![json!(["K", "V"])]; + values.extend((1..=5).map(|n| json!([format!("{keys}{n}"), n]))); + s.execute("range.setValues", json!({"range": format!("{col}1"), "values": values})).unwrap(); } for range in ["A1:B6", "D1:E6", "G1:H6"] { s.execute("insert.table", json!({"range": range, "header": true})).unwrap(); From dbacb4cc80ebe27eafd67c44528eb01b52c3887f Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:33:24 -0500 Subject: [PATCH 13/17] Filter: refuse a partial range over the active table; filtering a table re-enables its buttons --- crates/engine/src/cmd/data/filter.rs | 15 ++++++++++++++ .../tests/it/subtotal_filter_roundtrip.rs | 20 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index f1214d61b6..641314ceb8 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -11,6 +11,19 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result { let has = s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.autofilter.is_some()); let in_table = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.table_at(at).map(|t| t.name.clone())); if let Some(name) = in_table { + // An explicit range over part of the table is refused, as when installing a filter on it. + if p.get("range").is_some() + && let Some(sh) = s.doc()?.wb.sheet(sheet) + && let Some(t) = sh.tables.iter().find(|t| t.name == name) + && t.range.intersects(&r) + && !(t.header_row + && t.range.start.row == r.start.row + && t.range.contains(r.start) + && t.range.contains(r.end) + && t.data_range().is_none_or(|data| r.end.row >= data.end.row)) + { + return Err(bad("data.filter", "a filter range can't overlap a table; filter inside the table instead")); + } return edit(s, |cx| { let sh = cx.sheet_mut(sheet)?; let filtered: Vec = sh.rows.keys().copied().filter(|r| sh.is_row_filtered(*r)).collect(); @@ -121,6 +134,8 @@ fn install_filter(s: &mut Session, p: &Json) -> Result { let sh = cx.sheet_mut(sheet)?; let mut criteria = vec![]; if let Some(t) = host.and_then(|i| sh.tables.get_mut(i)) { + // The criteria are saved with the table only while its filter buttons are on. + t.filter_button = true; let shift = r.start.col.saturating_sub(t.range.start.col); criteria = std::mem::take(&mut t.filter).into_iter().filter_map(|(o, c)| Some((o.checked_sub(shift)?, c))).collect(); } diff --git a/crates/engine/tests/it/subtotal_filter_roundtrip.rs b/crates/engine/tests/it/subtotal_filter_roundtrip.rs index 54931640f9..f3379959b4 100644 --- a/crates/engine/tests/it/subtotal_filter_roundtrip.rs +++ b/crates/engine/tests/it/subtotal_filter_roundtrip.rs @@ -218,3 +218,23 @@ fn turning_a_table_filter_off_hides_the_rows_of_all_other_filtered_tables() { assert!(sh.is_row_hidden(row), "row {} is excluded by one of the two other tables", row + 1); } } + +#[test] +fn filtering_a_table_whose_buttons_were_turned_off_turns_them_back_on() { + let mut s = table_book(); + s.execute("data.filter", json!({})).unwrap(); + assert!(!wb(&s).active().unwrap().tables[0].filter_button); + s.execute("data.filterBy", json!({"column":"A","values":["a"]})).unwrap(); + assert!(wb(&s).active().unwrap().tables[0].filter_button); + let back = reopened(wb(&s)); + assert_eq!(back.active().unwrap().tables[0].filter.len(), 1, "the criteria are saved with the table"); +} + +#[test] +fn a_partial_range_inside_the_active_table_is_refused_not_a_toggle() { + let mut s = table_book(); + s.execute("data.filterBy", json!({"column":"A","values":["a"]})).unwrap(); + assert!(s.execute("data.filter", json!({"range":"B1:B7"})).is_err()); + let sh = wb(&s).active().unwrap(); + assert!(sh.tables[0].filter_button && sh.autofilter.is_some(), "the filter is untouched"); +} From cf17534e7bb85041b5f10098aefcfa0623b97f68 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:47:30 -0500 Subject: [PATCH 14/17] Filter test: the sheet-prefix table toggle names the whole table, as a partial range over a table is refused --- crates/engine/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 13fbb9b3a4..b82dc1d91e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1501,7 +1501,7 @@ fn filter_with_a_sheet_prefix_toggles_the_table_at_the_range() { wb.sheet(wb.sheet_index("Prices").unwrap()).unwrap().clone() }; assert!(prices(&s).tables[0].filter_button); - s.execute("data.filter", json!({"range": "Prices!A2:B3"})).unwrap(); + s.execute("data.filter", json!({"range": "Prices!A1:B3"})).unwrap(); assert!(!prices(&s).tables[0].filter_button); assert!(prices(&s).autofilter.is_none()); assert!(s.doc().unwrap().wb.active().unwrap().autofilter.is_none()); From cc3858a394e14d78d88e1a64d65bbf5a6d8a1d7c Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:01:50 -0500 Subject: [PATCH 15/17] Filter: a range over only some of the active table's columns is refused too --- crates/engine/src/cmd/data/filter.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index 641314ceb8..4bdbbe22fa 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -20,6 +20,8 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result { && t.range.start.row == r.start.row && t.range.contains(r.start) && t.range.contains(r.end) + && r.start.col == t.range.start.col + && r.end.col == t.range.end.col && t.data_range().is_none_or(|data| r.end.row >= data.end.row)) { return Err(bad("data.filter", "a filter range can't overlap a table; filter inside the table instead")); From 2295cc71c65768d20bc6c944e169264a66d16178 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Wed, 28 Oct 2026 11:51:45 -0500 Subject: [PATCH 16/17] Remove unused filter region import --- crates/engine/src/cmd/data/filter.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index 74d3456396..8efc2d6d92 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -1,7 +1,7 @@ use super::sort::sort_key; use super::{ AutoFilter, CellRef, EngineError, FilterCriterion, Json, Ordering, RangeRef, Result, Session, Sheet, Value, Workbook, bad, bool_param, col_param, - current_region, data_target, edit, json, + data_target, edit, json, }; // ---------------------------------------------------------------- filter From 25715e77c313f336fdc031729dbe2f0979116b5d Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:52:47 -0600 Subject: [PATCH 17/17] Format filtered table selection helper --- crates/engine/src/selection.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/engine/src/selection.rs b/crates/engine/src/selection.rs index afefb01010..ab40996447 100644 --- a/crates/engine/src/selection.rs +++ b/crates/engine/src/selection.rs @@ -249,9 +249,7 @@ pub fn current_region_outside_tables(sheet: &Sheet, c: CellRef) -> RangeRef { /// The current region around `c`, counting only filled cells that `counts` accepts. fn region_where(sheet: &Sheet, c: CellRef, counts: impl Fn(CellRef) -> bool) -> RangeRef { - let filled = |c: CellRef| { - (sheet.cell(c).is_some_and(gridcraft_model::Cell::has_content) || sheet.spill.contains_key(&c)) && counts(c) - }; + let filled = |c: CellRef| (sheet.cell(c).is_some_and(gridcraft_model::Cell::has_content) || sheet.spill.contains_key(&c)) && counts(c); // Whether a row (or column) has a filled cell between two columns (rows), inclusive. let row_has = |row: u32, a: u32, b: u32| (a..=b).any(|col| filled(CellRef::new(row, col))); let col_has = |col: u32, a: u32, b: u32| (a..=b).any(|row| filled(CellRef::new(row, col)));