diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index c76701ad1d..18688e7412 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -3,6 +3,7 @@ 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, }; +use std::collections::{HashMap, HashSet}; // ---------------------------------------------------------------- filter @@ -181,14 +182,11 @@ pub(crate) fn grow_autofilter(sh: &mut Sheet, at: CellRef) { } /// Statistics use the original range, regardless of the other active criteria. -fn filter_stats(sh: &Sheet, af: &AutoFilter, excluded_offset: Option) -> std::collections::HashMap, f64)> { +fn filter_stats(sh: &Sheet, af: &AutoFilter) -> HashMap, f64)> { let r = af.range; // Precompute per-criterion top10 threshold and average once, not per row. - let mut col_stats: std::collections::HashMap, f64)> = std::collections::HashMap::new(); + let mut col_stats = HashMap::new(); for (i, (off, c)) in af.criteria.iter().enumerate() { - if Some(*off) == excluded_offset { - continue; - } if matches!(c, FilterCriterion::Top10 { .. } | FilterCriterion::AboveAverage(_)) { let Some(col) = r.start.col.checked_add(*off) else { continue }; let mut nums: Vec = (r.start.row + 1..=r.end.row).filter_map(|row| sh.value(CellRef::new(row, col)).as_f64()).collect(); @@ -208,29 +206,46 @@ fn filter_stats(sh: &Sheet, af: &AutoFilter, excluded_offset: Option) -> st col_stats } -/// Evaluate criteria directly, without conflating manual visibility with filter results. -fn filter_row_matches( - wb: &Workbook, - sh: &Sheet, - af: &AutoFilter, - row: u32, - col_stats: &std::collections::HashMap, f64)>, - excluded_offset: Option, -) -> bool { - for (i, (off, crit)) in af.criteria.iter().enumerate() { - if Some(*off) == excluded_offset { - continue; - } - let Some(col) = af.range.start.col.checked_add(*off) else { continue }; +/// Shared row and checkbox matching, with thresholds and Values lookups prepared once per query. +struct FilterMatcher<'a> { + wb: &'a Workbook, + sh: &'a Sheet, + af: &'a AutoFilter, + stats: HashMap, f64)>, + values: HashMap>, +} + +impl<'a> FilterMatcher<'a> { + fn new(wb: &'a Workbook, sh: &'a Sheet, af: &'a AutoFilter) -> Self { + let values = af + .criteria + .iter() + .enumerate() + .filter_map(|(i, (_, crit))| match crit { + FilterCriterion::Values { values, .. } => Some((i, values.iter().map(|v| v.to_ascii_lowercase()).collect())), + _ => None, + }) + .collect(); + Self { wb, sh, af, stats: filter_stats(sh, af), values } + } + + fn row_matches(&self, row: u32, excluded_offset: Option) -> bool { + self.af.criteria.iter().enumerate().all(|(i, (off, crit))| Some(*off) == excluded_offset || self.criterion_matches(row, i, *off, crit)) + } + + fn criterion_matches(&self, row: u32, i: usize, off: u32, crit: &FilterCriterion) -> bool { + let Some(col) = self.af.range.start.col.checked_add(off) else { return true }; let c = CellRef::new(row, col); - let v = sh.value(c); - let text = crate::display::cell_text(wb, sh, c); - let ok = match crit { - FilterCriterion::Values { values, blanks } => { + let v = self.sh.value(c); + let text = crate::display::cell_text(self.wb, self.sh, c); + match crit { + FilterCriterion::Values { blanks, .. } => { if filter_blank(&v) { *blanks } else { - values.iter().any(|x| x.eq_ignore_ascii_case(&text) || x.eq_ignore_ascii_case(&v.display())) + self.values + .get(&i) + .is_some_and(|values| values.contains(&text.to_ascii_lowercase()) || values.contains(&v.display().to_ascii_lowercase())) } } FilterCriterion::Custom { a, b, and } => { @@ -243,14 +258,14 @@ fn filter_row_matches( None => x, } } - FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), col_stats.get(&i)) { + FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), self.stats.get(&i)) { (Some(n), Some((thr, _))) => { let thr = thr.unwrap_or(n); if *bottom { n <= thr } else { n >= thr } } _ => false, }, - FilterCriterion::AboveAverage(above) => match (v.as_f64(), col_stats.get(&i)) { + FilterCriterion::AboveAverage(above) => match (v.as_f64(), self.stats.get(&i)) { (Some(n), Some((_, avg))) => { if *above { n > *avg @@ -260,16 +275,12 @@ fn filter_row_matches( } _ => false, }, - FilterCriterion::FillColor(col) => wb.styles.get(sh.style_id(c)).fill.fg == *col, - FilterCriterion::FontColor(col) => wb.styles.get(sh.style_id(c)).font.color == *col, + FilterCriterion::FillColor(col) => self.wb.styles.get(self.sh.style_id(c)).fill.fg == *col, + FilterCriterion::FontColor(col) => self.wb.styles.get(self.sh.style_id(c)).font.color == *col, // Icon criteria are retained from files but cannot be evaluated yet. FilterCriterion::Icon { .. } => true, - }; - if !ok { - return false; } } - true } /// Hides rows of the autofilter range that fail any criterion. @@ -277,12 +288,11 @@ pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) { let Some(sh) = wb.sheet(sheet) else { return }; let Some(af) = sh.autofilter.clone() else { return }; let r = af.range; - let col_stats = filter_stats(sh, &af, None); + let matcher = FilterMatcher::new(wb, sh, &af); // Reapplying a retained icon filter preserves visibility until icons can be evaluated. let has_icon = af.criteria.iter().any(|(_, c)| matches!(c, FilterCriterion::Icon { .. })); - let hide: Vec<_> = (r.start.row + 1..=r.end.row) - .map(|row| (row, !filter_row_matches(wb, sh, &af, row, &col_stats, None) || (has_icon && sh.is_row_hidden(row)))) - .collect(); + let hide: Vec<_> = + (r.start.row + 1..=r.end.row).map(|row| (row, !matcher.row_matches(row, None) || (has_icon && sh.is_row_hidden(row)))).collect(); let Some(shm) = wb.sheet_mut(sheet) else { return }; for (row, h) in hide { if h { @@ -345,27 +355,18 @@ fn column_filter_values(wb: &Workbook, sheet: usize, col: u32, eligible_only: bo return vec![]; } let off = col - af.range.start.col; - let selected: Option<&FilterCriterion> = af.criteria.iter().find(|(o, _)| *o == off).map(|(_, c)| c); - let col_stats = if eligible_only { filter_stats(sh, af, Some(off)) } else { Default::default() }; + let selected = af.criteria.iter().enumerate().find(|(_, (o, _))| *o == off); + let matcher = FilterMatcher::new(wb, sh, af); let mut seen = std::collections::BTreeMap::new(); for row in af.range.start.row.saturating_add(1)..=af.range.end.row.min(af.range.start.row.saturating_add(1_000_000)) { - if eligible_only && !filter_row_matches(wb, sh, af, row, &col_stats, Some(off)) { + if eligible_only && !matcher.row_matches(row, Some(off)) { continue; } let c = CellRef::new(row, col); let v = sh.value(c); let blank = filter_blank(&v); let t = if blank { "(Blanks)".to_string() } else { crate::display::cell_text(wb, sh, c) }; - let on = match selected { - Some(FilterCriterion::Values { values, blanks }) => { - if blank { - *blanks - } else { - values.iter().any(|x| x.eq_ignore_ascii_case(&t)) - } - } - _ => true, - }; + let on = selected.is_none_or(|(i, (off, crit))| matcher.criterion_matches(row, i, *off, crit)); let key = if blank { sort_key(&Value::Empty) } else { sort_key(&v) }; seen.entry((key, t)).or_insert(on); } diff --git a/crates/engine/tests/it/cascading_filter_values.rs b/crates/engine/tests/it/cascading_filter_values.rs index 45346b39a1..345c4f4da5 100644 --- a/crates/engine/tests/it/cascading_filter_values.rs +++ b/crates/engine/tests/it/cascading_filter_values.rs @@ -63,14 +63,14 @@ fn slicer_criteria_outside_the_sheet_filters_columns_are_still_applied() { #[test] fn choices_use_the_same_custom_and_statistical_criteria_as_filtering() { - for (criterion, expected) in [ - (json!({"custom": {"op": ">=", "value": 20, "op2": "<", "value2": 100}}), vec!["mid", "upper"]), - (json!({"custom": {"op": "=", "value": 10, "op2": "=", "value2": 100, "and": false}}), vec!["high", "low"]), - (json!({"custom": {"op": "=", "value": "n?*"}}), vec!["text"]), - (json!({"top": {"count": 2}}), vec!["high", "upper"]), - (json!({"top": {"count": 50, "percent": true, "bottom": true}}), vec!["low", "mid"]), - (json!({"aboveAverage": true}), vec!["high"]), - (json!({"aboveAverage": false}), vec!["low", "mid", "upper"]), + for (criterion, expected, mid_checked) in [ + (json!({"custom": {"op": ">=", "value": 20, "op2": "<", "value2": 100}}), vec!["mid", "upper"], true), + (json!({"custom": {"op": "=", "value": 10, "op2": "=", "value2": 100, "and": false}}), vec!["high", "low"], false), + (json!({"custom": {"op": "=", "value": "n?*"}}), vec!["text"], false), + (json!({"top": {"count": 2}}), vec!["high", "upper"], false), + (json!({"top": {"count": 50, "percent": true, "bottom": true}}), vec!["low", "mid"], true), + (json!({"aboveAverage": true}), vec!["high"], false), + (json!({"aboveAverage": false}), vec!["low", "mid", "upper"], true), ] { let mut s = Session::new(); s.new_workbook(); @@ -93,8 +93,8 @@ fn choices_use_the_same_custom_and_statistical_criteria_as_filtering() { assert_eq!(actual, expected, "{criterion}, with the current column filtered"); assert_eq!( filter_values(&s.doc().unwrap().wb, 0, 1), - vec![("20".into(), true)], - "the numeric column's own criterion must be excluded: {criterion}" + vec![("20".into(), mid_checked)], + "the numeric column's criterion sets checkboxes without excluding alternatives: {criterion}" ); } } @@ -220,6 +220,7 @@ fn choices_match_color_criteria_and_do_not_infer_icon_matches_from_hidden_rows() sh.autofilter.as_mut().unwrap().criteria = vec![(1, criterion)]; s.execute("data.reapply", json!({})).unwrap(); assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("red".into(), true)]); + assert_eq!(filter_selection(&s.doc().unwrap().wb, 0, 1, &[]), vec![("1".into(), true), ("2".into(), false)]); } let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); sh.autofilter.as_mut().unwrap().criteria = vec![(1, FilterCriterion::Icon { set: "3Arrows".into(), id: Some(0) })]; @@ -283,3 +284,74 @@ fn choices_are_bounded_at_the_last_sheet_row_and_empty_for_missing_data() { s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap(); assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 2), vec![("Last East".into(), true)]); } + +#[test] +fn merging_hidden_choices_preserves_the_active_criterion() { + for (criterion, checked) in [ + (json!({"values": ["7"], "blanks": true}), [false, true, false, false, true]), + (json!({"custom": {"op": ">=", "value": 7}}), [false, true, true, true, false]), + (json!({"top": {"count": 2}}), [false, false, true, true, false]), + (json!({"aboveAverage": true}), [false, false, false, true, false]), + (json!({"aboveAverage": false}), [true, true, true, false, false]), + ] { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [["Region", "Amount"], ["East", 1], ["East", 9], ["West", 7], ["West", 20], ["West", null]]}), + ) + .unwrap(); + s.execute("home.numberFormat", json!({"range": "B2:B6", "code": "0.00"})).unwrap(); + s.execute("data.filter", json!({"range": "A1:B6"})).unwrap(); + s.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap(); + let mut params = criterion.clone(); + params["column"] = json!("B"); + s.execute("data.filterBy", params).unwrap(); + let doc = s.doc().unwrap(); + let choices = filter_values(&doc.wb, 0, 1); + let selection = filter_selection(&doc.wb, 0, 1, &choices); + let expected: Vec<_> = + ["1.00", "7.00", "9.00", "20.00", "(Blanks)"].into_iter().zip(checked).map(|(label, on)| (label.to_string(), on)).collect(); + assert_eq!(selection, expected, "unchanged eligible choices must preserve hidden matches: {criterion}"); + let values: Vec<_> = selection.iter().filter(|(label, on)| *on && label != "(Blanks)").map(|(label, _)| label.clone()).collect(); + s.execute("data.filterBy", json!({"column": "B", "values": values, "blanks": checked[4]})).unwrap(); + s.execute("data.filterBy", json!({"column": "A", "clear": true})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + for (row, on) in [checked[0], checked[2], checked[1], checked[3], checked[4]].into_iter().enumerate() { + assert_eq!(!sh.is_row_hidden(row as u32 + 1), on, "row after Apply and clearing the other filter: {criterion}"); + } + } +} + +#[test] +fn large_values_criteria_preserve_ascii_case_and_blank_matching() { + use gridcraft_engine::core::RangeRef; + use gridcraft_engine::model::AutoFilter; + let mut s = Session::new(); + s.new_workbook(); + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + let mut selected = Vec::new(); + for row in 1..=5_000 { + sh.set_cell(CellRef::new(row, 0), Cell { value: Value::Text(format!("item-{row}").into()), ..Default::default() }); + sh.set_cell(CellRef::new(row, 1), Cell { value: Value::Number(f64::from(row)), ..Default::default() }); + selected.push(format!("ITEM-{row}")); + } + selected.extend(["ITEM-1".into(), "Ä".into()]); + for (row, value, label) in [ + (5_001, Value::Text("Ä".into()), "unicode selected"), + (5_002, Value::Text("ä".into()), "unicode excluded"), + (5_003, Value::Empty, "blank row"), + ] { + sh.set_cell(CellRef::new(row, 0), Cell { value, ..Default::default() }); + sh.set_cell(CellRef::new(row, 1), Cell { value: Value::Text(label.into()), ..Default::default() }); + } + sh.autofilter = Some(AutoFilter { + range: RangeRef::new(CellRef::new(0, 0), CellRef::new(5_003, 1)), + criteria: vec![(0, FilterCriterion::Values { values: selected, blanks: true })], + }); + let choices = filter_values(&s.doc().unwrap().wb, 0, 1); + assert_eq!(choices.len(), 5_002); + assert!(choices.contains(&("unicode selected".into(), true))); + assert!(choices.contains(&("blank row".into(), true))); + assert!(!choices.iter().any(|(label, _)| label == "unicode excluded")); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c94ccb7550..eb86b356e7 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (cascading AutoFilter choices and pending popup selections per document window; form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (AutoFilter checkbox state follows the active criterion and Values lookups are prepared once per query; earlier: cascading AutoFilter choices and pending popup selections per document window; form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md). **UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured @@ -14,6 +14,7 @@ Sources: `crates/ui-egui/src` (ribbon, grid, editor, formula bar, dialogs, panes | Element | Excel | GridCraft | Status | |---|---|---|---| +| 2026-11-04 | minor | AutoFilter checkboxes and hidden-choice merging use the active row criterion, including raw/formatted Values, custom comparisons, Top 10, averages and colors; Values criteria use one prepared ASCII-insensitive lookup per query (#2641) | | 2026-10-14 | minor | Dialogs (Find and Replace, Go To, Format Cells, Sort and the rest) move by their title bar instead of staying pinned to the centre (#1250) | | Title bar, Quick Access Toolbar, AutoSave toggle | yes | yes | done; macOS window controls misaligned (#170), Dock icon size (#169) | | Ribbon: tabs, groups, split buttons, galleries, contextual tabs | yes | yes (Table Design, Chart Design, Format, PivotTable, Header & Footer tabs); Fill Color, Font Color and the Format Cells colour pickers end with Recent Colors and More Colors… (#928); large split buttons (Formulas › AutoSum); arrows at the card's edges scroll a tab wider than the window | done; missing contextual tabs for pictures, shapes, sparklines, slicers; groups do not collapse when narrow | @@ -86,6 +87,10 @@ this logic, with one undo step. describes additive column filters and restricting other dropdowns to the filtered range. The current column is excluded from enumeration so its unchecked alternatives remain available. The existing one-million-data-row enumeration limit and value sorting remain unchanged. +Checkbox state uses the row matcher for the active criterion, including raw and formatted +Values matches, custom comparisons, numeric thresholds and colors. Hidden choices retain +that state when Apply merges the eligible edits. Values criteria prepare ASCII-insensitive +lookup sets once per query rather than scanning every selected value for each row. This changes the population behind the pending row-count work (#1737, and its stacked Only button #1741): a future count beside a choice should count eligible rows satisfying the other @@ -287,7 +292,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | 2026-10-31 | minor | Esc in a File-page text field leaves the field and cancels editing; the next Esc returns to the sheet (#3035) | | 2026-10-31 | minor | Recently Used lists the functions most recently entered in a formula from any source, kept with the preferences; the Insert Function dialog is titled as in Excel, its category list (Most Recently Used, All, each category) works, and its category column follows the widest name shown | | 2026-10-31 | minor | Formulas › Function Library: Insert Function, the AutoSum split button and three columns of labelled small buttons with category colours; category menus end with Insert Function…; More Functions cascades; Home › Editing shares the AutoSum menu; MR key tip for Recently Used | -| 2026-10-30 | minor | AutoFilter choices cascade across other columns while retaining current-column alternatives and blanks (#2641); Apply without search preserves selected and excluded values and blanks hidden by other filters; searched Apply excludes hidden nonmatches while retaining hidden matches; document pending counts, date grouping and table roundtrip integration; retain slicer row filtering when its criterion is outside the sheet filter columns | +| 2026-10-30 | minor | AutoFilter choices cascade across other columns while retaining current-column alternatives and blanks (#2641); Apply without search preserves selected and excluded values and blanks hidden by other filters; searched Apply excludes hidden nonmatches while retaining hidden matches; documents pending counts, date grouping and table roundtrip integration; retains slicer row filtering when its criterion is outside the sheet filter columns | | 2026-10-30 | minor | Checkbox cells print and export to PDF as boxes, as on screen: unchecked white with a grey outline, checked green with a white tick (#2972). They printed their value as TRUE or FALSE; other values in a checkbox cell still print as text | | 2026-10-29 | minor | Formula pointing from the keyboard: Ctrl+arrow (⌘arrow) moves the pointed cell to the edge of its data and Ctrl+Shift+arrow (⌘⇧arrow) extends the pointed range there, as the same keys move and extend the selection, so typing `=COUNTIF(`, clicking the top of a column and pressing ⌘⇧↓ points at the whole column of data; the keys used to move or extend by one cell. A range reaching the sheet edge is written as whole columns or rows (`A:B`). The editor reads the modifiers of the arrow's own key event, so a keystroke pressed and released within one frame (a control client's `ui.key`, an automation tool) keeps its Shift and Ctrl | | 2026-10-29 | minor | Insert Hyperlink opens with an existing link's address, display text and ScreenTip (#2876). An address-only edit preserves the cell's content and formula; Cancel leaves the link unchanged, and Undo restores the edit |