diff --git a/ROADMAP.md b/ROADMAP.md index 7f010d56a..0c404d123 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -156,6 +156,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-26 | Arabic PDF export shapes licensed glyph outlines and preserves searchable logical text; characters the font lacks, or a missing Arabic font, fall back to the standard fonts instead of failing the export | | 2026-10-26 | Arabic bidi display/editing preserve logical source text; per-cell reading direction is editable and survives undo, XLSX and conditional-format priority | | 2026-10-26 | Arabic text shows in cells and the interface through a system, fontconfig or craft-fonts Arabic face; workbook fonts keep their script fallbacks | +| 2026-10-25 | Fill handle: from numbers, the right-drag menu offers Linear Trend and Growth Trend, which continue the best-fit line or exponential curve of the source (1, 2 gives 3, 4, 5 or 4, 8, 16) | | 2026-10-25 | AutoSum over a selection does what Excel does: a selected row gets one total to its right (in its last cell if that is empty), not a one-cell total under each cell; a block whose last column is empty gets each row's total there, one whose last row is empty each column's, and with both the corner gets the total of the block; otherwise totals go under each column as before | | 2026-10-24 | Macro interface ([macros.md](docs/macros.md#in-the-window)): an Automate › Macros group (Record Macro, which turns into Stop Recording, Use Relative References, Run Macro with recent macros); "Recording · N steps" with Stop in the status bar; a Record Macro dialog (checked name, free Ctrl+Shift shortcut, description); the Macros dialog lists macros beside Automate scripts and a VBA project, with Run, Step Into, Edit, Create, Delete and Options; Ctrl+Shift+letter macro shortcuts; questions that offer Run, Overwrite, Shift Down or Shift Right; a step editor with a breakpoint gutter, drag to reorder, a command picker, reference boxes that switch between relative tokens and absolute references, Inputs and Output tabs, a debug bar (Check, Run, Step, Continue, Run to Here, Stop with keep or undo) and grid overlays for inputs, writes, conflicts and the current step | | 2026-10-24 | Go To lists the named ranges of every sheet (`Sheet2!Name` for a name scoped to another sheet; hidden names, constants and formulas left out) and the references entered before, a double-click goes to an entry, and the Reference box takes several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30`) | diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index c11ff655a..b8ce56bf6 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -130,7 +130,7 @@ pub fn specs() -> Vec { "AutoFill", [], None, - "{source: \"A1:A2\", target: \"A1:A10\", mode?: series|alternate|copy|formats|values|extend|days|weekdays|months|years}: the fill-handle drag (alternate = Ctrl+drag: a lone number counts up, any other series copies; values = Fill Without Formatting: the series, targets keep their formats; extend = Fill Series: the series, and a lone number counts up; days, weekdays, months, years = Fill Days, Fill Weekdays, Fill Months, Fill Years: dates step by one unit, or by the difference between the first two dates in that unit, and weekdays skip Saturday and Sunday)", + "{source: \"A1:A2\", target: \"A1:A10\", mode?: series|alternate|copy|formats|values|extend|days|weekdays|months|years|linearTrend|growthTrend}: the fill-handle drag (alternate = Ctrl+drag: a lone number counts up, any other series copies; values = Fill Without Formatting: the series, targets keep their formats; extend = Fill Series: the series, and a lone number counts up; days, weekdays, months, years = Fill Days, Fill Weekdays, Fill Months, Fill Years: dates step by one unit, or by the difference between the first two dates in that unit, and weekdays skip Saturday and Sunday; linearTrend, growthTrend = Linear Trend, Growth Trend: the targets continue the least-squares line or the exponential curve fitted to each row or column of source numbers, and the source keeps its values; an error when a source cell is not a number or holds a formula, or for growthTrend when a row or column mixes signs or holds zero)", has_doc, auto_fill ), diff --git a/crates/engine/src/cmd/edit/fill.rs b/crates/engine/src/cmd/edit/fill.rs index 489eca2a4..869d5273b 100644 --- a/crates/engine/src/cmd/edit/fill.rs +++ b/crates/engine/src/cmd/edit/fill.rs @@ -52,6 +52,8 @@ pub(super) fn auto_fill(s: &mut Session, p: &Json) -> Result { "weekdays" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Weekday), "months" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Month), "years" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Year), + "linearTrend" => crate::fill::FillMode::LinearTrend, + "growthTrend" => crate::fill::FillMode::GrowthTrend, _ => crate::fill::FillMode::Series, }; if target.count() > crate::fill::MAX_FILL_CELLS || src.count() > crate::fill::MAX_FILL_CELLS { diff --git a/crates/engine/src/fill.rs b/crates/engine/src/fill.rs index 25e137878..a43fa6e81 100644 --- a/crates/engine/src/fill.rs +++ b/crates/engine/src/fill.rs @@ -28,6 +28,12 @@ pub enum FillMode { /// counted in that unit (one unit when they fall in the same one). A source that isn't dates /// extends like a plain drag. Dates(DateUnit), + /// Linear Trend: the targets continue the least-squares line (y = mx + b) through the source's + /// numbers. The source keeps its values. + LinearTrend, + /// Growth Trend: the targets continue the exponential curve (y = b·m^x) fitted to the source's + /// numbers. The source keeps its values. + GrowthTrend, } /// The step of a [`FillMode::Dates`] fill. @@ -47,6 +53,87 @@ impl FillMode { } } +/// Whether a fill from `src` to `target` runs down or up the sheet rather than across it. +fn fills_vertically(src: RangeRef, target: RangeRef) -> bool { + target.height() != src.height() || target.width() == src.width() +} + +/// The numbers in each lane of `src` that a fill to `target` continues, or `None` when a source +/// cell is empty or holds text, a logical value, an error, a formula or Python code. +fn numeric_lanes(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef) -> Option>> { + let sh = wb.sheet(sheet)?; + lane_cells(src, target).map(|lane| lane.map(|c| trend_number(sh, c)).collect()).collect() +} + +/// The cells of each lane of `src` that a fill to `target` continues: each column when the fill +/// runs down or up the sheet, each row when it runs across. +fn lane_cells(src: RangeRef, target: RangeRef) -> impl Iterator> { + let vertical = fills_vertically(src, target); + let (lanes, len) = if vertical { (src.start.col..=src.end.col, src.height()) } else { (src.start.row..=src.end.row, src.width()) }; + lanes.map(move |lane| (0..len).map(move |i| if vertical { CellRef::new(src.start.row + i, lane) } else { CellRef::new(lane, src.start.col + i) })) +} + +/// The sign Growth Trend fits a lane's numbers by: 1 when they are all above zero, -1 when they +/// are all below zero, and `None` otherwise. +fn growth_sign(nums: impl IntoIterator) -> Option { + let (mut above, mut below) = (true, true); + for y in nums { + above &= y > 0.0; + below &= y < 0.0; + } + if above { + Some(1.0) + } else if below { + Some(-1.0) + } else { + None + } +} + +/// The number a trend fill reads from source cell `c`, or `None` when it is empty or holds text, a +/// logical value, an error, a formula or Python code. +fn trend_number(sh: &gridcraft_model::Sheet, c: CellRef) -> Option { + let cell = sh.cell(c)?; + if cell.formula.is_some() || cell.py.is_some() || !cell.value.is_number() { + return None; + } + cell.value.as_f64() +} + +/// Whether the fill menu offers Linear Trend (`growth` false) or Growth Trend (`growth` true) for a +/// fill from `src` to `target`: every source cell holds a number, and for Growth Trend the numbers +/// of each lane are all above zero or all below zero. A source or target larger than +/// [`MAX_FILL_CELLS`], or a target that doesn't hold the source in a corner, is refused by +/// `edit.autoFill`, so neither trend applies to it and no source cell is read. +pub fn trend_applies(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef, growth: bool) -> bool { + let (linear, growth_fits) = trends_that_apply(wb, sheet, src, target); + if growth { growth_fits } else { linear } +} + +/// [`trend_applies`] for both trends from one read of the source: (Linear Trend, Growth Trend). It +/// checks each cell's number and sign and fits nothing, so the menu does not wait on a fit. +pub fn trends_that_apply(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef) -> (bool, bool) { + if src.count() > MAX_FILL_CELLS || target.count() > MAX_FILL_CELLS || !holds_source_in_corner(src, target) { + return (false, false); + } + let Some(sh) = wb.sheet(sheet) else { return (false, false) }; + let mut growth = true; + // The lanes and the sign rule are the ones the fill uses (`numeric_lanes`, `Pattern::growth`). + for lane in lane_cells(src, target) { + let mut missing = false; + let sign = growth_sign(lane.map_while(|c| { + let y = trend_number(sh, c); + missing |= y.is_none(); + y + })); + if missing { + return (false, false); + } + growth &= sign.is_some(); + } + (true, growth) +} + /// Whether a number format shows a calendar date (`YYYY-MM-DD` and `m/d/yyyy h:mm` do; `0 "days"` /// and `h:mm` don't). fn is_date_format(fmt: &str) -> bool { @@ -102,7 +189,7 @@ pub fn fill_except( let custom = cx.wb.custom_lists.clone(); let Some(sh) = cx.wb.sheet(sheet) else { return Ok(()) }; // Direction: down/up if target extends rows, else right/left. - let vertical = target.height() != src.height() || target.width() == src.width(); + let vertical = fills_vertically(src, target); let forward = if vertical { target.end.row > src.end.row || target.start.row == src.start.row } else { @@ -120,11 +207,25 @@ pub fn fill_except( if u64::from(lane_count).saturating_mul(u64::from(steps)) > MAX_FILL_CELLS { return Err(crate::EngineError::Other("The fill is too large.".into())); } + // Linear Trend and Growth Trend fit each lane's numbers. + let trends: Vec = match mode { + FillMode::LinearTrend | FillMode::GrowthTrend => { + let Some(lanes) = numeric_lanes(&cx.wb, sheet, src, target) else { + return Err(crate::EngineError::Other("Linear Trend and Growth Trend need a number in every source cell.".into())); + }; + let fit = |nums: &Vec| if mode == FillMode::GrowthTrend { Pattern::growth(nums) } else { Some(Pattern::linear(nums)) }; + let Some(trends) = lanes.iter().map(fit).collect() else { + return Err(crate::EngineError::Other("Growth Trend needs numbers that are all above zero or all below zero.".into())); + }; + trends + } + _ => Vec::new(), + }; let lanes: Vec = if vertical { (src.start.col..=src.end.col).collect() } else { (src.start.row..=src.end.row).collect() }; let src_len = if vertical { src.height() } else { src.width() }; let mut writes: Vec<(CellRef, Option)> = Vec::new(); let mut pictures = Vec::new(); - for lane in lanes { + for (lane_i, lane) in lanes.into_iter().enumerate() { let src_cells: Vec<(CellRef, Option)> = (0..src_len) .map(|i| { let c = if vertical { CellRef::new(src.start.row + i, lane) } else { CellRef::new(lane, src.start.col + i) }; @@ -142,7 +243,9 @@ pub fn fill_except( }; targets.retain(|t| !skip_rows.contains(&t.row)); let fmt = |c: &(CellRef, Option)| cx.wb.styles.get(c.1.as_ref().map(|c| c.style).unwrap_or_default()).num_fmt.as_str(); - let pattern = if mode.extends_series() || mode == FillMode::Alternate { + let pattern = if let Some(trend) = trends.get(lane_i) { + trend.clone() + } else if mode.extends_series() || mode == FillMode::Alternate { let first_fmt = src_cells.first().map(fmt).unwrap_or_default(); let dates = match mode { FillMode::Dates(unit) => Pattern::dates(&src_cells, unit, cx.wb.date_system, first_fmt), @@ -176,7 +279,14 @@ pub fn fill_except( writes.push((*t, Some(existing))); continue; } - FillMode::ValuesOnly | FillMode::Series | FillMode::Alternate | FillMode::Copy | FillMode::Extend | FillMode::Dates(_) => { + FillMode::ValuesOnly + | FillMode::Series + | FillMode::Alternate + | FillMode::Copy + | FillMode::Extend + | FillMode::Dates(_) + | FillMode::LinearTrend + | FillMode::GrowthTrend => { let style = if mode == FillMode::ValuesOnly { sh.cell(*t).map(|c| c.style).unwrap_or_default() } else { cell.style }; if let Some(f) = &cell.formula { if let Some(e) = f.expr() { @@ -259,9 +369,42 @@ enum Pattern { step: i64, sys: gridcraft_core::DateSystem, }, + /// Growth Trend, kept as logarithms so that a value the curve reaches is not lost to an + /// overflow or underflow on the way: the logarithms of the fitted magnitudes at the source's + /// last and first cells, the logarithm of the factor between neighboring cells, and the sign + /// of every value (1 or -1). + Growth { + last: f64, + first: f64, + step: f64, + sign: f64, + }, } impl Pattern { + /// Linear Trend: the least-squares line through `nums`. A lone number is copied unchanged. + fn linear(nums: &[f64]) -> Pattern { + if nums.len() == 1 { + return Pattern::Copy; + } + let (first, last, step) = least_squares(nums); + Pattern::Linear { last, first, step } + } + + /// The exponential curve y = b·m^x fitted to `nums` at positions 0, 1, 2… by least squares on + /// the logarithms, as the GROWTH function fits positive numbers. Numbers below zero are fitted + /// by their magnitudes and keep their sign. `None` when the numbers are not all above zero or + /// all below zero. A lone number, or the same number repeated, is copied unchanged. + fn growth(nums: &[f64]) -> Option { + let sign = growth_sign(nums.iter().copied())?; + if nums.windows(2).all(|w| w.first() == w.last()) { + return Some(Pattern::Copy); + } + let logs: Vec = nums.iter().map(|y| (y * sign).ln()).collect(); + let (first, last, step) = least_squares(&logs); + Some(Pattern::Growth { last, first, step, sign }) + } + /// The pattern of Fill Days, Fill Weekdays, Fill Months or Fill Years, or `None` when the /// source isn't all dates (numbers, not formulas, under a date format in its first cell). fn dates(cells: &[(CellRef, Option)], unit: DateUnit, sys: gridcraft_core::DateSystem, fmt: &str) -> Option { @@ -344,19 +487,7 @@ impl Pattern { } } // Least-squares step for 2+ values (Excel uses a linear trend). - let n = nums.len() as f64; - let mean_x = (n - 1.0) / 2.0; - let mean_y = nums.iter().sum::() / n; - let mut num = 0.0; - let mut den = 0.0; - for (i, y) in nums.iter().enumerate() { - num += (i as f64 - mean_x) * (y - mean_y); - den += (i as f64 - mean_x).powi(2); - } - let step = if den == 0.0 { 0.0 } else { num / den }; - let fitted_last = mean_y + step * (n - 1.0 - mean_x); - let fitted_first = mean_y - step * mean_x; - return Pattern::Linear { last: fitted_last, first: fitted_first, step }; + return Pattern::linear(&nums); } // Text. if !vals.is_empty() && vals.iter().all(|v| v.is_text()) { @@ -450,10 +581,45 @@ impl Pattern { let base = if forward { *last } else { *first }; Some(Value::number(add_weekdays(*sys, base, step.checked_mul(k)?.checked_mul(sign)?)?)) } + Pattern::Growth { last, first, step, sign: growth_sign } => { + let base = if forward { *last } else { *first }; + Some(Value::number(round15(growth_sign * (base + step * (k * sign) as f64).exp()))) + } } } } +/// 2^600 and 2^-600, both exact. +const TWO_POW_600: f64 = f64::from_bits((1023 + 600) << 52); +const TWO_POW_MINUS_600: f64 = f64::from_bits((1023 - 600) << 52); + +/// The least-squares line through `nums` at positions 0, 1, 2…: its values at the first and last +/// positions, and its step. A lone number gives a step of zero. When a number is larger than 2^600, +/// the fit runs on the numbers multiplied by 2^-600 and its results are multiplied by 2^600, so the +/// sums stay finite for numbers up to the largest double. When every number is smaller than 2^-600, +/// the fit runs on the numbers multiplied by 2^600 and its results are multiplied by 2^-600, so +/// subnormal numbers keep their step instead of rounding it to zero. +fn least_squares(nums: &[f64]) -> (f64, f64, f64) { + let (down, up) = if nums.iter().any(|y| y.abs() > TWO_POW_600) { + (TWO_POW_MINUS_600, TWO_POW_600) + } else if nums.iter().all(|y| y.abs() < TWO_POW_MINUS_600) { + (TWO_POW_600, TWO_POW_MINUS_600) + } else { + (1.0, 1.0) + }; + let n = nums.len() as f64; + let mean_x = (n - 1.0) / 2.0; + let mean_y = nums.iter().map(|y| y * down).sum::() / n; + let mut num = 0.0; + let mut den = 0.0; + for (i, y) in nums.iter().enumerate() { + num += (i as f64 - mean_x) * (y * down - mean_y); + den += (i as f64 - mean_x).powi(2); + } + let step = if den == 0.0 { 0.0 } else { num / den }; + ((mean_y - step * mean_x) * up, (mean_y + step * (n - 1.0 - mean_x)) * up, step * up) +} + /// Whether `serial` falls on Monday to Friday; `None` outside the supported date range. fn is_weekday(sys: gridcraft_core::DateSystem, serial: f64) -> Option { datetime_from_serial(sys, serial).map(|d| d.weekday != 0 && d.weekday != 6) @@ -514,13 +680,27 @@ fn add_months_clamped(sys: gridcraft_core::DateSystem, serial: f64, months: i64) serial_from_ymd(sys, year, month, (d.day as i64).min(last as i64)).map(|day| day + serial - serial.floor()) } +/// `x` rounded to 15 significant digits through its exact decimal expansion, so a number that +/// already has 15 or fewer digits comes back unchanged at any size. A number near the largest +/// double whose rounding would pass it keeps its value. A whole number below 10^15 is returned +/// as it is, and other numbers are written to a buffer on the stack, so a fill does not allocate +/// for each cell. fn round15(x: f64) -> f64 { - if x == 0.0 || !x.is_finite() { + use std::io::Write; + if x == 0.0 || !x.is_finite() || (x.fract() == 0.0 && x.abs() < 1e15) { return x; } - let mag = x.abs().log10().floor() as i32; - let p = 10f64.powi(14 - mag); - if !p.is_finite() || p == 0.0 { x } else { (x * p).round() / p } + // "-1.23456789012345e-308" is the longest expansion: 22 bytes. + let mut buf = [0u8; 32]; + let mut out = &mut buf[..]; + if write!(out, "{x:.14e}").is_err() { + return x; + } + let len = 32 - out.len(); + match buf.get(..len).and_then(|b| std::str::from_utf8(b).ok()).and_then(|s| s.parse::().ok()) { + Some(r) if r.is_finite() => r, + _ => x, + } } /// `1st Period` → `2nd Period`: an English ordinal ending is rewritten to suit the new number. @@ -811,6 +991,21 @@ mod tests { assert_eq!(sh.value(CellRef::new(1, 1)), Value::from("03/12/2023")); } + #[test] + fn round15_matches_the_decimal_expansion_without_allocating() { + let by_string = |x: f64| match format!("{x:.14e}").parse::() { + Ok(r) if r.is_finite() => r, + _ => x, + }; + let tiny = f64::from_bits(1); + let whole = [1.0, -7.0, 999_999_999_999_999.0, 1e15, 1e15 + 1.0, 123_456_789_012_345_680.0]; + let other = [0.1 + 0.2, -1.0 / 3.0, tiny, -tiny, 1e-308, f64::MAX, -f64::MAX, 1.7976931348623e308]; + for x in whole.into_iter().chain(other) { + assert_eq!(round15(x).to_bits(), by_string(x).to_bits(), "{x:e}"); + } + assert_eq!(round15(-0.0).to_bits(), (-0.0f64).to_bits()); + } + #[test] fn series_keeps_value_equal_to_stop_after_float_drift() { let mut s = crate::Session::new(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 691b81fed..ac3aad28f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1349,6 +1349,177 @@ fn fill_days_weekdays_months_and_years_step_a_date_by_that_unit() { assert_eq!(v(&s, "J2"), Value::Number(46081.5)); } +#[test] +fn linear_and_growth_trend_continue_the_fitted_line_or_curve() { + let mut s = s(); + let nums = |s: &Session, cells: &[&str]| cells.iter().map(|c| v(s, c)).collect::>(); + let n = |xs: &[f64]| xs.iter().map(|x| Value::Number(*x)).collect::>(); + let fill = + |s: &mut Session, src: &str, target: &str, mode: &str| s.execute("edit.autoFill", json!({"source": src, "target": target, "mode": mode})); + // The examples on Excel's "Project values in a series" page: 1, 2 and 1, 3 for both trends, 2, 3 + // for Growth Trend and 100, 95 for Linear Trend. 2, 3 gives 4, 5, 6 by Linear Trend. + for (col, start, linear, growth) in [ + ("A", [1.0, 2.0], [3.0, 4.0, 5.0], [4.0, 8.0, 16.0]), + ("B", [1.0, 3.0], [5.0, 7.0, 9.0], [9.0, 27.0, 81.0]), + ("C", [2.0, 3.0], [4.0, 5.0, 6.0], [4.5, 6.75, 10.125]), + ] { + s.execute("range.setValues", json!({"range": format!("{col}1"), "values": [[start[0]], [start[1]]]})).unwrap(); + let (src, target) = (format!("{col}1:{col}2"), format!("{col}1:{col}5")); + let cells: Vec = (3..=5).map(|r| format!("{col}{r}")).collect(); + let cells: Vec<&str> = cells.iter().map(String::as_str).collect(); + fill(&mut s, &src, &target, "linearTrend").unwrap(); + assert_eq!(nums(&s, &cells), n(&linear), "Linear Trend from {start:?}"); + fill(&mut s, &src, &target, "growthTrend").unwrap(); + assert_eq!(nums(&s, &cells), n(&growth), "Growth Trend from {start:?}"); + } + s.execute("range.setValues", json!({"range": "F1", "values": [[100], [95]]})).unwrap(); + fill(&mut s, "F1:F2", "F1:F4", "linearTrend").unwrap(); + assert_eq!(nums(&s, &["F3", "F4"]), n(&[90.0, 85.0])); + // Three numbers: the targets follow the best fit and the source keeps its values. 1, 3, 4 fit + // y = 1.5x + 7/6; 1, 2, 8 fit y = 0.8909·2.8284^x. + s.execute("range.setValues", json!({"range": "D1", "values": [[1, 1], [3, 2], [4, 8]]})).unwrap(); + fill(&mut s, "D1:D3", "D1:D5", "linearTrend").unwrap(); + assert_eq!(nums(&s, &["D1", "D2", "D3", "D4", "D5"]), n(&[1.0, 3.0, 4.0, 5.66666666666667, 7.16666666666667])); + fill(&mut s, "E1:E3", "E1:E4", "growthTrend").unwrap(); + assert_eq!(nums(&s, &["E1", "E2", "E3", "E4"]), n(&[1.0, 2.0, 8.0, 20.158736798318])); + // Upward and leftward the trend continues backward: 1, 2 gives 0 and -1, or 0.5 and 0.25. + s.execute("range.setValues", json!({"range": "G3", "values": [[1], [2]]})).unwrap(); + fill(&mut s, "G3:G4", "G1:G4", "linearTrend").unwrap(); + assert_eq!(nums(&s, &["G2", "G1"]), n(&[0.0, -1.0])); + s.execute("range.setValues", json!({"range": "J1", "values": [[1, 2]]})).unwrap(); + fill(&mut s, "J1:K1", "H1:K1", "growthTrend").unwrap(); + assert_eq!(nums(&s, &["I1", "H1"]), n(&[0.5, 0.25])); + // Negative numbers grow away from zero: -2, -4 gives -8. + s.execute("range.setValues", json!({"range": "L1", "values": [[-2], [-4]]})).unwrap(); + fill(&mut s, "L1:L2", "L1:L3", "growthTrend").unwrap(); + assert_eq!(v(&s, "L3"), Value::Number(-8.0)); + // A tiny start with a huge factor still reaches 1e300 without overflowing on the way. + s.execute("range.setValues", json!({"range": "S1", "values": [[1e-200], [1e-100]]})).unwrap(); + fill(&mut s, "S1:S2", "S1:S6", "growthTrend").unwrap(); + let Value::Number(s6) = v(&s, "S6") else { panic!("S6 is {:?}", v(&s, "S6")) }; + assert!((s6 / 1e300 - 1.0).abs() < 1e-9, "S6 = {s6}"); + // Numbers near the largest double continue their line without a sum overflowing: two equal + // numbers repeat, and 1e308 four times then 0 fit a step of -2e307 and continue at 2e307. + s.execute("range.setValues", json!({"range": "T1", "values": [[1e308, 1e308], [1e308, 1e308], [0, 1e308], [0, 1e308], [0, 0]]})).unwrap(); + fill(&mut s, "T1:T2", "T1:T3", "linearTrend").unwrap(); + fill(&mut s, "U1:U5", "U1:U6", "linearTrend").unwrap(); + for (cell, want) in [("T3", 1e308), ("U6", 2e307)] { + let Value::Number(got) = v(&s, cell) else { panic!("{cell} is {:?}", v(&s, cell)) }; + assert!((got / want - 1.0).abs() < 1e-9, "{cell} = {got}"); + } + // A lone number repeats, and dates a month apart step by their days, not by months. + s.execute("cell.set", json!({"cell": "M1", "input": "7"})).unwrap(); + fill(&mut s, "M1", "M1:M2", "linearTrend").unwrap(); + assert_eq!(v(&s, "M2"), Value::Number(7.0)); + // It repeats unchanged, with every digit and at any size, by either trend. + s.execute("range.setValues", json!({"range": "V1", "values": [[1e308, 0.12345678901234567]]})).unwrap(); + fill(&mut s, "V1", "V1:V3", "growthTrend").unwrap(); + fill(&mut s, "W1", "W1:W3", "linearTrend").unwrap(); + assert_eq!(nums(&s, &["V2", "V3", "W2", "W3"]), n(&[1e308, 1e308, 0.12345678901234567, 0.12345678901234567])); + // The smallest double three times repeats rather than averaging to zero. + let tiny = f64::from_bits(1); + s.execute("range.setValues", json!({"range": "X1", "values": [[tiny], [tiny], [tiny]]})).unwrap(); + fill(&mut s, "X1:X3", "X1:X4", "linearTrend").unwrap(); + assert_eq!(v(&s, "X4"), Value::Number(tiny)); + // The two smallest doubles continue their step: 1 and 2 times the smallest give 3 and 4 times it. + s.execute("range.setValues", json!({"range": "AD1", "values": [[tiny], [f64::from_bits(2)]]})).unwrap(); + fill(&mut s, "AD1:AD2", "AD1:AD4", "linearTrend").unwrap(); + assert_eq!(nums(&s, &["AD3", "AD4"]), n(&[f64::from_bits(3), f64::from_bits(4)])); + // Huge numbers three times repeat exactly: the largest double, and one with 14 digits. + let (big, big14) = (f64::MAX, 1.7976931348623e308); + s.execute("range.setValues", json!({"range": "Y1", "values": [[big, big14], [big, big14], [big, big14]]})).unwrap(); + fill(&mut s, "Y1:Z3", "Y1:Z4", "linearTrend").unwrap(); + assert_eq!(nums(&s, &["Y4", "Z4"]), n(&[big, big14])); + // Growth Trend repeats the same number exactly too, huge, tiny or below zero. + s.execute("range.setValues", json!({"range": "AA1", "values": [[1e300, 1e-300, -0.3], [1e300, 1e-300, -0.3]]})).unwrap(); + fill(&mut s, "AA1:AC2", "AA1:AC4", "growthTrend").unwrap(); + assert_eq!(nums(&s, &["AA4", "AB4", "AC4"]), n(&[1e300, 1e-300, -0.3])); + s.execute("cell.set", json!({"cell": "N1", "input": "1/15/2026"})).unwrap(); + s.execute("cell.set", json!({"cell": "N2", "input": "2/15/2026"})).unwrap(); + fill(&mut s, "N1:N2", "N1:N3", "linearTrend").unwrap(); + assert_eq!(v(&s, "N3"), Value::Number(46099.0), "2/15/2026 plus 31 days"); + // Text or an empty cell in the source, and zero or mixed signs for Growth Trend, are refused + // and fill nothing. + s.execute("range.setValues", json!({"range": "O1", "values": [[1, 1, 0], ["x", -2, 2]]})).unwrap(); + assert!(fill(&mut s, "O1:O2", "O1:O3", "linearTrend").is_err()); + assert!(fill(&mut s, "P1:P2", "P1:P3", "growthTrend").is_err()); + assert!(fill(&mut s, "Q1:Q2", "Q1:Q3", "growthTrend").is_err()); + assert!(fill(&mut s, "R1:R2", "R1:R3", "linearTrend").is_err()); + assert_eq!(nums(&s, &["O3", "P3", "Q3", "R3"]), [Value::Empty, Value::Empty, Value::Empty, Value::Empty]); + fill(&mut s, "P1:P2", "P1:P3", "linearTrend").unwrap(); + assert_eq!(v(&s, "P3"), Value::Number(-5.0)); +} + +#[test] +fn trend_fills_are_offered_for_numbers_only() { + let mut s = s(); + let offered = |s: &Session, src: &str, target: &str, growth: bool| { + let r = |a: &str| gridcraft_core::RangeRef::parse(a).unwrap(); + crate::fill::trend_applies(&s.doc().unwrap().wb, 0, r(src), r(target), growth) + }; + s.execute("range.setValues", json!({"range": "A1", "values": [[1, -1, 1], [2, -3, "x"]]})).unwrap(); + s.execute("cell.set", json!({"cell": "D1", "input": "=A1"})).unwrap(); + s.execute("cell.set", json!({"cell": "D2", "input": "5"})).unwrap(); + assert!(offered(&s, "A1:A2", "A1:A5", false) && offered(&s, "A1:A2", "A1:A5", true)); + // Down A1:B2, each column keeps one sign; across it, row 1 holds 1 and -1. + assert!(offered(&s, "A1:B2", "A1:B5", true)); + assert!(offered(&s, "A1:B2", "A1:E2", false) && !offered(&s, "A1:B2", "A1:E2", true)); + let r = |a: &str| gridcraft_core::RangeRef::parse(a).unwrap(); + assert_eq!(crate::fill::trends_that_apply(&s.doc().unwrap().wb, 0, r("A1:B2"), r("A1:E2")), (true, false)); + assert_eq!(crate::fill::trends_that_apply(&s.doc().unwrap().wb, 0, r("A1:B2"), r("A1:B5")), (true, true)); + assert!(!offered(&s, "C1:C2", "C1:C4", false), "text"); + assert!(!offered(&s, "D1:D2", "D1:D4", false), "a formula"); + assert!(!offered(&s, "E1:E2", "E1:E4", false), "empty cells"); + // A fill `edit.autoFill` refuses is not offered: five columns down to the last row is more than + // MAX_FILL_CELLS cells, and a target that doesn't hold the source in a corner. + s.execute("range.setValues", json!({"range": "F1", "values": [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10]]})).unwrap(); + assert!(offered(&s, "F1:J2", "F1:J1000", false) && offered(&s, "F1:J2", "F1:J1000", true)); + assert!(!offered(&s, "F1:J2", "F1:J1048576", false) && !offered(&s, "F1:J2", "F1:J1048576", true), "too large"); + assert!(!offered(&s, "F1:J2", "F2:J5", false), "source outside the target"); +} + +#[test] +fn trend_fills_fit_each_lane_of_a_two_dimensional_source() { + let mut s = s(); + let nums = |s: &Session, cells: &[&str]| cells.iter().map(|c| v(s, c)).collect::>(); + let n = |xs: &[f64]| xs.iter().map(|x| Value::Number(*x)).collect::>(); + let fill = + |s: &mut Session, src: &str, target: &str, mode: &str| s.execute("edit.autoFill", json!({"source": src, "target": target, "mode": mode})); + // Down: column A holds 1, 2 and column B 10, 20, and one command fits each column on its own. + s.execute("range.setValues", json!({"range": "A1", "values": [[1, 10], [2, 20]]})).unwrap(); + let down = ["A3", "A4", "A5", "B3", "B4", "B5"]; + fill(&mut s, "A1:B2", "A1:B5", "linearTrend").unwrap(); + assert_eq!(nums(&s, &down), n(&[3.0, 4.0, 5.0, 30.0, 40.0, 50.0])); + fill(&mut s, "A1:B2", "A1:B5", "growthTrend").unwrap(); + assert_eq!(nums(&s, &down), n(&[4.0, 8.0, 16.0, 40.0, 80.0, 160.0])); + // Across: row 1 holds 1, 10 and row 2 holds 2, 20, and each row is fitted on its own. + s.execute("range.setValues", json!({"range": "H1", "values": [[1, 10], [2, 20]]})).unwrap(); + let across = ["J1", "K1", "L1", "J2", "K2", "L2"]; + fill(&mut s, "H1:I2", "H1:L2", "linearTrend").unwrap(); + assert_eq!(nums(&s, &across), n(&[19.0, 28.0, 37.0, 38.0, 56.0, 74.0])); + fill(&mut s, "H1:I2", "H1:L2", "growthTrend").unwrap(); + assert_eq!(nums(&s, &across), n(&[100.0, 1000.0, 10000.0, 200.0, 2000.0, 20000.0])); + // The sources keep their values. + assert_eq!(nums(&s, &["A1", "A2", "B1", "B2", "H1", "I1", "H2", "I2"]), n(&[1.0, 2.0, 10.0, 20.0, 1.0, 10.0, 2.0, 20.0])); +} + +#[test] +fn a_trend_fill_undoes_as_one_step() { + let mut s = s(); + let nums = |s: &Session, cells: &[&str]| cells.iter().map(|c| v(s, c)).collect::>(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1, 10], [2, 20]]})).unwrap(); + s.execute("cell.set", json!({"cell": "A4", "input": "99"})).unwrap(); + s.execute("edit.autoFill", json!({"source": "A1:B2", "target": "A1:B5", "mode": "linearTrend"})).unwrap(); + assert_eq!(v(&s, "A4"), Value::Number(4.0)); + s.execute("edit.undo", json!({})).unwrap(); + // The targets are back as they were (empty, and 99 in A4), and the source is unchanged. + assert_eq!( + nums(&s, &["A3", "A4", "A5", "B3", "B4", "B5"]), + [Value::Empty, Value::Number(99.0), Value::Empty, Value::Empty, Value::Empty, Value::Empty] + ); + assert_eq!(nums(&s, &["A1", "A2", "B1", "B2"]), [Value::Number(1.0), Value::Number(2.0), Value::Number(10.0), Value::Number(20.0)]); +} + #[test] fn only_a_number_in_a_date_format_offers_the_date_fills() { let mut s = s(); diff --git a/crates/engine/src/tests/python_cells.rs b/crates/engine/src/tests/python_cells.rs index 1dea97faf..297fc1070 100644 --- a/crates/engine/src/tests/python_cells.rs +++ b/crates/engine/src/tests/python_cells.rs @@ -546,6 +546,18 @@ fn xl_references_follow_name_and_table_renames() { assert_eq!(code(&s, 0, "E1").as_deref(), Some("a = xl(\"Choices\")\nb = xl(\"Data[v]\")")); } +#[test] +fn a_python_cell_is_not_a_trend_source() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A2", "input": "2"})).unwrap(); + plant(&mut s, 0, "A1", "1"); + let offered = |s: &Session, growth: bool| { + let r = |a: &str| gridcraft_core::RangeRef::parse(a).unwrap(); + crate::fill::trend_applies(&s.doc().unwrap().wb, 0, r("A1:A2"), r("A1:A5"), growth) + }; + assert!(!offered(&s, false) && !offered(&s, true)); +} + #[test] fn inserting_a_link_without_text_preserves_an_empty_python_cell() { let mut s = s(); diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index b0d34890b..503803a0c 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -21,6 +21,8 @@ pub(crate) type PaneQuad = ((u32, u32), (u32, u32), Rect); type PagesCache = ((u64, u64, usize), Vec<(RangeRef, u32)>); /// Cached Show Details cells, keyed by (doc uid, revision, sheet, pivot). type DetailsCache = ((u64, u64, usize, usize), Option>); +/// Cached fill-menu trend entries (label, mode), keyed by (doc uid, revision, sheet, source, dragged range). +pub type FillTrendsCache = ((u64, u64, usize, RangeRef, RangeRef), Vec<(&'static str, &'static str)>); mod active_row; pub use active_row::active_row_band; @@ -330,6 +332,9 @@ pub struct GridState { pub context_menu_frame: u64, /// After a right-drag of the fill handle: the source, the dragged range and where to open the menu. pub fill_menu: Option<(RangeRef, RangeRef, Pos2)>, + /// The trends the fill menu lists, cached per (doc uid, revision, sheet, source, dragged range): + /// finding them reads every source cell. + pub fill_menu_trends: Option, /// After a left-drag of the fill handle: the Auto Fill Options button beside the filled cells. pub fill_tag: Option, /// The right-clicked chart, picture, shape or slicer: where to open its menu, its kind and id. diff --git a/crates/ui-egui/src/grid/menus.rs b/crates/ui-egui/src/grid/menus.rs index 16b06e9e3..b6546dacf 100644 --- a/crates/ui-egui/src/grid/menus.rs +++ b/crates/ui-egui/src/grid/menus.rs @@ -274,6 +274,26 @@ fn fill_modes(app: &SheetApp, src: RangeRef) -> Vec<(&'static str, &'static str) FILL_MODES.into_iter().chain(DATE_FILL_MODES.into_iter().filter(|_| dates)).collect() } +/// Linear Trend and Growth Trend, which the right-drag fill menu adds after the other fill modes +/// when they apply to a fill from `src` to `target` on the active sheet. +fn trend_fill_modes(app: &mut SheetApp, src: RangeRef, target: RangeRef) -> Vec<(&'static str, &'static str)> { + let Some(d) = app.session.active() else { return Vec::new() }; + let key = (d.uid, d.revision, d.wb.active_sheet(), src, target); + if let Some((k, modes)) = &app.grid.fill_menu_trends + && *k == key + { + return modes.clone(); + } + let (linear, growth) = gridcraft_engine::fill::trends_that_apply(&d.wb, d.wb.active_sheet(), src, target); + let modes: Vec<(&'static str, &'static str)> = [("Linear Trend", "linearTrend", linear), ("Growth Trend", "growthTrend", growth)] + .into_iter() + .filter(|(_, _, applies)| *applies) + .map(|(label, mode, _)| (label, mode)) + .collect(); + app.grid.fill_menu_trends = Some((key, modes.clone())); + modes +} + /// Remembers the fill just made so the Auto Fill Options button can offer the other ways. pub(super) fn set_fill_tag(app: &mut SheetApp, src: RangeRef, target: RangeRef) { app.grid.fill_tag = @@ -357,6 +377,7 @@ pub(super) fn fill_menu(app: &mut SheetApp, ui: &mut egui::Ui, was_open: bool) { let Some((src, target, at)) = app.grid.fill_menu else { return }; let mut close = false; let mut items = fill_modes(app, src); + items.extend(trend_fill_modes(app, src, target)); items.extend([("-", ""), ("Series…", "ui:series")]); let response = egui::Area::new(egui::Id::unique("fill_menu")).fixed_pos(at).order(egui::Order::Foreground).show(ui.ctx(), |ui| { egui::Frame::popup(ui.style()).show(ui, |ui| { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index cdc0ebd5f..7be979474 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -509,6 +509,21 @@ mod tests { } } + /// The right-drag fill menu's Linear Trend and Growth Trend have a row in every catalog, with + /// no English fallback. + #[test] + fn trend_fill_labels_are_translated_in_every_catalog() { + for key in ["Linear Trend", "Growth Trend"] { + assert_eq!(Language::En.tr(key), key); + for language in Language::ALL.into_iter().filter(|l| *l != Language::En) { + let code = language.code(); + let shown = language.translated(key).unwrap_or_else(|| panic!("{code}: no row for {key:?}")); + assert!(!shown.trim().is_empty() && !shown.contains('\n'), "{code}: bad translation of {key:?}: {shown:?}"); + assert_ne!(shown, key, "{code}: the row for {key:?} is still English"); + } + } + } + /// The note under a validation list that was cut short is a sentence, not a feature name: a /// catalog without it shows the English sentence in the middle of a translated interface. #[test] diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index b13e6feee..20f20197a 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -3,6 +3,8 @@ /// Returns the Czech translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Lineární trend", + "Growth Trend" => "Exponenciální trend", "Diagram" => "Diagram", "Decorative Text" => "Ozdobný text", "Paste" => "Vložit", diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 14d7920e2..760375da2 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -4,6 +4,8 @@ /// Returns the German translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Linearer Trend", + "Growth Trend" => "Exponentieller Trend", "Diagram" => "Schema", "Decorative Text" => "Dekorativer Text", "Paste" => "Einfügen", diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index 07c9fdd6f..61a74a7d9 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -5,6 +5,8 @@ /// Returns the Greek translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Γραμμική τάση", + "Growth Trend" => "Εκθετική τάση", "Diagram" => "Διάγραμμα", "Decorative Text" => "Διακοσμητικό κείμενο", "Paste" => "Επικόλληση", diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 905d1052c..848c75bbb 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -5,6 +5,8 @@ /// Returns the Spanish translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Tendencia lineal", + "Growth Trend" => "Tendencia geométrica", "Diagram" => "Diagrama", "Decorative Text" => "Texto decorativo", "Paste" => "Pegar", diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index bac02bb67..01da21c42 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -3,6 +3,8 @@ /// Returns the French translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Tendance linéaire", + "Growth Trend" => "Tendance géométrique", "Diagram" => "Diagramme", "Decorative Text" => "Texte décoratif", "Different First Page" => "Première page différente", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index dffcced0d..fc5c311e1 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -5,6 +5,8 @@ /// Returns the Italian translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Tendenza lineare", + "Growth Trend" => "Tendenza esponenziale", "Diagram" => "Diagramma", "Decorative Text" => "Testo decorativo", "Paste" => "Incolla", diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 6a5883649..02b610268 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1149,6 +1149,8 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[ /// Portuguese catalog has no entry for them either). Kept apart so the two catalogs above keep the /// same key set; it never overlaps them. pub(super) const EXTRA: &[(&str, &str)] = &[ + ("Linear Trend", "線形近似"), + ("Growth Trend", "乗算近似"), ("Cut (⌘X)", "切り取り (⌘X)"), ("Copy (⌘C)", "コピー (⌘C)"), ("Bold (⌘B)", "太字 (⌘B)"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index d0aca424a..d39249047 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -3,6 +3,8 @@ /// Returns the Korean translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "선형 추세", + "Growth Trend" => "지수 추세", "Diagram" => "다이어그램", "Decorative Text" => "장식 텍스트", "Paste" => "붙여넣기", diff --git a/crates/ui-egui/src/i18n/nl.rs b/crates/ui-egui/src/i18n/nl.rs index 220400b3e..8b1f4cf64 100644 --- a/crates/ui-egui/src/i18n/nl.rs +++ b/crates/ui-egui/src/i18n/nl.rs @@ -3,6 +3,8 @@ /// Returns the Dutch translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Lineaire trend", + "Growth Trend" => "Groeitrend", "Diagram" => "Diagram", "Decorative Text" => "Decoratieve tekst", "Paste" => "Plakken", diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index b3055a32b..5c2281e10 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -1,6 +1,8 @@ /// Returns the Polish translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Trend liniowy", + "Growth Trend" => "Trend wykładniczy", "Diagram" => "Diagram", "Decorative Text" => "Tekst ozdobny", "Paste" => "Wklej", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index f82dba498..8d322d713 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -4,6 +4,8 @@ /// Returns the Portuguese translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Tendência Linear", + "Growth Trend" => "Tendência de Crescimento", "Diagram" => "Diagrama", "Decorative Text" => "Texto decorativo", "Paste" => "Colar", diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index 63eec7354..76ff0cb45 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -8,6 +8,8 @@ /// Returns the Romanian translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Tendință liniară", + "Growth Trend" => "Tendință de creștere", "Diagram" => "Schemă", "Decorative Text" => "Text decorativ", "Paste" => "Lipire", diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index b8e2794af..9cdd789ba 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -3,6 +3,8 @@ /// Returns the Russian translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Линейное приближение", + "Growth Trend" => "Экспоненциальное приближение", "Diagram" => "Схема", "Decorative Text" => "Декоративный текст", "Paste" => "Вставить", diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index 947d60960..11cead1c7 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -3,6 +3,8 @@ /// Returns the Serbian translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Linearni trend", + "Growth Trend" => "Eksponencijalni trend", "Diagram" => "Dijagram", "Decorative Text" => "Ukrasni tekst", "Paste" => "Nalepi", diff --git a/crates/ui-egui/src/i18n/tr.rs b/crates/ui-egui/src/i18n/tr.rs index 776397b13..eb3545859 100644 --- a/crates/ui-egui/src/i18n/tr.rs +++ b/crates/ui-egui/src/i18n/tr.rs @@ -4,6 +4,8 @@ /// Returns the Turkish translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Doğrusal Eğilim", + "Growth Trend" => "Büyüme Eğilimi", "Diagram" => "Diyagram", "Decorative Text" => "Dekoratif Metin", "Paste" => "Yapıştır", diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index b829cc1b6..739c4db15 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -3,6 +3,8 @@ /// Returns the Ukrainian translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Лінійне наближення", + "Growth Trend" => "Експоненційне наближення", "Diagram" => "Схема", "Decorative Text" => "Декоративний текст", "Paste" => "Вставити", diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index e0faa0826..14e3c68d7 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -4,6 +4,8 @@ /// Returns the Vietnamese translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "Xu hướng tuyến tính", + "Growth Trend" => "Xu hướng tăng trưởng", "Diagram" => "Sơ đồ", "Decorative Text" => "Chữ trang trí", "Paste" => "Dán", diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index 0c0042fa6..b0b82ff39 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -3,6 +3,8 @@ /// Returns the Chinese translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { Some(match text { + "Linear Trend" => "线性趋势", + "Growth Trend" => "等比趋势", "Diagram" => "图示", "Decorative Text" => "装饰文字", "Paste" => "粘贴", diff --git a/crates/ui-egui/tests/it/fill_handle_right_drag.rs b/crates/ui-egui/tests/it/fill_handle_right_drag.rs index d8ffbff9a..54d45bf7a 100644 --- a/crates/ui-egui/tests/it/fill_handle_right_drag.rs +++ b/crates/ui-egui/tests/it/fill_handle_right_drag.rs @@ -1,6 +1,7 @@ //! Dragging the fill handle with the right button fills nothing on release: it opens Excel's fill -//! menu (Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, Series…, and from -//! a date Fill Days, Fill Weekdays, Fill Months and Fill Years). +//! menu (Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, Series…, from a +//! date Fill Days, Fill Weekdays, Fill Months and Fill Years, and from numbers Linear Trend and +//! Growth Trend). use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2}; use egui_kittest::kittest::Queryable; @@ -224,6 +225,42 @@ fn a_number_gets_no_date_fills() { } } +#[test] +fn growth_trend_multiplies_and_linear_trend_adds() { + let mut h = harness(one_two); + drag_handle(&mut h, "B2", "B5", PointerButton::Secondary); + h.get_by_label("Growth Trend").click(); + h.run_steps(3); + assert_eq!(values(&h, &["B1", "B2", "B3", "B4", "B5"]), [n(1.0), n(2.0), n(4.0), n(8.0), n(16.0)]); + assert!(h.state().grid.fill_menu.is_none()); + assert_eq!(selection(&h), "B1:B5"); + + let mut h = harness(one_two); + drag_handle(&mut h, "B2", "B5", PointerButton::Secondary); + h.get_by_label("Linear Trend").click(); + h.run_steps(3); + assert_eq!(values(&h, &["B3", "B4", "B5"]), [n(3.0), n(4.0), n(5.0)]); +} + +#[test] +fn text_and_mixed_signs_leave_out_the_trends() { + let mut h = harness(|s| { + s.execute("range.setValues", json!({"range": "B1", "values": [["Item 1"], ["Item 2"]]})).unwrap(); + s.execute("selection.set", json!({"range": "B1:B2"})).unwrap(); + }); + drag_handle(&mut h, "B2", "B4", PointerButton::Secondary); + assert!(h.query_by_label("Fill Series").is_some()); + assert!(h.query_by_label("Linear Trend").is_none() && h.query_by_label("Growth Trend").is_none()); + + let mut h = harness(|s| { + s.execute("range.setValues", json!({"range": "B1", "values": [[-1], [2]]})).unwrap(); + s.execute("selection.set", json!({"range": "B1:B2"})).unwrap(); + }); + drag_handle(&mut h, "B2", "B4", PointerButton::Secondary); + assert!(h.query_by_label("Linear Trend").is_some()); + assert!(h.query_by_label("Growth Trend").is_none()); +} + #[test] fn escape_mid_right_drag_cancels_it() { let mut h = harness(|s| { diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 963c93c1d..7ad6382c7 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -57,7 +57,7 @@ this logic, with one undo step. | Cursor while dragging cells, headers, freeze handles and objects | stable for the active drag (#936); Draw tools keep their crosshair; header arrows and a custom cell cursor remain unimplemented | | Selection outline glides to a new selection (Excel: "Provide feedback with animation") | done (10-11): 0.12 s, decelerating, with the fill and fill handle; View ▸ Animations (`view.animations`) turns it off. The timing is an estimate, not yet measured against Excel; the system's reduced-motion setting isn't followed yet | | Highlight the active cell's row (no Excel equivalent; Focus Cell tints the row and the column) | done (11-03): File › Options › General, off by default; a preference for every sheet and workbook, nothing saved in the file. Tints over the fills and under the text, in Normal and Page Layout views (`options.highlightActiveRow`) | -| Fill handle: drag to fill series, double-click to fill down, right-drag menu | fill done (Ctrl+drag swaps copy and series; month patterns use the workbook's 1900 or 1904 date system); right-drag menu partial: Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, and from a date Fill Days, Fill Weekdays, Fill Months and Fill Years, then Series…; a left-drag leaves an Auto Fill Options button with the same fill choices (gone once the workbook changes or the selection moves); Linear/Growth Trend and Flash Fill missing | +| Fill handle: drag to fill series, double-click to fill down, right-drag menu | fill done (Ctrl+drag swaps copy and series; month patterns use the workbook's 1900 or 1904 date system); right-drag menu partial: Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, and from a date Fill Days, Fill Weekdays, Fill Months and Fill Years, and from numbers Linear Trend and Growth Trend, then Series…; a left-drag leaves an Auto Fill Options button with the same fill choices except Linear Trend and Growth Trend (gone once the workbook changes or the selection moves); Flash Fill missing | | Drag-move and drag-copy cells (border drag, Ctrl/Option, Shift to insert) | border drag moves (M3) and asks "There's already data here. Do you want to replace it?" before replacing cells that hold data (`range.move`, #3136); Ctrl/Option to copy and Shift to insert are not wired to the border drag yet (reorder whole columns by their headers instead) | | In-cell editing, Enter/Tab movement, Alt/Option+Enter line breaks | done; a leading `+` or `-` starts a formula, as in Excel (`+5+4` enters `=+5+4`, #2023) | | Point mode (click/drag/arrow references), reference colouring, F4 | done; dragging over row or column headers points at whole rows or columns (`A:C`, `2:5`); Command/Ctrl-click adds separate arguments with the edit's locale separator, and Shift-click extends the current reference from a fixed anchor on the same sheet. Pointer-event regressions cover repeated/reversed selections, manual separators, sheet switches and keyboard continuation. AutoSum on one cell leaves its proposed range pointed and selected (#1834) |