diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index 143763a5e9..7aa0f3cbaf 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -33,7 +33,7 @@ use tools::split_delimited; use tools::{remove_duplicates, text_to_columns}; pub use validation::{check_validation, list_items}; use validation::{circle_invalid, validate_cmd, validation}; -pub(super) use validation::{move_rule_formula, remove_validation_cells}; +pub(super) use validation::{move_cf_rule, move_rule_formula, remove_cond_format_cells, remove_validation_cells}; pub fn specs() -> Vec { vec![ diff --git a/crates/engine/src/cmd/data/validation.rs b/crates/engine/src/cmd/data/validation.rs index ce0d7e3b8e..d858fbe0dd 100644 --- a/crates/engine/src/cmd/data/validation.rs +++ b/crates/engine/src/cmd/data/validation.rs @@ -1,3 +1,5 @@ +use gridcraft_model::{CfRule, CfValueKind}; + use super::{ Cell, CellRef, CfOperator, EngineError, ErrorStyle, Json, RangeRef, Result, Session, Validation, ValidationKind, Value, Workbook, bad, bool_param, cell_param, edit, json, ok, str_param, target_ranges, target_sheet, @@ -47,6 +49,16 @@ pub(in super::super) fn remove_validation_cells(validations: &mut Vec, cuts: &[RangeRef]) { + for cf in cond_formats.iter_mut() { + for cut in cuts { + cf.ranges = cf.ranges.iter().flat_map(|r| subtract_range(*r, cut)).collect(); + } + } + cond_formats.retain(|c| !c.ranges.is_empty()); +} + pub(super) fn validation(s: &mut Session, p: &Json) -> Result { let ranges = target_ranges(s, p)?; let sheet = target_sheet(s, p)?; @@ -248,6 +260,41 @@ pub(in super::super) fn move_rule_formula(f: &str, first: CellRef, to: CellRef) if has_relative { format!("{eq}{moved}") } else { f.to_string() } } +/// A conditional-format rule copied from a range anchored at `from` to one anchored at `to`: the +/// relative references in its formulas move with it. The flag says the rule holds formulas. +pub(in super::super) fn move_cf_rule(rule: &CfRule, from: CellRef, to: CellRef) -> (CfRule, bool) { + let formulas = std::cell::Cell::new(false); + let text = |f: &str| { + if f.trim_start().starts_with('=') { + formulas.set(true); + } + move_rule_formula(f, from, to) + }; + let kind = |k: &CfValueKind| match k { + CfValueKind::Formula(f) => { + formulas.set(true); + CfValueKind::Formula(move_rule_formula(f, from, to)) + } + other => other.clone(), + }; + let moved = match rule { + CfRule::CellIs { op, a, b, style } => CfRule::CellIs { op: *op, a: text(a), b: b.as_deref().map(text), style: style.clone() }, + CfRule::Expression { formula, style } => { + formulas.set(true); + CfRule::Expression { formula: move_rule_formula(formula, from, to), style: style.clone() } + } + CfRule::ColorScale { stops } => CfRule::ColorScale { stops: stops.iter().map(|(k, c)| (kind(k), *c)).collect() }, + CfRule::DataBar { min, max, color, gradient, show_value } => { + CfRule::DataBar { min: kind(min), max: kind(max), color: *color, gradient: *gradient, show_value: *show_value } + } + CfRule::IconSet { set, thresholds, reverse, show_value } => { + CfRule::IconSet { set: set.clone(), thresholds: thresholds.iter().map(kind).collect(), reverse: *reverse, show_value: *show_value } + } + other => other.clone(), + }; + (moved, formulas.get()) +} + fn compare_op(op: CfOperator, n: f64, a: Option, b: Option) -> bool { let Some(a) = a else { return false }; match op { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 27e2174746..3e957183d9 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -34,8 +34,8 @@ pub use go_to::go_to_names; use go_to::go_to_special; #[cfg(test)] use go_to::{GO_TO_MAX_AREAS, GO_TO_RECENT, reference_parts}; -use paste_special::paste_special; pub(crate) use paste_special::rewrite_all_formulas; +use paste_special::{copy_cond_formats, paste_special}; use selection::{select_all, select_col, select_region, select_row, selection_move, selection_next, selection_set}; pub fn specs() -> Vec { @@ -239,6 +239,10 @@ fn clear(s: &mut Session, p: &Json, what: &str) -> Result { }) }; edit(s, |cx| { + if matches!(what, "all" | "formats") { + // Conditional formats are formatting too, and may cover cells that hold nothing. + super::data::remove_cond_format_cells(&mut cx.sheet_mut(sheet)?.cond_formats, &ranges); + } for r in &ranges { let r = match cx.wb.sheet(sheet).and_then(|sh| sh.used_range()) { Some(u) => match r.intersection(&u) { @@ -326,6 +330,7 @@ fn format_painter(s: &mut Session, p: &Json) -> Result { let Some((wb, sheet, src, sticky)) = s.format_painter.clone() else { return Err(EngineError::Other("Pick up a format first.".into())) }; let dest_sheet = s.doc()?.wb.active_sheet(); let same = std::sync::Arc::ptr_eq(&wb, &s.doc()?.wb) || s.doc()?.wb.styles == wb.styles; + let mut cf_formulas = false; edit(s, |cx| { let Some(src_sheet) = wb.sheet(sheet) else { return Ok(()) }; let (h, w) = (src.height(), src.width()); @@ -394,9 +399,24 @@ fn format_painter(s: &mut Session, p: &Json) -> Result { cx.sheet_mut(dest_sheet)?.set_style(c, st); cx.touch(dest_sheet, c); } + // The painter lifts conditional formats along with the cell formats. + let mut tiles = Vec::new(); + for tr in 0..dest.height().div_ceil(h) { + for tc in 0..dest.width().div_ceil(w) { + let Some(origin) = dest.start.offset((tr * h) as i64, (tc * w) as i64) else { continue }; + let clip = RangeRef::new(origin, origin.offset_clamped(h as i64 - 1, w as i64 - 1)).intersection(&dest); + tiles.extend(clip.map(|clip| (origin, clip))); + } + } + cf_formulas = copy_cond_formats(cx.sheet_mut(dest_sheet)?, src_sheet, src, &tiles); *cx.sel = crate::Selection::range(dest); Ok(()) })?; + // Rules with formulas from another workbook leave this one untrusted, as pasting them does. + if cf_formulas && !same { + let d = s.doc_mut()?; + d.trust = d.trust.receive(crate::Trust::FromFile); + } if !sticky { s.format_painter = None; } diff --git a/crates/engine/src/cmd/edit/paste_special.rs b/crates/engine/src/cmd/edit/paste_special.rs index 0a6d14247f..b8423900f9 100644 --- a/crates/engine/src/cmd/edit/paste_special.rs +++ b/crates/engine/src/cmd/edit/paste_special.rs @@ -46,6 +46,32 @@ fn operation_symbol(op: &str) -> Option { } } +/// Pastes the conditional formats of `src` at `at`, tiled `(tiles_r, tiles_c)` times. `cut_from` is `None` when +/// the paste carries none, `Some(None)` for a copy and `Some(Some(sheet))` for a cut, which takes them from `sheet`. Returns whether a pasted rule holds formulas. +fn paste_cond_formats( + cx: &mut crate::cmd::Ctx, + cut_from: Option>, + dest_sheet: usize, + src_sheet: &gridcraft_model::Sheet, + src: RangeRef, + at: CellRef, + (h, w, tiles_r, tiles_c): (u32, u32, u32, u32), +) -> Result { + let Some(cut_from) = cut_from else { return Ok(false) }; + if let Some(sheet) = cut_from { + super::super::data::remove_cond_format_cells(&mut cx.sheet_mut(sheet)?.cond_formats, &[src]); + } + let mut tiles = Vec::new(); + for tr in 0..tiles_r { + for tc in 0..tiles_c { + let Some(origin) = at.offset((tr * h) as i64, (tc * w) as i64) else { continue }; + let Some(end) = origin.offset(h as i64 - 1, w as i64 - 1) else { continue }; + tiles.push((origin, RangeRef::new(origin, end))); + } + } + Ok(copy_cond_formats(cx.sheet_mut(dest_sheet)?, src_sheet, src, &tiles)) +} + fn copy_merges( cx: &mut crate::cmd::Ctx, dest_sheet: usize, @@ -72,6 +98,51 @@ fn copy_merges( Ok(()) } +/// Copies the conditional formats of `src` on `from` onto `sheet`. Each tile is where a copy of +/// `src` starts and the area it may fill: the destination loses its own rules there and takes the +/// copied ones, one rule per copied rule across all tiles (so a color scale copied from one cell +/// scales over the whole destination). Relative references in rule formulas move with the rule. +/// Returns whether a pasted rule holds formulas. +pub(super) fn copy_cond_formats( + sheet: &mut gridcraft_model::Sheet, + from: &gridcraft_model::Sheet, + src: RangeRef, + tiles: &[(CellRef, RangeRef)], +) -> bool { + let rules: Vec<&gridcraft_model::CondFormat> = from.cond_formats.iter().filter(|cf| cf.ranges.iter().any(|r| r.intersects(&src))).collect(); + let mut pieces: Vec> = vec![Vec::new(); rules.len()]; + for (origin, clip) in tiles { + super::super::data::remove_cond_format_cells(&mut sheet.cond_formats, &[*clip]); + for (cf, out) in rules.iter().zip(pieces.iter_mut()) { + out.extend(cf.ranges.iter().filter_map(|r| r.intersection(&src)).filter_map(|i| { + let (dr, dc) = (i.start.row as i64 - src.start.row as i64, i.start.col as i64 - src.start.col as i64); + let (er, ec) = (i.end.row as i64 - src.start.row as i64, i.end.col as i64 - src.start.col as i64); + RangeRef::new(origin.offset(dr, dc)?, origin.offset(er, ec)?).intersection(clip) + })); + } + } + let mut formulas = false; + let mut pasted = Vec::new(); + for (cf, ranges) in rules.iter().zip(pieces) { + let (Some(anchor), Some(first)) = (cf.ranges.first().map(|r| r.start), ranges.first().map(|r| r.start)) else { continue }; + let (rule, has_formulas) = super::super::data::move_cf_rule(&cf.rule, anchor, first); + formulas |= has_formulas; + pasted.push(gridcraft_model::CondFormat { ranges, rule, priority: 0, stop_if_true: cf.stop_if_true }); + } + if !pasted.is_empty() { + // Pasted rules rank above the destination's, in the order they were copied. + let n = pasted.len() as u32; + for cf in sheet.cond_formats.iter_mut() { + cf.priority = cf.priority.saturating_add(n); + } + for (i, cf) in pasted.iter_mut().enumerate() { + cf.priority = i as u32 + 1; + } + sheet.cond_formats.splice(0..0, pasted); + } + formulas +} + pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { let Some(clip) = s.clipboard.clone() else { return Err(EngineError::Other("Nothing to paste.".into())) }; let what = match str_param(p, "what").unwrap_or("all") { @@ -117,6 +188,9 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { // Check the whole footprint before the source is emptied, so a move that overflows the grid loses nothing. return Err(EngineError::Other("The cut area doesn't fit at this position; nothing was moved.".into())); } + let mut cf_formulas = false; + let carries_cond_formats = !link && !transpose && matches!(what, What::All | What::Formats | What::AllExceptBorders); + let cond_formats_from = carries_cond_formats.then(|| cut_move.then_some(clip.sheet)); edit(s, |cx| { // Styles from another workbook must be re-interned. let mut style_map = std::collections::HashMap::new(); @@ -282,6 +356,9 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { } cx.touch(dest_sheet, dest); } + // Conditional formats travel with the formats: the destination takes the copied block's + // rules (and loses its own, as in Excel), and a cut takes them from the source. + cf_formulas |= paste_cond_formats(cx, cond_formats_from, dest_sheet, src_sheet, src, at, (h, w, tiles_r, tiles_c))?; // Merged areas inside the copied block travel with it. copy_merges(cx, dest_sheet, src_sheet, src, at, what, transpose)?; if cut_move { @@ -299,12 +376,13 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { *cx.sel = crate::Selection { active: at, anchor: at, ranges: vec![RangeRef::new(at, end)] }; Ok(()) })?; - // Formulas and validation from an untrusted file leave the destination untrusted; plain values, - // formats (cell styles and merged areas, no conditional formats), column widths and notes - // carry nothing active. A linked paste writes a formula into every cell whatever `what` says, - // except for column widths and notes, which write no cells at all. - let passive = - matches!(what, What::ColumnWidths | What::Comments) || (!link && matches!(what, What::Formats | What::Values | What::ValuesAndNumberFormats)); + // Formulas and validation from an untrusted file leave the destination untrusted, as do + // conditional formats that hold formulas; plain values, formats (cell styles, merged areas and + // conditional formats without formulas), column widths and notes carry nothing active. A linked + // paste writes a formula into every cell whatever `what` says, except for column widths and + // notes, which write no cells at all. + let passive = matches!(what, What::ColumnWidths | What::Comments) + || (!link && matches!(what, What::Formats | What::Values | What::ValuesAndNumberFormats) && !cf_formulas); if !same_doc && !passive { let d = s.doc_mut()?; d.trust = d.trust.receive(clip.trust); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b61d85c766..57abaed38b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2896,6 +2896,107 @@ fn delete_on_filtered_checkboxes_skips_the_hidden_rows() { assert_eq!(v(&s, "B3"), Value::Bool(true)); } +#[test] +fn clear_formats_and_clear_all_remove_conditional_formats_in_the_selection_only() { + let mut s = s(); + for (i, r) in ["A1", "A2", "A3"].iter().enumerate() { + s.execute("cell.set", json!({"cell": r, "input": (i + 1).to_string()})).unwrap(); + } + s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale"}})).unwrap(); + let ranges = |s: &Session| -> Vec { + s.doc().unwrap().wb.sheet(0).unwrap().cond_formats.iter().flat_map(|c| c.ranges.iter().map(|r| r.a1())).collect() + }; + assert_eq!(ranges(&s), ["A1:A3"]); + s.execute("edit.clearFormats", json!({"range": "A2"})).unwrap(); + assert_eq!(ranges(&s), ["A1", "A3"]); + s.execute("edit.clearAll", json!({"range": "A1:A3"})).unwrap(); + assert!(ranges(&s).is_empty()); +} + +#[test] +fn paste_formats_and_all_carry_conditional_formats_and_values_do_not() { + let mut s = s(); + for (i, r) in ["A1", "A2", "A3"].iter().enumerate() { + s.execute("cell.set", json!({"cell": r, "input": (i + 1).to_string()})).unwrap(); + } + s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale"}})).unwrap(); + s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "=A1>1", "preset": "yellowFill"}})) + .unwrap(); + let rules = |s: &Session| -> Vec<(String, String)> { + s.doc() + .unwrap() + .wb + .sheet(0) + .unwrap() + .cond_formats + .iter() + .map(|c| { + let kind = match &c.rule { + gridcraft_model::CfRule::ColorScale { .. } => "scale".to_string(), + gridcraft_model::CfRule::Expression { formula, .. } => format!("expr {formula}"), + _ => "other".into(), + }; + (c.ranges.iter().map(|r| r.a1()).collect::>().join(","), kind) + }) + .collect() + }; + s.execute("edit.copy", json!({"range": "A1:A3"})).unwrap(); + // Values alone carry no formatting. + s.execute("edit.pasteSpecial", json!({"what": "values", "at": "C1"})).unwrap(); + assert_eq!(rules(&s).len(), 2); + // Formats copy both rules, with the formula's relative reference moved. + s.execute("edit.pasteSpecial", json!({"what": "formats", "at": "C1"})).unwrap(); + let r = rules(&s); + assert_eq!(r.len(), 4); + assert!(r.contains(&("C1:C3".into(), "scale".into()))); + assert!(r.contains(&("C1:C3".into(), "expr C1>1".into())), "{r:?}"); + // Pasting again replaces what the destination had instead of stacking. + s.execute("edit.pasteSpecial", json!({"what": "all", "at": "C1"})).unwrap(); + assert_eq!(rules(&s).len(), 4); + // Pasting over part of a covered area splits the old rule instead of dropping it. + s.execute("edit.copy", json!({"range": "A1"})).unwrap(); + s.execute("edit.pasteSpecial", json!({"what": "formats", "at": "C2"})).unwrap(); + let r = rules(&s); + assert!(r.contains(&("C2".into(), "scale".into())), "{r:?}"); + assert!( + r.contains(&("C1,C3".into(), "scale".into())) || (r.contains(&("C1".into(), "scale".into())) && r.contains(&("C3".into(), "scale".into()))), + "{r:?}" + ); +} + +#[test] +fn pasting_formats_from_one_cell_over_a_range_makes_one_rule_over_the_range() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap(); + s.execute("home.bold", json!({"range": "A1"})).unwrap(); + s.execute("home.conditionalFormat", json!({"range": "A1", "rule": {"type": "colorScale"}})).unwrap(); + s.execute("edit.copy", json!({"range": "A1"})).unwrap(); + s.execute("selection.set", json!({"range": "C1:C5"})).unwrap(); + s.execute("edit.pasteSpecial", json!({"what": "formats"})).unwrap(); + let sh = s.doc().unwrap().wb.sheet(0).unwrap().clone(); + let on_c: Vec<_> = sh.cond_formats.iter().filter(|c| c.ranges.iter().any(|r| r.start.col == 2)).collect(); + assert_eq!(on_c.len(), 1); + assert_eq!(on_c[0].ranges.iter().map(|r| r.count()).sum::(), 5); + assert!(s.doc().unwrap().wb.styles.get(sh.cell(gridcraft_core::CellRef::new(4, 2)).map_or(Default::default(), |c| c.style)).font.bold); +} + +#[test] +fn the_format_painter_carries_conditional_formats_over_the_painted_range() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap(); + s.execute("home.conditionalFormat", json!({"range": "A1", "rule": {"type": "colorScale"}})).unwrap(); + s.execute("home.conditionalFormat", json!({"range": "C1:C5", "rule": {"type": "dataBar"}})).unwrap(); + s.execute("selection.set", json!({"range": "A1"})).unwrap(); + s.execute("edit.formatPainter", json!({})).unwrap(); + s.execute("edit.formatPainter", json!({"apply": "C1:C5"})).unwrap(); + let sh = s.doc().unwrap().wb.sheet(0).unwrap().clone(); + // The destination's own rule is replaced by one copied scale over the whole range. + assert_eq!(sh.cond_formats.len(), 2); + let scale = sh.cond_formats.iter().find(|c| matches!(c.rule, gridcraft_model::CfRule::ColorScale { .. })).unwrap(); + assert_eq!(scale.ranges.iter().map(|r| r.count()).sum::(), 5); + assert!(sh.cond_formats.iter().all(|c| !matches!(c.rule, gridcraft_model::CfRule::DataBar { .. }))); +} + #[test] fn checkboxes_survive_xlsx_as_cell_controls() { let mut s = s(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 82b2526074..cad871d2de 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -78,7 +78,10 @@ pub struct Dialog { /// reference at the caret instead of selecting it, and a drag grows it into a range. #[derive(Clone, Debug)] struct RefPick { + /// The box grid clicks go to: the last of `keys` that had the keyboard. key: &'static str, + /// Every box of the dialog that takes references (the second value of "between" too). + keys: &'static [&'static str], /// The sheet the dialog was opened on, by name: its index changes when sheets are inserted or /// moved while the dialog is open. References to another sheet carry that sheet's name. sheet: String, @@ -808,7 +811,9 @@ impl Dialog { fields, json!({"preset": "lightRedFillDarkRedText", "period": "today"}), ); - if ty == "expression" { + if ty == "expression" || ty == "cellIs" { + let (key, keys): (&'static str, &'static [&'static str]) = + if ty == "expression" { ("formula", &["formula"]) } else { ("value", &["value", "value2"]) }; let (sheet, applies_to) = app .session .active() @@ -819,7 +824,7 @@ impl Dialog { ) }) .unwrap_or_default(); - d.pick = Some(RefPick { key: "formula", sheet, caret: 0, point: None, anchor: CellRef::new(0, 0), refocus: false, applies_to }); + d.pick = Some(RefPick { key, keys, sheet, caret: 0, point: None, anchor: CellRef::new(0, 0), refocus: false, applies_to }); } d.values.insert("type".into(), json!(ty)); d.values.insert("operator".into(), p("operator")); diff --git a/crates/ui-egui/src/dialogs/show.rs b/crates/ui-egui/src/dialogs/show.rs index 07debbca69..19d3854f28 100644 --- a/crates/ui-egui/src/dialogs/show.rs +++ b/crates/ui-egui/src/dialogs/show.rs @@ -496,6 +496,11 @@ fn track_pick(pick: &mut RefPick, r: &egui::Response, typed: bool) { pub(super) fn form_fields(ui: &mut egui::Ui, d: &mut Dialog) { // Field labels, choices and notes are English source strings, translated as they are drawn. let lang = crate::i18n::current(ui.ctx()); + // Only the first box takes the keyboard when the form opens (a later one asking too would win). + let first_box = d.fields.iter().find_map(|f| match f { + Field::Text { key, .. } | Field::Number { key, .. } => Some(*key), + _ => None, + }); egui::Grid::new("form").num_columns(1).spacing(vec2(8.0, 6.0)).show(ui, |ui| { for f in d.fields.clone() { match f { @@ -513,10 +518,18 @@ pub(super) fn form_fields(ui: &mut egui::Ui, d: &mut Dialog) { } else { ui.add(egui::TextEdit::singleline(&mut s).desired_width(320.0)).labelled_by(label.id) }; - take_first_focus(d, &r); + if first_box == Some(key) { + take_first_focus(d, &r); + } if r.changed() { d.values.insert(key.into(), json!(s)); } + // Grid clicks go to whichever of the dialog's reference boxes was used last. + if let Some(pick) = d.pick.as_mut().filter(|pick| pick.key != key && pick.keys.contains(&key) && r.has_focus()) { + pick.key = key; + pick.caret = s.chars().count(); + pick.point = None; + } if let Some(pick) = d.pick.as_mut().filter(|pick| pick.key == key) { track_pick(pick, &r, r.changed()); } @@ -541,7 +554,9 @@ pub(super) fn form_fields(ui: &mut egui::Ui, d: &mut Dialog) { // Typed values count straight away: otherwise Enter or OK in the same frame // confirms the old value, because a number field only commits when it loses focus. let r = ui.add(egui::DragValue::new(&mut n).speed(0.5).update_while_editing(true)).labelled_by(label.id); - take_first_focus(d, &r); + if first_box == Some(key) { + take_first_focus(d, &r); + } if r.changed() { d.values.insert(key.into(), json!(n)); } diff --git a/crates/ui-egui/tests/it/cf_rule_pick.rs b/crates/ui-egui/tests/it/cf_rule_pick.rs index 710827bc1a..0fd8507c0b 100644 --- a/crates/ui-egui/tests/it/cf_rule_pick.rs +++ b/crates/ui-egui/tests/it/cf_rule_pick.rs @@ -2,6 +2,7 @@ //! into the formula box at its caret, as in Excel, and leaves the selection the rule applies to alone. use egui::{Event, Key, Modifiers, PointerButton, Pos2, pos2, vec2}; +use egui_kittest::kittest::Queryable; use gridcraft_engine::Session; use gridcraft_ui_egui::{SheetApp, grid::Geo}; use serde_json::json; @@ -9,6 +10,10 @@ use serde_json::json; type Harness = egui_kittest::Harness<'static, SheetApp>; fn harness() -> Harness { + harness_with(json!({"type": "expression", "title": "New Formatting Rule"})) +} + +fn harness_with(dialog: serde_json::Value) -> Harness { let mut session = Session::new(); session.new_workbook(); session.execute("home.insertSheet", json!({})).unwrap(); @@ -22,11 +27,15 @@ fn harness() -> Harness { crate::common::app(session), ); h.run_steps(4); - h.state_mut().open_dialog("cfQuick", json!({"type": "expression", "title": "New Formatting Rule"})); + h.state_mut().open_dialog("cfQuick", dialog); h.run_steps(6); h } +fn value(h: &Harness, key: &str) -> String { + h.state().dialog.as_ref().and_then(|d| d.values.get(key)).and_then(|v| v.as_str()).unwrap_or("").to_string() +} + fn formula(h: &Harness) -> String { h.state().dialog.as_ref().and_then(|d| d.values.get("formula")).and_then(|v| v.as_str()).unwrap_or("").to_string() } @@ -195,3 +204,32 @@ fn the_rule_follows_its_sheet_when_sheets_move_while_the_dialog_is_open() { let cf = sheet1.cond_formats.last().expect("the rule stays on Sheet1"); assert_eq!(cf.ranges.iter().map(|r| r.a1()).collect::>(), ["F8:G9"]); } + +#[test] +fn highlight_cell_rules_take_a_clicked_cell_as_the_value() { + let mut h = harness_with(json!({"type": "cellIs", "operator": "greaterThan", "title": "Greater Than"})); + click(&mut h, "B2"); + assert_eq!(value(&h, "value"), "=$B$2"); + assert_eq!(selection(&h), "F8:G9", "the range the rule applies to is still selected"); +} + +#[test] +fn between_sends_clicks_to_whichever_value_box_was_used_last() { + let mut h = harness_with(json!({"type": "cellIs", "operator": "between", "title": "Between"})); + click(&mut h, "B2"); + assert_eq!(value(&h, "value"), "=$B$2"); + // Focus the second box by clicking into it, then pick on the grid. + let key_box = + h.get_all_by_role(egui::accesskit::Role::TextInput).map(|n| n.rect()).max_by(|a, b| a.top().total_cmp(&b.top())).map(|r| r.center()); + if let Some(pos) = key_box { + h.input_mut().events.extend([ + Event::PointerMoved(pos), + Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }, + Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }, + ]); + h.run_steps(3); + click(&mut h, "D5"); + assert_eq!(value(&h, "value2"), "=$D$5"); + assert_eq!(value(&h, "value"), "=$B$2"); + } +}