diff --git a/ROADMAP.md b/ROADMAP.md index 9ba40b023..6df4e6c94 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365) > **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-11-16 | A selected chart outlines its data as Excel does (series names red, category labels purple, values one blue block), and dragging a corner of the values outline changes the cells the chart plots: series keep their formatting, a wider block adds series, aligned names and labels follow, one undo step, Esc cancels; `chart.setValuesRange` does the same for scripts, the CLI and MCP (#4389, #4390) | | 2026-11-06 | A sheet keeps its own scroll position when sheets are inserted, deleted or moved before it: a new PivotTable or inserted sheet opens at the top instead of where its neighbour was scrolled; a closed window's positions are let go (#3485) | | 2026-11-02 | Form controls: Insert › Controls places buttons, sliders (scroll bars) and spin buttons on the sheet. A slider or spin button holds a whole number from 0 to 30000 in a linked cell (a drag or a held arrow is one undo step, and editing the cell moves the control); a button runs a macro or one command through the macro policy, asking first in a workbook opened from a file; Assign Action and Format Control edit them, and XLSX files read and write them (control properties, `` and VML), alongside the form controls GridCraft keeps unchanged | | 2026-11-02 | Dialogs take ranges by selection on the grid: reference boxes (RefEdit) with a collapse button that shrinks the dialog while the person selects, in Goal Seek, Solver (including the Model Range of Load/Save) and Data Analysis; while collapsed, the arrow keys move the selection and Shift+arrow extends it, and F4 cycles a reference's anchors | @@ -278,6 +279,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Progress log: chart data outline in three colours, dragged from its corners (#4389, #4390) | | 2026-11-06 | trivial | Progress log: scroll positions follow their sheet through sheet inserts, deletes and moves (#3485) | | 2026-11-05 | minor | Reconcile upstream form-control progress with the CJK baseline update | | 2026-11-02 | minor | Form controls; catalog 277 / 292 → 281 / 296 (Developer › Controls); progress log row | diff --git a/crates/engine/src/chart_data.rs b/crates/engine/src/chart_data.rs new file mode 100644 index 000000000..47bcef2fe --- /dev/null +++ b/crates/engine/src/chart_data.rs @@ -0,0 +1,213 @@ +//! Where a chart's data sits on a sheet, as the blocks a selected chart outlines: series names in +//! red, category labels in purple and values in blue (#4390). Dragging a corner of the values +//! block points the chart at other cells, and the names and categories follow it (#4389). + +use gridcraft_core::{CellRef, RangeRef, col_to_letters}; +use gridcraft_formula::{Expr, RefKind, SheetSel, parse, quote_sheet}; +use gridcraft_model::{Chart, Series, Workbook}; + +/// Most series a chart takes from a dragged block (Excel's limit per chart). +pub const MAX_SERIES: u32 = 255; +/// Most cells a dragged values block may span, as for `chart.selectData`. +pub const MAX_CELLS: u64 = 1_000_000; + +/// A chart's data as blocks of cells on one sheet. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ChartData { + /// The sheet the data is on. + pub sheet: usize, + /// Every series' values: one column per series (one row with `by_rows`), in series order. + pub values: RangeRef, + /// Series run across rows rather than down columns. + pub by_rows: bool, + /// The category labels every series shares, when they line up beside `values`. + pub categories: Option, + /// One name cell per series, in the line beside `values`, when every series has one there. + pub names: Option, +} + +impl ChartData { + /// The blocks after the values move to `to`: category labels keep their column (row) and + /// span the new points, and names keep their row (column) and span the new series. + pub fn moved(&self, to: RangeRef) -> ChartData { + let (categories, names) = if self.by_rows { + ( + self.categories.map(|c| RangeRef::new(CellRef::new(c.start.row, to.start.col), CellRef::new(c.start.row, to.end.col))), + self.names.map(|n| RangeRef::new(CellRef::new(to.start.row, n.start.col), CellRef::new(to.end.row, n.start.col))), + ) + } else { + ( + self.categories.map(|c| RangeRef::new(CellRef::new(to.start.row, c.start.col), CellRef::new(to.end.row, c.start.col))), + self.names.map(|n| RangeRef::new(CellRef::new(n.start.row, to.start.col), CellRef::new(n.start.row, to.end.col))), + ) + }; + ChartData { values: to, categories, names, ..*self } + } + + /// The cells of series `i` within `values` (`None` past the last series). + fn line(&self, values: RangeRef, i: u32) -> Option { + if self.by_rows { + let row = values.start.row.checked_add(i).filter(|r| *r <= values.end.row)?; + Some(RangeRef::new(CellRef::new(row, values.start.col), CellRef::new(row, values.end.col))) + } else { + let col = values.start.col.checked_add(i).filter(|c| *c <= values.end.col)?; + Some(RangeRef::new(CellRef::new(values.start.row, col), CellRef::new(values.end.row, col))) + } + } + + /// How many series `values` holds. + fn count(&self, values: RangeRef) -> u32 { + if self.by_rows { values.height() } else { values.width() } + } +} + +/// The sheet and cells a series reference names. `home` is the chart's own sheet, for an +/// unqualified reference. Literals, names, 3-D spans, other workbooks and whole rows or columns +/// are not blocks. +fn block(wb: &Workbook, home: usize, text: &str) -> Option<(usize, RangeRef)> { + let Ok(Expr::Ref(r)) = parse(text.trim().trim_start_matches('=')) else { return None }; + let sheet = match &r.sheet { + SheetSel::Current => home, + SheetSel::Named(n) => wb.sheet_index(n)?, + SheetSel::Span(..) => return None, + }; + matches!(r.kind, RefKind::Cell(_) | RefKind::Range(..)).then(|| (sheet, r.range())) +} + +/// `chart`'s data on `home`'s workbook as blocks, when its series form one: every series' values +/// on one sheet, in adjacent columns (or rows) of the same extent, in series order. `None` for +/// any other layout, and for a PivotChart, whose series follow its PivotTable. +pub fn chart_data(wb: &Workbook, home: usize, chart: &Chart) -> Option { + if chart.pivot.is_some() { + return None; + } + let first = chart.series.first()?; + let (sheet, r0) = block(wb, home, &first.values)?; + let by_rows = match (r0.width(), r0.height()) { + (1, 1) => chart.by_rows, + (1, _) => false, + (_, 1) => true, + _ => return None, + }; + let n = u32::try_from(chart.series.len()).ok()?; + let last = n.checked_sub(1)?; + let values = if by_rows { + RangeRef::new(r0.start, CellRef::new(r0.end.row.checked_add(last)?, r0.end.col)) + } else { + RangeRef::new(r0.start, CellRef::new(r0.end.row, r0.end.col.checked_add(last)?)) + }; + let mut data = ChartData { sheet, values, by_rows, categories: None, names: None }; + for (i, se) in (0..n).zip(&chart.series) { + if block(wb, home, &se.values) != Some((sheet, data.line(values, i)?)) { + return None; + } + } + // Category labels shared by every series, in one line beside the points. Compared as blocks, + // not text: `=Sheet1!$A$2:$A$4` and `Sheet1!$A$2:$A$4` are the same labels. + let cats = |se: &Series| se.categories.as_deref().and_then(|t| block(wb, home, t)); + if let Some((s, c)) = cats(first) + && s == sheet + && chart.series.iter().all(|se| cats(se) == Some((s, c))) + { + let lines_up = if by_rows { + c.height() == 1 + && (c.start.col, c.end.col) == (values.start.col, values.end.col) + && !(values.start.row..=values.end.row).contains(&c.start.row) + } else { + c.width() == 1 + && (c.start.row, c.end.row) == (values.start.row, values.end.row) + && !(values.start.col..=values.end.col).contains(&c.start.col) + }; + data.categories = lines_up.then_some(c); + } + // A name cell for every series, all in one line beside the values. + let names: Option> = chart + .series + .iter() + .map(|se| se.name.as_deref().and_then(|t| block(wb, home, t)).filter(|(s, r)| *s == sheet && r.is_single()).map(|(_, r)| r.start)) + .collect(); + if let Some(cells) = names + && let (Some(a), Some(b)) = (cells.first(), cells.last()) + { + let lines_up = (0..n).zip(&cells).all(|(i, c)| { + if by_rows { + c.col == a.col && Some(c.row) == values.start.row.checked_add(i) && !(values.start.col..=values.end.col).contains(&c.col) + } else { + c.row == a.row && Some(c.col) == values.start.col.checked_add(i) && !(values.start.row..=values.end.row).contains(&c.row) + } + }); + data.names = lines_up.then(|| RangeRef::new(*a, *b)); + } + Some(data) +} + +/// Why [`with_values`] refused. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ValuesError { + /// The chart's series are not one block of cells ([`chart_data`] is `None`). + NotABlock, + /// The block is over [`MAX_CELLS`] cells or [`MAX_SERIES`] series. + TooLarge, +} + +/// `chart` with its values moved to `to` on the data's own sheet, as dragging a corner of the +/// values outline does. Series `i` takes the `i`-th column (row) of `to` and keeps everything +/// else it had (colour, kind, axis, trendlines); a wider block adds series and a narrower one +/// drops the last ones. Category labels and names that line up follow the block; ones that don't +/// stay as they are. A data range kept for Switch Row/Column becomes the moved blocks. +pub fn with_values(wb: &Workbook, home: usize, chart: &Chart, to: RangeRef) -> Result { + let data = chart_data(wb, home, chart).ok_or(ValuesError::NotABlock)?; + if to.count() > MAX_CELLS || data.count(to) > MAX_SERIES { + return Err(ValuesError::TooLarge); + } + let sheet = wb.sheet(data.sheet).ok_or(ValuesError::NotABlock)?; + let q = quote_sheet(&sheet.name); + let row = |r: u32| u64::from(r) + 1; + let range = |r: RangeRef| format!("{q}!${}${}:${}${}", col_to_letters(r.start.col), row(r.start.row), col_to_letters(r.end.col), row(r.end.row)); + let cell = |c: CellRef| format!("{q}!${}${}", col_to_letters(c.col), row(c.row)); + let moved = data.moved(to); + let shared_cats = chart.series.first().and_then(|se| se.categories.clone()); + let mut out = chart.clone(); + // Keep the orientation the series were read in: a block of one cell per series is read by + // `by_rows`, so a stale flag would make the moved series unreadable as a block. + out.by_rows = data.by_rows; + out.series = (0..data.count(to)) + .filter_map(|i| { + let line = moved.line(to, i)?; + let old = chart.series.get(i as usize); + let mut se = old.cloned().unwrap_or_else(|| Series { categories: shared_cats.clone(), ..Series::default() }); + se.values = range(line); + if let Some(c) = moved.categories { + se.categories = Some(range(c)); + } + if let Some(n) = moved.names { + se.name = + Some(cell(if data.by_rows { CellRef::new(line.start.row, n.start.col) } else { CellRef::new(n.start.row, line.start.col) })); + } + // Bubble sizes in a line of their own beside the old points span the new ones. + if let (Some(old_line), Some(text)) = (data.line(data.values, i), se.bubble_sizes.clone()) + && let Some((s, b)) = block(wb, home, &text) + && s == data.sheet + { + let follows = if data.by_rows { + b.height() == 1 && (b.start.col, b.end.col) == (old_line.start.col, old_line.end.col) + } else { + b.width() == 1 && (b.start.row, b.end.row) == (old_line.start.row, old_line.end.row) + }; + if follows { + se.bubble_sizes = Some(range(if data.by_rows { + RangeRef::new(CellRef::new(b.start.row, to.start.col), CellRef::new(b.start.row, to.end.col)) + } else { + RangeRef::new(CellRef::new(to.start.row, b.start.col), CellRef::new(to.end.row, b.start.col)) + })); + } + } + Some(se) + }) + .collect(); + if out.source.is_some() { + let all = [moved.categories, moved.names].into_iter().flatten().fold(to, |a, r| a.union(&r)); + out.source = Some(format!("{q}!{}", all.a1())); + } + Ok(out) +} diff --git a/crates/engine/src/cmd/extra.rs b/crates/engine/src/cmd/extra.rs index 6325de45a..47526bf4a 100644 --- a/crates/engine/src/cmd/extra.rs +++ b/crates/engine/src/cmd/extra.rs @@ -22,7 +22,7 @@ mod window; pub(crate) use cells::is_checkbox_cell; use cells::{background, checkbox, draw_border, new_cell_style, recently_used, theme_colors, theme_fonts, toggle_checkbox, use_in_formula}; -use chart::{add_element, change_colors, format_series, move_chart, quick_layout, select_data}; +use chart::{add_element, change_colors, format_series, move_chart, quick_layout, select_data, set_values_range}; use data::{from_csv, from_table_range, queries, table_resize}; use objects::{align, arrange, rotate, selection_pane, shape_fill, shape_outline}; pub(crate) use scripts::has_scripts; @@ -61,6 +61,16 @@ pub fn specs() -> Vec { has_doc, select_data ), + // Dragging a corner of a selected chart's values outline on the sheet (#4389). + cmd!( + "chart.setValuesRange", + "Resize Chart Data", + [], + None, + "{chart?, range: \"B2:C9\" (the block every series' values come from, one column or row per series, on the data's sheet; names and category labels that line up follow it, series keep their formatting)}", + has_doc, + set_values_range + ), cmd!("chart.changeType", "Change Chart Type…", ["Chart Design", "Type"], None, "{chart?, type, subtype?}", has_doc, |s, p| s .execute("chart.set", p.clone())), cmd!( diff --git a/crates/engine/src/cmd/extra/chart.rs b/crates/engine/src/cmd/extra/chart.rs index 8d9af2064..b6ed184ed 100644 --- a/crates/engine/src/cmd/extra/chart.rs +++ b/crates/engine/src/cmd/extra/chart.rs @@ -233,6 +233,38 @@ pub(super) fn select_data(s: &mut Session, p: &Json) -> Result { }) } +/// Points the chart's series at another block of cells on their sheet, keeping each series' +/// formatting, as dragging a corner of the selected chart's values outline does (#4389). +pub(super) fn set_values_range(s: &mut Session, p: &Json) -> Result { + use crate::chart_data::{ValuesError, chart_data, with_values}; + let text = str_param(p, "range").ok_or_else(|| bad("chart.setValuesRange", "missing `range`"))?; + let (si, ci) = find_chart(s, p)?; + let d = s.doc()?; + let chart = d.wb.sheet(si).and_then(|sh| sh.charts.get(ci)).ok_or_else(|| bad("chart", "no such chart"))?; + let Some(data) = chart_data(&d.wb, si, chart) else { + return Err(bad("chart.setValuesRange", "the chart's series are not one block of cells")); + }; + let (sheet_name, body) = split_sheet(text.trim().trim_start_matches('=')); + if let Some(n) = sheet_name + && d.wb.sheet_index(&n) != Some(data.sheet) + { + return Err(bad("chart.setValuesRange", "the range must be on the sheet the chart's data is on")); + } + let to = RangeRef::parse(body).ok_or_else(|| bad("chart.setValuesRange", "not a range"))?; + let new = with_values(&d.wb, si, chart, to).map_err(|e| match e { + ValuesError::NotABlock => bad("chart.setValuesRange", "the chart's series are not one block of cells"), + ValuesError::TooLarge => bad("chart.setValuesRange", "range too large for a chart"), + })?; + let values = format!("{}!{}", gridcraft_formula::quote_sheet(d.wb.sheet(data.sheet).map_or("", |sh| sh.name.as_str())), to.a1()); + with_chart(s, p, move |c| { + c.series = new.series; + c.source = new.source; + c.by_rows = new.by_rows; + Ok(()) + }) + .map(|r| json!({"chart": r["chart"], "values": values})) +} + pub(super) fn move_chart(s: &mut Session, p: &Json) -> Result { let (si, ci) = find_chart(s, p)?; let target = match p.get("sheet").and_then(Json::as_str) { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 99fb64efd..d33a020b6 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -8,6 +8,7 @@ pub mod catalog; pub mod cf; +pub mod chart_data; mod chart_svg; mod clip_html; pub mod cmd; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cd699bf1c..15dfdd43e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6712,6 +6712,7 @@ fn a_script_cannot_switch_windows() { assert_eq!(v(&s, "A1"), Value::number(2.0)); } +mod chart_data; mod controls; mod equation; mod json_golden; diff --git a/crates/engine/src/tests/chart_data.rs b/crates/engine/src/tests/chart_data.rs new file mode 100644 index 000000000..f8b03124b --- /dev/null +++ b/crates/engine/src/tests/chart_data.rs @@ -0,0 +1,177 @@ +//! A chart's data as blocks on the sheet, and `chart.setValuesRange`, which dragging a corner of a +//! selected chart's values outline runs (#4389, #4390). + +use gridcraft_core::RangeRef; +use gridcraft_model::{Chart, Color}; +use serde_json::json; + +use super::s; +use crate::Session; +use crate::chart_data::{ChartData, chart_data}; + +fn r(a: &str) -> RangeRef { + RangeRef::parse(a).unwrap() +} + +fn chart(s: &Session) -> Chart { + s.doc().unwrap().wb.active().unwrap().charts[0].clone() +} + +fn data(s: &Session) -> Option { + chart_data(&s.doc().unwrap().wb, 0, &chart(s)) +} + +/// Points each plotted series has, as the chart resolves them. +fn points(s: &Session) -> Vec { + gridcraft_chart::resolve(&s.doc().unwrap().wb, 0, &chart(s)).series.iter().map(|se| se.values.len()).collect() +} + +/// 10..80 down A1:A8, charted from A1:A5 only. +fn single_column() -> Session { + let mut s = s(); + let values: Vec<_> = (1..=8).map(|i| json!([i * 10])).collect(); + s.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap(); + s.execute("selection.set", json!({"range": "A1:A5"})).unwrap(); + s.execute("insert.chart", json!({"type": "column"})).unwrap(); + s +} + +/// Region names across row 1, quarters down column A, charted from A1:C4. +fn table() -> Session { + let mut s = s(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["", "North", "South", "East"], + ["Q1", 10, 15, 12], + ["Q2", 20, 25, 22], + ["Q3", 30, 35, 32], + ["Q4", 40, 45, 42], + ["Q5", 50, 55, 52], + ]}), + ) + .unwrap(); + s.execute("selection.set", json!({"range": "A1:C4"})).unwrap(); + s.execute("insert.chart", json!({"type": "column"})).unwrap(); + s +} + +#[test] +fn a_plain_column_chart_is_one_values_block() { + let s = single_column(); + assert_eq!(data(&s), Some(ChartData { sheet: 0, values: r("A1:A5"), by_rows: false, categories: None, names: None })); +} + +#[test] +fn a_table_chart_has_names_categories_and_values_blocks() { + let s = table(); + assert_eq!(data(&s), Some(ChartData { sheet: 0, values: r("B2:C4"), by_rows: false, categories: Some(r("A2:A4")), names: Some(r("B1:C1")) })); +} + +#[test] +fn dragging_the_values_down_plots_the_new_rows_and_undo_puts_them_back() { + let mut s = single_column(); + assert_eq!(points(&s), [5]); + let out = s.execute("chart.setValuesRange", json!({"range": "A1:A8"})).unwrap(); + assert_eq!(out["values"], "Sheet1!A1:A8"); + assert_eq!(chart(&s).series[0].values, "Sheet1!$A$1:$A$8"); + assert_eq!(points(&s), [8]); + assert_eq!(data(&s).unwrap().values, r("A1:A8")); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(points(&s), [5]); + assert_eq!(chart(&s).series[0].values, "Sheet1!$A$1:$A$5"); +} + +#[test] +fn a_wider_block_adds_series_and_existing_series_keep_their_formatting() { + let mut s = table(); + s.execute("chart.formatSelection", json!({"series": 1, "color": "#C00000"})).unwrap(); + let south = chart(&s).series[1].color; + assert!(south.is_some()); + s.execute("chart.setValuesRange", json!({"range": "B2:D6"})).unwrap(); + let c = chart(&s); + assert_eq!(c.series.len(), 3); + assert_eq!(c.series[1].color, south, "South keeps its colour"); + assert_eq!(c.series[2].color, None::, "the new series takes the automatic colour"); + let names: Vec<_> = c.series.iter().map(|se| se.name.clone().unwrap()).collect(); + assert_eq!(names, ["Sheet1!$B$1", "Sheet1!$C$1", "Sheet1!$D$1"], "names follow along the header row"); + assert!(c.series.iter().all(|se| se.categories.as_deref() == Some("Sheet1!$A$2:$A$6")), "labels span the new points"); + assert_eq!(c.series[2].values, "Sheet1!$D$2:$D$6"); + assert_eq!(c.source.as_deref(), Some("Sheet1!A1:D6"), "Switch Row/Column sees the moved blocks"); + assert_eq!(points(&s), [5, 5, 5]); + assert_eq!(data(&s), Some(ChartData { sheet: 0, values: r("B2:D6"), by_rows: false, categories: Some(r("A2:A6")), names: Some(r("B1:D1")) })); + // A narrower block drops the last series. + s.execute("chart.setValuesRange", json!({"range": "B2:B3"})).unwrap(); + let c = chart(&s); + assert_eq!(c.series.len(), 1); + assert_eq!(c.series[0].categories.as_deref(), Some("Sheet1!$A$2:$A$3")); + s.execute("chart.switchRowColumn", json!({})).unwrap(); +} + +#[test] +fn series_in_rows_grow_across_the_columns() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2, 3, 4, 5, 6, 7], [7, 6, 5, 4, 3, 2, 1]]})).unwrap(); + s.execute("selection.set", json!({"range": "A1:E2"})).unwrap(); + s.execute("insert.chart", json!({"type": "line"})).unwrap(); + assert_eq!(data(&s).map(|d| (d.values, d.by_rows)), Some((r("A1:E2"), true))); + s.execute("chart.setValuesRange", json!({"range": "A1:G2"})).unwrap(); + assert_eq!(points(&s), [7, 7]); + assert_eq!(chart(&s).series[1].values, "Sheet1!$A$2:$G$2"); +} + +/// Changes the first chart on the first sheet in place, as a file can leave it. +fn edit_chart(s: &mut Session, f: impl FnOnce(&mut Chart)) { + let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb); + f(&mut wb.sheet_mut(0).unwrap().charts[0]); +} + +#[test] +fn category_labels_written_with_and_without_equals_are_one_block() { + let mut s = table(); + edit_chart(&mut s, |c| c.series[1].categories = Some("=Sheet1!$A$2:$A$4".into())); + assert_eq!(data(&s).unwrap().categories, Some(r("A2:A4"))); + s.execute("chart.setValuesRange", json!({"range": "B2:C6"})).unwrap(); + assert!(chart(&s).series.iter().all(|se| se.categories.as_deref() == Some("Sheet1!$A$2:$A$6")), "both series' labels follow"); +} + +#[test] +fn series_read_in_rows_stay_resizable_after_shrinking_to_one_cell_each() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]})).unwrap(); + s.execute("selection.set", json!({"range": "A1:E2"})).unwrap(); + s.execute("insert.chart", json!({"type": "line"})).unwrap(); + // A file can carry series in rows without saying so; the layout is read from the series. + edit_chart(&mut s, |c| c.by_rows = false); + assert_eq!(data(&s).map(|d| d.by_rows), Some(true)); + s.execute("chart.setValuesRange", json!({"range": "A1:A2"})).unwrap(); + assert!(chart(&s).by_rows); + assert_eq!(data(&s).map(|d| (d.values, d.by_rows)), Some((r("A1:A2"), true)), "still one block, still in rows"); + s.execute("chart.setValuesRange", json!({"range": "A1:C2"})).unwrap(); + assert_eq!(points(&s), [3, 3]); +} + +#[test] +fn set_values_range_refuses_what_it_cannot_do() { + let mut s = table(); + let before = chart(&s); + for (params, why) in [ + (json!({}), "missing `range`"), + (json!({"range": "not a range"}), "not a range"), + (json!({"range": "A1:Z100000"}), "too large"), + (json!({"range": "A1:JA2"}), "too large"), + (json!({"range": "Sheet2!B2:C4"}), ""), + (json!({"chart": 999, "range": "B2:C4"}), "chart"), + ] { + let err = s.execute("chart.setValuesRange", params.clone()).unwrap_err(); + assert!(err.to_string().contains(why), "{params}: {err}"); + assert_eq!(chart(&s), before, "{params} left the chart as it was"); + } + // Series with a gap between them are not one block. + s.execute("selection.set", json!({"range": "A1:D4"})).unwrap(); + s.execute("chart.selectData", json!({"range": "A1:D4"})).unwrap(); + s.execute("chart.selectData", json!({"removeSeries": [1]})).unwrap(); + assert_eq!(data(&s), None); + let err = s.execute("chart.setValuesRange", json!({"range": "B2:C4"})).unwrap_err(); + assert!(err.to_string().contains("not one block"), "{err}"); +} diff --git a/crates/ui-egui/src/chartview.rs b/crates/ui-egui/src/chartview.rs index 48f0846ae..216534614 100644 --- a/crates/ui-egui/src/chartview.rs +++ b/crates/ui-egui/src/chartview.rs @@ -298,9 +298,12 @@ pub(crate) fn paint_objects(app: &SheetApp, p: &Painter, geo: &Geo, wb: &Arc Option<(u32, gridcraft_engine::chart_data::ChartData)> { + if objects_hidden(wb) { + return None; + } + let id = app.selected_chart()?; + let ch = sh.charts.iter().find(|ch| ch.id == id)?; + let dragged = match app.grid.drag { + crate::grid::Drag::ChartData { chart, to, .. } if chart == id => Some(to), + _ => None, + }; + // A drag that scrolls the chart away keeps its preview: the block is still being dragged. + if dragged.is_none() && !anchor_rect(geo, sh, &ch.anchor).intersects(clip) { + return None; + } + let data = gridcraft_engine::chart_data::chart_data(wb, si, ch).filter(|d| d.sheet == si)?; + Some((id, dragged.flatten().map_or(data, |to| data.moved(to)))) +} + +/// Where the handle on corner `h` of the values outline `rr` is painted. +fn data_handle_rect(h: crate::objects::Handle, rr: Rect) -> Rect { + Rect::from_center_size(h.pos(rr), vec2(7.0, 7.0)) +} + +/// Outlines a chart's data as Excel does: series names in red, category labels in purple and +/// values in blue (#4390), with a handle on each corner of the values (#4389). Each pane clips +/// its own part, so frozen panes show the block once. +fn paint_chart_data(p: &Painter, geo: &Geo, sh: &Sheet, data: &gridcraft_engine::chart_data::ChartData) { + let t = Tokens::get(p.ctx()); + let blocks = [(data.names, 1, false), (data.categories, 2, false), (Some(data.values), 0, true)]; + for (range, color, handles) in blocks.into_iter().filter_map(|(r, c, h)| r.map(|r| (r, t.ref_color(c, true), h))) { + let rr = geo.range_rect(sh, range); + for pane in geo.range_panes(range) { + let pp = p.with_clip_rect(pane.intersect(p.clip_rect())); + pp.rect_stroke(rr, 0.0, Stroke::new(1.5, color), StrokeKind::Inside); + if handles { + for h in DATA_HANDLES { + pp.rect_filled(data_handle_rect(h, rr), 0.0, Color32::WHITE); + pp.rect_filled(data_handle_rect(h, rr).shrink(1.0), 0.0, color); + } + } + } + } +} + +/// The corner of the selected chart's values outline under `p`, with the chart and its values +/// block. Like [`hit`], only over the cell area and while objects show; the caller asks +/// [`hit`] first, since objects paint over the outline. +pub fn chart_data_handle(app: &SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) -> Option<(u32, gridcraft_engine::core::RangeRef, crate::objects::Handle)> { + if !geo.cells.contains(p) { + return None; + } + let wb = &app.session.active()?.wb; + let (id, data) = selected_chart_data(app, geo, wb, wb.active_sheet(), sh, geo.cells)?; + let rr = geo.range_rect(sh, data.values); + // Only a corner some pane paints: with frozen panes, a corner scrolled under the frozen band + // is hidden, and the frozen cells it lies under keep the press. + let panes = geo.range_panes(data.values); + DATA_HANDLES + .into_iter() + .filter(|h| panes.iter().any(|pane| pane.intersects(data_handle_rect(*h, rr)))) + .map(|h| (h, h.pos(rr).distance(p))) + .filter(|(_, d)| *d <= DATA_HANDLE_REACH) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(h, _)| (id, data.values, h)) +} + /// Where object `o` sits on the sheet (logical coordinates), when it exists on `sh`. pub fn object_rect(geo: &Geo, sh: &Sheet, o: ObjRef) -> Option { sh.object_anchor(o).map(|a| anchor_rect(geo, sh, &a)) diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index 684b651fb..3a7279f8e 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -151,6 +151,14 @@ pub enum Drag { /// step of an earlier drag. stepped: bool, }, + /// Dragging a corner of the selected chart's values outline (#4389): `to` is the previewed + /// block, which the release gives the chart. + ChartData { + chart: u32, + orig: RangeRef, + corner: crate::objects::Handle, + to: Option, + }, } /// The fill a left-drag of the handle just made, which the Auto Fill Options button can redo diff --git a/crates/ui-egui/src/grid/cursor.rs b/crates/ui-egui/src/grid/cursor.rs index 38de611d8..9a1286f3a 100644 --- a/crates/ui-egui/src/grid/cursor.rs +++ b/crates/ui-egui/src/grid/cursor.rs @@ -57,7 +57,7 @@ fn drag_cursor(drag: &Drag, rtl: bool) -> Option { Drag::ResizeCol { .. } => Some(CursorIcon::ResizeColumn), Drag::ResizeRow { .. } => Some(CursorIcon::ResizeRow), Drag::Freeze { cols, .. } => Some(if *cols { CursorIcon::ResizeHorizontal } else { CursorIcon::ResizeVertical }), - Drag::Object { handle: Some(h), .. } => Some(h.cursor(rtl)), + Drag::Object { handle: Some(h), .. } | Drag::ChartData { corner: h, .. } => Some(h.cursor(rtl)), } } @@ -87,7 +87,9 @@ fn hover_cursor(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response, poin let mods = ctx.input(|i| i.modifiers); let works = hit.is_some_and(|(o, _)| o.kind == ObjKind::Control && app.selected_object != Some(o) && !mods.command && !mods.ctrl); let on_object = hit.is_some(); - if let Some(h) = object_handle { + // A corner of the selected chart's values outline resizes the chart's data, where no object covers it. + let data_handle = if idle && !on_object { crate::chartview::chart_data_handle(app, geo, sh, p).map(|(.., h)| h) } else { None }; + if let Some(h) = object_handle.or(data_handle) { ctx.set_cursor_icon(h.cursor(geo.rtl)); } else if works { ctx.set_cursor_icon(CursorIcon::PointingHand); diff --git a/crates/ui-egui/src/grid/interact.rs b/crates/ui-egui/src/grid/interact.rs index 9d61758d7..6bf0e5d8c 100644 --- a/crates/ui-egui/src/grid/interact.rs +++ b/crates/ui-egui/src/grid/interact.rs @@ -157,6 +157,20 @@ pub(super) fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Respo } return; } + // A corner of the selected chart's values outline drags the block the chart plots + // (#4389); a click on it keeps the chart selected. + if let Some(p) = at + && app.editor.is_none() + && let Some((chart, orig, corner)) = crate::chartview::chart_data_handle(app, geo, sh, p) + { + if primary_drag { + app.grid.drag = Drag::ChartData { chart, orig, corner, to: None }; + if let Some(now) = pos { + drag_chart_data(app, geo, sh, now); + } + } + return; + } app.selected_object = None; } // A right-click on a chart, picture, shape, slicer or form control opens the object's menu, not @@ -630,22 +644,30 @@ fn handle_context_menu_and_keyboard(app: &mut SheetApp, input: &InteractionInput keyboard(app, &ctx, resp, geo, sh); } +/// Whether Esc was pressed this frame, with any modifiers; every Esc press is then spent, so the +/// grid's own Esc doesn't also drop a pending copy or Format Painter. +fn spend_escape(ctx: &egui::Context) -> bool { + ctx.input_mut(|i| { + let pressed = i.key_pressed(egui::Key::Escape); + if pressed { + i.events.retain(|e| !matches!(e, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. })); + } + pressed + }) +} + fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) { let (geo, sh, wb, sel, pos) = (input.geo, input.sheet, input.workbook, &input.selection, input.position); let resp = input.response; // Esc during a header-boundary drag cancels it: undo the preview, ignore the release. egui // aborts the drag on Esc, so `resp.dragged()` is already false in this frame. The key is // spent on the drag, so the grid's Esc doesn't also drop a pending copy or Format Painter. - if matches!(app.grid.drag, Drag::ResizeCol { .. } | Drag::ResizeRow { .. }) - && input.context.input_mut(|i| { - let pressed = i.key_pressed(egui::Key::Escape); - if pressed { - // With any modifiers, as before: the drag is cancelled and every Esc press spent. - i.events.retain(|e| !matches!(e, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. })); - } - pressed - }) - { + // Esc during a drag of a chart's values outline drops it: the chart keeps its data, whatever + // modifiers are held (egui ends the drag on any Esc, so the release must not apply it). + if matches!(app.grid.drag, Drag::ChartData { .. }) && spend_escape(&input.context) { + app.grid.drag = Drag::None; + } + if matches!(app.grid.drag, Drag::ResizeCol { .. } | Drag::ResizeRow { .. }) && spend_escape(&input.context) { // Undo back to where the drag began, but never past it into an earlier edit. let steps = resize_steps(app); if steps > 0 { @@ -742,6 +764,10 @@ fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) { scroll_by(app, auto); } Drag::Object { .. } => drag_object(app, geo, sh, p), + Drag::ChartData { .. } => { + drag_chart_data(app, geo, sh, p); + scroll_by(app, auto); + } Drag::None => {} } } @@ -822,6 +848,23 @@ fn handle_release(app: &mut SheetApp, input: &InteractionInput<'_>) { coalesce_resize_undo(app); } } + // The release may be the first frame to report the pointer's last position, so the + // block is taken from there. (Esc already dropped a cancelled drag, and so did a + // change to the chart's data; one in the release's own frame is caught here.) + Drag::ChartData { chart, orig, corner, to } => { + let to = if resp.drag_stopped() + && let Some(p) = pos + { + Some(chart_data_target(geo, sh, orig, corner, p)) + } else { + to + }; + if let Some(to) = to.filter(|to| *to != orig) + && chart_still_plots(app, chart, orig) + { + app.run_or_alert("chart.setValuesRange", json!({"chart": chart, "range": to.a1()})); + } + } Drag::MoveCols { source, before: Some(before) } => { if let Err(e) = app.run("sheet.moveColumns", json!({"cols": source.a1(), "before": before})) { app.message = Some(("GridCraft".into(), crate::clean_error(&e))); @@ -1201,6 +1244,69 @@ fn drag_object(app: &mut SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) { } } +/// Previews the selected chart's values block with the grabbed corner dragged to `p` (logical +/// coordinates); the opposite corner stays. The release gives the chart the block +/// (`chart.setValuesRange`). +fn drag_chart_data(app: &mut SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) { + let Drag::ChartData { chart, orig, corner, .. } = app.grid.drag else { return }; + // The chart's data changed under the drag: drop it, as Esc does, rather than preview a + // block the release would put over that change. + if !chart_still_plots(app, chart, orig) { + app.grid.drag = Drag::None; + return; + } + app.grid.drag = Drag::ChartData { chart, orig, corner, to: Some(chart_data_target(geo, sh, orig, corner, p)) }; +} + +/// Whether chart `chart` on the active sheet still plots the values block `orig` its drag +/// started from. A command run between frames (the control channel, a macro) may have changed +/// or removed it, and the dragged block would then overwrite that change. Read from the session, +/// not the frame's workbook, which predates such a command. +fn chart_still_plots(app: &SheetApp, chart: u32, orig: RangeRef) -> bool { + let Some(wb) = app.session.active().map(|d| &d.wb) else { return false }; + let si = wb.active_sheet(); + wb.sheet(si) + .and_then(|sh| sh.charts.iter().find(|ch| ch.id == chart)) + .and_then(|ch| gridcraft_engine::chart_data::chart_data(wb, si, ch)) + .is_some_and(|data| data.sheet == si && data.values == orig) +} + +/// The values block `orig` with its `corner` dragged to `p`. Each edge the corner moves snaps +/// to the gridline nearest the pointer, so every row and column changes over at its own middle +/// whatever its height or width, and a release where the press was (on the corner's own +/// gridlines) changes nothing. The block may flip past its fixed edges, as a selection does; a +/// moving edge dropped on its fixed edge keeps one row or column. +fn chart_data_target(geo: &Geo, sh: &Sheet, orig: RangeRef, corner: crate::objects::Handle, p: Pos2) -> RangeRef { + let (sx, sy) = corner.sides(); + let (x, y) = (p.x.clamp(geo.cells.left() + 1.0, geo.cells.right() - 1.0), p.y.clamp(geo.cells.top() + 1.0, geo.cells.bottom() - 1.0)); + // Gridline `k` is the top (left) edge of row (column) `k`; the last one closes the sheet. + let row = geo.row_at(sh, y); + let row_line = nearest_line(geo.y(sh, row), sh.row_height(row) * geo.z, row, y, MAX_ROWS); + let col = geo.col_at(sh, x); + let col_line = nearest_line(geo.x(sh, col), sh.col_width(col) * geo.z, col, x, MAX_COLS); + let (r0, r1) = between_lines(if sy < 0 { orig.end.row.saturating_add(1) } else { orig.start.row }, row_line, sy); + let (c0, c1) = between_lines(if sx < 0 { orig.end.col.saturating_add(1) } else { orig.start.col }, col_line, sx); + RangeRef::new(CellRef::new(r0, c0), CellRef::new(r1, c1)) +} + +/// The gridline nearest `v` for line `index`, which starts at `start` and is `size` long: its +/// own start, or the next line's past its middle (never past `last`). +fn nearest_line(start: f32, size: f32, index: u32, v: f32, last: u32) -> u32 { + if v - start < size / 2.0 { index } else { index.saturating_add(1).min(last) } +} + +/// The rows (columns) from gridline `fixed` to gridline `moving`. A moving edge on the fixed one +/// keeps one line on its own side: after it for a bottom or right edge (`dir` > 0), before it +/// for a top or left edge. +fn between_lines(fixed: u32, moving: u32, dir: i8) -> (u32, u32) { + let moving = match (moving == fixed, dir > 0) { + (false, _) => moving, + (true, true) => fixed.saturating_add(1), + (true, false) => fixed.saturating_sub(1), + }; + (fixed.min(moving), fixed.max(moving).saturating_sub(1)) +} + /// A click on a hyperlink. References select; web and e-mail addresses ask first (the dialog's /// OK calls `Session::open_confirmed_link`, since `link.open` refuses them for programmatic /// callers, #2181); every other kind is refused with a message. The decision is the engine's @@ -1253,6 +1359,28 @@ pub fn point_move(app: &mut SheetApp, ed: &mut EditState, dr: i64, dc: i64, exte mod resize_tests { use super::*; + #[test] + fn a_chart_data_edge_snaps_to_the_nearest_gridline_of_any_size() { + // Row 5 starts at 100 and is 20 tall: before its middle the line is its own, past it the next. + assert_eq!(nearest_line(100.0, 20.0, 5, 109.0, MAX_ROWS), 5); + assert_eq!(nearest_line(100.0, 20.0, 5, 111.0, MAX_ROWS), 6); + // A 100-tall row changes over at 50 into it, not at the grabbed row's middle. + assert_eq!(nearest_line(100.0, 100.0, 5, 149.0, MAX_ROWS), 5); + assert_eq!(nearest_line(100.0, 100.0, 5, 151.0, MAX_ROWS), 6); + assert_eq!(nearest_line(0.0, 20.0, MAX_ROWS - 1, 19.0, MAX_ROWS), MAX_ROWS); + // A1:A5 (lines 0 and 5) by its bottom edge: on line 5 it stays, on 8 it grows, on 2 it shrinks. + assert_eq!(between_lines(0, 5, 1), (0, 4)); + assert_eq!(between_lines(0, 8, 1), (0, 7)); + assert_eq!(between_lines(0, 2, 1), (0, 1)); + // Dropped on its fixed edge it keeps one row; past it the block flips. + assert_eq!(between_lines(4, 4, 1), (4, 4)); + assert_eq!(between_lines(4, 2, 1), (2, 3)); + // By its top edge (fixed line 5, below A5). + assert_eq!(between_lines(5, 0, -1), (0, 4)); + assert_eq!(between_lines(5, 5, -1), (4, 4)); + assert_eq!(between_lines(5, 7, -1), (5, 6)); + } + #[test] fn resize_targets_follow_the_selection_only_when_the_dragged_line_is_in_it() { let sel = [RangeRef::cols(0, 0), RangeRef::cols(2, 3)]; diff --git a/crates/ui-egui/tests/it/chart_data_drag.rs b/crates/ui-egui/tests/it/chart_data_drag.rs new file mode 100644 index 000000000..3c2066e33 --- /dev/null +++ b/crates/ui-egui/tests/it/chart_data_drag.rs @@ -0,0 +1,265 @@ +//! #4389 and #4390: a selected chart outlines its data in the sheet (series names red, category +//! labels purple, values blue), and dragging a corner of the values outline changes what the +//! chart plots, through real pointer input. + +use egui::{Event, Key, Modifiers, PointerButton, Pos2, Shape, vec2}; +use gridcraft_engine::core::RangeRef; +use gridcraft_ui_egui::theme::Tokens; +use serde_json::json; + +type Harness = egui_kittest::Harness<'static, gridcraft_ui_egui::SheetApp>; + +/// 10..50 down A1:A5 and 5s below them, charted from A1:A5, which stays the cell selection as +/// after Insert › Chart, so the fill handle sits on the outline's bottom-right corner. +fn fixture() -> (Harness, u32) { + let mut session = crate::support::blank_session(); + let values: Vec<_> = [10, 20, 30, 40, 50, 5, 5, 5].iter().map(|v| json!([v])).collect(); + session.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap(); + session.execute("selection.set", json!({"range": "A1:A5"})).unwrap(); + let chart = session.execute("insert.chart", json!({"type": "column", "at": "D3", "width": 300, "height": 200})).unwrap(); + let id = chart["chart"].as_u64().unwrap() as u32; + let mut h = crate::support::stepped_harness(session); + h.state_mut().select_object_id(Some(id)); + h.run_steps(2); + (h, id) +} + +fn values(h: &Harness) -> String { + h.state().session.doc().unwrap().wb.active().unwrap().charts[0].series[0].values.clone() +} + +/// On-screen rect of `range`. +fn rect(h: &Harness, range: &str) -> egui::Rect { + let app = h.state(); + let sh = app.session.doc().unwrap().wb.active().unwrap(); + app.grid.geo.as_ref().unwrap().range_rect(sh, RangeRef::parse(range).unwrap()) +} + +fn hover(h: &mut Harness, at: Pos2) { + h.input_mut().events.push(Event::PointerMoved(at)); + h.run_steps(2); +} + +fn button(h: &mut Harness, at: Pos2, pressed: bool) { + h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +/// Presses at `from` and moves to `to` in small steps, leaving the button down. +fn press_and_move(h: &mut Harness, from: Pos2, to: Pos2) { + hover(h, from); + button(h, from, true); + press_and_move_on(h, from, to); +} + +/// With the button already down, moves from `from` to `to` in small steps. +fn press_and_move_on(h: &mut Harness, from: Pos2, to: Pos2) { + for i in 1..=8 { + h.input_mut().events.push(Event::PointerMoved(from + (to - from) * (i as f32 / 8.0))); + h.run_steps(1); + } +} + +#[test] +fn dragging_the_values_corner_extends_the_chart_data() { + let (mut h, id) = fixture(); + assert_eq!(values(&h), "Sheet1!$A$1:$A$5"); + let corner = rect(&h, "A1:A5").right_bottom(); + hover(&mut h, corner); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::ResizeNwSe, "the corner shows a resize cursor, not the fill cross"); + // Three rows down from the corner, as the hand moves it. + let target = rect(&h, "A8").right_bottom(); + press_and_move(&mut h, corner, target); + // The outline previews the new block while the button is held; the chart is unchanged. + let blue = Tokens::get(&h.ctx).ref_color(0, true); + let preview = rect(&h, "A1:A8"); + let previewed = h.output().shapes.iter().any(|s| matches!(&s.shape, Shape::Rect(r) if r.rect == preview && r.stroke.color == blue)); + assert!(previewed, "the outline follows the pointer"); + assert_eq!(values(&h), "Sheet1!$A$1:$A$5"); + button(&mut h, target, false); + assert_eq!(values(&h), "Sheet1!$A$1:$A$8", "the chart plots the dragged block"); + assert_eq!(h.state().selected_chart(), Some(id), "the chart stays selected"); + let a6 = h.state().session.doc().unwrap().wb.active().unwrap().value(gridcraft_engine::core::CellRef::parse("A6").unwrap()); + assert_eq!(a6, gridcraft_engine::core::Value::number(5.0), "the press did not drag the fill handle"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(values(&h), "Sheet1!$A$1:$A$5", "one undo step puts the block back"); +} + +#[test] +fn dragging_the_top_corner_down_shrinks_the_chart_data() { + let (mut h, _) = fixture(); + let corner = rect(&h, "A1:A5").left_top() + vec2(1.0, 1.0); + let target = rect(&h, "A3").left_top() + vec2(1.0, 1.0); + press_and_move(&mut h, corner, target); + button(&mut h, target, false); + assert_eq!(values(&h), "Sheet1!$A$3:$A$5"); +} + +/// #4391 review: a corner lies on the boundary of the next row and column, so reading the pointer +/// as is put a press on the bottom-right corner of A1:A5 in B6. +#[test] +fn a_drag_back_to_the_grabbed_corner_or_along_its_edge_keeps_the_other_axis() { + // Away and back to the very point pressed: nothing changes. + let (mut h, _) = fixture(); + let corner = rect(&h, "A1:A5").right_bottom(); + press_and_move(&mut h, corner, corner + vec2(40.0, 30.0)); + press_and_move_on(&mut h, corner + vec2(40.0, 30.0), corner); + button(&mut h, corner, false); + assert_eq!(values(&h), "Sheet1!$A$1:$A$5", "a release where the press was leaves the data alone"); + // Straight down the right edge of column A: rows only, no column B. + let (mut h, _) = fixture(); + let corner = rect(&h, "A1:A5").right_bottom(); + let target = rect(&h, "A6").right_bottom(); + press_and_move(&mut h, corner, target); + button(&mut h, target, false); + assert_eq!(values(&h), "Sheet1!$A$1:$A$6"); +} + +/// #4391 review: the drag read the pointer from the middle of the grabbed row, so with a tall +/// row 5 the pointer could reach the bottom of a short row 6 and the block stayed at A1:A5. +#[test] +fn a_drag_past_rows_of_unequal_height_follows_the_rows_under_the_pointer() { + let (mut h, _) = fixture(); + h.state_mut().run("home.rowHeight", json!({"rows": "5:5", "height": 120})).unwrap(); + h.run_steps(2); + let corner = rect(&h, "A1:A5").right_bottom(); + let row6 = rect(&h, "A6"); + assert!(rect(&h, "A5").height() > 3.0 * row6.height(), "row 5 is much taller than row 6"); + // Short of the middle of row 6 the edge stays on row 5's bottom gridline. + let short = corner + vec2(0.0, row6.height() * 0.4); + press_and_move(&mut h, corner, short); + assert!(values_outline_at(&h, "A1:A5")); + // At the bottom of row 6 the block takes row 6, in the preview and on release. + let target = row6.right_bottom(); + press_and_move_on(&mut h, short, target); + assert!(values_outline_at(&h, "A1:A6"), "the preview takes row 6"); + button(&mut h, target, false); + assert_eq!(values(&h), "Sheet1!$A$1:$A$6"); +} + +#[test] +fn escape_cancels_a_values_drag() { + let (mut h, _) = fixture(); + let corner = rect(&h, "A1:A5").right_bottom(); + let target = rect(&h, "A8").right_bottom(); + press_and_move(&mut h, corner, target); + h.key_press(Key::Escape); + h.run_steps(2); + button(&mut h, target, false); + assert_eq!(values(&h), "Sheet1!$A$1:$A$5"); +} + +/// Whether the last frame stroked `range` in the values blue. +fn values_outline_at(h: &Harness, range: &str) -> bool { + let blue = Tokens::get(&h.ctx).ref_color(0, true); + let want = rect(h, range); + h.output().shapes.iter().any(|s| matches!(&s.shape, Shape::Rect(r) if r.rect == want && r.stroke.color == blue)) +} + +#[test] +fn a_release_in_the_same_frame_as_the_last_move_takes_the_release_position() { + let (mut h, _) = fixture(); + let (corner, a6, end) = (rect(&h, "A1:A5").right_bottom(), rect(&h, "A6").right_bottom(), rect(&h, "A8").right_bottom()); + press_and_move(&mut h, corner, a6); + // The pointer reaches A8 and the button goes up within one frame. + h.input_mut().events.push(Event::PointerMoved(end)); + h.input_mut().events.push(Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert_eq!(values(&h), "Sheet1!$A$1:$A$8"); +} + +/// A command that changes the chart's data while the button is held (the control channel runs +/// between frames) makes the drag stale: releasing must not put the dragged block over it, +/// whether the pointer moves on first or is released straight away. +#[test] +fn a_chart_data_change_during_the_drag_is_not_overwritten_by_the_release() { + for move_on in [true, false] { + let (mut h, id) = fixture(); + let (corner, a7, a8) = (rect(&h, "A1:A5").right_bottom(), rect(&h, "A7").right_bottom(), rect(&h, "A8").right_bottom()); + press_and_move(&mut h, corner, a7); + h.state_mut().session.execute("chart.setValuesRange", json!({"chart": id, "range": "A2:A4"})).unwrap(); + if move_on { + press_and_move_on(&mut h, a7, a8); + } + button(&mut h, if move_on { a8 } else { a7 }, false); + assert_eq!(values(&h), "Sheet1!$A$2:$A$4", "the newer data stays (pointer moved on: {move_on})"); + assert!(!values_outline_at(&h, "A1:A8") && !values_outline_at(&h, "A1:A7"), "no stale preview is left (pointer moved on: {move_on})"); + } +} + +#[test] +fn escape_with_ctrl_held_still_cancels_a_values_drag() { + let (mut h, _) = fixture(); + let (corner, target) = (rect(&h, "A1:A5").right_bottom(), rect(&h, "A8").right_bottom()); + press_and_move(&mut h, corner, target); + h.input_mut().events.push(Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::CTRL }); + h.run_steps(2); + button(&mut h, target, false); + assert_eq!(values(&h), "Sheet1!$A$1:$A$5"); +} + +#[test] +fn the_preview_stays_while_the_drag_scrolls_the_chart_away() { + let (mut h, _) = fixture(); + // Column A stays in a frozen pane while the chart in D:H scrolls off to the left. + h.state_mut().run("view.freezePanes", json!({"cell": "B1"})).unwrap(); + h.run_steps(2); + let (corner, target) = (rect(&h, "A1:A5").right_bottom(), rect(&h, "A8").right_bottom()); + press_and_move(&mut h, corner, target); + assert!(values_outline_at(&h, "A1:A8")); + h.state_mut().view_mut().unwrap().scroll.x = 3000.0; + h.run_steps(2); + assert!(values_outline_at(&h, "A1:A8"), "the dragged block is still previewed"); + button(&mut h, target, false); + assert_eq!(values(&h), "Sheet1!$A$1:$A$8"); +} + +#[test] +fn a_corner_hidden_under_frozen_rows_cannot_be_grabbed() { + let mut session = crate::support::blank_session(); + let values: Vec<_> = (1..=12).map(|v| json!([v])).collect(); + session.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap(); + session.execute("selection.set", json!({"range": "A5:A8"})).unwrap(); + let chart = session.execute("insert.chart", json!({"type": "column", "at": "D2", "width": 300, "height": 200})).unwrap(); + session.execute("view.freezePanes", json!({"cell": "A4"})).unwrap(); + let mut h = crate::support::stepped_harness(session); + h.state_mut().select_object_id(Some(chart["chart"].as_u64().unwrap() as u32)); + // Scroll two rows, so the top of row 5 lies under the frozen rows 1-3. + let two_rows = { + let sh = h.state().session.doc().unwrap().wb.active().unwrap().clone(); + (sh.row_top(5) - sh.row_top(3)) as f32 + }; + h.state_mut().view_mut().unwrap().scroll.y = two_rows; + h.run_steps(2); + let app = h.state(); + let sh = app.session.doc().unwrap().wb.active().unwrap(); + let geo = app.grid.geo.as_ref().unwrap(); + let block = geo.range_rect(sh, RangeRef::parse("A5:A8").unwrap()); + let hidden = block.left_top(); + let frozen_bottom = geo.y(sh, 2) + sh.row_height(2) as f32 * geo.z; + assert!(geo.cells.contains(hidden) && hidden.y + 4.0 < frozen_bottom, "the top corner lies over the frozen rows: {hidden:?} {frozen_bottom}"); + assert!(gridcraft_ui_egui::chartview::chart_data_handle(app, geo, sh, hidden).is_none(), "a hidden corner is not a handle"); + assert!(gridcraft_ui_egui::chartview::chart_data_handle(app, geo, sh, block.right_bottom()).is_some(), "a visible corner still is"); +} + +#[test] +fn a_selected_chart_outlines_names_categories_and_values_in_their_colours() { + let mut session = crate::support::blank_session(); + session + .execute("range.setValues", json!({"range": "A1", "values": [["", "North", "South"], ["Q1", 10, 15], ["Q2", 20, 25], ["Q3", 30, 35]]})) + .unwrap(); + session.execute("selection.set", json!({"range": "A1:C4"})).unwrap(); + let chart = session.execute("insert.chart", json!({"type": "column", "at": "F2", "width": 300, "height": 200})).unwrap(); + let mut h = crate::support::stepped_harness(session); + h.state_mut().select_object_id(Some(chart["chart"].as_u64().unwrap() as u32)); + h.run_steps(2); + let t = Tokens::get(&h.ctx); + let stroked = |h: &Harness, range: &str, color: egui::Color32| { + let want = rect(h, range); + h.output().shapes.iter().any(|s| matches!(&s.shape, Shape::Rect(r) if r.rect == want && r.stroke.color == color && r.stroke.width == 1.5)) + }; + assert!(stroked(&h, "B1:C1", t.ref_color(1, true)), "series names in red"); + assert!(stroked(&h, "A2:A4", t.ref_color(2, true)), "category labels in purple"); + assert!(stroked(&h, "B2:C4", t.ref_color(0, true)), "the values as one blue block"); + assert!(!stroked(&h, "B2:B4", t.ref_color(0, true)), "not one outline per series"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index ad4d67c4c..83f4b5736 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -16,6 +16,7 @@ mod cell_editor_caret; mod cell_pictures; mod cf_rule_pick; mod cf_rules_manager; +mod chart_data_drag; mod chart_data_table; mod chart_resize; mod chart_source_layering; diff --git a/docs/chart-parity.md b/docs/chart-parity.md index 39851f2bc..4967b0020 100644 --- a/docs/chart-parity.md +++ b/docs/chart-parity.md @@ -1,6 +1,6 @@ # Chart parity -> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-11-07 · **Change:** minor (chart-data-table keys pass the series index to the shared combo plot-kind rule, restoring compilation after #1150; earlier: doughnut charts: every series is a concentric ring, the first series innermost; hole size and first slice angle kept; rotated slices cover their own sweep; legend names categories; earlier: charts resize from eight handles, chart data tables, legend keys and borders, native XLSX round-trip and print/PDF; earlier: selected chart source outlines stay beneath floating objects) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-11-16 · **Change:** minor (a selected chart outlines its series names, category labels and values in Excel's colours, and dragging a corner of the values outline changes the plotted block, #4389, #4390; earlier: chart-data-table keys pass the series index to the shared combo plot-kind rule, restoring compilation after #1150; earlier: doughnut charts: every series is a concentric ring, the first series innermost; hole size and first slice angle kept; rotated slices cover their own sweep; legend names categories; earlier: charts resize from eight handles, chart data tables, legend keys and borders, native XLSX round-trip and print/PDF; earlier: selected chart source outlines stay beneath floating objects) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Excel's chart types and chart elements against GridCraft. Part of [target-app-parity.md](target-app-parity.md). **Breadth ~50%, ready ~30%, 40–60 h** (estimated). @@ -40,7 +40,8 @@ Sources: `crates/model/src/features.rs` (`ChartKind`, `Chart`, `Series`), `crate | Element | Excel | GridCraft | |---|---|---| | Move and resize the chart object | yes | yes (eight handles, each moving only its own edges; Format Chart Area Size fields) (#190) | -| Selected chart source-data outline | visible on uncovered cells, beneath floating objects | painted above cells and below charts, shapes, pictures and slicers; retains pane clipping and right-to-left cell geometry (#2861) | +| Selected chart source-data outline | visible on uncovered cells, beneath floating objects | painted above cells and below charts, shapes, pictures and slicers; retains pane clipping and right-to-left cell geometry (#2861); series names red, category labels purple, values one blue block (#4390); series that are not one block keep a blue outline per series | +| Drag the source-data outline to change the chart's data | corner handles on the outline resize the plotted range | the values outline's four corners show resize cursors; a drag previews the block and the release runs `chart.setValuesRange` as one undo step: series keep their formatting, a wider block adds series and a narrower one drops them, aligned names and category labels follow; Esc cancels (#4389). Moving the block by its edge and dragging the name or category outlines are not done | | Chart title, axis titles | text, linked to cells, full formatting | text only | | Legend | position, overlay, formatting, per-entry delete | position only | | Data labels | value, category, series, percentage, from cells, callouts, position | one on/off flag | @@ -107,6 +108,7 @@ are (#1686). Such series get no `numCache`/`strCache` on save (#1690). | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | A selected chart outlines its series names (red), category labels (purple) and values (one blue block), and the values outline has corner handles: dragging one changes the block the series plot through the new `chart.setValuesRange` command, keeping each series' formatting (#4389, #4390). Engine and real-input UI tests cover growing, shrinking, adding series, undo and Esc. No readiness score change. | | 2026-11-07 | minor | Chart-data-table keys use the shared plot-kind helper with their series index after #1150. A focused regression checks the first combo series uses a column key and later series use line keys. No readiness score change. | | 2026-11-02 | minor | Charts move and resize from eight handles, each moving only its own edges (#190); resizing leaves the work list (1–2 h, within the 40–60 h rounding) | | 2026-11-01 | minor | Chart data tables for column, bar, line, area and compatible combo charts: command/UI controls, formatted source values, blanks, grouped category headers, legend keys, independent borders, shared print/PDF rendering and native c:dTable import/export. Dense tables show a space notice; no readiness score change. |