mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-28 17:30:24 +01:00
commit
77a569cf91
56 files changed
+2929
-161
No files matched your search
@@ -190,6 +190,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-15 | File › Options › Formulas: Maximum Iterations and Maximum Change fields for iterative calculation, disabled while it is off, with Excel's limits (1 to 32767, 0 or more) |
|
||||
| 2026-10-15 | Function help follows the interface language: argument hints, autocomplete, Insert Function (search and readable categories) and the Formulas-tab menus read per-language tables of descriptions and argument names; Spanish keeps its 10 functions in the new format |
|
||||
| 2026-10-15 | Row auto-fit counts a cell's line breaks only when the cell wraps, as Excel does: a file whose unwrapped cells hold multi-line text no longer opens with tall rows (typing a break still turns wrap on and grows the row) |
|
||||
| 2026-10-15 | Keyboard: F8 Extend Selection and Shift+F8 Add or Remove Selection: arrows and clicks extend from the anchor or build multi-area selections without holding Shift or Ctrl, the status bar names the mode, and Esc, the key again or editing a cell ends it |
|
||||
| 2026-10-14 | SORT, SORTBY and Data > Sort order numbers exactly like Excel, so 0.3 sorts before `=0.1+0.2` whatever the input order; `=` and COUNTIF keep their 15-digit comparison |
|
||||
| 2026-10-14 | Set precision as displayed is applied: with the option on, formula results, spills and numbers typed or reformatted are stored as their number format shows them and formulas calculate from those values; `formulas.calculationOptions` gains `precisionAsDisplayed` (turning it on rounds existing constants; locked constants on a protected sheet keep their value; numbers written to a new sheet are rounded too) (#1343) |
|
||||
| 2026-10-14 | Lookups (MATCH, XMATCH, VLOOKUP, HLOOKUP, XLOOKUP, LOOKUP) compare numbers exactly like Excel, so a computed key such as `=0.1+0.2` no longer finds 0.3; `=` and COUNTIF/SUMIF keep their 15-digit comparison |
|
||||
@@ -322,11 +323,13 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-20 | minor | Dutch (nl) listed under other shipped languages; progress log row |
|
||||
| 2026-10-19 | minor | Progress log: long flat operator chains (#916) |
|
||||
| 2026-10-19 | trivial | Progress log: desktop theme portal read timeout |
|
||||
| 2026-10-17 | minor | Conditional formatting: 2-/3-colour scale editor with per-stop type/value/colour, and in-place rule editing (part of #1165) |
|
||||
| 2026-10-16 | minor | Progress log: undo steps share picture and macro bytes |
|
||||
| 2026-10-16 | minor | Progress log: floating pictures' textures bounded and kept per workbook |
|
||||
| 2026-10-16 | trivial | Progress log: web preferences kept between visits (#1562) |
|
||||
| 2026-10-16 | minor | Progress log: interface fonts held once instead of twice |
|
||||
| 2026-10-15 | trivial | Progress log: XIRR and IRR follow Excel's solvers |
|
||||
| 2026-10-15 | minor | Progress log: F8 and Shift+F8 selection modes |
|
||||
| 2026-10-14 | minor | Progress log: sorts order numbers exactly |
|
||||
| 2026-10-14 | minor | Progress log: Set precision as displayed applied in calculation (#1343) |
|
||||
| 2026-10-14 | minor | Progress log: `.xls` import reads cell formatting |
|
||||
|
||||
@@ -121,3 +121,6 @@ sync_github_name = true
|
||||
|
||||
[people.gmrmad1]
|
||||
real_name = "Madhav Agarwal"
|
||||
|
||||
[people.alosslessdev]
|
||||
real_name = "Francisco Herrera"
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::{CellRef, EngineError, Json, RangeRef, Result, Session, TableColumn, TotalsFn, Value, bad, edit, json, ok, str_param, target_range};
|
||||
use gridcraft_model::Cell;
|
||||
|
||||
pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let r = str_param(p, "range").and_then(RangeRef::parse).ok_or_else(|| bad("table.resize", "missing `range`"))?;
|
||||
@@ -11,30 +12,85 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
.ok_or_else(|| bad("table.resize", "select a cell in a table"))?;
|
||||
edit(s, |cx| {
|
||||
let sheet = cx.sheet_mut(si)?;
|
||||
let headers: Vec<String> = (r.start.col..=r.end.col).map(|c| sheet.value(CellRef::new(r.start.row, c)).display()).collect();
|
||||
if sheet.tables.iter().enumerate().any(|(i, o)| i != ti && o.range.intersects(&r)) {
|
||||
return Err(EngineError::Other("A table can't overlap another table.".into()));
|
||||
}
|
||||
let t = sheet.tables.get_mut(ti).ok_or_else(|| bad("table", "gone"))?;
|
||||
let wb = &cx.wb;
|
||||
let sheet = wb.sheet(si).ok_or(EngineError::NoDocument)?;
|
||||
let t = sheet.tables.get(ti).ok_or_else(|| bad("table", "gone"))?;
|
||||
if r.start.row != t.range.start.row || !r.intersects(&t.range) {
|
||||
return Err(EngineError::Other(
|
||||
"The headers must remain in the same row, and the resulting table range must overlap the original table range.".into(),
|
||||
));
|
||||
}
|
||||
let mut cols = Vec::new();
|
||||
for (i, h) in headers.iter().enumerate() {
|
||||
let name = if h.is_empty() { format!("Column{}", i + 1) } else { h.clone() };
|
||||
let existing = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(&name)).cloned();
|
||||
cols.push(existing.unwrap_or(TableColumn {
|
||||
name,
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
xml: None,
|
||||
}));
|
||||
// Like Excel, the new range can't take in another table, a merged area, a PivotTable or a
|
||||
// multi-cell array formula (a spill is fine: it shows #SPILL! inside the table).
|
||||
if sheet.tables.iter().enumerate().any(|(i, o)| i != ti && o.range.intersects(&r)) {
|
||||
return Err(EngineError::Other("A table can't overlap another table.".into()));
|
||||
}
|
||||
if sheet.merges.iter().any(|m| m.intersects(&r)) {
|
||||
return Err(EngineError::Other("A table can't overlap merged cells.".into()));
|
||||
}
|
||||
if sheet.pivots.iter().any(|pt| pt.last_range.unwrap_or_else(|| RangeRef::new(pt.anchor, pt.anchor)).intersects(&r)) {
|
||||
return Err(EngineError::Other("A table can't overlap a PivotTable report.".into()));
|
||||
}
|
||||
if sheet.cells.iter().any(|(_, x)| x.formula.as_ref().and_then(|f| f.array).is_some_and(|a| !a.is_single() && a.intersects(&r))) {
|
||||
return Err(EngineError::Other("Multi-cell array formulas aren't allowed in tables.".into()));
|
||||
}
|
||||
// Header text per new column (`None`: empty). Without a header row, a column that stays
|
||||
// keeps its name.
|
||||
let texts: Vec<Option<String>> = (r.start.col..=r.end.col)
|
||||
.map(|c| {
|
||||
if !t.header_row {
|
||||
return c.checked_sub(t.range.start.col).and_then(|i| t.columns.get(i as usize)).map(|x| x.name.clone());
|
||||
}
|
||||
let at = CellRef::new(r.start.row, c);
|
||||
let v = sheet.value(at);
|
||||
let text = match v.as_text() {
|
||||
Some(x) => x.to_string(),
|
||||
None => crate::display::value_text(wb, sheet, at),
|
||||
};
|
||||
(!text.trim().is_empty()).then_some(text)
|
||||
})
|
||||
.collect();
|
||||
let names = resized_column_names(&texts);
|
||||
let old = t.range;
|
||||
let old_cols = t.columns.clone();
|
||||
let header_row = t.header_row;
|
||||
let mut cols = Vec::with_capacity(names.len());
|
||||
for (c, name) in (r.start.col..=r.end.col).zip(&names) {
|
||||
// A column that stays keeps its settings (totals, calculated formula): with a header
|
||||
// row it's found by name, without one by position.
|
||||
let existing = if header_row {
|
||||
// A header that was normalized into a generated name keeps the settings of the
|
||||
// column at its address, not of whichever column already has that name.
|
||||
let raw = texts.get((c - r.start.col) as usize).and_then(|x| x.as_deref());
|
||||
if c >= old.start.col && c <= old.end.col && raw != Some(name.as_str()) {
|
||||
old_cols.get((c - old.start.col) as usize)
|
||||
} else {
|
||||
old_cols.iter().find(|x| x.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
} else if c >= old.start.col && c <= old.end.col {
|
||||
old_cols.get((c - old.start.col) as usize)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
cols.push(match existing {
|
||||
Some(x) => TableColumn { name: name.clone(), ..x.clone() },
|
||||
None => TableColumn { name: name.clone(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None },
|
||||
});
|
||||
}
|
||||
let sheet = cx.sheet_mut(si)?;
|
||||
if header_row {
|
||||
// Headers hold constant text: a generated or de-duplicated name is written into its
|
||||
// cell, so the header row and the column names never disagree.
|
||||
for (c, col) in (r.start.col..=r.end.col).zip(&cols) {
|
||||
let at = CellRef::new(r.start.row, c);
|
||||
let constant_text = sheet.value(at).as_text() == Some(col.name.as_str()) && sheet.cell(at).is_some_and(|x| x.formula.is_none());
|
||||
if !constant_text {
|
||||
let style = sheet.style_id(at);
|
||||
sheet.set_cell(at, Cell { value: Value::text(col.name.as_str()), style, ..Default::default() });
|
||||
}
|
||||
}
|
||||
}
|
||||
let t = sheet.tables.get_mut(ti).ok_or_else(|| bad("table", "gone"))?;
|
||||
t.columns = cols;
|
||||
t.range = r;
|
||||
cx.structural = true;
|
||||
@@ -42,6 +98,56 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Unique column names for a resized table, from each column's header text (`None` = empty), the
|
||||
/// way Excel names them: a repeated header gets the lowest free suffix (`Qty`, `Qty2`, `Qty3`,
|
||||
/// compared without case), and an empty header continues a `ColumnN` neighbour on its left
|
||||
/// (`Column3` → `Column4`, or `Column32` when `Column4` is taken) or else takes the lowest free
|
||||
/// `ColumnN`.
|
||||
fn resized_column_names(texts: &[Option<String>]) -> Vec<String> {
|
||||
use std::collections::{HashMap, HashSet};
|
||||
let mut taken: HashSet<String> = HashSet::new();
|
||||
let mut next_suffix: HashMap<String, u64> = HashMap::new();
|
||||
// The lowest `ColumnN` not yet tried, so many empty headers stay linear.
|
||||
let mut lowest = 1u64;
|
||||
let mut names: Vec<String> = Vec::with_capacity(texts.len());
|
||||
let dedupe = |base: &str, taken: &HashSet<String>, next_suffix: &mut HashMap<String, u64>| {
|
||||
let k = next_suffix.entry(base.to_lowercase()).or_insert(2);
|
||||
let mut n = base.to_string();
|
||||
while taken.contains(&n.to_lowercase()) {
|
||||
n = format!("{base}{k}");
|
||||
*k = k.saturating_add(1);
|
||||
}
|
||||
n
|
||||
};
|
||||
for text in texts {
|
||||
let name = match text {
|
||||
Some(t) => dedupe(t, &taken, &mut next_suffix),
|
||||
None => {
|
||||
let left = names.last().and_then(|l| {
|
||||
l.strip_prefix("Column")
|
||||
.filter(|d| !d.starts_with('0') && !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit()))
|
||||
.and_then(|d| d.parse::<u64>().ok())
|
||||
});
|
||||
match left {
|
||||
Some(n) => {
|
||||
let cand = format!("Column{}", n.saturating_add(1));
|
||||
if taken.contains(&cand.to_lowercase()) { dedupe(&format!("Column{n}"), &taken, &mut next_suffix) } else { cand }
|
||||
}
|
||||
None => {
|
||||
while taken.contains(&format!("column{lowest}")) {
|
||||
lowest = lowest.saturating_add(1);
|
||||
}
|
||||
format!("Column{lowest}")
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
taken.insert(name.to_lowercase());
|
||||
names.push(name);
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
/// Most cells (rows × columns, blanks included) Get Data imports. The rows are built densely
|
||||
/// before they are written, so a few sparse records or one far-away CSV cell must not expand
|
||||
/// into a rectangle of billions of slots.
|
||||
|
||||
@@ -553,7 +553,12 @@ fn format_cells(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
{
|
||||
*st = new;
|
||||
}
|
||||
})
|
||||
})?;
|
||||
// A number format set here widens columns as the ribbon's do (observed: Excel 16.0).
|
||||
if patch.get("num_fmt").is_some() {
|
||||
widen_for_numbers(s, p)?;
|
||||
}
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The style patch with camelCase keys (`numFmt`, `diagDown`, as documented) renamed to the
|
||||
@@ -732,9 +737,95 @@ fn number_format(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
set_fmt(s, p, &code)
|
||||
}
|
||||
|
||||
/// How many stored cells [`widen_for_numbers`] looks at in one command.
|
||||
const MAX_WIDEN_CELLS: usize = 1_000_000;
|
||||
|
||||
fn set_fmt(s: &mut Session, p: &Json, code: &str) -> Result<Json> {
|
||||
let nf = NumFmt::new(code);
|
||||
apply_style(s, p, |st| st.num_fmt = nf.clone())
|
||||
apply_style(s, p, |st| st.num_fmt = nf.clone())?;
|
||||
widen_for_numbers(s, p)
|
||||
}
|
||||
|
||||
/// After a number format from the ribbon (Increase Decimal, Comma Style, the Number Format list…) or
|
||||
/// Format Cells, a column nobody sized by hand widens so the formatted numbers in the target fit,
|
||||
/// instead of showing ####. Observed in Excel 16.0 (build 17932): a column at the default width, AutoFitted, or
|
||||
/// widened this way before widens to the widest number in the range, also with Wrap Text and a large
|
||||
/// font. A width set with Column Width (or by dragging) stays, even when it equals the default. Hidden
|
||||
/// columns, text, General numbers (they round to fit), shrink-to-fit and merged cells don't widen,
|
||||
/// and columns never narrow.
|
||||
fn widen_for_numbers(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let ranges = target_ranges(s, p)?;
|
||||
let measure = s.text_width.clone();
|
||||
edit(s, |cx| {
|
||||
let Some(sh) = cx.wb.sheet(sheet) else { return Ok(Json::Null) };
|
||||
let Some(used) = sh.used_range() else { return Ok(Json::Null) };
|
||||
if sh.show_formulas {
|
||||
return Ok(Json::Null);
|
||||
}
|
||||
let targets: Vec<RangeRef> = ranges.iter().filter_map(|r| r.intersection(&used)).collect();
|
||||
// Merged areas over the targets as sorted row intervals per column, so each cell is checked
|
||||
// with a binary search rather than a scan of every merge.
|
||||
let mut merged: std::collections::HashMap<u32, Vec<(u32, u32)>> = Default::default();
|
||||
for m in sh.merges.iter().filter(|m| !m.is_single()) {
|
||||
for x in targets.iter().filter_map(|r| m.intersection(r)) {
|
||||
for col in x.start.col..=x.end.col {
|
||||
merged.entry(col).or_default().push((m.start.row, m.end.row));
|
||||
}
|
||||
}
|
||||
}
|
||||
for v in merged.values_mut() {
|
||||
v.sort_unstable();
|
||||
v.dedup();
|
||||
}
|
||||
let in_merge = |c: CellRef| {
|
||||
merged.get(&c.col).is_some_and(|v| {
|
||||
let i = v.partition_point(|&(r0, _)| r0 <= c.row);
|
||||
i > 0 && v.get(i - 1).is_some_and(|&(_, r1)| c.row <= r1)
|
||||
})
|
||||
};
|
||||
let mut need: std::collections::BTreeMap<u32, f32> = std::collections::BTreeMap::new();
|
||||
// Measured as AutoFit Column Width measures (the UI's font when it supplies one).
|
||||
let mut measured: std::collections::HashMap<(StyleId, String), f32> = Default::default();
|
||||
// The stored cells looked at are capped, not the area: a sparse target as tall as the sheet
|
||||
// still widens for the numbers it holds. Spilled values count as the grid shows them.
|
||||
let mut budget = MAX_WIDEN_CELLS;
|
||||
for r in &targets {
|
||||
let spilled = sh.spill.range(r.start..=r.end).map(|(c, _)| *c).filter(|c| r.contains(*c));
|
||||
for c in sh.cells.iter_range(*r).map(|(c, _)| c).chain(spilled) {
|
||||
if budget == 0 {
|
||||
break;
|
||||
}
|
||||
budget -= 1;
|
||||
if !matches!(sh.value_ref(c), Some(gridcraft_core::Value::Number(_)))
|
||||
|| sh.cols.get(&c.col).is_some_and(|i| i.custom || i.hidden)
|
||||
|| in_merge(c)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let id = sh.style_id(c);
|
||||
let st = cx.wb.styles.get(id);
|
||||
if st.num_fmt.as_str() == "General" || st.align.shrink || st.align.h == HAlign::Fill {
|
||||
continue;
|
||||
}
|
||||
let text = crate::display::cell_text(&cx.wb, sh, c);
|
||||
let exact = measured.len() < EXACT_TEXT_WIDTHS;
|
||||
let w = *measured.entry((id, text)).or_insert_with_key(|(_, t)| match &measure {
|
||||
Some(m) => m(t, &st.font, exact),
|
||||
None => approx_text_width(t, st.font.size, st.font.bold),
|
||||
});
|
||||
let w = w + 6.0 + st.align.indent as f32 * 9.0;
|
||||
let e = need.entry(c.col).or_insert(0.0);
|
||||
*e = e.max(w);
|
||||
}
|
||||
}
|
||||
let widen: Vec<(u32, f32)> = need.into_iter().filter(|&(c, w)| w > sh.col_width(c)).collect();
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
for (c, w) in widen {
|
||||
sh.cols.entry(c).or_default().size = Some(w.ceil().min(1785.0));
|
||||
}
|
||||
Ok(Json::Null)
|
||||
})
|
||||
}
|
||||
|
||||
/// Adds or removes one decimal place in the number format (Increase/Decrease Decimal).
|
||||
@@ -819,8 +910,8 @@ mod sizes;
|
||||
|
||||
use cell_styles::cell_style;
|
||||
pub use cell_styles::{CELL_STYLE_NAMES, builtin_cell_style};
|
||||
use sizes::{EXACT_TEXT_WIDTHS, autofit_cols, autofit_rows, col_width, default_width, hide, row_height};
|
||||
pub use sizes::{approx_text_width, chars_to_points};
|
||||
use sizes::{autofit_cols, autofit_rows, col_width, default_width, hide, row_height};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -856,6 +947,112 @@ mod tests {
|
||||
assert_eq!(adjust_decimals("0%", &v, 1), "0.0%");
|
||||
}
|
||||
|
||||
fn col(s: &crate::Session, c: u32) -> (f32, bool) {
|
||||
let sh = s.active().unwrap().wb.active().unwrap();
|
||||
(sh.col_width(c), sh.cols.get(&c).is_some_and(|i| i.custom))
|
||||
}
|
||||
|
||||
/// #1077: Increase Decimal widened the format but not the column, so the number turned into ####.
|
||||
#[test]
|
||||
fn increase_decimal_widens_a_column_nobody_sized() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "3.14159265"})).unwrap();
|
||||
let (default, _) = col(&s, 0);
|
||||
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
|
||||
let (w, custom) = col(&s, 0);
|
||||
let text = s.execute("cell.get", json!({"cell": "A1"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert_eq!(text, "3.141592650");
|
||||
assert!(w > default, "the column widens for {text}: {w} vs {default}");
|
||||
assert!(w >= approx_text_width(&text, gridcraft_model::DEFAULT_FONT_SIZE, false), "and fits it");
|
||||
assert!(!custom, "it isn't a width set by hand, so it can widen again");
|
||||
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
|
||||
assert!(col(&s, 0).0 > w, "one more decimal, a little wider again");
|
||||
let wide = col(&s, 0).0;
|
||||
s.execute("home.decreaseDecimal", json!({"range": "A1"})).unwrap();
|
||||
assert_eq!(col(&s, 0).0, wide, "fewer decimals don't narrow it");
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(col(&s, 0).0, w, "Undo takes back the format and the width in one step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_formats_keep_a_width_set_by_hand_and_general_numbers_round_instead() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[1234567.891, 1234567.891, 1234567.891, 1234567.891]]})).unwrap();
|
||||
s.execute("home.columnWidth", json!({"cols": "A:A", "width": 40})).unwrap();
|
||||
assert_eq!(col(&s, 0), (40.0, true), "Column Width (and dragging the border) is a width set by hand");
|
||||
s.execute("home.hideColumns", json!({"cols": "D:D"})).unwrap();
|
||||
for a in ["A1", "B1", "D1"] {
|
||||
s.execute("home.comma", json!({"range": a})).unwrap();
|
||||
}
|
||||
s.execute("home.numberFormat", json!({"range": "C1", "format": "General"})).unwrap();
|
||||
let (default, _) = col(&s, 4);
|
||||
assert_eq!(col(&s, 0), (40.0, true), "a width set by hand stays: the cell shows ####, as in Excel");
|
||||
assert!(col(&s, 1).0 > default, "B widens for 1,234,567.89");
|
||||
assert_eq!(col(&s, 2).0, default, "General rounds to fit instead");
|
||||
assert_eq!(col(&s, 3).0, 0.0, "a hidden column stays hidden");
|
||||
// AutoFit makes a width set by hand automatic again; Wrap Text doesn't stop the widening.
|
||||
s.execute("home.autofitColumnWidth", json!({"cols": "A:A"})).unwrap();
|
||||
assert!(!col(&s, 0).1);
|
||||
s.execute("home.wrapText", json!({"range": "A1", "on": true})).unwrap();
|
||||
let fitted = col(&s, 0).0;
|
||||
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
|
||||
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
|
||||
assert!(col(&s, 0).0 > fitted, "after AutoFit, with Wrap Text, A widens again");
|
||||
}
|
||||
|
||||
fn book() -> (crate::Session, f32) {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
let (default, _) = col(&s, 0);
|
||||
(s, default)
|
||||
}
|
||||
|
||||
/// Whole columns as tall as the sheet with two numbers: the cells are looked at, not the area.
|
||||
#[test]
|
||||
fn a_sparse_target_widens_for_the_numbers_it_holds() {
|
||||
let (mut s, default) = book();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "E1000000", "input": "1234567.891"})).unwrap();
|
||||
s.execute("home.comma", json!({"range": "A:E"})).unwrap();
|
||||
assert!(col(&s, 4).0 > default, "E widens for 1,234,567.89 a million rows down");
|
||||
}
|
||||
|
||||
/// A spilled number counts as the grid shows it: G1's formula spills 1,234,567.891 into H1.
|
||||
#[test]
|
||||
fn a_spilled_number_widens_its_column() {
|
||||
let (mut s, default) = book();
|
||||
s.execute("cell.set", json!({"cell": "G1", "input": "=SEQUENCE(1,2,1,1234566.891)"})).unwrap();
|
||||
s.execute("home.numberFormat", json!({"range": "H1", "code": "#,##0.000"})).unwrap();
|
||||
assert!(col(&s, 7).0 > default, "H widens for the value it shows");
|
||||
}
|
||||
|
||||
/// A merged area keeps its columns; the cell beside it widens.
|
||||
#[test]
|
||||
fn a_merged_area_keeps_its_columns() {
|
||||
let (mut s, default) = book();
|
||||
s.execute("range.setValues", json!({"range": "J1", "values": [[1234567.891, null, 1234567.891]]})).unwrap();
|
||||
s.execute("home.mergeCells", json!({"range": "J1:K1"})).unwrap();
|
||||
s.execute("home.comma", json!({"range": "J1:L1"})).unwrap();
|
||||
assert_eq!((col(&s, 9).0, col(&s, 10).0), (default, default), "the merged J1:K1 doesn't widen J or K");
|
||||
assert!(col(&s, 11).0 > default, "L does");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_cells_widens_for_a_number_format_only() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[1234567.891, 1234567.891]]})).unwrap();
|
||||
let (default, _) = col(&s, 0);
|
||||
s.execute("home.formatCells", json!({"range": "B1", "style": {"font": {"bold": true}}})).unwrap();
|
||||
assert_eq!(col(&s, 1).0, default, "no number format, no widening");
|
||||
s.execute("home.formatCells", json!({"range": "A1", "style": {"numFmt": "#,##0.000000"}})).unwrap();
|
||||
assert!(col(&s, 0).0 > default, "A widens for 1,234,567.891000, as Excel's Format Cells does");
|
||||
assert!(!col(&s, 0).1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_cells_takes_the_documented_keys() {
|
||||
let mut s = crate::Session::new();
|
||||
@@ -870,6 +1067,20 @@ mod tests {
|
||||
assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"]["num_fmt"], "0.00");
|
||||
}
|
||||
|
||||
/// A table draws its header row bold; AutoFit measures that, not the cell's own plain font.
|
||||
#[test]
|
||||
fn autofit_measures_a_table_header_in_the_table_style_font() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
let heading = "Quarterly Revenue by Region";
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[heading, heading], [1, 1]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "A1:A2", "header": true})).unwrap();
|
||||
s.execute("home.autofitColumnWidth", json!({"cols": "A:B"})).unwrap();
|
||||
let sh = s.active().unwrap().wb.active().unwrap();
|
||||
let (table, plain) = (sh.col_width(0) - sh.filter_button_space(CellRef::new(0, 0)), sh.col_width(1));
|
||||
assert!(table > plain, "the bold table header is wider than the same plain text: {table} vs {plain}");
|
||||
}
|
||||
|
||||
/// Outlined letters have no Font-group command; Format Cells' style JSON sets and clears them.
|
||||
#[test]
|
||||
fn format_cells_sets_outlined_letters() {
|
||||
|
||||
@@ -107,6 +107,7 @@ pub(super) fn col_width(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let e = sh.cols.entry(c).or_default();
|
||||
e.size = Some(w as f32);
|
||||
e.hidden = w == 0.0;
|
||||
e.custom = true;
|
||||
}
|
||||
}
|
||||
Ok(Json::Null)
|
||||
@@ -187,14 +188,15 @@ fn arabic_em(c: char) -> Option<f32> {
|
||||
|
||||
/// Distinct texts AutoFit measures exactly; past this many, `Session::text_width` is asked for a
|
||||
/// quick measure so a huge column doesn't lay out every value.
|
||||
const EXACT_TEXT_WIDTHS: usize = 2_000;
|
||||
pub(super) const EXACT_TEXT_WIDTHS: usize = 2_000;
|
||||
|
||||
pub(super) fn autofit_cols(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (si, lines) = line_targets(s, p, false)?;
|
||||
let measure = s.text_width.clone();
|
||||
edit(s, |cx| {
|
||||
let Some(sh) = cx.wb.sheet(si) else { return Ok(Json::Null) };
|
||||
let mut measured: std::collections::HashMap<StyleId, std::collections::HashMap<String, f32>> = Default::default();
|
||||
// Keyed by style and boldness: a table's style can make a cell bold (its header row).
|
||||
let mut measured: std::collections::HashMap<(StyleId, bool), std::collections::HashMap<String, f32>> = Default::default();
|
||||
let mut distinct = 0usize;
|
||||
// Selected columns, then one pass over the populated cells (the store is row-oriented, so a
|
||||
// scan per column would revisit every row for each selected column, empty or not).
|
||||
@@ -228,22 +230,26 @@ pub(super) fn autofit_cols(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
let id = sh.style_id(cell);
|
||||
let st = cx.wb.styles.get(id);
|
||||
// The font as the grid draws the cell: in a table, the table style's (a bold
|
||||
// header row), not only the cell's own.
|
||||
let table_font = sh.table_at(cell).map(|t| crate::tables::table_cell_style(&cx.wb, si, t, cell).font);
|
||||
let font = table_font.as_ref().unwrap_or(&st.font);
|
||||
let text = crate::display::cell_text(&cx.wb, sh, cell);
|
||||
for line in text.lines() {
|
||||
let w = match &measure {
|
||||
Some(m) => {
|
||||
let known = measured.entry(id).or_default();
|
||||
let known = measured.entry((id, font.bold)).or_default();
|
||||
match known.get(line) {
|
||||
Some(w) => *w,
|
||||
None => {
|
||||
let w = m(line, &st.font, distinct < EXACT_TEXT_WIDTHS);
|
||||
let w = m(line, font, distinct < EXACT_TEXT_WIDTHS);
|
||||
known.insert(line.to_owned(), w);
|
||||
distinct += 1;
|
||||
w
|
||||
}
|
||||
}
|
||||
}
|
||||
None => approx_text_width(line, st.font.size, st.font.bold),
|
||||
None => approx_text_width(line, font.size, font.bold),
|
||||
};
|
||||
let w = w + 6.0 + st.align.indent as f32 * 9.0 + sh.filter_button_space(cell);
|
||||
let max = maxes.entry(cell.col).or_insert(0.0);
|
||||
@@ -258,6 +264,7 @@ pub(super) fn autofit_cols(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let e = sh.cols.entry(c).or_default();
|
||||
e.size = Some(w.ceil());
|
||||
e.hidden = false;
|
||||
e.custom = false; // AutoFit makes a width set by hand automatic again (Excel).
|
||||
}
|
||||
Ok(Json::Null)
|
||||
})
|
||||
|
||||
@@ -217,7 +217,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Conditional Formatting",
|
||||
["Home", "Styles"],
|
||||
None,
|
||||
"{range?, rule: {type: cellIs|expression|containsText|beginsWith|endsWith|blanks|noBlanks|errors|noErrors|duplicate|unique|top10|aboveAverage|timePeriod|colorScale|dataBar|iconSet, operator?, value?, value2?, formula?, text?, rank?, bottom?, percent?, below?, period?, colors?: [..], color?, set?, style?: {font?: {bold?, italic?, color?}, fill?: \"#FFC7CE\" | {pattern?, fg?, bg?}, borders?, num_fmt?} (colours \"#RRGGBB\") | preset?: lightRedFill|redText|yellowFill|greenFill|redBorder|lightRedFillDarkRedText…}; a text `value` is matched as text, or kept when already a quoted literal}",
|
||||
"{range?, rule: {type: cellIs|expression|containsText|beginsWith|endsWith|blanks|noBlanks|errors|noErrors|duplicate|unique|top10|aboveAverage|timePeriod|colorScale|dataBar|iconSet, operator?, value?, value2?, formula?, text?, rank?, bottom?, percent?, below?, period?, colors?: [..], stops?: [{type: min|max|num|percent|percentile|formula, value?, color}], color?, set?, style?: {font?: {bold?, italic?, color?}, fill?: \"#FFC7CE\" | {pattern?, fg?, bg?}, borders?, num_fmt?} (colours \"#RRGGBB\") | preset?: lightRedFill|redText|yellowFill|greenFill|redBorder|lightRedFillDarkRedText…}; a text `value` is matched as text, or kept when already a quoted literal}",
|
||||
has_doc,
|
||||
add_cf
|
||||
),
|
||||
@@ -227,7 +227,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Manage Rules…",
|
||||
["Home", "Styles", "Conditional Formatting"],
|
||||
None,
|
||||
"{delete?: index, moveUp?: index, moveDown?: index}",
|
||||
"{delete?: index, moveUp?: index, moveDown?: index, edit?: index, rule?: {...} (with edit)}",
|
||||
has_doc,
|
||||
manage_cf
|
||||
),
|
||||
@@ -496,4 +496,302 @@ mod tests {
|
||||
s.execute("table.rename", json!({"table": "Table1", "name": "Table1"})).unwrap();
|
||||
s.execute("table.rename", json!({"table": "Table1", "name": "Rates"})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_scale_thresholds_are_clamped_to_the_percent_range() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"home.conditionalFormat",
|
||||
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
|
||||
{"type": "percent", "value": -5, "color": "#112233"},
|
||||
{"type": "percentile", "value": 150, "color": "#445566"},
|
||||
{"type": "max", "color": "#778899"},
|
||||
]}}),
|
||||
)
|
||||
.unwrap();
|
||||
let list = s.execute("home.manageRules", json!({})).unwrap();
|
||||
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
|
||||
let CfRule::ColorScale { stops } = rule else { panic!("expected a colour scale") };
|
||||
assert_eq!(
|
||||
stops,
|
||||
vec![
|
||||
(CfValueKind::Percent(0.0), Color::Rgb(0x112233)),
|
||||
(CfValueKind::Percentile(100.0), Color::Rgb(0x445566)),
|
||||
(CfValueKind::Max, Color::Rgb(0x778899)),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_scale_stops_reject_empty_formulas_and_unknown_types() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let with_stops = |stops: Json| json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": stops}});
|
||||
let err = s
|
||||
.execute(
|
||||
"home.conditionalFormat",
|
||||
with_stops(json!([
|
||||
{"type": "min", "color": "#112233"},
|
||||
{"type": "formula", "value": " ", "color": "#445566"},
|
||||
{"type": "max", "color": "#778899"},
|
||||
])),
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("home.conditionalFormat"), "{err}");
|
||||
assert!(err.contains("formula"), "{err}");
|
||||
|
||||
let err = s
|
||||
.execute(
|
||||
"home.conditionalFormat",
|
||||
with_stops(json!([
|
||||
{"type": "min", "color": "#112233"},
|
||||
{"type": "median", "value": 50, "color": "#445566"},
|
||||
{"type": "max", "color": "#778899"},
|
||||
])),
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("unknown stop type `median`"), "{err}");
|
||||
let rules = s.execute("home.manageRules", json!({})).unwrap();
|
||||
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_scale_rejects_a_stops_value_that_is_not_an_array() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
// `stops` present but misshapen used to fall back to the default scale instead of erroring.
|
||||
for stops in [json!({}), json!(null), json!("min")] {
|
||||
let err = s
|
||||
.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": stops}}))
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("home.conditionalFormat"), "{err}");
|
||||
assert!(err.contains("`stops` must be an array"), "{err}");
|
||||
}
|
||||
let rules = s.execute("home.manageRules", json!({})).unwrap();
|
||||
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0), "an invalid `stops` creates no rule");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_scale_formulas_are_stored_verbatim() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"home.conditionalFormat",
|
||||
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
|
||||
{"type": "min", "color": "#112233"},
|
||||
{"type": "formula", "value": "=$Z$1", "color": "#445566"},
|
||||
{"type": "max", "color": "#778899"},
|
||||
]}}),
|
||||
)
|
||||
.unwrap();
|
||||
let list = s.execute("home.manageRules", json!({})).unwrap();
|
||||
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
|
||||
let CfRule::ColorScale { stops } = rule else { panic!("expected a colour scale") };
|
||||
assert_eq!(stops[1].0, CfValueKind::Formula("=$Z$1".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manage_rules_rejects_a_non_index_edit() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})).unwrap();
|
||||
for bad in [json!("0"), json!(1.5), json!(-1), json!(true)] {
|
||||
let err = s
|
||||
.execute("home.manageRules", json!({"edit": bad, "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}}))
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("`edit` must be a rule index"), "{err}");
|
||||
}
|
||||
let rules = s.execute("home.manageRules", json!({})).unwrap();
|
||||
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manage_rules_rejects_an_edit_past_the_last_rule() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})).unwrap();
|
||||
let err = s
|
||||
.execute("home.manageRules", json!({"edit": 1, "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}}))
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("home.manageRules"), "{err}");
|
||||
assert!(err.contains("index 1"), "{err}");
|
||||
let rules = s.execute("home.manageRules", json!({})).unwrap();
|
||||
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(1), "the failed edit leaves the rule alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manage_rules_rejects_an_edit_index_that_does_not_fit_a_usize() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "A1>2"}})).unwrap();
|
||||
// On a 32-bit target this used to cast to zero and replace the rule at index 0.
|
||||
let err =
|
||||
s.execute("home.manageRules", json!({"edit": 4294967296u64, "rule": {"type": "expression", "formula": "A1>3"}})).unwrap_err().to_string();
|
||||
assert!(err.contains("home.manageRules"), "{err}");
|
||||
assert!(err.contains("index 4294967296"), "{err}");
|
||||
let rule: CfRule = serde_json::from_value(s.execute("home.manageRules", json!({})).unwrap()["rules"][0]["rule"].clone()).unwrap();
|
||||
let CfRule::Expression { formula, .. } = rule else { panic!("expected a formula rule, got {rule:?}") };
|
||||
assert_eq!(formula, "A1>2", "the failed edit leaves the rule alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manage_rules_names_itself_in_a_style_error() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})).unwrap();
|
||||
// A style shared by both commands must name the one that was called.
|
||||
let rule = json!({"type": "cellIs", "operator": "greater", "value": 1, "style": {"nope": 1}});
|
||||
let err = s.execute("home.manageRules", json!({"edit": 0, "rule": rule.clone()})).unwrap_err().to_string();
|
||||
assert!(err.contains("home.manageRules"), "{err}");
|
||||
assert!(!err.contains("home.conditionalFormat"), "{err}");
|
||||
let err = s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": rule})).unwrap_err().to_string();
|
||||
assert!(err.contains("home.conditionalFormat"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manage_rules_names_itself_in_a_stop_count_error() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let err = s
|
||||
.execute(
|
||||
"home.manageRules",
|
||||
json!({"edit": 0, "rule": {"type": "colorScale", "stops": [
|
||||
{"type": "min", "color": "#112233"},
|
||||
]}}),
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("home.manageRules"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_formula_rule_needs_a_formula_that_parses() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
// An empty box used to create a rule that never applies.
|
||||
let err =
|
||||
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": ""}})).unwrap_err().to_string();
|
||||
assert!(err.contains("formula is empty"), "{err}");
|
||||
// `=C1>` used to be written as `<formula>C1></formula>`, which Excel refuses to open.
|
||||
let err = s
|
||||
.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "=C1>"}}))
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("invalid"), "{err}");
|
||||
assert!(err.contains("does not parse"), "{err}");
|
||||
let rules = s.execute("home.manageRules", json!({})).unwrap();
|
||||
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0), "a refused rule is not stored");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invalid_formula_on_edit_leaves_the_rule_alone() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "A1>2"}})).unwrap();
|
||||
let err = s.execute("home.manageRules", json!({"edit": 0, "rule": {"type": "expression", "formula": "=C1>"}})).unwrap_err().to_string();
|
||||
assert!(err.contains("home.manageRules"), "{err}");
|
||||
let rule: CfRule = serde_json::from_value(s.execute("home.manageRules", json!({})).unwrap()["rules"][0]["rule"].clone()).unwrap();
|
||||
let CfRule::Expression { formula, .. } = rule else { panic!("expected a formula rule, got {rule:?}") };
|
||||
assert_eq!(formula, "A1>2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_given_stop_value_must_be_a_number() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
for ty in ["num", "percent", "percentile"] {
|
||||
let err = s
|
||||
.execute(
|
||||
"home.conditionalFormat",
|
||||
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
|
||||
{"type": ty, "value": "5", "color": "#112233"},
|
||||
{"type": "max", "color": "#778899"},
|
||||
]}}),
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("home.conditionalFormat"), "{ty}: {err}");
|
||||
assert!(err.contains(&format!("`{ty}` stop's `value` must be a number")), "{ty}: {err}");
|
||||
}
|
||||
// A refused scale stores nothing.
|
||||
let rules = s.execute("home.manageRules", json!({})).unwrap();
|
||||
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_omitted_stop_value_is_zero() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"home.conditionalFormat",
|
||||
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
|
||||
{"type": "num", "color": "#112233"},
|
||||
{"type": "percent", "color": "#445566"},
|
||||
{"type": "percentile", "color": "#778899"},
|
||||
]}}),
|
||||
)
|
||||
.unwrap();
|
||||
let list = s.execute("home.manageRules", json!({})).unwrap();
|
||||
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
|
||||
let CfRule::ColorScale { stops } = rule else { panic!("expected a colour scale") };
|
||||
assert_eq!(
|
||||
stops,
|
||||
vec![
|
||||
(CfValueKind::Number(0.0), Color::Rgb(0x112233)),
|
||||
(CfValueKind::Percent(0.0), Color::Rgb(0x445566)),
|
||||
(CfValueKind::Percentile(0.0), Color::Rgb(0x778899)),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_scale_stops_keep_their_thresholds_and_can_be_edited() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"home.conditionalFormat",
|
||||
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
|
||||
{"type": "min", "color": "#112233"},
|
||||
{"type": "num", "value": 5, "color": "#445566"},
|
||||
{"type": "percentile", "value": 90, "color": "#778899"},
|
||||
]}}),
|
||||
)
|
||||
.unwrap();
|
||||
let list = s.execute("home.manageRules", json!({})).unwrap();
|
||||
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
|
||||
let stops = match rule {
|
||||
CfRule::ColorScale { stops } => stops,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
assert_eq!(
|
||||
stops,
|
||||
vec![
|
||||
(CfValueKind::Min, Color::Rgb(0x112233)),
|
||||
(CfValueKind::Number(5.0), Color::Rgb(0x445566)),
|
||||
(CfValueKind::Percentile(90.0), Color::Rgb(0x778899)),
|
||||
]
|
||||
);
|
||||
|
||||
s.execute(
|
||||
"home.manageRules",
|
||||
json!({"edit": 0, "rule": {"type": "colorScale", "stops": [
|
||||
{"type": "formula", "value": "$B$1", "color": "#ABCABC"},
|
||||
{"type": "max", "color": "#DEFDEF"},
|
||||
]}}),
|
||||
)
|
||||
.unwrap();
|
||||
let list = s.execute("home.manageRules", json!({})).unwrap();
|
||||
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
|
||||
let stops = match rule {
|
||||
CfRule::ColorScale { stops } => stops,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
assert_eq!(stops, vec![(CfValueKind::Formula("$B$1".into()), Color::Rgb(0xABCABC)), (CfValueKind::Max, Color::Rgb(0xDEFDEF))]);
|
||||
}
|
||||
}
|
||||
@@ -46,9 +46,9 @@ fn is_string_literal(v: &str) -> bool {
|
||||
/// written as `format_range` takes it (`"#RRGGBB"`, `{theme, tint}`, `"auto"`) and `fill` may be a
|
||||
/// colour alone (a solid fill) or `"none"` (no fill). An unknown key is an error rather than
|
||||
/// dropped: dropped, it left a rule with an empty format that matches and shows nothing.
|
||||
fn cf_style_json(st: &Json) -> Result<Json> {
|
||||
fn cf_style_json(st: &Json, cmd: &str) -> Result<Json> {
|
||||
const KEYS: [&str; 6] = ["font", "fill", "borders", "align", "num_fmt", "protection"];
|
||||
let err = |m: String| bad("home.conditionalFormat", m);
|
||||
let err = |m: String| bad(cmd, m);
|
||||
let Some(obj) = st.as_object() else { return Err(err("`style` must be an object, e.g. {\"fill\": \"#FFC7CE\"}".into())) };
|
||||
let mut st = obj.clone();
|
||||
if let Some(k) = st.keys().find(|k| !KEYS.contains(&k.as_str())) {
|
||||
@@ -103,36 +103,40 @@ fn cf_style_json(st: &Json) -> Result<Json> {
|
||||
fn check_cf_formula(cmd: &str, what: &str, formula: &str) -> Result<()> {
|
||||
// Strip exactly one leading '=', the way the XLSX writer does: a value like '===A1'
|
||||
// only parses after several strips and would still be saved unparseable. (#1999 review)
|
||||
if gridcraft_formula::parse(formula.strip_prefix('=').unwrap_or(formula)).is_err() {
|
||||
let parsed = formula.strip_prefix('=').unwrap_or(formula);
|
||||
// A rule with no formula never applies; the dialog also keeps OK disabled for it.
|
||||
if parsed.trim().is_empty() {
|
||||
return Err(bad(cmd, format!("the {what} formula is empty")));
|
||||
}
|
||||
if gridcraft_formula::parse(parsed).is_err() {
|
||||
return Err(bad(cmd, format!("invalid {what} formula `{formula}` — it does not parse; Excel would reject the saved file")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_cf_value(what: &str, v: &gridcraft_model::features::CfValueKind) -> Result<()> {
|
||||
fn check_cf_value(cmd: &str, what: &str, v: &gridcraft_model::features::CfValueKind) -> Result<()> {
|
||||
if let gridcraft_model::features::CfValueKind::Formula(f) = v {
|
||||
check_cf_formula("home.conditionalFormat", what, f)?;
|
||||
check_cf_formula(cmd, what, f)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_cf_rule(rule: &CfRule) -> Result<()> {
|
||||
const CMD: &str = "home.conditionalFormat";
|
||||
fn check_cf_rule(cmd: &str, rule: &CfRule) -> Result<()> {
|
||||
match rule {
|
||||
CfRule::CellIs { a, b, .. } => {
|
||||
check_cf_formula(CMD, "comparison value", a)?;
|
||||
check_cf_formula(cmd, "comparison value", a)?;
|
||||
if let Some(b) = b {
|
||||
check_cf_formula(CMD, "second comparison value", b)?;
|
||||
check_cf_formula(cmd, "second comparison value", b)?;
|
||||
}
|
||||
}
|
||||
CfRule::Expression { formula, .. } => check_cf_formula(CMD, "rule", formula)?,
|
||||
CfRule::Expression { formula, .. } => check_cf_formula(cmd, "rule", formula)?,
|
||||
CfRule::DataBar { min, max, .. } => {
|
||||
check_cf_value("data bar minimum", min)?;
|
||||
check_cf_value("data bar maximum", max)?;
|
||||
check_cf_value(cmd, "data bar minimum", min)?;
|
||||
check_cf_value(cmd, "data bar maximum", max)?;
|
||||
}
|
||||
CfRule::ColorScale { stops } => {
|
||||
for (kind, _) in stops {
|
||||
check_cf_value("color scale threshold", kind)?;
|
||||
check_cf_value(cmd, "color scale threshold", kind)?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -140,41 +144,53 @@ fn check_cf_rule(rule: &CfRule) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn add_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let ranges = target_ranges(s, p)?;
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let Some(rule) = p.get("rule") else {
|
||||
s.ui_requests.push(crate::UiRequest::Dialog("newFormattingRule".into(), json!({})));
|
||||
return ok();
|
||||
};
|
||||
fn cf_style(rule: &Json, cmd: &str) -> Result<Style> {
|
||||
let g = |k: &str| rule.get(k).and_then(Json::as_str).map(str::to_string);
|
||||
let style = Box::new(match rule.get("style") {
|
||||
match rule.get("style") {
|
||||
Some(st) if !st.is_null() => {
|
||||
let st = cf_style_json(st)?;
|
||||
let st = cf_style_json(st, cmd)?;
|
||||
let base = serde_json::to_value(Style::default()).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
serde_json::from_value(crate::cmd::format::merge_json(base, &st)).map_err(|e| bad("home.conditionalFormat", e.to_string()))?
|
||||
Ok(serde_json::from_value(crate::cmd::format::merge_json(base, &st)).map_err(|e| bad(cmd, e.to_string()))?)
|
||||
}
|
||||
_ => preset_style(g("preset").as_deref().unwrap_or("lightRedFillDarkRedText")),
|
||||
});
|
||||
let kind = g("type").unwrap_or_else(|| "cellIs".into());
|
||||
let value_kind = |v: Option<&Json>, default: CfValueKind| -> CfValueKind {
|
||||
match v {
|
||||
Some(Json::Object(o)) => {
|
||||
let t = o.get("type").and_then(Json::as_str).unwrap_or("num");
|
||||
let val = o.get("value").and_then(Json::as_f64).unwrap_or(0.0);
|
||||
match t {
|
||||
"min" => CfValueKind::Min,
|
||||
"max" => CfValueKind::Max,
|
||||
"percent" => CfValueKind::Percent(val),
|
||||
"percentile" => CfValueKind::Percentile(val),
|
||||
"formula" => CfValueKind::Formula(o.get("value").and_then(Json::as_str).unwrap_or("").into()),
|
||||
_ => CfValueKind::Number(val),
|
||||
}
|
||||
}
|
||||
_ => default,
|
||||
_ => Ok(preset_style(g("preset").as_deref().unwrap_or("lightRedFillDarkRedText"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn cf_value_kind(v: Option<&Json>, default: CfValueKind, cmd: &str) -> Result<CfValueKind> {
|
||||
let Some(Json::Object(o)) = v else { return Ok(default) };
|
||||
let t = o.get("type").and_then(Json::as_str).unwrap_or("num");
|
||||
// A value that is given must be a number: a string used to be read as 0 without a word.
|
||||
// Only an omitted `value` defaults to zero.
|
||||
let number = || -> Result<f64> {
|
||||
match o.get("value") {
|
||||
None => Ok(0.0),
|
||||
Some(v) => v.as_f64().ok_or_else(|| bad(cmd, format!("the `{t}` stop's `value` must be a number, not {v}"))),
|
||||
}
|
||||
};
|
||||
let rule = match kind.as_str() {
|
||||
Ok(match t {
|
||||
"min" => CfValueKind::Min,
|
||||
"max" => CfValueKind::Max,
|
||||
// The dialog clamps these to 0-100; engine callers get the same range.
|
||||
"percent" => CfValueKind::Percent(number()?.clamp(0.0, 100.0)),
|
||||
"percentile" => CfValueKind::Percentile(number()?.clamp(0.0, 100.0)),
|
||||
"formula" => {
|
||||
let f = o.get("value").and_then(Json::as_str).unwrap_or("");
|
||||
if f.trim().is_empty() {
|
||||
return Err(bad(cmd, "a formula stop needs a formula"));
|
||||
}
|
||||
// Stored exactly: the evaluator takes the formula as written.
|
||||
CfValueKind::Formula(f.into())
|
||||
}
|
||||
"num" => CfValueKind::Number(number()?),
|
||||
other => return Err(bad(cmd, format!("unknown stop type `{other}`"))),
|
||||
})
|
||||
}
|
||||
|
||||
fn cf_rule(rule: &Json, cmd: &str) -> Result<CfRule> {
|
||||
let g = |k: &str| rule.get(k).and_then(Json::as_str).map(str::to_string);
|
||||
let style = Box::new(cf_style(rule, cmd)?);
|
||||
let kind = g("type").unwrap_or_else(|| "cellIs".into());
|
||||
match kind.as_str() {
|
||||
"cellIs" => {
|
||||
// Excel's file and VBA names (`lessThan`, …) are accepted too.
|
||||
let op = match g("operator").as_deref().unwrap_or("greater") {
|
||||
@@ -186,7 +202,7 @@ pub(super) fn add_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
"greaterOrEqual" | "greaterThanOrEqual" => CfOperator::GreaterOrEqual,
|
||||
"lessOrEqual" | "lessThanOrEqual" => CfOperator::LessOrEqual,
|
||||
"greater" | "greaterThan" => CfOperator::Greater,
|
||||
other => return Err(bad("home.conditionalFormat", format!("unknown operator `{other}`"))),
|
||||
other => return Err(bad(cmd, format!("unknown operator `{other}`"))),
|
||||
};
|
||||
let a = rule.get("value").map(crate::cmd::edit::json_to_input).unwrap_or_default();
|
||||
let b = rule.get("value2").map(crate::cmd::edit::json_to_input);
|
||||
@@ -201,59 +217,85 @@ pub(super) fn add_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
format!("\"{}\"", v.replace('"', "\"\""))
|
||||
}
|
||||
};
|
||||
CfRule::CellIs { op, a: quote(a), b: b.map(quote), style }
|
||||
Ok(CfRule::CellIs { op, a: quote(a), b: b.map(quote), style })
|
||||
}
|
||||
"expression" => CfRule::Expression { formula: g("formula").unwrap_or_default().trim_start_matches('=').to_string(), style },
|
||||
"containsText" => CfRule::ContainsText { text: g("text").unwrap_or_default(), style },
|
||||
"notContainsText" => CfRule::NotContainsText { text: g("text").unwrap_or_default(), style },
|
||||
"beginsWith" => CfRule::BeginsWith { text: g("text").unwrap_or_default(), style },
|
||||
"endsWith" => CfRule::EndsWith { text: g("text").unwrap_or_default(), style },
|
||||
"blanks" => CfRule::Blanks { style },
|
||||
"noBlanks" => CfRule::NoBlanks { style },
|
||||
"errors" => CfRule::Errors { style },
|
||||
"noErrors" => CfRule::NoErrors { style },
|
||||
"duplicate" => CfRule::Duplicate { style },
|
||||
"unique" => CfRule::Unique { style },
|
||||
"top10" => CfRule::Top10 {
|
||||
"expression" => Ok(CfRule::Expression { formula: g("formula").unwrap_or_default().trim_start_matches('=').to_string(), style }),
|
||||
"containsText" => Ok(CfRule::ContainsText { text: g("text").unwrap_or_default(), style }),
|
||||
"notContainsText" => Ok(CfRule::NotContainsText { text: g("text").unwrap_or_default(), style }),
|
||||
"beginsWith" => Ok(CfRule::BeginsWith { text: g("text").unwrap_or_default(), style }),
|
||||
"endsWith" => Ok(CfRule::EndsWith { text: g("text").unwrap_or_default(), style }),
|
||||
"blanks" => Ok(CfRule::Blanks { style }),
|
||||
"noBlanks" => Ok(CfRule::NoBlanks { style }),
|
||||
"errors" => Ok(CfRule::Errors { style }),
|
||||
"noErrors" => Ok(CfRule::NoErrors { style }),
|
||||
"duplicate" => Ok(CfRule::Duplicate { style }),
|
||||
"unique" => Ok(CfRule::Unique { style }),
|
||||
"top10" => Ok(CfRule::Top10 {
|
||||
bottom: rule.get("bottom").and_then(Json::as_bool).unwrap_or(false),
|
||||
percent: rule.get("percent").and_then(Json::as_bool).unwrap_or(false),
|
||||
rank: rule.get("rank").and_then(Json::as_u64).unwrap_or(10) as u32,
|
||||
style,
|
||||
},
|
||||
"aboveAverage" => CfRule::AboveAverage { below: rule.get("below").and_then(Json::as_bool).unwrap_or(false), equal: false, std_dev: 0, style },
|
||||
"timePeriod" => CfRule::TimePeriod { period: g("period").unwrap_or_else(|| "today".into()), style },
|
||||
"colorScale" => {
|
||||
let cols: Vec<Color> = rule
|
||||
.get("colors")
|
||||
.and_then(Json::as_array)
|
||||
.map(|a| a.iter().filter_map(|c| crate::cmd::format::color_param(Some(c))).collect())
|
||||
.unwrap_or_else(|| vec![Color::rgb(0xF8, 0x69, 0x6B), Color::rgb(0xFF, 0xEB, 0x84), Color::rgb(0x63, 0xBE, 0x7B)]);
|
||||
let stops = match cols.len() {
|
||||
2 => vec![(CfValueKind::Min, cols[0]), (CfValueKind::Max, cols[1])],
|
||||
_ => vec![
|
||||
(CfValueKind::Min, cols.first().copied().unwrap_or_default()),
|
||||
(CfValueKind::Percentile(50.0), cols.get(1).copied().unwrap_or_default()),
|
||||
(CfValueKind::Max, cols.get(2).copied().unwrap_or_default()),
|
||||
],
|
||||
};
|
||||
CfRule::ColorScale { stops }
|
||||
}),
|
||||
"aboveAverage" => {
|
||||
Ok(CfRule::AboveAverage { below: rule.get("below").and_then(Json::as_bool).unwrap_or(false), equal: false, std_dev: 0, style })
|
||||
}
|
||||
"dataBar" => CfRule::DataBar {
|
||||
min: value_kind(rule.get("min"), CfValueKind::Min),
|
||||
max: value_kind(rule.get("max"), CfValueKind::Max),
|
||||
"timePeriod" => Ok(CfRule::TimePeriod { period: g("period").unwrap_or_else(|| "today".into()), style }),
|
||||
"colorScale" => {
|
||||
let stops = if let Some(stops) = rule.get("stops") {
|
||||
// A present but misshapen `stops` is a mistake, not a request for `colors`.
|
||||
let list = stops.as_array().ok_or_else(|| bad(cmd, "`stops` must be an array"))?;
|
||||
let mut out = Vec::with_capacity(list.len().min(3));
|
||||
for stop in list {
|
||||
let color = crate::cmd::format::color_param(stop.get("color")).ok_or_else(|| bad(cmd, "a colour-scale stop needs a colour"))?;
|
||||
out.push((cf_value_kind(Some(stop), CfValueKind::Min, cmd)?, color));
|
||||
}
|
||||
if !(2..=3).contains(&out.len()) {
|
||||
return Err(bad(cmd, "a colour scale needs two or three stops"));
|
||||
}
|
||||
out
|
||||
} else {
|
||||
let cols: Vec<Color> = rule
|
||||
.get("colors")
|
||||
.and_then(Json::as_array)
|
||||
.map(|a| a.iter().filter_map(|c| crate::cmd::format::color_param(Some(c))).collect())
|
||||
.unwrap_or_else(|| vec![Color::rgb(0xF8, 0x69, 0x6B), Color::rgb(0xFF, 0xEB, 0x84), Color::rgb(0x63, 0xBE, 0x7B)]);
|
||||
match cols.len() {
|
||||
2 => vec![(CfValueKind::Min, cols[0]), (CfValueKind::Max, cols[1])],
|
||||
_ => vec![
|
||||
(CfValueKind::Min, cols.first().copied().unwrap_or_default()),
|
||||
(CfValueKind::Percentile(50.0), cols.get(1).copied().unwrap_or_default()),
|
||||
(CfValueKind::Max, cols.get(2).copied().unwrap_or_default()),
|
||||
],
|
||||
}
|
||||
};
|
||||
Ok(CfRule::ColorScale { stops })
|
||||
}
|
||||
"dataBar" => Ok(CfRule::DataBar {
|
||||
min: cf_value_kind(rule.get("min"), CfValueKind::Min, cmd)?,
|
||||
max: cf_value_kind(rule.get("max"), CfValueKind::Max, cmd)?,
|
||||
color: crate::cmd::format::color_param(rule.get("color")).unwrap_or(Color::rgb(0x63, 0x8E, 0xC6)),
|
||||
gradient: rule.get("gradient").and_then(Json::as_bool).unwrap_or(true),
|
||||
show_value: true,
|
||||
},
|
||||
"iconSet" => CfRule::IconSet {
|
||||
}),
|
||||
"iconSet" => Ok(CfRule::IconSet {
|
||||
set: g("set").unwrap_or_else(|| "3TrafficLights1".into()),
|
||||
thresholds: vec![],
|
||||
reverse: rule.get("reverse").and_then(Json::as_bool).unwrap_or(false),
|
||||
show_value: true,
|
||||
},
|
||||
other => return Err(bad("home.conditionalFormat", format!("unknown rule type `{other}`"))),
|
||||
}),
|
||||
other => Err(bad(cmd, format!("unknown rule type `{other}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn add_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let ranges = target_ranges(s, p)?;
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let Some(rule) = p.get("rule") else {
|
||||
s.ui_requests.push(crate::UiRequest::Dialog("newFormattingRule".into(), json!({})));
|
||||
return ok();
|
||||
};
|
||||
check_cf_rule(&rule)?;
|
||||
let rule = cf_rule(rule, "home.conditionalFormat")?;
|
||||
check_cf_rule("home.conditionalFormat", &rule)?;
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let priority = sh.cond_formats.iter().map(|c| c.priority).max().unwrap_or(0) + 1;
|
||||
@@ -295,17 +337,33 @@ pub(super) fn clear_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
pub(super) fn manage_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
if p.get("delete").is_none() && p.get("moveUp").is_none() && p.get("moveDown").is_none() {
|
||||
if p.get("delete").is_none() && p.get("moveUp").is_none() && p.get("moveDown").is_none() && p.get("edit").is_none() {
|
||||
let list: Vec<Json> = s
|
||||
.doc()?
|
||||
.wb
|
||||
.sheet(sheet)
|
||||
.map(|sh| {
|
||||
sh.cond_formats.iter().map(|c| json!({"ranges": c.ranges.iter().map(|r| r.a1()).collect::<Vec<_>>(), "rule": c.rule})).collect()
|
||||
sh.cond_formats
|
||||
.iter()
|
||||
.map(|c| json!({"ranges": c.ranges.iter().map(|r| r.a1()).collect::<Vec<_>>(), "rule": c.rule, "priority": c.priority}))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
return Ok(json!({"rules": list}));
|
||||
}
|
||||
let edited = match (p.get("edit"), p.get("rule")) {
|
||||
(None, _) => None,
|
||||
(Some(_), None) => return Err(bad("home.manageRules", "missing `rule` for an edit")),
|
||||
(Some(e), Some(rule)) => {
|
||||
let i = e.as_u64().ok_or_else(|| bad("home.manageRules", "`edit` must be a rule index"))?;
|
||||
// A number too large for `usize` on this target names no rule: casting it would
|
||||
// wrap to a real index and replace that rule instead of reporting out of range.
|
||||
let i = usize::try_from(i).map_err(|_| bad("home.manageRules", format!("no conditional format at index {i}")))?;
|
||||
let rule = cf_rule(rule, "home.manageRules")?;
|
||||
check_cf_rule("home.manageRules", &rule)?;
|
||||
Some((i, rule))
|
||||
}
|
||||
};
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
// The count is taken again after each step: a delete shortens the list.
|
||||
@@ -314,6 +372,10 @@ pub(super) fn manage_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
{
|
||||
sh.cond_formats.remove(i);
|
||||
}
|
||||
if let Some((i, rule)) = edited {
|
||||
let cf = sh.cond_formats.get_mut(i).ok_or_else(|| bad("home.manageRules", format!("no conditional format at index {i}")))?;
|
||||
cf.rule = rule;
|
||||
}
|
||||
if let Some(i) = u32_param(p, "moveUp").map(|v| v as usize)
|
||||
&& i > 0
|
||||
&& i < sh.cond_formats.len()
|
||||
|
||||
@@ -7,6 +7,9 @@ fn table() -> Session {
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range":"A1", "values":[["Quarterly Revenue"], ["1"]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range":"A1:A2", "header":true})).unwrap();
|
||||
// Bold in its own style too, so the table style's bold header row changes nothing here and
|
||||
// these tests compare only the filter button's room, with or without the table.
|
||||
s.execute("home.bold", json!({"range":"A1", "on": true})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
|
||||
@@ -54,3 +54,168 @@ fn resize_next_to_another_table_still_works() {
|
||||
s.execute("table.resize", json!({"table":"T", "range":"A1:C3"})).unwrap();
|
||||
assert_eq!(ranges(&s), ["A1:C3", "D1:E2"]);
|
||||
}
|
||||
|
||||
fn sheet(s: &Session) -> &gridcraft_engine::model::Sheet {
|
||||
s.doc().unwrap().wb.active().unwrap()
|
||||
}
|
||||
|
||||
fn names(s: &Session, table: usize) -> Vec<String> {
|
||||
sheet(s).tables[table].columns.iter().map(|c| c.name.clone()).collect()
|
||||
}
|
||||
|
||||
fn headers(s: &Session, table: usize) -> Vec<String> {
|
||||
let sh = sheet(s);
|
||||
let r = sh.tables[table].range;
|
||||
(r.start.col..=r.end.col).map(|c| sh.value(gridcraft_core::CellRef::new(r.start.row, c)).display()).collect()
|
||||
}
|
||||
|
||||
fn with_headers(range: &str, row: &[&str]) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let rows = vec![row.iter().map(|h| json!(h)).collect::<Vec<_>>(), row.iter().map(|_| json!(1)).collect(), row.iter().map(|_| json!(2)).collect()];
|
||||
s.execute("range.setValues", json!({"range": range, "values": rows})).unwrap();
|
||||
s.execute("insert.table", json!({"range": range, "header": true, "name": "T"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_onto_another_table_is_rejected() {
|
||||
// From the sales sample, growing Table2 over Table1 used to leave two overlapping tables.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"sample": "sales"})).unwrap();
|
||||
s.execute("insert.table", json!({"header": true, "range": "M2:N5"})).unwrap();
|
||||
s.execute("insert.table", json!({"header": true, "range": "P2:Q5"})).unwrap();
|
||||
let e = s.execute("table.resize", json!({"range": "M2:Q5", "table": "Table2"})).unwrap_err().to_string();
|
||||
assert!(e.contains("overlap another table"), "{e}");
|
||||
let ranges: Vec<String> = sheet(&s).tables.iter().map(|t| t.range.a1()).collect();
|
||||
assert!(ranges.contains(&"M2:N5".to_string()) && ranges.contains(&"P2:Q5".to_string()), "{ranges:?}");
|
||||
// Down over a table below, or around a whole table, is refused too; next to it is fine.
|
||||
let mut s = table();
|
||||
s.execute("range.setValues", json!({"range": "A5", "values": [["c"], ["1"]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "A5:A6", "header": true, "name": "U"})).unwrap();
|
||||
assert!(s.execute("table.resize", json!({"table": "T", "range": "A1:B5"})).is_err());
|
||||
assert!(s.execute("table.resize", json!({"table": "T", "range": "A1:C9"})).is_err());
|
||||
s.execute("table.resize", json!({"table": "T", "range": "A1:B4"})).unwrap();
|
||||
assert_eq!(table_range(&s), "A1:B4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_onto_merged_cells_pivot_or_array_is_rejected() {
|
||||
let mut s = table();
|
||||
s.execute("home.mergeCenter", json!({"range": "D2:E2"})).unwrap();
|
||||
let e = s.execute("table.resize", json!({"table": "T", "range": "A1:D2"})).unwrap_err().to_string();
|
||||
assert!(e.contains("merged"), "{e}");
|
||||
assert_eq!(table_range(&s), "A1:B2");
|
||||
|
||||
let mut s = table();
|
||||
s.execute("selection.set", json!({"range": "D1:D2"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "D1", "input": "=ROW(1:2)", "array": true})).unwrap();
|
||||
let e = s.execute("table.resize", json!({"table": "T", "range": "A1:D2"})).unwrap_err().to_string();
|
||||
assert!(e.contains("array"), "{e}");
|
||||
assert_eq!(table_range(&s), "A1:B2");
|
||||
|
||||
let mut s = table();
|
||||
s.execute("range.setValues", json!({"range": "H1", "values": [["k", "v"], ["x", "1"], ["y", "2"]]})).unwrap();
|
||||
s.execute("insert.pivotTable", json!({"source": "Sheet1!$H$1:$I$3", "destination": "Sheet1!D3", "filters": ["k"], "values": ["v"]})).unwrap();
|
||||
assert!(!sheet(&s).pivots.is_empty());
|
||||
let e = s.execute("table.resize", json!({"table": "T", "range": "A1:E2"})).unwrap_err().to_string();
|
||||
assert!(e.contains("PivotTable"), "{e}");
|
||||
assert_eq!(table_range(&s), "A1:B2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_onto_a_spill_is_allowed() {
|
||||
// Excel lets a table take in a spilled formula (the spill then shows #SPILL!).
|
||||
let mut s = table();
|
||||
s.execute("cell.set", json!({"cell": "D2", "input": "=SEQUENCE(1,2)"})).unwrap();
|
||||
s.execute("table.resize", json!({"table": "T", "range": "A1:D2"})).unwrap();
|
||||
assert_eq!(table_range(&s), "A1:D2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resized_in_columns_get_excel_names_written_into_the_header_row() {
|
||||
// A resize whose new columns repeated a name left the header row and the column
|
||||
// names out of step ("Column3" in memory, "Column32" after reopening).
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"sample": "grades"})).unwrap();
|
||||
s.execute("home.formatAsTable", json!({"header": "x", "range": "I3:K9", "style": false})).unwrap();
|
||||
s.execute("table.resize", json!({"range": "K3:N7", "table": "Table1"})).unwrap();
|
||||
let ti = sheet(&s).tables.iter().position(|t| t.name == "Table1").unwrap();
|
||||
assert_eq!(names(&s, ti), headers(&s, ti));
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
assert!(names(&s, ti).iter().all(|n| seen.insert(n.to_lowercase())), "{:?}", names(&s, ti));
|
||||
let bytes = gridcraft_engine::io::save_bytes(&s.doc().unwrap().wb, "t.xlsx").unwrap();
|
||||
let (back, _) = gridcraft_engine::io::open_bytes("t.xlsx", &bytes).unwrap();
|
||||
let t = back.active().unwrap().tables.iter().find(|t| t.name == "Table1").unwrap();
|
||||
assert_eq!(t.columns.iter().map(|c| c.name.clone()).collect::<Vec<_>>(), names(&s, ti));
|
||||
|
||||
// Names Excel gives (observed): an empty header continues a ColumnN on its left, else takes
|
||||
// the lowest free ColumnN; a repeated header gets the next free suffix.
|
||||
let cases: [(&str, &[&str], &str, &[&str]); 5] = [
|
||||
("A1:B3", &["a", "b"], "A1:E3", &["a", "b", "Column1", "Column2", "Column3"]),
|
||||
("A1:C3", &["Column2", "b", "c"], "A1:F3", &["Column2", "b", "c", "Column1", "Column12", "Column13"]),
|
||||
("A1:B3", &["Column3", "b"], "A1:E3", &["Column3", "b", "Column1", "Column2", "Column22"]),
|
||||
("A1:B3", &["Column1", "b"], "A1:D3", &["Column1", "b", "Column2", "Column3"]),
|
||||
("A1:C3", &["Column1", "Column2", "Column3"], "C1:F3", &["Column3", "Column4", "Column5", "Column6"]),
|
||||
];
|
||||
for (range, row, to, want) in cases {
|
||||
let mut s = with_headers(range, row);
|
||||
s.execute("table.resize", json!({"table": "T", "range": to})).unwrap();
|
||||
assert_eq!(names(&s, 0), want.iter().map(|w| w.to_string()).collect::<Vec<_>>(), "{row:?} -> {to}");
|
||||
assert_eq!(headers(&s, 0), names(&s, 0), "{row:?} -> {to}");
|
||||
}
|
||||
|
||||
// Headers already in the new columns are kept, made unique and turned into text.
|
||||
let mut s = with_headers("A1:B3", &["x", "y"]);
|
||||
s.execute("range.setValues", json!({"range": "C1", "values": [["X", "x", 5]]})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "F1", "input": "=1+1"})).unwrap();
|
||||
s.execute("table.resize", json!({"table": "T", "range": "A1:F3"})).unwrap();
|
||||
assert_eq!(names(&s, 0), ["x", "y", "X2", "x3", "5", "2"]);
|
||||
assert_eq!(headers(&s, 0), names(&s, 0));
|
||||
assert!(sheet(&s).cell(gridcraft_core::CellRef::new(0, 5)).is_some_and(|c| c.formula.is_none()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resizing_a_table_without_a_header_row_keeps_its_names_and_data() {
|
||||
let mut s = with_headers("A1:B3", &["a", "b"]);
|
||||
// As a file can have it: the table starts at its first data row (A2:B3), with no header row.
|
||||
{
|
||||
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
|
||||
let t = &mut std::sync::Arc::make_mut(&mut wb.sheets[0]).tables[0];
|
||||
t.header_row = false;
|
||||
t.range.start.row = 1;
|
||||
}
|
||||
let r = sheet(&s).tables[0].range;
|
||||
assert!(!sheet(&s).tables[0].header_row);
|
||||
let to = gridcraft_core::RangeRef::new(r.start, gridcraft_core::CellRef::new(r.end.row, r.end.col + 1));
|
||||
let first = sheet(&s).value(r.start).display();
|
||||
s.execute("table.resize", json!({"table": "T", "range": to.a1()})).unwrap();
|
||||
assert_eq!(names(&s, 0), ["a", "b", "Column1"]);
|
||||
assert_eq!(sheet(&s).value(r.start).display(), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resized_formula_header_is_named_by_its_value_when_formulas_show() {
|
||||
let mut s = with_headers("A1:B3", &["x", "y"]);
|
||||
s.execute("cell.set", json!({"cell": "C1", "input": "=1+1"})).unwrap();
|
||||
{
|
||||
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
|
||||
std::sync::Arc::make_mut(&mut wb.sheets[0]).show_formulas = true;
|
||||
}
|
||||
s.execute("table.resize", json!({"table": "T", "range": "A1:C3"})).unwrap();
|
||||
assert_eq!(names(&s, 0), ["x", "y", "2"]);
|
||||
assert_eq!(headers(&s, 0), names(&s, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resized_picture_header_is_replaced_and_its_picture_removed() {
|
||||
let mut s = with_headers("A1:B3", &["x", "y"]);
|
||||
{
|
||||
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
|
||||
let picture = gridcraft_engine::model::CellPicture { data: vec![1, 2, 3], mime: "image/png".into(), alt: String::new() };
|
||||
std::sync::Arc::make_mut(&mut wb.sheets[0]).set_picture(gridcraft_core::CellRef::new(0, 2), std::sync::Arc::new(picture));
|
||||
}
|
||||
s.execute("table.resize", json!({"table": "T", "range": "A1:C3"})).unwrap();
|
||||
assert!(!sheet(&s).cell_pictures.contains_key(&gridcraft_core::CellRef::new(0, 2)));
|
||||
assert_eq!(headers(&s, 0), names(&s, 0));
|
||||
}
|
||||
@@ -258,7 +258,8 @@ pub struct LineInfo {
|
||||
pub outline: u8,
|
||||
pub collapsed: bool,
|
||||
pub style: Option<crate::style::StyleId>,
|
||||
/// The size was set by the user (rows): automatic heights follow the content.
|
||||
/// The size was set by the user. Rows without it follow their content's height; columns
|
||||
/// without it widen when a number format makes their numbers wider (`home.increaseDecimal`…).
|
||||
#[serde(default)]
|
||||
pub custom: bool,
|
||||
}
|
||||
|
||||
@@ -327,6 +327,18 @@ impl SheetApp {
|
||||
self.open_dialog(name, p.clone());
|
||||
Ok(json!({"dialog": self.dialog.as_ref().map(|d| d.name())}))
|
||||
}
|
||||
"ui.selectionMode" => {
|
||||
// `{"mode": "extend"}` (F8), `"add"` (Shift+F8) or `"off"`; `{}` reports the mode.
|
||||
match p.get("mode").and_then(Json::as_str) {
|
||||
Some(id) => match crate::grid::SelectionMode::parse(id) {
|
||||
Some(mode) => self.grid.set_selection_mode(mode),
|
||||
None => return Some(Err(format!("unknown selection mode {id:?} (use \"extend\", \"add\" or \"off\")"))),
|
||||
},
|
||||
None if p.get("mode").is_some_and(|v| !v.is_null()) => return Some(Err("`mode` must be \"extend\", \"add\" or \"off\"".into())),
|
||||
None => {}
|
||||
}
|
||||
Ok(json!({"mode": self.grid.selection_mode.id()}))
|
||||
}
|
||||
"ui.pythonMode" => {
|
||||
// `{"on": true}` starts Python mode on the active cell (or switches the edit in
|
||||
// progress to it), `{"on": false}` leaves it; without `on` it switches. A start
|
||||
|
||||
@@ -18,6 +18,8 @@ impl SheetApp {
|
||||
self.message = Some(("Text Box".into(), clean_error(&e)));
|
||||
return;
|
||||
}
|
||||
// Editing a cell ends Extend and Add mode, as in Excel.
|
||||
self.grid.set_selection_mode(crate::grid::SelectionMode::Off);
|
||||
let Some(d) = self.session.active() else { return };
|
||||
let Some(sh) = d.wb.active() else { return };
|
||||
let at = sh.merge_at(d.selection.active).map(|m| m.start).unwrap_or(d.selection.active);
|
||||
|
||||
@@ -280,6 +280,11 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
|
||||
("ui.window.close", "Close Window", ""),
|
||||
("ui.window.beginResize", "Resize Window", "{direction: north|south|east|west|northeast|northwest|southeast|southwest}"),
|
||||
("ui.dialog", "Open Dialog", ""),
|
||||
(
|
||||
"ui.selectionMode",
|
||||
"Extend or Add to Selection",
|
||||
"{mode?: \"extend\" (F8) | \"add\" (Shift+F8) | \"off\"} → {mode}; {} reports the mode",
|
||||
),
|
||||
("ui.backstage", "File (Backstage view)", "{page?: home|new|open|info|saveAs|print|export|options|account|close}"),
|
||||
(
|
||||
"ui.printSettings",
|
||||
|
||||
@@ -1011,6 +1011,7 @@ impl Dialog {
|
||||
dialog
|
||||
}
|
||||
"manageRules" => Dialog::custom("manageRules", "Conditional Formatting Rules Manager", json!({})),
|
||||
"newFormattingRule" => cond_format_rules::new_rule_dialog(app, ¶ms),
|
||||
"commandSearch" => Dialog::custom("commandSearch", "Search Commands", json!({})),
|
||||
"agents" => Dialog::custom("agents", "Agent Control", json!({})),
|
||||
"about" => {
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
use super::{Json, SheetApp, json};
|
||||
//! Conditional formatting dialogs: the rules manager, and the New / Edit Formatting Rule editor
|
||||
//! with its 2- and 3-colour scale stops.
|
||||
|
||||
use super::show::{ok_cancel_enabled, track_pick};
|
||||
use super::{Dialog, Json, RefPick, SheetApp, json};
|
||||
use egui::{Color32, Sense, Stroke, StrokeKind, vec2};
|
||||
use gridcraft_engine::core::{CellRef, RangeRef};
|
||||
use gridcraft_engine::model::{CfRule, CfValueKind, Color as CellColor, Theme};
|
||||
|
||||
/// The list scrolls inside the dialog: a sheet read from a file can carry thousands of rules, and
|
||||
/// a list laid out in full made the window as tall as all of them (issue #3321).
|
||||
const LIST_HEIGHT: f32 = 360.0;
|
||||
|
||||
pub(super) fn manage_rules(app: &mut SheetApp, ui: &mut egui::Ui) {
|
||||
let lang = app.ui.language;
|
||||
// Read the rules in place: running `home.manageRules` for them each frame copied and
|
||||
// serialised every rule and journaled a step 60 times a second.
|
||||
let count = app.session.active().and_then(|d| d.wb.active()).map_or(0, |sh| sh.cond_formats.len());
|
||||
@@ -13,15 +21,20 @@ pub(super) fn manage_rules(app: &mut SheetApp, ui: &mut egui::Ui) {
|
||||
return;
|
||||
}
|
||||
let mut action: Option<Json> = None;
|
||||
let mut edit: Option<(usize, Json)> = None;
|
||||
let row_height = ui.spacing().interact_size.y;
|
||||
egui::ScrollArea::both().max_height(LIST_HEIGHT).auto_shrink([false, true]).show_rows(ui, row_height, count, |ui, rows| {
|
||||
let Some(sh) = app.session.active().and_then(|d| d.wb.active()) else { return };
|
||||
for i in rows {
|
||||
let Some(cf) = sh.cond_formats.get(i) else { break };
|
||||
let kind = serde_json::to_value(&cf.rule).ok().and_then(|r| r.as_object().and_then(|o| o.keys().next().cloned())).unwrap_or_default();
|
||||
let rule = serde_json::to_value(&cf.rule).unwrap_or(Json::Null);
|
||||
let kind = rule.as_object().and_then(|o| o.keys().next().cloned()).unwrap_or_default();
|
||||
let ranges = cf.ranges.iter().map(|r| r.a1()).collect::<Vec<_>>().join(",");
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(format!("{}. {kind} applies to {ranges}", i + 1));
|
||||
if kind.contains("ColorScale") && ui.small_button(lang.tr("Edit")).clicked() {
|
||||
edit = Some((i, rule.clone()));
|
||||
}
|
||||
if ui.small_button("▲").clicked() {
|
||||
action = Some(json!({"moveUp": i}));
|
||||
}
|
||||
@@ -34,7 +47,443 @@ pub(super) fn manage_rules(app: &mut SheetApp, ui: &mut egui::Ui) {
|
||||
});
|
||||
}
|
||||
});
|
||||
if let Some((i, rule)) = edit {
|
||||
app.open_dialog("newFormattingRule", json!({"edit": i, "rule": rule}));
|
||||
}
|
||||
if let Some(params) = action {
|
||||
app.run_or_alert("home.manageRules", params);
|
||||
}
|
||||
}
|
||||
|
||||
/// The New Formatting Rule dialog, or the rule editor Manage Rules opens on an existing colour
|
||||
/// scale (`edit` and `rule` in the params).
|
||||
pub(super) fn new_rule_dialog(app: &mut SheetApp, params: &Json) -> Dialog {
|
||||
let theme = app.session.active().map(|d| d.wb.theme.clone()).unwrap_or_default();
|
||||
// Excel titles the Manage Rules path "Edit Formatting Rule": OK replaces the rule rather than
|
||||
// adding one, and the window should say so.
|
||||
let editing = params.get("edit").is_some();
|
||||
let title = if editing { "Edit Formatting Rule" } else { "New Formatting Rule" };
|
||||
let mut d = Dialog::custom("newFormattingRule", title, new_rule_defaults(params, &theme));
|
||||
d.command = Some(if editing { "home.manageRules" } else { "home.conditionalFormat" });
|
||||
// The sheet and selection the rule was opened on: Excel's "Applies to" stays put
|
||||
// even if the selection moves or another sheet is shown before OK.
|
||||
let (sheet, applies_to) = app
|
||||
.session
|
||||
.active()
|
||||
.map(|doc| {
|
||||
(
|
||||
doc.wb.active().map(|sh| sh.name.clone()).unwrap_or_default(),
|
||||
doc.selection.ranges.iter().map(RangeRef::a1).collect::<Vec<_>>().join(","),
|
||||
)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
d.values.insert("sheet".into(), json!(sheet));
|
||||
d.values.insert("applies_to".into(), json!(applies_to));
|
||||
sync_rule_pick(&mut d);
|
||||
d
|
||||
}
|
||||
|
||||
/// The command params OK sends: the rule the editor describes, on the scope it opened with.
|
||||
pub(super) fn rule_params(d: &Dialog) -> Json {
|
||||
let mut out = match d.values.get("ruleType").and_then(Json::as_str).unwrap_or("allCells") {
|
||||
"formula" => {
|
||||
let formula = d.values.get("formula").and_then(Json::as_str).unwrap_or("").to_string();
|
||||
let preset = d.values.get("preset").and_then(Json::as_str).unwrap_or("lightRedFillDarkRedText");
|
||||
json!({"rule": {"type": "expression", "formula": formula, "preset": preset}})
|
||||
}
|
||||
_ => {
|
||||
let stops: Vec<Json> = d.values.get("stops").and_then(Json::as_array).map(|a| a.iter().map(cf_stop_params).collect()).unwrap_or_default();
|
||||
json!({"rule": {"type": "colorScale", "stops": stops}})
|
||||
}
|
||||
};
|
||||
// The rule covers the sheet and range the dialog opened on, not whatever the
|
||||
// selection shows now: a formula rule's pick box holds the same opening scope, and
|
||||
// colour scales have no pick box but need it just as much to edit in place.
|
||||
let sheet = d.values.get("sheet").and_then(Json::as_str).unwrap_or_default();
|
||||
let applies_to = d.values.get("applies_to").and_then(Json::as_str).unwrap_or_default();
|
||||
if !sheet.is_empty() && !applies_to.is_empty() {
|
||||
out["sheet"] = json!(sheet);
|
||||
out["range"] = json!(applies_to);
|
||||
}
|
||||
if let Some(edit) = d.values.get("edit").and_then(Json::as_u64) {
|
||||
out["edit"] = json!(edit);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Draws the rule-type list and the editor for the chosen type, then OK/Cancel. OK stays disabled
|
||||
/// while the rule description is incomplete (a formula stop or rule with no formula, or a rule
|
||||
/// type this PR does not implement yet).
|
||||
pub(super) fn new_formatting_rule(ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool, open: &mut bool) {
|
||||
let lang = crate::i18n::current(ui.ctx());
|
||||
ui.label(lang.tr("Select a Rule Type"));
|
||||
let mut rule_type = d.values.get("ruleType").and_then(Json::as_str).unwrap_or("allCells").to_string();
|
||||
for (v, label) in RULE_TYPES {
|
||||
ui.selectable_value(&mut rule_type, (*v).to_string(), lang.tr(label));
|
||||
}
|
||||
d.values.insert("ruleType".into(), json!(rule_type));
|
||||
// Only a formula rule's box takes grid references, and it keeps the sheet and "Applies to"
|
||||
// range the dialog opened on.
|
||||
sync_rule_pick(d);
|
||||
ui.separator();
|
||||
ui.label(lang.tr("Edit the Rule Description"));
|
||||
let supported = match rule_type.as_str() {
|
||||
"allCells" => {
|
||||
colour_scale_editor(ui, d, lang);
|
||||
// A formula stop needs a formula: one whose value is missing, not a string, or
|
||||
// blank would create a rule that never applies. Other stops confirm as they are.
|
||||
d.values.get("stops").and_then(Json::as_array).is_none_or(|stops| {
|
||||
stops.iter().all(|s| {
|
||||
s.get("type").and_then(Json::as_str) != Some("formula")
|
||||
|| s.get("value").and_then(Json::as_str).is_some_and(|f| !f.trim().is_empty())
|
||||
})
|
||||
})
|
||||
}
|
||||
"formula" => {
|
||||
ui.label(lang.tr("Format values where this formula is true:"));
|
||||
let mut formula = d.values.get("formula").and_then(Json::as_str).unwrap_or("").to_string();
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut formula).desired_width(360.0));
|
||||
if r.changed() {
|
||||
d.values.insert("formula".into(), json!(formula.clone()));
|
||||
}
|
||||
if let Some(pick) = d.pick.as_mut().filter(|pick| pick.key == "formula") {
|
||||
track_pick(pick, &r, r.changed());
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(lang.tr("with"));
|
||||
preset_combo(ui, d, lang);
|
||||
});
|
||||
// A formula rule with no formula never applies; OK waits for one.
|
||||
!formula.trim().is_empty()
|
||||
}
|
||||
_ => {
|
||||
ui.label(lang.tr("This rule type isn't available yet."));
|
||||
false
|
||||
}
|
||||
};
|
||||
ok_cancel_enabled(ui, confirm, open, supported);
|
||||
}
|
||||
|
||||
fn cf_stop_json(kind: CfValueKind, color: &CellColor, theme: &Theme) -> Json {
|
||||
let (ty, value) = match kind {
|
||||
CfValueKind::Min => ("min", Json::Null),
|
||||
CfValueKind::Max => ("max", Json::Null),
|
||||
CfValueKind::Number(n) => ("num", json!(n)),
|
||||
CfValueKind::Percent(n) => ("percent", json!(n)),
|
||||
CfValueKind::Percentile(n) => ("percentile", json!(n)),
|
||||
CfValueKind::Formula(f) => ("formula", json!(f)),
|
||||
};
|
||||
let hex = color.hex(theme).unwrap_or_else(|| "#000000".into());
|
||||
// `source` keeps a theme colour by reference: OK without touching the picker sends it back
|
||||
// unchanged, instead of freezing the theme's current RGB into the rule.
|
||||
json!({"type": ty, "value": value, "color": hex.clone(), "source": color, "sourceHex": hex})
|
||||
}
|
||||
|
||||
/// The stop as the engine takes it, dropping the dialog's bookkeeping. A colour the user did not
|
||||
/// change keeps its original theme reference; a changed one is sent as the picked RGB.
|
||||
fn cf_stop_params(stop: &Json) -> Json {
|
||||
let mut obj = stop.as_object().cloned().unwrap_or_default();
|
||||
let source = obj.remove("source").and_then(|v| serde_json::from_value::<CellColor>(v).ok());
|
||||
let source_hex = obj.remove("sourceHex").and_then(|v| v.as_str().map(str::to_string));
|
||||
if let (Some(source), Some(source_hex)) = (source, source_hex)
|
||||
&& obj.get("color").and_then(Json::as_str).is_some_and(|c| c.eq_ignore_ascii_case(&source_hex))
|
||||
{
|
||||
obj.insert(
|
||||
"color".into(),
|
||||
match source {
|
||||
CellColor::Auto => json!("auto"),
|
||||
CellColor::Rgb(v) => json!(format!("#{v:06X}")),
|
||||
CellColor::Theme(i, tint) => json!({"theme": i, "tint": tint as f64 / 1000.0}),
|
||||
},
|
||||
);
|
||||
}
|
||||
Json::Object(obj)
|
||||
}
|
||||
|
||||
fn default_scale_stops(style: &str) -> Vec<Json> {
|
||||
if style == "2color" {
|
||||
vec![json!({"type": "min", "value": null, "color": "#F8696B"}), json!({"type": "max", "value": null, "color": "#63BE7B"})]
|
||||
} else {
|
||||
vec![
|
||||
json!({"type": "min", "value": null, "color": "#F8696B"}),
|
||||
json!({"type": "percentile", "value": 50, "color": "#FFEB84"}),
|
||||
json!({"type": "max", "value": null, "color": "#63BE7B"}),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
fn new_rule_defaults(params: &Json, theme: &Theme) -> Json {
|
||||
// Excel's New Formatting Rule opens on the first type. Manage Rules edits a colour scale,
|
||||
// so an edit always stays on that branch.
|
||||
let mut rule_type = params.get("ruleType").and_then(Json::as_str).unwrap_or("allCells").to_string();
|
||||
if params.get("edit").is_some() || !matches!(rule_type.as_str(), "allCells" | "formula") {
|
||||
rule_type = "allCells".into();
|
||||
}
|
||||
let mut style = params.get("style").and_then(Json::as_str).unwrap_or("3color").to_string();
|
||||
if !matches!(style.as_str(), "2color" | "3color") {
|
||||
style = "3color".into();
|
||||
}
|
||||
let existing = params.get("rule").and_then(|rule| serde_json::from_value::<CfRule>(rule.clone()).ok()).and_then(|rule| match rule {
|
||||
CfRule::ColorScale { stops } if (2..=3).contains(&stops.len()) => {
|
||||
Some(stops.into_iter().map(|(kind, color)| cf_stop_json(kind, &color, theme)).collect::<Vec<_>>())
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let stops = match existing {
|
||||
Some(stops) => {
|
||||
style = if stops.len() == 2 { "2color".into() } else { "3color".into() };
|
||||
stops
|
||||
}
|
||||
None => default_scale_stops(&style),
|
||||
};
|
||||
json!({
|
||||
"ruleType": rule_type,
|
||||
"style": style,
|
||||
"stops": stops,
|
||||
"formula": "",
|
||||
"preset": "lightRedFillDarkRedText",
|
||||
"edit": params.get("edit").cloned(),
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_hex_color(s: &str) -> Color32 {
|
||||
let h = s.trim_start_matches('#');
|
||||
u32::from_str_radix(h.get(..6).unwrap_or("000000"), 16)
|
||||
.map(|v| Color32::from_rgb((v >> 16) as u8, (v >> 8) as u8, v as u8))
|
||||
.unwrap_or(Color32::WHITE)
|
||||
}
|
||||
|
||||
fn hex_color(c: Color32) -> String {
|
||||
format!("#{:02X}{:02X}{:02X}", c.r(), c.g(), c.b())
|
||||
}
|
||||
|
||||
fn scale_preview(ui: &mut egui::Ui, stops: &[Json]) {
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(280.0, 26.0), Sense::hover());
|
||||
let colors: Vec<Color32> = stops.iter().map(|s| parse_hex_color(s.get("color").and_then(Json::as_str).unwrap_or("#FFFFFF"))).collect();
|
||||
if colors.is_empty() {
|
||||
return;
|
||||
}
|
||||
let n = 64;
|
||||
for i in 0..n {
|
||||
let t = i as f32 / (n - 1) as f32;
|
||||
let pos = t * (colors.len() - 1) as f32;
|
||||
let lo = pos.floor() as usize;
|
||||
let hi = (lo + 1).min(colors.len() - 1);
|
||||
let f = pos - lo as f32;
|
||||
let a = colors[lo];
|
||||
let b = colors[hi];
|
||||
let c = Color32::from_rgb(
|
||||
(a.r() as f32 + (b.r() as f32 - a.r() as f32) * f) as u8,
|
||||
(a.g() as f32 + (b.g() as f32 - a.g() as f32) * f) as u8,
|
||||
(a.b() as f32 + (b.b() as f32 - a.b() as f32) * f) as u8,
|
||||
);
|
||||
let x = rect.left() + rect.width() * i as f32 / n as f32;
|
||||
ui.painter().rect_filled(egui::Rect::from_min_size(egui::pos2(x, rect.top()), vec2(rect.width() / n as f32 + 0.5, rect.height())), 0.0, c);
|
||||
}
|
||||
ui.painter().rect_stroke(rect, 0.0, Stroke::new(1.0, Color32::from_gray(190)), StrokeKind::Inside);
|
||||
}
|
||||
|
||||
fn stop_combo(ui: &mut egui::Ui, id: (&'static str, usize), current: &mut String, options: &[(&str, &str)], lang: crate::i18n::Language) {
|
||||
let shown = options.iter().find(|(v, _)| *v == current).map(|(_, l)| lang.tr(l)).unwrap_or(current.as_str());
|
||||
egui::ComboBox::from_id_salt(id).selected_text(shown).width(120.0).show_ui(ui, |ui| {
|
||||
for (v, l) in options {
|
||||
if ui.selectable_label(current == v, lang.tr(l)).clicked() {
|
||||
*current = (*v).to_string();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn colour_scale_editor(ui: &mut egui::Ui, d: &mut Dialog, lang: crate::i18n::Language) {
|
||||
ui.label(lang.tr("Format all cells based on their values"));
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(lang.tr("Format Style:"));
|
||||
let mut style = d.values.get("style").and_then(Json::as_str).unwrap_or("3color").to_string();
|
||||
egui::ComboBox::from_id_salt("newFormattingRule.style")
|
||||
.selected_text(lang.tr(if style == "2color" { "2-Color Scale" } else { "3-Color Scale" }))
|
||||
.width(150.0)
|
||||
.show_ui(ui, |ui| {
|
||||
for (v, l) in [("2color", "2-Color Scale"), ("3color", "3-Color Scale")] {
|
||||
if ui.selectable_label(style == v, lang.tr(l)).clicked() {
|
||||
style = v.to_string();
|
||||
}
|
||||
}
|
||||
});
|
||||
d.values.insert("style".into(), json!(style));
|
||||
// The midpoint comes back as the default #FFEB84 rather than a copy of the minimum's
|
||||
// colour, so 3 → 2 → 3 restores Excel's scale.
|
||||
let mut stops = d.values.get("stops").and_then(Json::as_array).cloned().unwrap_or_default();
|
||||
if style == "2color" && stops.len() == 3 {
|
||||
stops.remove(1);
|
||||
} else if style == "3color" && stops.len() == 2 {
|
||||
stops.insert(1, json!({"type": "percentile", "value": 50, "color": "#FFEB84"}));
|
||||
}
|
||||
d.values.insert("stops".into(), Json::Array(stops));
|
||||
});
|
||||
let mut stops = d.values.get("stops").and_then(Json::as_array).cloned().unwrap_or_default();
|
||||
let count = stops.len();
|
||||
for i in 0..count {
|
||||
let mut obj = stops.get(i).and_then(Json::as_object).cloned().unwrap_or_default();
|
||||
let mut ty = obj.get("type").and_then(Json::as_str).unwrap_or("num").to_string();
|
||||
let options: &[(&str, &str)] = if i == 0 {
|
||||
&[("min", "Lowest value"), ("num", "Number"), ("percent", "Percent"), ("percentile", "Percentile"), ("formula", "Formula")]
|
||||
} else if i + 1 == count {
|
||||
&[("max", "Highest value"), ("num", "Number"), ("percent", "Percent"), ("percentile", "Percentile"), ("formula", "Formula")]
|
||||
} else {
|
||||
&[("num", "Number"), ("percent", "Percent"), ("percentile", "Percentile"), ("formula", "Formula")]
|
||||
};
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(lang.tr(if i == 0 {
|
||||
"Minimum"
|
||||
} else if i + 1 == count {
|
||||
"Maximum"
|
||||
} else {
|
||||
"Midpoint"
|
||||
}));
|
||||
stop_combo(ui, ("newFormattingRule.stopType", i), &mut ty, options, lang);
|
||||
match ty.as_str() {
|
||||
"min" | "max" => {
|
||||
ui.label(lang.tr(if ty == "min" { "Lowest value" } else { "Highest value" }));
|
||||
}
|
||||
"formula" => {
|
||||
let mut f = obj.get("value").and_then(Json::as_str).unwrap_or("").to_string();
|
||||
ui.add(egui::TextEdit::singleline(&mut f).desired_width(120.0).hint_text(lang.tr("Formula")));
|
||||
// Store what the field shows as a string even when it was not edited: a
|
||||
// stop switched from Number still holds that number, which is no formula.
|
||||
obj.insert("value".into(), json!(f));
|
||||
}
|
||||
_ => {
|
||||
let mut n = obj.get("value").and_then(Json::as_f64).unwrap_or(0.0);
|
||||
let speed = if ty == "num" { 1.0 } else { 0.1 };
|
||||
if ui.add(egui::DragValue::new(&mut n).speed(speed).range(if ty == "num" { f64::MIN..=f64::MAX } else { 0.0..=100.0 })).changed()
|
||||
{
|
||||
obj.insert("value".into(), json!(n));
|
||||
}
|
||||
// A numeric stop must carry a number: a stop switched from Lowest or
|
||||
// Highest value still holds `null`, which the engine refuses.
|
||||
if obj.get("value").and_then(Json::as_f64).is_none() {
|
||||
obj.insert("value".into(), json!(n));
|
||||
}
|
||||
}
|
||||
}
|
||||
let c = parse_hex_color(obj.get("color").and_then(Json::as_str).unwrap_or("#FFFFFF"));
|
||||
let mut rgb = [c.r(), c.g(), c.b()];
|
||||
if ui.color_edit_button_srgb(&mut rgb).changed() {
|
||||
obj.insert("color".into(), json!(hex_color(Color32::from_rgb(rgb[0], rgb[1], rgb[2]))));
|
||||
}
|
||||
});
|
||||
obj.insert("type".into(), json!(ty));
|
||||
stops[i] = Json::Object(obj);
|
||||
}
|
||||
d.values.insert("stops".into(), Json::Array(stops.clone()));
|
||||
scale_preview(ui, &stops);
|
||||
}
|
||||
|
||||
fn preset_combo(ui: &mut egui::Ui, d: &mut Dialog, lang: crate::i18n::Language) {
|
||||
const PRESETS: &[(&str, &str)] = &[
|
||||
("lightRedFillDarkRedText", "Light Red Fill with Dark Red Text"),
|
||||
("yellowFillDarkYellowText", "Yellow Fill with Dark Yellow Text"),
|
||||
("greenFillDarkGreenText", "Green Fill with Dark Green Text"),
|
||||
("lightRedFill", "Light Red Fill"),
|
||||
("redText", "Red Text"),
|
||||
("redBorder", "Red Border"),
|
||||
];
|
||||
let mut preset = d.values.get("preset").and_then(Json::as_str).unwrap_or("lightRedFillDarkRedText").to_string();
|
||||
let shown = PRESETS.iter().find(|(v, _)| *v == preset).map(|(_, l)| lang.tr(l)).unwrap_or(preset.as_str());
|
||||
egui::ComboBox::from_id_salt("newFormattingRule.preset").selected_text(shown).width(260.0).show_ui(ui, |ui| {
|
||||
for (v, l) in PRESETS {
|
||||
if ui.selectable_label(preset == *v, lang.tr(l)).clicked() {
|
||||
preset = (*v).to_string();
|
||||
}
|
||||
}
|
||||
});
|
||||
d.values.insert("preset".into(), json!(preset));
|
||||
}
|
||||
|
||||
/// Excel's six rule types, in its order.
|
||||
const RULE_TYPES: &[(&str, &str)] = &[
|
||||
("allCells", "Format all cells based on their values"),
|
||||
("cellsThatContain", "Format only cells that contain"),
|
||||
("topBottom", "Format only top or bottom ranked values"),
|
||||
("aboveBelow", "Format only values that are above or below average"),
|
||||
("uniqueDuplicate", "Format only unique or duplicate values"),
|
||||
("formula", "Use a formula to determine which cells to format"),
|
||||
];
|
||||
|
||||
/// Gives a formula rule's box point mode, on the sheet and selection the dialog opened on;
|
||||
/// other rule types take clicks on the grid as selection.
|
||||
fn sync_rule_pick(d: &mut Dialog) {
|
||||
if d.values.get("ruleType").and_then(Json::as_str) != Some("formula") {
|
||||
d.pick = None;
|
||||
return;
|
||||
}
|
||||
if d.pick.is_some() {
|
||||
return;
|
||||
}
|
||||
let sheet = d.values.get("sheet").and_then(Json::as_str).unwrap_or_default().to_string();
|
||||
let applies_to = d.values.get("applies_to").and_then(Json::as_str).unwrap_or_default().to_string();
|
||||
d.pick = Some(RefPick { key: "formula", sheet, caret: 0, point: None, anchor: CellRef::new(0, 0), refocus: false, applies_to });
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn formula_rule_picks_references_and_keeps_the_opening_range() {
|
||||
let mut session = gridcraft_engine::Session::default();
|
||||
session.new_workbook();
|
||||
session.execute("selection.set", json!({"range": "B2:C5"})).unwrap();
|
||||
let mut app = SheetApp::new(session, Default::default());
|
||||
let sheet = app.session.active().unwrap().wb.active().unwrap().name.clone();
|
||||
let mut d = Dialog::open(&mut app, "newFormattingRule", json!({"ruleType": "formula"})).unwrap();
|
||||
assert!(d.picks_references());
|
||||
assert_eq!(d.pick.as_ref().unwrap().sheet, sheet);
|
||||
|
||||
// A grid click writes the reference into the formula box.
|
||||
d.pick_reference(CellRef::new(0, 0), &sheet, false);
|
||||
assert_eq!(d.values["formula"], "=$A$1");
|
||||
|
||||
// Moving the selection before OK must not move the rule.
|
||||
app.session.execute("selection.set", json!({"range": "D2:E6"})).unwrap();
|
||||
let params = super::super::build_params(&d);
|
||||
assert_eq!(params["sheet"], sheet.as_str());
|
||||
assert_eq!(params["range"], "B2:C5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rule_switched_to_formula_picks_on_the_opening_scope() {
|
||||
let mut session = gridcraft_engine::Session::default();
|
||||
session.new_workbook();
|
||||
session.execute("selection.set", json!({"range": "B2:C5"})).unwrap();
|
||||
let mut app = SheetApp::new(session, Default::default());
|
||||
let sheet = app.session.active().unwrap().wb.active().unwrap().name.clone();
|
||||
// The dialog opens on the default (colour scale) type; choosing the formula type later
|
||||
// turns point mode on, still on the sheet and range it opened with.
|
||||
let mut d = Dialog::open(&mut app, "newFormattingRule", json!({})).unwrap();
|
||||
assert!(!d.picks_references());
|
||||
d.values.insert("ruleType".into(), json!("formula"));
|
||||
sync_rule_pick(&mut d);
|
||||
assert!(d.picks_references());
|
||||
|
||||
app.session.execute("selection.set", json!({"range": "D2:E6"})).unwrap();
|
||||
let params = super::super::build_params(&d);
|
||||
assert_eq!(params["sheet"], sheet.as_str());
|
||||
assert_eq!(params["range"], "B2:C5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_scale_rule_keeps_the_opening_range_without_grid_references() {
|
||||
let mut session = gridcraft_engine::Session::default();
|
||||
session.new_workbook();
|
||||
session.execute("selection.set", json!({"range": "B2:C5"})).unwrap();
|
||||
let mut app = SheetApp::new(session, Default::default());
|
||||
let sheet = app.session.active().unwrap().wb.active().unwrap().name.clone();
|
||||
let d = Dialog::open(&mut app, "newFormattingRule", json!({})).unwrap();
|
||||
assert!(!d.picks_references());
|
||||
// No pick box, but the rule still covers the range and sheet the dialog opened on.
|
||||
let params = super::super::build_params(&d);
|
||||
assert_eq!(params["sheet"], sheet.as_str());
|
||||
assert_eq!(params["range"], "B2:C5");
|
||||
}
|
||||
}
|
||||
@@ -91,6 +91,7 @@ pub(crate) fn build_params(d: &Dialog) -> Json {
|
||||
v["range"] = json!(pick.applies_to);
|
||||
}
|
||||
}
|
||||
"newFormattingRule" => v = super::cond_format_rules::rule_params(d),
|
||||
"series" => {
|
||||
if let Some(s) = d.values.get("stop").and_then(Json::as_str).and_then(|s| s.parse::<f64>().ok()) {
|
||||
v["stop"] = json!(s);
|
||||
@@ -149,7 +150,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
let width = match d.name.as_str() {
|
||||
"formatCells" => 560.0,
|
||||
"about" => 820.0,
|
||||
"insertFunction" | "commandSearch" | "nameManager" | "manageRules" | "journal" | "agents" | "equation" => 520.0,
|
||||
"insertFunction" | "commandSearch" | "nameManager" | "manageRules" | "newFormattingRule" | "journal" | "agents" | "equation" => 520.0,
|
||||
"macros" => 480.0,
|
||||
"recommendedCharts" => 600.0,
|
||||
"analysisToolPak" => 420.0,
|
||||
@@ -195,6 +196,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
"nameManager" => name_manager(app, ui, &mut d, &mut open),
|
||||
"pasteName" => paste_name(app, ui, &mut d, &mut confirm, &mut open),
|
||||
"manageRules" => manage_rules(app, ui),
|
||||
"newFormattingRule" => super::cond_format_rules::new_formatting_rule(ui, &mut d, &mut confirm, &mut open),
|
||||
"recommendedCharts" => recommended_charts(app, ui, &mut d, &mut confirm, &mut open),
|
||||
"selectData" => select_data(app, ui, &mut d, &mut confirm, &mut open),
|
||||
"commandSearch" => command_search(app, ui, &mut d, &mut confirm),
|
||||
@@ -524,6 +526,11 @@ pub(super) fn open_confirmed_link(app: &mut SheetApp, d: &Dialog) -> Result<(),
|
||||
}
|
||||
|
||||
pub(super) fn ok_cancel(ui: &mut egui::Ui, confirm: &mut bool, open: &mut bool) {
|
||||
ok_cancel_enabled(ui, confirm, open, true);
|
||||
}
|
||||
|
||||
/// Like [`ok_cancel`], but OK (and Enter) do nothing while `enabled` is false.
|
||||
pub(super) fn ok_cancel_enabled(ui: &mut egui::Ui, confirm: &mut bool, open: &mut bool, enabled: bool) {
|
||||
ui.add_space(8.0);
|
||||
// A row as tall as the buttons: a right-to-left layout straight in the window takes all the
|
||||
// height it is offered, which stretched every form dialog to the screen's height.
|
||||
@@ -531,14 +538,15 @@ pub(super) fn ok_cancel(ui: &mut egui::Ui, confirm: &mut bool, open: &mut bool)
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let lang = crate::i18n::current(ui.ctx());
|
||||
let t = crate::theme::Tokens::get(ui.ctx());
|
||||
let ok = ui.add(egui::Button::new(egui::RichText::new(format!(" {} ", lang.tr("OK"))).color(t.on_accent)).fill(t.accent));
|
||||
if ok.clicked() || ui.input(|i| i.key_pressed(Key::Enter)) {
|
||||
let ok =
|
||||
ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(format!(" {} ", lang.tr("OK"))).color(t.on_accent)).fill(t.accent));
|
||||
if enabled && (ok.clicked() || ui.input(|i| i.key_pressed(Key::Enter))) {
|
||||
*confirm = true;
|
||||
}
|
||||
if ui.button(format!(" {} ", lang.tr("Cancel"))).clicked() {
|
||||
*open = false;
|
||||
}
|
||||
})
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -571,7 +579,7 @@ pub(super) fn take_first_focus(d: &mut Dialog, r: &egui::Response) {
|
||||
|
||||
/// Keeps a picking formula box's caret, and gives it the keyboard back after a grid click put a
|
||||
/// reference in it (the click took the focus), its caret after the reference.
|
||||
fn track_pick(pick: &mut RefPick, r: &egui::Response, typed: bool) {
|
||||
pub(super) fn track_pick(pick: &mut RefPick, r: &egui::Response, typed: bool) {
|
||||
if typed {
|
||||
pick.point = None;
|
||||
}
|
||||
|
||||
@@ -401,10 +401,71 @@ pub struct GridState {
|
||||
pub wheel_zoom: Option<WheelZoom>,
|
||||
/// A one-finger touch drag in progress: it pans the sheet instead of selecting.
|
||||
pub touch_pan: bool,
|
||||
/// F8 Extend Selection or Shift+F8 Add or Remove Selection mode (see [`SelectionMode`]).
|
||||
pub selection_mode: SelectionMode,
|
||||
/// Add mode: the last area is the cell an arrow key moved to, not yet extended, so the next
|
||||
/// arrow moves it again instead of keeping it.
|
||||
pub add_pending: Option<RangeRef>,
|
||||
/// Add mode header drag: the areas kept from before the drag, which the dragged range joins.
|
||||
pub header_drag_base: Vec<String>,
|
||||
/// What the macro step editor shows on the grid (Check, debugging).
|
||||
pub macro_overlay: Option<crate::macro_editor::MacroOverlay>,
|
||||
}
|
||||
|
||||
/// Excel's keyboard selection modes, shown in the status bar. In Extend mode (F8) arrow keys and
|
||||
/// clicks extend from the anchor as if Shift were held. In Add mode (Shift+F8) arrow keys move the
|
||||
/// active cell without dropping the selected areas, Shift+arrows grow a new area from there, and a
|
||||
/// click adds an area (or removes one already selected) as Ctrl+click does. Esc, the same key
|
||||
/// again, or editing a cell turns the mode off.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum SelectionMode {
|
||||
#[default]
|
||||
Off,
|
||||
Extend,
|
||||
Add,
|
||||
}
|
||||
|
||||
impl SelectionMode {
|
||||
/// The id the `ui.selectionMode` command takes and returns.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Off => "off",
|
||||
Self::Extend => "extend",
|
||||
Self::Add => "add",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(id: &str) -> Option<Self> {
|
||||
match id.trim().to_ascii_lowercase().as_str() {
|
||||
"off" | "none" => Some(Self::Off),
|
||||
"extend" => Some(Self::Extend),
|
||||
"add" => Some(Self::Add),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The status bar text (an i18n catalog key), when the mode shows one.
|
||||
pub fn status_text(self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::Off => None,
|
||||
Self::Extend => Some("Extend Selection"),
|
||||
Self::Add => Some("Add or Remove Selection"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GridState {
|
||||
/// Turns `mode` on, or off when it is already on (F8 / Shift+F8); the other mode ends.
|
||||
pub fn toggle_selection_mode(&mut self, mode: SelectionMode) {
|
||||
self.set_selection_mode(if self.selection_mode == mode { SelectionMode::Off } else { mode });
|
||||
}
|
||||
|
||||
pub fn set_selection_mode(&mut self, mode: SelectionMode) {
|
||||
self.selection_mode = mode;
|
||||
self.add_pending = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Ctrl+wheel zoom for one (doc uid, sheet). egui eases a notch in over several frames and
|
||||
/// fine-grained wheels send parts of one, so the turning is counted in notches, and each whole
|
||||
/// notch steps [`WHEEL_ZOOM_LADDER`]. With animations on the zoom then glides to that step.
|
||||
|
||||
@@ -4,11 +4,11 @@ use super::editor::validation_arrow;
|
||||
use super::geo::Geo;
|
||||
use super::keyboard::keyboard;
|
||||
use super::menus::set_fill_tag;
|
||||
use super::selection::select_ranges;
|
||||
use super::selection::{add_mode_base, select_ranges};
|
||||
use super::tables::{is_filter_button, table_headings};
|
||||
use super::{
|
||||
CellRef, Color32, CursorIcon, Drag, EditState, MAX_COLS, MAX_ROWS, Painter, Pos2, RangeRef, Rect, Sheet, SheetApp, Stroke, Tokens, Workbook,
|
||||
json, pos2, vec2,
|
||||
CellRef, Color32, CursorIcon, Drag, EditState, MAX_COLS, MAX_ROWS, Painter, Pos2, RangeRef, Rect, SelectionMode, Sheet, SheetApp, Stroke, Tokens,
|
||||
Workbook, json, pos2, vec2,
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ interaction
|
||||
@@ -23,6 +23,7 @@ struct InteractionInput<'a> {
|
||||
press_origin: Option<Pos2>,
|
||||
any_pointer_down: bool,
|
||||
modifiers: egui::Modifiers,
|
||||
selection_modifiers: egui::Modifiers,
|
||||
position: Option<Pos2>,
|
||||
primary_clicked: bool,
|
||||
in_cells: bool,
|
||||
@@ -58,6 +59,12 @@ pub(super) fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Respo
|
||||
let primary_clicked = resp.clicked_by(egui::PointerButton::Primary);
|
||||
let pointer = ctx.input(|i| i.pointer.clone());
|
||||
let mods = ctx.input(|i| i.modifiers);
|
||||
let mut selection_modifiers = mods;
|
||||
match app.grid.selection_mode {
|
||||
SelectionMode::Extend => selection_modifiers.shift = true,
|
||||
SelectionMode::Add => selection_modifiers.command = true,
|
||||
SelectionMode::Off => {}
|
||||
}
|
||||
// Hit-testing works in logical coordinates (see `Geo::rtl`).
|
||||
let pos = pointer.interact_pos().or(pointer.hover_pos()).map(|p| geo.mirror_pos(p));
|
||||
let in_cells = pos.is_some_and(|p| geo.in_cells(p));
|
||||
@@ -91,6 +98,7 @@ pub(super) fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Respo
|
||||
press_origin: pointer.press_origin(),
|
||||
any_pointer_down: pointer.any_down(),
|
||||
modifiers: mods,
|
||||
selection_modifiers,
|
||||
position: pos,
|
||||
primary_clicked,
|
||||
in_cells,
|
||||
@@ -341,7 +349,7 @@ fn handle_header_autofit(app: &mut SheetApp, input: &InteractionInput<'_>) -> bo
|
||||
|
||||
fn handle_column_header_press(app: &mut SheetApp, input: &InteractionInput<'_>, p: Pos2) {
|
||||
let (geo, sh, wb, sel) = (input.geo, input.sheet, input.workbook, &input.selection);
|
||||
let mods = input.modifiers;
|
||||
let mods = input.selection_modifiers;
|
||||
let resp = input.response;
|
||||
let in_col_header = input.in_column_header;
|
||||
if in_col_header {
|
||||
@@ -372,6 +380,7 @@ fn handle_column_header_press(app: &mut SheetApp, input: &InteractionInput<'_>,
|
||||
return;
|
||||
}
|
||||
let range = if mods.shift { RangeRef::cols(sel.anchor.col.min(c), sel.anchor.col.max(c)) } else { RangeRef::cols(c, c) };
|
||||
app.grid.header_drag_base = add_mode_base(app);
|
||||
note_selecting_press(app);
|
||||
select_ranges(app, range, mods.command, CellRef::new(geo.row_at(sh, geo.cells.top() + 1.0), c));
|
||||
app.grid.drag = Drag::Cols(if mods.shift { sel.anchor.col } else { c });
|
||||
@@ -380,7 +389,7 @@ fn handle_column_header_press(app: &mut SheetApp, input: &InteractionInput<'_>,
|
||||
|
||||
fn handle_row_header_press(app: &mut SheetApp, input: &InteractionInput<'_>, p: Pos2) {
|
||||
let (geo, sh, wb, sel) = (input.geo, input.sheet, input.workbook, &input.selection);
|
||||
let mods = input.modifiers;
|
||||
let mods = input.selection_modifiers;
|
||||
let in_row_header = input.in_row_header;
|
||||
if in_row_header {
|
||||
if let Some((r, y)) = row_edge(geo, sh, p.y) {
|
||||
@@ -394,6 +403,7 @@ fn handle_row_header_press(app: &mut SheetApp, input: &InteractionInput<'_>, p:
|
||||
return;
|
||||
}
|
||||
let range = if mods.shift { RangeRef::rows(sel.anchor.row.min(r), sel.anchor.row.max(r)) } else { RangeRef::rows(r, r) };
|
||||
app.grid.header_drag_base = add_mode_base(app);
|
||||
note_selecting_press(app);
|
||||
select_ranges(app, range, mods.command, CellRef::new(r, geo.col_at(sh, geo.cells.left() + 1.0)));
|
||||
app.grid.drag = Drag::Rows(if mods.shift { sel.anchor.row } else { r });
|
||||
@@ -403,6 +413,7 @@ fn handle_row_header_press(app: &mut SheetApp, input: &InteractionInput<'_>, p:
|
||||
fn handle_press(app: &mut SheetApp, input: &InteractionInput<'_>) {
|
||||
let (geo, sh, wb, resp) = (input.geo, input.sheet, input.workbook, input.response);
|
||||
let (pos, mods, sel) = (input.position, input.modifiers, &input.selection);
|
||||
let sel_mods = input.selection_modifiers;
|
||||
let (primary_clicked, in_cells, in_col_header, in_row_header, in_corner) =
|
||||
(input.primary_clicked, input.in_cells, input.in_column_header, input.in_row_header, input.in_corner);
|
||||
let (freeze_cols, freeze_rows) = (input.freeze_columns, input.freeze_rows);
|
||||
@@ -520,13 +531,27 @@ fn handle_press(app: &mut SheetApp, input: &InteractionInput<'_>) {
|
||||
return;
|
||||
}
|
||||
app.grid.last_click = Some((c, now));
|
||||
if mods.shift {
|
||||
if sel_mods.shift {
|
||||
note_selecting_press(app);
|
||||
app.grid.header_drag_base = add_mode_base(app);
|
||||
let mut ranges = app.grid.header_drag_base.clone();
|
||||
if let Some(pending) = app.grid.add_pending.take()
|
||||
&& ranges.last().is_some_and(|r| r == &pending.a1())
|
||||
{
|
||||
ranges.pop();
|
||||
}
|
||||
ranges.push(RangeRef::new(sel.anchor, c).a1());
|
||||
let _ = app.run("selection.set", json!({"range": ranges.join(","), "active": sel.active.a1()}));
|
||||
if let Some(d) = app.session.active_mut() {
|
||||
d.selection.anchor = sel.anchor;
|
||||
}
|
||||
} else if mods.shift {
|
||||
note_selecting_press(app);
|
||||
let _ = app.session.run("selection.set", json!({"range": RangeRef::new(sel.anchor, c).a1(), "active": sel.active.a1()}));
|
||||
if let Some(d) = app.session.active_mut() {
|
||||
d.selection.anchor = sel.anchor;
|
||||
}
|
||||
} else if mods.command {
|
||||
} else if mods.command || sel_mods.command {
|
||||
// Ctrl+click (without Alt) on a hyperlink's text follows it instead of adding the cell to the selection.
|
||||
if let Some(h) = sh.hyperlinks.get(&c).cloned()
|
||||
&& acts
|
||||
@@ -719,14 +744,16 @@ fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) {
|
||||
}
|
||||
Drag::Rows(anchor) => {
|
||||
let r = geo.row_at(sh, p.y);
|
||||
let _ =
|
||||
app.session.run("selection.set", json!({"range": RangeRef::rows(anchor.min(r), anchor.max(r)).a1(), "active": sel.active.a1()}));
|
||||
let range = RangeRef::rows(anchor.min(r), anchor.max(r)).a1();
|
||||
let ranges = app.grid.header_drag_base.iter().map(String::as_str).chain([range.as_str()]).collect::<Vec<_>>().join(",");
|
||||
let _ = app.run("selection.set", json!({"range": ranges, "active": sel.active.a1()}));
|
||||
scroll_by(app, vec2(0.0, auto.y));
|
||||
}
|
||||
Drag::Cols(anchor) => {
|
||||
let c = geo.col_at(sh, p.x);
|
||||
let _ =
|
||||
app.session.run("selection.set", json!({"range": RangeRef::cols(anchor.min(c), anchor.max(c)).a1(), "active": sel.active.a1()}));
|
||||
let range = RangeRef::cols(anchor.min(c), anchor.max(c)).a1();
|
||||
let ranges = app.grid.header_drag_base.iter().map(String::as_str).chain([range.as_str()]).collect::<Vec<_>>().join(",");
|
||||
let _ = app.run("selection.set", json!({"range": ranges, "active": sel.active.a1()}));
|
||||
scroll_by(app, vec2(auto.x, 0.0));
|
||||
}
|
||||
drag @ (Drag::PointRows(_) | Drag::PointCols(_)) => {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use super::geo::Geo;
|
||||
use super::interact::object_key;
|
||||
use super::menus::is_checkbox;
|
||||
use super::{CellRef, Drag, Sheet, SheetApp, json};
|
||||
use super::selection::add_mode_move;
|
||||
use super::{CellRef, Drag, SelectionMode, Sheet, SheetApp, json};
|
||||
|
||||
/// Whether something other than the grid owns the keyboard this frame: an editor, a dialog, a
|
||||
/// message, a menu or another focused widget. Kept out of [`keyboard`] to hold its complexity
|
||||
@@ -82,6 +83,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
}
|
||||
egui::Event::Key { key, physical_key, pressed: true, modifiers: m, .. } => {
|
||||
use egui::Key;
|
||||
let Some(m) = selection_mode_key(app, sh, key, m) else { continue };
|
||||
let nudged = object_key(app, sh, key, m);
|
||||
if nudged || crate::keymap::dispatch(app, ctx, key, physical_key, m, geo, sh) {
|
||||
shortcut_ran |= !nudged;
|
||||
@@ -89,13 +91,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
}
|
||||
let cmd = m.command;
|
||||
let shift = m.shift;
|
||||
let mv = |app: &mut SheetApp, dr: i64, dc: i64| {
|
||||
let from = app.session.active().map(|d| if shift { d.selection.moving_end() } else { d.selection.active });
|
||||
let _ = app.session.run("selection.move", json!({"dr": dr, "dc": dc, "extend": shift, "jump": cmd}));
|
||||
app.grid.ensure_visible = true;
|
||||
app.grid.reveal_moving_end = shift;
|
||||
app.grid.reveal_from = from;
|
||||
};
|
||||
let mv = |app: &mut SheetApp, dr: i64, dc: i64| move_selection(app, dr, dc, shift, cmd);
|
||||
match key {
|
||||
Key::ArrowUp => mv(app, -1, 0),
|
||||
Key::ArrowDown => mv(app, 1, 0),
|
||||
@@ -106,6 +102,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
Key::PageUp if !cmd => mv(app, -page, 0),
|
||||
Key::PageDown => app.run_or_alert("sheet.next", json!({})),
|
||||
Key::PageUp => app.run_or_alert("sheet.previous", json!({})),
|
||||
// Add mode: Home and End move the active cell as arrows do, keeping the selected areas.
|
||||
Key::Home if cmd => {
|
||||
let r = sh.freeze.map(|f| f.0).unwrap_or(0);
|
||||
let c = sh.freeze.map(|f| f.1).unwrap_or(0);
|
||||
@@ -149,11 +146,13 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
}
|
||||
}
|
||||
Key::Escape if app.selected_object.is_some() => app.selected_object = None,
|
||||
Key::Escape => cancel_pending(app),
|
||||
Key::Escape => cancel_pending_and_selection_mode(app),
|
||||
Key::Space if !cmd && !shift && is_checkbox(sh, app) => app.run_or_alert("cell.toggleCheckbox", json!({})),
|
||||
// F8 Extend Selection, Shift+F8 Add or Remove Selection: each toggles its mode.
|
||||
Key::F8 if m.alt => {
|
||||
app.open_dialog("macros", json!({}));
|
||||
}
|
||||
Key::F8 if !cmd => toggle_selection_mode(app, shift),
|
||||
Key::F9 => app.run_or_alert("formulas.calculateNow", json!({})),
|
||||
Key::F4 if !cmd => {}
|
||||
// Ctrl+Shift+letter (⌘⇧letter) runs the macro with that shortcut, unless GridCraft uses it.
|
||||
@@ -243,6 +242,76 @@ fn request_grid_ime(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response,
|
||||
});
|
||||
}
|
||||
|
||||
/// The F8 selection modes' part of a key press. Extend mode makes the navigation keys extend from
|
||||
/// the anchor as if Shift were held; Add mode moves Shift+Home and Ctrl+Shift+End within the area
|
||||
/// being added, and Home, Ctrl+Home and Ctrl+End move the active cell keeping the areas. The modifiers to handle the key with, or `None` when the key was handled here.
|
||||
/// Kept out of [`keyboard`] to hold its complexity within the workspace limit.
|
||||
fn selection_mode_key(app: &mut SheetApp, sh: &Sheet, key: egui::Key, m: egui::Modifiers) -> Option<egui::Modifiers> {
|
||||
use egui::Key;
|
||||
let navigation =
|
||||
matches!(key, Key::ArrowUp | Key::ArrowDown | Key::ArrowLeft | Key::ArrowRight | Key::PageUp | Key::PageDown | Key::Home | Key::End);
|
||||
let m = if navigation && app.grid.selection_mode == SelectionMode::Extend { egui::Modifiers { shift: true, ..m } } else { m };
|
||||
if app.grid.selection_mode == SelectionMode::Add && m.shift && (key == Key::Home || (m.command && key == Key::End)) {
|
||||
let from = app.session.active().map(|d| d.selection.moving_end()).unwrap_or_default();
|
||||
let to = match (key, m.command) {
|
||||
(Key::Home, true) => CellRef::new(0, 0),
|
||||
(Key::Home, false) => CellRef::new(from.row, 0),
|
||||
(Key::End, true) => sh.used_range().map(|u| u.end).unwrap_or_default(),
|
||||
_ => from,
|
||||
};
|
||||
add_mode_move(app, i64::from(to.row) - i64::from(from.row), i64::from(to.col) - i64::from(from.col), true, false);
|
||||
return None;
|
||||
}
|
||||
if add_mode_home_end(app, sh, key, m.command) {
|
||||
return None;
|
||||
}
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// An arrow or Page key's move: `selection.move` (extending with Shift, jumping with Ctrl), or in
|
||||
/// Add mode a move of the active cell that keeps the selected areas.
|
||||
fn move_selection(app: &mut SheetApp, dr: i64, dc: i64, shift: bool, cmd: bool) {
|
||||
let from = app.session.active().map(|d| if shift { d.selection.moving_end() } else { d.selection.active });
|
||||
if app.grid.selection_mode == SelectionMode::Add {
|
||||
add_mode_move(app, dr, dc, shift, cmd);
|
||||
app.grid.reveal_from = from;
|
||||
return;
|
||||
}
|
||||
let _ = app.session.run("selection.move", json!({"dr": dr, "dc": dc, "extend": shift, "jump": cmd}));
|
||||
app.grid.ensure_visible = true;
|
||||
app.grid.reveal_moving_end = shift;
|
||||
app.grid.reveal_from = from;
|
||||
}
|
||||
|
||||
/// Add mode: Home and Ctrl+Home/Ctrl+End move the active cell as the arrows do, keeping the
|
||||
/// selected areas. Whether the key was one of those (and so was handled).
|
||||
fn add_mode_home_end(app: &mut SheetApp, sh: &Sheet, key: egui::Key, cmd: bool) -> bool {
|
||||
if app.grid.selection_mode != SelectionMode::Add || !(cmd || key == egui::Key::Home) {
|
||||
return false;
|
||||
}
|
||||
let a = app.session.active().map(|d| d.selection.active).unwrap_or_default();
|
||||
let to = match key {
|
||||
egui::Key::Home if cmd => CellRef::new(sh.freeze.map(|f| f.0).unwrap_or(0), sh.freeze.map(|f| f.1).unwrap_or(0)),
|
||||
egui::Key::End => sh.used_range().map(|u| u.end).unwrap_or_default(),
|
||||
_ => CellRef::new(a.row, 0),
|
||||
};
|
||||
add_mode_move(app, i64::from(to.row) - i64::from(a.row), i64::from(to.col) - i64::from(a.col), false, false);
|
||||
true
|
||||
}
|
||||
|
||||
/// Esc: what [`cancel_pending`] cancels, and the F8 selection modes end.
|
||||
fn cancel_pending_and_selection_mode(app: &mut SheetApp) {
|
||||
cancel_pending(app);
|
||||
let _ = app.run("ui.selectionMode", json!({"mode": "off"}));
|
||||
}
|
||||
|
||||
/// F8 toggles Extend Selection, Shift+F8 Add or Remove Selection.
|
||||
fn toggle_selection_mode(app: &mut SheetApp, shift: bool) {
|
||||
let target = if shift { SelectionMode::Add } else { SelectionMode::Extend };
|
||||
let mode = if app.grid.selection_mode == target { SelectionMode::Off } else { target };
|
||||
let _ = app.run("ui.selectionMode", json!({"mode": mode.id()}));
|
||||
}
|
||||
|
||||
/// This frame's input events, without those the focused form control took.
|
||||
fn grid_events(app: &mut SheetApp, ctx: &egui::Context, sh: &Sheet) -> Vec<egui::Event> {
|
||||
let events = ctx.input(|i| i.events.clone());
|
||||
|
||||
@@ -3,7 +3,7 @@ use super::geo::Geo;
|
||||
use super::interact::{hidden_col_edge, hidden_row_edge};
|
||||
#[cfg(test)]
|
||||
use super::show::hidden_around;
|
||||
use super::{CellRef, Color32, Painter, RangeRef, Rect, Sheet, SheetApp, Stroke, StrokeKind, Tokens, json, pos2, vec2};
|
||||
use super::{CellRef, Color32, Painter, RangeRef, Rect, SelectionMode, Sheet, SheetApp, Stroke, StrokeKind, Tokens, json, pos2, vec2};
|
||||
|
||||
/// Where the active cell is on screen: the whole merged cell when it is part of one.
|
||||
fn active_rect(geo: &Geo, sh: &Sheet, sel: &gridcraft_engine::Selection) -> Rect {
|
||||
@@ -190,15 +190,67 @@ fn toggled_ranges(mut ranges: Vec<String>, clicked: String, add: bool) -> Vec<St
|
||||
ranges
|
||||
}
|
||||
|
||||
/// An arrow (or Page Up/Down, Ctrl+arrow) in Add mode. Without Shift the active cell moves and the
|
||||
/// selected areas stay, the cell it lands on becoming a provisional last area that the next arrow
|
||||
/// moves again; with Shift that area grows from its anchor and is kept, so the next arrow starts
|
||||
/// another one.
|
||||
pub(super) fn add_mode_move(app: &mut SheetApp, dr: i64, dc: i64, shift: bool, jump: bool) {
|
||||
app.grid.ensure_visible = true;
|
||||
app.grid.reveal_moving_end = shift;
|
||||
if shift {
|
||||
let _ = app.run("selection.move", json!({"dr": dr, "dc": dc, "extend": true, "jump": jump}));
|
||||
app.grid.add_pending = None;
|
||||
return;
|
||||
}
|
||||
let Some(mut keep) = app.session.active().map(|d| d.selection.ranges.clone()) else { return };
|
||||
// Only the provisional area this mode made is dropped, and only while it is still the last area.
|
||||
if let Some(p) = app.grid.add_pending.take()
|
||||
&& keep.last() == Some(&p)
|
||||
{
|
||||
keep.pop();
|
||||
}
|
||||
// The engine works out where the cell lands (hidden rows, merged cells, Ctrl+arrow jumps).
|
||||
let _ = app.run("selection.move", json!({"dr": dr, "dc": dc, "extend": false, "jump": jump}));
|
||||
let Some((area, active)) = app.session.active().map(|d| (d.selection.current(), d.selection.active)) else { return };
|
||||
// Landing on an area already kept leaves it kept: the next arrow doesn't drop it.
|
||||
let kept = keep.contains(&area);
|
||||
keep.retain(|r| *r != area);
|
||||
keep.push(area);
|
||||
let range = keep.iter().map(|r| r.a1()).collect::<Vec<_>>().join(",");
|
||||
let _ = app.run("selection.set", json!({"range": range, "active": active.a1()}));
|
||||
app.grid.add_pending = (!kept).then_some(area);
|
||||
}
|
||||
|
||||
/// The active sheet's areas in Add mode, as `selection.set` takes them; empty in other modes.
|
||||
pub(super) fn add_mode_base(app: &SheetApp) -> Vec<String> {
|
||||
if app.grid.selection_mode != SelectionMode::Add {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut ranges = app.session.active().map(|d| d.selection.ranges.iter().map(|x| x.a1()).collect::<Vec<_>>()).unwrap_or_default();
|
||||
if let Some(pending) = app.grid.add_pending
|
||||
&& ranges.last().is_some_and(|range| range == &pending.a1())
|
||||
{
|
||||
ranges.pop();
|
||||
}
|
||||
ranges
|
||||
}
|
||||
|
||||
pub(super) fn select_ranges(app: &mut SheetApp, r: RangeRef, add: bool, active: CellRef) {
|
||||
let current: Vec<String> =
|
||||
if add { app.session.active().map(|d| d.selection.ranges.iter().map(|x| x.a1()).collect()).unwrap_or_default() } else { vec![] };
|
||||
// A clicked area is kept: the next Add mode arrow starts a new one.
|
||||
app.grid.add_pending = None;
|
||||
let current: Vec<RangeRef> = if add { app.session.active().map(|d| d.selection.ranges.clone()).unwrap_or_default() } else { vec![] };
|
||||
let clicked = r.a1();
|
||||
let ranges = toggled_ranges(current, clicked.clone(), add);
|
||||
// A click on a cell inside a larger kept area removes that area, as a click on a single-cell area does.
|
||||
let inside =
|
||||
(add && current.len() > 1 && r.start == r.end).then(|| current.iter().position(|x| x.a1() != clicked && x.contains(r.start))).flatten();
|
||||
let ranges: Vec<String> = match inside {
|
||||
Some(i) => current.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, x)| x.a1()).collect(),
|
||||
None => toggled_ranges(current.iter().map(|x| x.a1()).collect(), clicked.clone(), add),
|
||||
};
|
||||
// A removed area takes the active cell with it; `selection.set` then puts it at the start of the last area.
|
||||
let params =
|
||||
if ranges.contains(&clicked) { json!({"range": ranges.join(","), "active": active.a1()}) } else { json!({"range": ranges.join(",")}) };
|
||||
let _ = app.session.run("selection.set", params);
|
||||
let _ = app.run("selection.set", params);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -435,6 +435,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Point" => "Výběr odkazu",
|
||||
"Calculate" => "Přepočítat",
|
||||
"Select destination and press Enter or choose Paste" => "Vyberte cíl a stiskněte Enter nebo zvolte Vložit",
|
||||
"Extend Selection" => "Rozšířit výběr",
|
||||
"Add or Remove Selection" => "Přidat nebo odebrat výběr",
|
||||
"General" => "Obecný",
|
||||
"Number" => "Číslo",
|
||||
"Currency" => "Měna",
|
||||
@@ -580,6 +582,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Previous sheet" => "Předchozí list",
|
||||
"Zoom In" => "Přiblížit",
|
||||
"Zoom Out" => "Oddálit",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Nové pravidlo formátování",
|
||||
"Edit Formatting Rule" => "Upravit pravidlo formátování",
|
||||
"Format all cells based on their values" => "Formátovat všechny buňky podle jejich hodnot",
|
||||
"Format Style:" => "Styl formátu:",
|
||||
"2-Color Scale" => "Dvoubarevná škála",
|
||||
"3-Color Scale" => "Tříbarevná škála",
|
||||
"Lowest value" => "Nejnižší hodnota",
|
||||
"Highest value" => "Nejvyšší hodnota",
|
||||
"Percent" => "Procento",
|
||||
"Percentile" => "Percentil",
|
||||
"Formula" => "Vzorec",
|
||||
"Midpoint" => "Střední bod",
|
||||
"More Rules…" => "Další pravidla…",
|
||||
"Select a Rule Type" => "Vybrat typ pravidla",
|
||||
"Edit the Rule Description" => "Upravit popis pravidla",
|
||||
"Format only cells that contain" => "Formátovat pouze buňky, které obsahují",
|
||||
"Format only top or bottom ranked values" => "Formátovat pouze hodnoty s nejvyšším nebo nejnižším pořadím",
|
||||
"Format only values that are above or below average" => "Formátovat pouze hodnoty nad nebo pod průměrem",
|
||||
"Format only unique or duplicate values" => "Formátovat pouze jedinečné nebo duplicitní hodnoty",
|
||||
"Use a formula to determine which cells to format" => "Pomocí vzorce určit, které buňky se mají formátovat",
|
||||
"Format values where this formula is true:" => "Formátovat hodnoty, pro které platí tento vzorec:",
|
||||
"with" => "s",
|
||||
"This rule type isn't available yet." => "Tento typ pravidla zatím není dostupný.",
|
||||
// widgets.rs (alphabetical keys).
|
||||
"Dismiss" => "Zavřít",
|
||||
"Rename" => "Přejmenovat",
|
||||
@@ -746,6 +772,13 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Fill Months" => "Vyplnit měsíce",
|
||||
"Fill Years" => "Vyplnit roky",
|
||||
"Auto Fill Options" => "Možnosti automatického vyplnění",
|
||||
// Conditional formatting: the formatting presets the rule editor offers.
|
||||
"Light Red Fill with Dark Red Text" => "Světle červená výplň s tmavě červeným textem",
|
||||
"Yellow Fill with Dark Yellow Text" => "Žlutá výplň s tmavě žlutým textem",
|
||||
"Green Fill with Dark Green Text" => "Zelená výplň s tmavě zeleným textem",
|
||||
"Light Red Fill" => "Světle červená výplň",
|
||||
"Red Text" => "Červený text",
|
||||
"Red Border" => "Červený rámeček",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -452,6 +452,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Point" => "Zeigen",
|
||||
"Calculate" => "Berechnen",
|
||||
"Select destination and press Enter or choose Paste" => "Ziel auswählen und die Eingabetaste drücken oder „Einfügen“ wählen",
|
||||
"Extend Selection" => "Markierung erweitern",
|
||||
"Add or Remove Selection" => "Markierung hinzufügen oder entfernen",
|
||||
"General" => "Standard",
|
||||
"Number" => "Zahl",
|
||||
"Currency" => "Währung",
|
||||
@@ -671,6 +673,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Series…" => "Reihe…",
|
||||
"Down" => "Nach unten",
|
||||
"Up" => "Nach oben",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Neue Formatierungsregel",
|
||||
"Edit Formatting Rule" => "Formatierungsregel bearbeiten",
|
||||
"Select a Rule Type" => "Regeltyp auswählen",
|
||||
"Edit the Rule Description" => "Regelbeschreibung bearbeiten",
|
||||
"Format all cells based on their values" => "Alle Zellen basierend auf ihren Werten formatieren",
|
||||
"Format only cells that contain" => "Nur Zellen formatieren, die enthalten",
|
||||
"Format only top or bottom ranked values" => "Nur Werte formatieren, die oben oder unten eingestuft sind",
|
||||
"Format only values that are above or below average" => "Nur Werte formatieren, die über oder unter dem Durchschnitt liegen",
|
||||
"Format only unique or duplicate values" => "Nur eindeutige oder doppelte Werte formatieren",
|
||||
"Use a formula to determine which cells to format" => "Formel zur Ermittlung der zu formatierenden Zellen verwenden",
|
||||
"This rule type isn't available yet." => "Dieser Regeltyp ist noch nicht verfügbar.",
|
||||
"Format Style:" => "Formatvorlage:",
|
||||
"2-Color Scale" => "2-Farben-Skala",
|
||||
"3-Color Scale" => "3-Farben-Skala",
|
||||
"Midpoint" => "Mittelpunkt",
|
||||
"Lowest value" => "Niedrigster Wert",
|
||||
"Highest value" => "Höchster Wert",
|
||||
"Percent" => "Prozent",
|
||||
"Percentile" => "Perzentil",
|
||||
"Formula" => "Formel",
|
||||
"Format values where this formula is true:" => "Werte formatieren, für die diese Formel wahr ist:",
|
||||
"with" => "mit",
|
||||
"More Rules…" => "Weitere Regeln…",
|
||||
// Conditional formatting: the formatting presets the rule editor offers.
|
||||
"Light Red Fill with Dark Red Text" => "Helle rote Füllung mit dunkelrotem Text",
|
||||
"Yellow Fill with Dark Yellow Text" => "Gelbe Füllung mit dunkelgelbem Text",
|
||||
"Green Fill with Dark Green Text" => "Grüne Füllung mit dunkelgrünem Text",
|
||||
"Light Red Fill" => "Helle rote Füllung",
|
||||
"Red Text" => "Roter Text",
|
||||
"Red Border" => "Roter Rahmen",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -1153,6 +1153,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Fill Months" => "Συμπλήρωση μηνών",
|
||||
"Fill Years" => "Συμπλήρωση ετών",
|
||||
"Auto Fill Options" => "Επιλογές αυτόματης συμπλήρωσης",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Νέος κανόνας μορφοποίησης",
|
||||
"Edit Formatting Rule" => "Επεξεργασία κανόνα μορφοποίησης",
|
||||
"Select a Rule Type" => "Επιλογή τύπου κανόνα",
|
||||
"Edit the Rule Description" => "Επεξεργασία περιγραφής κανόνα",
|
||||
"Format all cells based on their values" => "Μορφοποίηση όλων των κελιών με βάση τις τιμές τους",
|
||||
"Format only cells that contain" => "Μορφοποίηση μόνο κελιών που περιέχουν",
|
||||
"Format only top or bottom ranked values" => "Μορφοποίηση μόνο τιμών με την υψηλότερη ή χαμηλότερη κατάταξη",
|
||||
"Format only values that are above or below average" => "Μορφοποίηση μόνο τιμών πάνω ή κάτω από τον μέσο όρο",
|
||||
"Format only unique or duplicate values" => "Μορφοποίηση μόνο μοναδικών ή διπλότυπων τιμών",
|
||||
"Use a formula to determine which cells to format" => "Χρήση τύπου για τον καθορισμό των κελιών που θα μορφοποιηθούν",
|
||||
"This rule type isn't available yet." => "Αυτός ο τύπος κανόνα δεν είναι ακόμη διαθέσιμος.",
|
||||
"Format Style:" => "Στυλ μορφής:",
|
||||
"2-Color Scale" => "Κλίμακα 2 χρωμάτων",
|
||||
"3-Color Scale" => "Κλίμακα 3 χρωμάτων",
|
||||
"Midpoint" => "Μέσο σημείο",
|
||||
"Lowest value" => "Χαμηλότερη τιμή",
|
||||
"Highest value" => "Υψηλότερη τιμή",
|
||||
"Percent" => "Ποσοστό",
|
||||
"Percentile" => "Εκατοστημόριο",
|
||||
"Formula" => "Τύπος",
|
||||
"More Rules…" => "Περισσότεροι κανόνες…",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -439,6 +439,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Point" => "Señalar",
|
||||
"Calculate" => "Calcular",
|
||||
"Select destination and press Enter or choose Paste" => "Seleccione el destino y presione Entrar o elija Pegar",
|
||||
"Extend Selection" => "Extender selección",
|
||||
"Add or Remove Selection" => "Agregar o quitar selección",
|
||||
"General" => "General",
|
||||
"Number" => "Número",
|
||||
"Currency" => "Moneda",
|
||||
@@ -677,6 +679,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Series…" => "Serie…",
|
||||
"Down" => "Hacia abajo",
|
||||
"Up" => "Hacia arriba",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Nueva regla de formato",
|
||||
"Edit Formatting Rule" => "Editar regla de formato",
|
||||
"Select a Rule Type" => "Seleccionar un tipo de regla",
|
||||
"Edit the Rule Description" => "Editar la descripción de la regla",
|
||||
"Format all cells based on their values" => "Dar formato a todas las celdas según sus valores",
|
||||
"Format only cells that contain" => "Dar formato solo a las celdas que contengan",
|
||||
"Format only top or bottom ranked values" => "Dar formato solo a los valores con clasificación superior o inferior",
|
||||
"Format only values that are above or below average" => "Dar formato solo a los valores que estén por encima o por debajo del promedio",
|
||||
"Format only unique or duplicate values" => "Dar formato solo a los valores únicos o duplicados",
|
||||
"Use a formula to determine which cells to format" => "Usar una fórmula para determinar qué celdas se van a aplicar formato",
|
||||
"This rule type isn't available yet." => "Este tipo de regla aún no está disponible.",
|
||||
"Format Style:" => "Estilo de formato:",
|
||||
"2-Color Scale" => "Escala de 2 colores",
|
||||
"3-Color Scale" => "Escala de 3 colores",
|
||||
"Midpoint" => "Punto medio",
|
||||
"Lowest value" => "Valor mínimo",
|
||||
"Highest value" => "Valor máximo",
|
||||
"Percent" => "Porcentaje",
|
||||
"Percentile" => "Percentil",
|
||||
"Formula" => "Fórmula",
|
||||
"Format values where this formula is true:" => "Dar formato a los valores donde esta fórmula sea verdadera:",
|
||||
"with" => "con",
|
||||
"More Rules…" => "Más reglas…",
|
||||
// Conditional formatting: the formatting presets the rule editor offers.
|
||||
"Light Red Fill with Dark Red Text" => "Relleno rojo claro con texto rojo oscuro",
|
||||
"Yellow Fill with Dark Yellow Text" => "Relleno amarillo con texto amarillo oscuro",
|
||||
"Green Fill with Dark Green Text" => "Relleno verde con texto verde oscuro",
|
||||
"Light Red Fill" => "Relleno rojo claro",
|
||||
"Red Text" => "Texto rojo",
|
||||
"Red Border" => "Borde rojo",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -314,6 +314,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Point" => "Point",
|
||||
"Calculate" => "Calculer",
|
||||
"Select destination and press Enter or choose Paste" => "Sélectionnez la destination et appuyez sur Entrée ou choisissez Coller",
|
||||
"Extend Selection" => "Étendre la sélection",
|
||||
"Add or Remove Selection" => "Ajouter ou supprimer la sélection",
|
||||
"General" => "Standard",
|
||||
"Number" => "Nombre",
|
||||
"Currency" => "Monétaire",
|
||||
@@ -639,6 +641,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Series…" => "Série…",
|
||||
"Down" => "Vers le bas",
|
||||
"Up" => "Vers le haut",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Nouvelle règle de mise en forme",
|
||||
"Edit Formatting Rule" => "Modifier la règle de mise en forme",
|
||||
"Select a Rule Type" => "Sélectionner un type de règle",
|
||||
"Edit the Rule Description" => "Modifier la description de la règle",
|
||||
"Format all cells based on their values" => "Mettre en forme toutes les cellules en fonction de leurs valeurs",
|
||||
"Format only cells that contain" => "Mettre en forme uniquement les cellules qui contiennent",
|
||||
"Format only top or bottom ranked values" => "Mettre en forme uniquement les valeurs classées en haut ou en bas",
|
||||
"Format only values that are above or below average" => "Mettre en forme uniquement les valeurs supérieures ou inférieures à la moyenne",
|
||||
"Format only unique or duplicate values" => "Mettre en forme uniquement les valeurs uniques ou en double",
|
||||
"Use a formula to determine which cells to format" => "Utiliser une formule pour déterminer pour quelles cellules le format sera appliqué",
|
||||
"This rule type isn't available yet." => "Ce type de règle n'est pas encore disponible.",
|
||||
"Format Style:" => "Style de mise en forme :",
|
||||
"2-Color Scale" => "Échelle à 2 couleurs",
|
||||
"3-Color Scale" => "Échelle à 3 couleurs",
|
||||
"Midpoint" => "Point milieu",
|
||||
"Lowest value" => "Valeur la plus basse",
|
||||
"Highest value" => "Valeur la plus haute",
|
||||
"Percent" => "Pourcentage",
|
||||
"Percentile" => "Centile",
|
||||
"Formula" => "Formule",
|
||||
"Format values where this formula is true:" => "Mettre en forme les valeurs pour lesquelles cette formule est vraie :",
|
||||
"with" => "avec",
|
||||
"More Rules…" => "Autres règles…",
|
||||
// Conditional formatting: the formatting presets the rule editor offers.
|
||||
"Light Red Fill with Dark Red Text" => "Remplissage rouge clair avec texte rouge foncé",
|
||||
"Yellow Fill with Dark Yellow Text" => "Remplissage jaune avec texte jaune foncé",
|
||||
"Green Fill with Dark Green Text" => "Remplissage vert avec texte vert foncé",
|
||||
"Light Red Fill" => "Remplissage rouge clair",
|
||||
"Red Text" => "Texte rouge",
|
||||
"Red Border" => "Bordure rouge",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -1157,6 +1157,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Fill Months" => "Riempi mesi",
|
||||
"Fill Years" => "Riempi anni",
|
||||
"Auto Fill Options" => "Opzioni di riempimento automatico",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Nuova regola di formattazione",
|
||||
"Edit Formatting Rule" => "Modifica regola di formattazione",
|
||||
"Select a Rule Type" => "Seleziona un tipo di regola",
|
||||
"Edit the Rule Description" => "Modifica la descrizione della regola",
|
||||
"Format all cells based on their values" => "Formatta tutte le celle in base ai loro valori",
|
||||
"Format only cells that contain" => "Formatta solo le celle che contengono",
|
||||
"Format only top or bottom ranked values" => "Formatta solo i valori con classificazione superiore o inferiore",
|
||||
"Format only values that are above or below average" => "Formatta solo i valori superiori o inferiori alla media",
|
||||
"Format only unique or duplicate values" => "Formatta solo valori univoci o duplicati",
|
||||
"Use a formula to determine which cells to format" => "Usa una formula per determinare quali celle formattare",
|
||||
"This rule type isn't available yet." => "Questo tipo di regola non è ancora disponibile.",
|
||||
"Format Style:" => "Stile formato:",
|
||||
"2-Color Scale" => "Scala a 2 colori",
|
||||
"3-Color Scale" => "Scala a 3 colori",
|
||||
"Midpoint" => "Punto medio",
|
||||
"Lowest value" => "Valore minimo",
|
||||
"Highest value" => "Valore massimo",
|
||||
"Percent" => "Percentuale",
|
||||
"Percentile" => "Percentile",
|
||||
"Formula" => "Formula",
|
||||
"More Rules…" => "Altre regole…",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -305,6 +305,8 @@ pub(super) const CORE: &[(&str, &str)] = &[
|
||||
("Point", "ポイント"),
|
||||
("Calculate", "計算"),
|
||||
("Select destination and press Enter or choose Paste", "貼り付け先を選び、Enter キーを押すか [貼り付け] を選びます"),
|
||||
("Extend Selection", "選択範囲の拡張"),
|
||||
("Add or Remove Selection", "選択範囲の追加または削除"),
|
||||
("General", "標準"),
|
||||
("Number", "数値"),
|
||||
("Currency", "通貨"),
|
||||
@@ -1143,6 +1145,26 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
|
||||
("\\@char has non-numeric argument {argument}", "\\@char の引数 {argument} が数値ではありません"),
|
||||
("\\@char with invalid code point {code}", "\\@char のコード ポイント {code} が無効です"),
|
||||
("Invalid environment name character: {character}", "環境名に無効な文字があります: {character}"),
|
||||
("New Formatting Rule", "新しい書式ルール"),
|
||||
("Edit Formatting Rule", "書式ルールの編集"),
|
||||
("Select a Rule Type", "ルールの種類を選択"),
|
||||
("Edit the Rule Description", "ルールの説明を編集"),
|
||||
("Format all cells based on their values", "値に基づいてすべてのセルを書式設定"),
|
||||
("Format only cells that contain", "含むセルのみを書式設定"),
|
||||
("Format only top or bottom ranked values", "上位または下位に入る値のみを書式設定"),
|
||||
("Format only values that are above or below average", "平均より上または下の値のみを書式設定"),
|
||||
("Format only unique or duplicate values", "重複する値または一意の値のみを書式設定"),
|
||||
("Use a formula to determine which cells to format", "数式を使用して、書式設定するセルを決定"),
|
||||
("This rule type isn't available yet.", "このルールの種類はまだ使用できません。"),
|
||||
("Format Style:", "書式スタイル:"),
|
||||
("2-Color Scale", "2 色スケール"),
|
||||
("3-Color Scale", "3 色スケール"),
|
||||
("Midpoint", "中間"),
|
||||
("Lowest value", "最小値"),
|
||||
("Highest value", "最大値"),
|
||||
("Percentile", "パーセンタイル"),
|
||||
("Formula", "数式"),
|
||||
("More Rules…", "その他のルール…"),
|
||||
];
|
||||
|
||||
/// Labels of the ribbon menus, pop-ups and palettes that the reference catalog does not cover (the
|
||||
|
||||
@@ -299,6 +299,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Point" => "가리키기",
|
||||
"Calculate" => "계산",
|
||||
"Select destination and press Enter or choose Paste" => "대상을 선택하고 Enter 키를 누르거나 [붙여넣기]를 선택하세요",
|
||||
"Extend Selection" => "선택 영역 확장",
|
||||
"Add or Remove Selection" => "선택 영역 추가 또는 제거",
|
||||
"General" => "일반",
|
||||
"Number" => "숫자",
|
||||
"Currency" => "통화",
|
||||
@@ -637,6 +639,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Series…" => "연속 데이터…",
|
||||
"Down" => "아래쪽",
|
||||
"Up" => "위쪽",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "새 서식 규칙",
|
||||
"Edit Formatting Rule" => "서식 규칙 편집",
|
||||
"Select a Rule Type" => "규칙 유형 선택",
|
||||
"Edit the Rule Description" => "규칙 설명 편집",
|
||||
"Format all cells based on their values" => "해당 값에 따라 모든 셀의 서식 지정",
|
||||
"Format only cells that contain" => "다음을 포함하는 셀만 서식 지정",
|
||||
"Format only top or bottom ranked values" => "순위가 위 또는 아래인 값만 서식 지정",
|
||||
"Format only values that are above or below average" => "평균보다 높거나 낮은 값만 서식 지정",
|
||||
"Format only unique or duplicate values" => "고유하거나 중복되는 값만 서식 지정",
|
||||
"Use a formula to determine which cells to format" => "수식을 사용하여 서식을 지정할 셀 결정",
|
||||
"This rule type isn't available yet." => "이 규칙 유형은 아직 사용할 수 없습니다.",
|
||||
"Format Style:" => "서식 스타일:",
|
||||
"2-Color Scale" => "2색조 눈금",
|
||||
"3-Color Scale" => "3색조 눈금",
|
||||
"Midpoint" => "중간점",
|
||||
"Lowest value" => "최저값",
|
||||
"Highest value" => "최고값",
|
||||
"Percent" => "백분율",
|
||||
"Percentile" => "백분위수",
|
||||
"Formula" => "수식",
|
||||
"Format values where this formula is true:" => "다음 수식을 만족하는 값에 서식 지정:",
|
||||
"with" => "서식:",
|
||||
"More Rules…" => "기타 규칙…",
|
||||
// Conditional formatting: the formatting presets the rule editor offers.
|
||||
"Light Red Fill with Dark Red Text" => "연한 빨강 채우기 및 진한 빨강 텍스트",
|
||||
"Yellow Fill with Dark Yellow Text" => "노랑 채우기 및 진한 노랑 텍스트",
|
||||
"Green Fill with Dark Green Text" => "연한 초록 채우기 및 진한 초록 텍스트",
|
||||
"Light Red Fill" => "연한 빨강 채우기",
|
||||
"Red Text" => "빨강 텍스트",
|
||||
"Red Border" => "빨강 테두리",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -305,6 +305,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Point" => "Aanwijzen",
|
||||
"Calculate" => "Berekenen",
|
||||
"Select destination and press Enter or choose Paste" => "Selecteer de bestemming en druk op Enter of kies Plakken",
|
||||
"Extend Selection" => "Selectie uitbreiden",
|
||||
"Add or Remove Selection" => "Selectie toevoegen of verwijderen",
|
||||
"General" => "Algemeen",
|
||||
"Number" => "Getal",
|
||||
"Currency" => "Valuta",
|
||||
@@ -709,6 +711,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Fill Months" => "Maanden vullen",
|
||||
"Fill Years" => "Jaren vullen",
|
||||
"Auto Fill Options" => "Opties voor automatisch vullen",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Nieuwe opmaakregel",
|
||||
"Edit Formatting Rule" => "Opmaakregel bewerken",
|
||||
"Select a Rule Type" => "Een regeltype selecteren",
|
||||
"Edit the Rule Description" => "De beschrijving van de regel bewerken",
|
||||
"Format all cells based on their values" => "Alle cellen opmaken op basis van hun waarden",
|
||||
"Format only cells that contain" => "Alleen cellen opmaken die bevatten",
|
||||
"Format only top or bottom ranked values" => "Alleen waarden met een hoge of lage rangorde opmaken",
|
||||
"Format only values that are above or below average" => "Alleen waarden boven of onder het gemiddelde opmaken",
|
||||
"Format only unique or duplicate values" => "Alleen unieke of dubbele waarden opmaken",
|
||||
"Use a formula to determine which cells to format" => "Een formule gebruiken om te bepalen welke cellen worden opgemaakt",
|
||||
"This rule type isn't available yet." => "Dit regeltype is nog niet beschikbaar.",
|
||||
"Format Style:" => "Opmaakstijl:",
|
||||
"2-Color Scale" => "Schaal met 2 kleuren",
|
||||
"3-Color Scale" => "Schaal met 3 kleuren",
|
||||
"Midpoint" => "Middelpunt",
|
||||
"Lowest value" => "Laagste waarde",
|
||||
"Highest value" => "Hoogste waarde",
|
||||
"Percent" => "Percentage",
|
||||
"Percentile" => "Percentiel",
|
||||
"Formula" => "Formule",
|
||||
"Format values where this formula is true:" => "Waarden opmaken waarop deze formule waar is:",
|
||||
"with" => "met",
|
||||
"More Rules…" => "Meer regels…",
|
||||
// Conditional formatting: the formatting presets the rule editor offers.
|
||||
"Light Red Fill with Dark Red Text" => "Lichte rode opvulling met donkerrode tekst",
|
||||
"Yellow Fill with Dark Yellow Text" => "Gele opvulling met donkergele tekst",
|
||||
"Green Fill with Dark Green Text" => "Groene opvulling met donkergroene tekst",
|
||||
"Light Red Fill" => "Lichte rode opvulling",
|
||||
"Red Text" => "Rode tekst",
|
||||
"Red Border" => "Rode rand",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -1145,6 +1145,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Fill Months" => "Wypełnij miesiącami",
|
||||
"Fill Years" => "Wypełnij latami",
|
||||
"Auto Fill Options" => "Opcje autowypełniania",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Nowa reguła formatowania",
|
||||
"Edit Formatting Rule" => "Edytuj regułę formatowania",
|
||||
"Select a Rule Type" => "Wybierz typ reguły",
|
||||
"Edit the Rule Description" => "Edytuj opis reguły",
|
||||
"Format all cells based on their values" => "Formatuj wszystkie komórki na podstawie ich wartości",
|
||||
"Format only cells that contain" => "Formatuj tylko komórki zawierające",
|
||||
"Format only top or bottom ranked values" => "Formatuj tylko wartości o najwyższej lub najniższej pozycji",
|
||||
"Format only values that are above or below average" => "Formatuj tylko wartości powyżej lub poniżej średniej",
|
||||
"Format only unique or duplicate values" => "Formatuj tylko wartości unikatowe lub zduplikowane",
|
||||
"Use a formula to determine which cells to format" => "Użyj formuły do określenia, które komórki mają być formatowane",
|
||||
"This rule type isn't available yet." => "Ten typ reguły nie jest jeszcze dostępny.",
|
||||
"Format Style:" => "Styl formatu:",
|
||||
"2-Color Scale" => "Skala dwukolorowa",
|
||||
"3-Color Scale" => "Skala trójkolorowa",
|
||||
"Midpoint" => "Punkt środkowy",
|
||||
"Lowest value" => "Najniższa wartość",
|
||||
"Highest value" => "Najwyższa wartość",
|
||||
"Percent" => "Procent",
|
||||
"Percentile" => "Percentyl",
|
||||
"Formula" => "Formuła",
|
||||
"More Rules…" => "Więcej reguł…",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -299,6 +299,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Point" => "Apontar",
|
||||
"Calculate" => "Calcular",
|
||||
"Select destination and press Enter or choose Paste" => "Selecione o destino e pressione Enter ou escolha Colar",
|
||||
"Extend Selection" => "Estender Seleção",
|
||||
"Add or Remove Selection" => "Adicionar ou Remover Seleção",
|
||||
"General" => "Geral",
|
||||
"Number" => "Número",
|
||||
"Currency" => "Moeda",
|
||||
@@ -1161,6 +1163,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Fill Months" => "Preencher Meses",
|
||||
"Fill Years" => "Preencher Anos",
|
||||
"Auto Fill Options" => "Opções de Autopreenchimento",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Nova Regra de Formatação",
|
||||
"Edit Formatting Rule" => "Editar Regra de Formatação",
|
||||
"Select a Rule Type" => "Selecionar um Tipo de Regra",
|
||||
"Edit the Rule Description" => "Editar a Descrição da Regra",
|
||||
"Format all cells based on their values" => "Formatar todas as células com base em seus valores",
|
||||
"Format only cells that contain" => "Formatar apenas células que contenham",
|
||||
"Format only top or bottom ranked values" => "Formatar apenas valores classificados acima ou abaixo",
|
||||
"Format only values that are above or below average" => "Formatar apenas valores acima ou abaixo da média",
|
||||
"Format only unique or duplicate values" => "Formatar apenas valores exclusivos ou duplicados",
|
||||
"Use a formula to determine which cells to format" => "Usar uma fórmula para determinar quais células devem ser formatadas",
|
||||
"This rule type isn't available yet." => "Este tipo de regra ainda não está disponível.",
|
||||
"Format Style:" => "Estilo de Formatação:",
|
||||
"2-Color Scale" => "Escala de 2 Cores",
|
||||
"3-Color Scale" => "Escala de 3 Cores",
|
||||
"Midpoint" => "Ponto Médio",
|
||||
"Lowest value" => "Valor mais baixo",
|
||||
"Highest value" => "Valor mais alto",
|
||||
"Percent" => "Porcentagem",
|
||||
"Percentile" => "Percentil",
|
||||
"Formula" => "Fórmula",
|
||||
"More Rules…" => "Mais Regras…",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -1207,6 +1207,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Fill Months" => "Umplere luni",
|
||||
"Fill Years" => "Umplere ani",
|
||||
"Auto Fill Options" => "Opțiuni de umplere automată",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Regulă de formatare nouă",
|
||||
"Edit Formatting Rule" => "Editați regula de formatare",
|
||||
"Select a Rule Type" => "Selectați un tip de regulă",
|
||||
"Edit the Rule Description" => "Editați descrierea regulii",
|
||||
"Format all cells based on their values" => "Formatați toate celulele în funcție de valorile lor",
|
||||
"Format only cells that contain" => "Formatați numai celulele care conțin",
|
||||
"Format only top or bottom ranked values" => "Formatați numai valorile clasate primele sau ultimele",
|
||||
"Format only values that are above or below average" => "Formatați numai valorile peste sau sub medie",
|
||||
"Format only unique or duplicate values" => "Formatați numai valorile unice sau duplicate",
|
||||
"Use a formula to determine which cells to format" => "Utilizați o formulă pentru a stabili ce celule să fie formatate",
|
||||
"This rule type isn't available yet." => "Acest tip de regulă nu este încă disponibil.",
|
||||
"Format Style:" => "Stil de formatare:",
|
||||
"2-Color Scale" => "Scară cu 2 culori",
|
||||
"3-Color Scale" => "Scară cu 3 culori",
|
||||
"Midpoint" => "Punct de mijloc",
|
||||
"Lowest value" => "Valoarea cea mai mică",
|
||||
"Highest value" => "Valoarea cea mai mare",
|
||||
"Percent" => "Procent",
|
||||
"Percentile" => "Percentilă",
|
||||
"Formula" => "Formulă",
|
||||
"More Rules…" => "Mai multe reguli…",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -301,6 +301,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Point" => "Указание",
|
||||
"Calculate" => "Вычисление",
|
||||
"Select destination and press Enter or choose Paste" => "Выберите место вставки и нажмите Enter или выберите «Вставить»",
|
||||
"Extend Selection" => "Расширить выделение",
|
||||
"Add or Remove Selection" => "Добавить или удалить выделение",
|
||||
"General" => "Общий",
|
||||
"Number" => "Числовой",
|
||||
"Currency" => "Денежный",
|
||||
@@ -1211,6 +1213,29 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Fill Months" => "Заполнить по месяцам",
|
||||
"Fill Years" => "Заполнить по годам",
|
||||
"Auto Fill Options" => "Параметры автозаполнения",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Новое правило форматирования",
|
||||
"Edit Formatting Rule" => "Изменение правила форматирования",
|
||||
"Select a Rule Type" => "Выбор типа правила",
|
||||
"Edit the Rule Description" => "Изменение описания правила",
|
||||
"Format all cells based on their values" => "Форматировать все ячейки на основе их значений",
|
||||
"Format only cells that contain" => "Форматировать только ячейки, которые содержат",
|
||||
"Format only top or bottom ranked values" => "Форматировать только значения, имеющие верхний или нижний рейтинг",
|
||||
"Format only values that are above or below average" => "Форматировать только значения выше или ниже среднего",
|
||||
"Format only unique or duplicate values" => "Форматировать только уникальные или повторяющиеся значения",
|
||||
"Use a formula to determine which cells to format" => "Использовать формулу для определения форматируемых ячеек",
|
||||
"This rule type isn't available yet." => "Этот тип правила пока недоступен.",
|
||||
"Format Style:" => "Стиль формата:",
|
||||
"2-Color Scale" => "Двухцветная шкала",
|
||||
"3-Color Scale" => "Трехцветная шкала",
|
||||
"Midpoint" => "Средняя точка",
|
||||
"Lowest value" => "Наименьшее значение",
|
||||
"Highest value" => "Наибольшее значение",
|
||||
"Percent" => "Процент",
|
||||
"Percentile" => "Процентиль",
|
||||
"Formula" => "Формула",
|
||||
"More Rules…" => "Другие правила…",
|
||||
// Conditional formatting: the formatting presets the rule editor offers.
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -304,6 +304,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Point" => "Pokaži",
|
||||
"Calculate" => "Izračunavanje",
|
||||
"Select destination and press Enter or choose Paste" => "Izaberi odredište i pritisni Enter ili izaberi Nalepi",
|
||||
"Extend Selection" => "Proširi izbor",
|
||||
"Add or Remove Selection" => "Dodaj ili ukloni izbor",
|
||||
"General" => "Opšte",
|
||||
"Number" => "Broj",
|
||||
"Currency" => "Valuta",
|
||||
@@ -630,6 +632,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Series…" => "Niz…",
|
||||
"Down" => "Nadole",
|
||||
"Up" => "Nagore",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Novo pravilo oblikovanja",
|
||||
"Edit Formatting Rule" => "Izmeni pravilo oblikovanja",
|
||||
"Select a Rule Type" => "Izaberi tip pravila",
|
||||
"Edit the Rule Description" => "Uredi opis pravila",
|
||||
"Format all cells based on their values" => "Oblikuj sve ćelije na osnovu njihovih vrednosti",
|
||||
"Format only cells that contain" => "Oblikuj samo ćelije koje sadrže",
|
||||
"Format only top or bottom ranked values" => "Oblikuj samo vrednosti rangirane na vrhu ili dnu",
|
||||
"Format only values that are above or below average" => "Oblikuj samo vrednosti iznad ili ispod proseka",
|
||||
"Format only unique or duplicate values" => "Oblikuj samo jedinstvene ili duplikatne vrednosti",
|
||||
"Use a formula to determine which cells to format" => "Koristi formulu za određivanje ćelija koje se oblikuju",
|
||||
"This rule type isn't available yet." => "Ovaj tip pravila još nije dostupan.",
|
||||
"Format Style:" => "Stil oblikovanja:",
|
||||
"2-Color Scale" => "Dvobojna skala",
|
||||
"3-Color Scale" => "Trobojna skala",
|
||||
"Midpoint" => "Srednja tačka",
|
||||
"Lowest value" => "Najniža vrednost",
|
||||
"Highest value" => "Najviša vrednost",
|
||||
"Percent" => "Procenat",
|
||||
"Percentile" => "Percentil",
|
||||
"Formula" => "Formula",
|
||||
"Format values where this formula is true:" => "Oblikuj vrednosti za koje je ova formula tačna:",
|
||||
"with" => "sa",
|
||||
"More Rules…" => "Druga pravila…",
|
||||
// Conditional formatting: the formatting presets the rule editor offers.
|
||||
"Light Red Fill with Dark Red Text" => "Svetlo crvena ispuna sa tamno crvenim tekstom",
|
||||
"Yellow Fill with Dark Yellow Text" => "Žuta ispuna sa tamno žutim tekstom",
|
||||
"Green Fill with Dark Green Text" => "Zelena ispuna sa tamno zelenim tekstom",
|
||||
"Light Red Fill" => "Svetlo crvena ispuna",
|
||||
"Red Text" => "Crveni tekst",
|
||||
"Red Border" => "Crveni okvir",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -602,6 +602,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Series…" => "Seri…",
|
||||
"Down" => "Aşağı",
|
||||
"Up" => "Yukarı",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Yeni Biçimlendirme Kuralı",
|
||||
"Edit Formatting Rule" => "Biçimlendirme Kuralını Düzenle",
|
||||
"Select a Rule Type" => "Kural Türü Seçin",
|
||||
"Edit the Rule Description" => "Kural Açıklamasını Düzenle",
|
||||
"Format all cells based on their values" => "Tüm hücreleri değerlerine göre biçimlendir",
|
||||
"Format only cells that contain" => "Yalnızca şunu içeren hücreleri biçimlendir",
|
||||
"Format only top or bottom ranked values" => "Yalnızca en yüksek veya en düşük sıralamadaki değerleri biçimlendir",
|
||||
"Format only values that are above or below average" => "Yalnızca ortalamanın üstündeki veya altındaki değerleri biçimlendir",
|
||||
"Format only unique or duplicate values" => "Yalnızca benzersiz veya yinelenen değerleri biçimlendir",
|
||||
"Use a formula to determine which cells to format" => "Hangi hücrelerin biçimlendirileceğini belirlemek için formül kullan",
|
||||
"This rule type isn't available yet." => "Bu kural türü henüz kullanılamıyor.",
|
||||
"Format Style:" => "Biçim Stili:",
|
||||
"2-Color Scale" => "2 Renkli Ölçek",
|
||||
"3-Color Scale" => "3 Renkli Ölçek",
|
||||
"Midpoint" => "Orta nokta",
|
||||
"Lowest value" => "En düşük değer",
|
||||
"Highest value" => "En yüksek değer",
|
||||
"Percent" => "Yüzde",
|
||||
"Percentile" => "Yüzdebirlik",
|
||||
"Formula" => "Formül",
|
||||
"Format values where this formula is true:" => "Bu formülün doğru olduğu değerleri biçimlendir:",
|
||||
"with" => "ile",
|
||||
"More Rules…" => "Diğer Kurallar…",
|
||||
// Conditional formatting: the formatting presets the rule editor offers.
|
||||
"Light Red Fill with Dark Red Text" => "Açık Kırmızı Dolgu ve Koyu Kırmızı Metin",
|
||||
"Yellow Fill with Dark Yellow Text" => "Sarı Dolgu ve Koyu Sarı Metin",
|
||||
"Green Fill with Dark Green Text" => "Yeşil Dolgu ve Koyu Yeşil Metin",
|
||||
"Light Red Fill" => "Açık Kırmızı Dolgu",
|
||||
"Red Text" => "Kırmızı Metin",
|
||||
"Red Border" => "Kırmızı Kenarlık",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -658,8 +658,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Last month" => "Last month",
|
||||
"This month" => "This month",
|
||||
"Next month" => "Next month",
|
||||
"Format values where this formula is true:" => "Format values where this formula is true:",
|
||||
"with" => "with",
|
||||
"Format values where this formula is true:" => "Форматувати значення, для яких ця формула істинна:",
|
||||
"with" => "з",
|
||||
"Light Red Fill with Dark Red Text" => "Light Red Fill with Dark Red Text",
|
||||
"Yellow Fill with Dark Yellow Text" => "Yellow Fill with Dark Yellow Text",
|
||||
"Green Fill with Dark Green Text" => "Green Fill with Dark Green Text",
|
||||
@@ -1149,6 +1149,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Fill Months" => "Заповнити місяці",
|
||||
"Fill Years" => "Заповнити роки",
|
||||
"Auto Fill Options" => "Параметри автозаповнення",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Нове правило форматування",
|
||||
"Edit Formatting Rule" => "Змінити правило форматування",
|
||||
"Select a Rule Type" => "Виберіть тип правила",
|
||||
"Edit the Rule Description" => "Редагувати опис правила",
|
||||
"Format all cells based on their values" => "Форматувати всі клітинки за їхніми значеннями",
|
||||
"Format only cells that contain" => "Форматувати лише клітинки, що містять",
|
||||
"Format only top or bottom ranked values" => "Форматувати лише значення з найвищим або найнижчим рейтингом",
|
||||
"Format only values that are above or below average" => "Форматувати лише значення вище або нижче середнього",
|
||||
"Format only unique or duplicate values" => "Форматувати лише унікальні або повторювані значення",
|
||||
"Use a formula to determine which cells to format" => "Використати формулу, щоб визначити, які клітинки форматувати",
|
||||
"This rule type isn't available yet." => "Цей тип правила ще недоступний.",
|
||||
"Format Style:" => "Стиль формату:",
|
||||
"2-Color Scale" => "Двоколірна шкала",
|
||||
"3-Color Scale" => "Триколірна шкала",
|
||||
"Midpoint" => "Середина",
|
||||
"Lowest value" => "Найнижче значення",
|
||||
"Highest value" => "Найвище значення",
|
||||
"Percent" => "Відсоток",
|
||||
"Percentile" => "Перцентиль",
|
||||
"Formula" => "Формула",
|
||||
"More Rules…" => "Більше правил…",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -598,6 +598,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Series…" => "Chuỗi…",
|
||||
"Down" => "Xuống",
|
||||
"Up" => "Lên",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Quy tắc định dạng mới",
|
||||
"Edit Formatting Rule" => "Chỉnh sửa quy tắc định dạng",
|
||||
"Select a Rule Type" => "Chọn loại quy tắc",
|
||||
"Edit the Rule Description" => "Sửa mô tả quy tắc",
|
||||
"Format all cells based on their values" => "Định dạng tất cả ô dựa trên giá trị của chúng",
|
||||
"Format only cells that contain" => "Chỉ định dạng các ô chứa",
|
||||
"Format only top or bottom ranked values" => "Chỉ định dạng các giá trị có thứ hạng cao nhất hoặc thấp nhất",
|
||||
"Format only values that are above or below average" => "Chỉ định dạng các giá trị trên hoặc dưới mức trung bình",
|
||||
"Format only unique or duplicate values" => "Chỉ định dạng các giá trị duy nhất hoặc trùng lặp",
|
||||
"Use a formula to determine which cells to format" => "Dùng công thức để xác định ô nào cần định dạng",
|
||||
"This rule type isn't available yet." => "Loại quy tắc này chưa khả dụng.",
|
||||
"Format Style:" => "Kiểu định dạng:",
|
||||
"2-Color Scale" => "Thang 2 màu",
|
||||
"3-Color Scale" => "Thang 3 màu",
|
||||
"Midpoint" => "Điểm giữa",
|
||||
"Lowest value" => "Giá trị thấp nhất",
|
||||
"Highest value" => "Giá trị cao nhất",
|
||||
"Percent" => "Phần trăm",
|
||||
"Percentile" => "Bách phân vị",
|
||||
"Formula" => "Công thức",
|
||||
"Format values where this formula is true:" => "Định dạng các giá trị mà công thức này đúng:",
|
||||
"with" => "với",
|
||||
"More Rules…" => "Thêm quy tắc…",
|
||||
// Conditional formatting: the formatting presets the rule editor offers.
|
||||
"Light Red Fill with Dark Red Text" => "Tô đỏ nhạt với chữ đỏ đậm",
|
||||
"Yellow Fill with Dark Yellow Text" => "Tô vàng với chữ vàng đậm",
|
||||
"Green Fill with Dark Green Text" => "Tô xanh lá nhạt với chữ xanh lá đậm",
|
||||
"Light Red Fill" => "Tô đỏ nhạt",
|
||||
"Red Text" => "Chữ đỏ",
|
||||
"Red Border" => "Viền đỏ",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -299,6 +299,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Point" => "指向",
|
||||
"Calculate" => "计算",
|
||||
"Select destination and press Enter or choose Paste" => "选择目标位置并按 Enter,或选择“粘贴”",
|
||||
"Extend Selection" => "扩展式选定",
|
||||
"Add or Remove Selection" => "添加或删除所选内容",
|
||||
"General" => "常规",
|
||||
"Number" => "数值",
|
||||
"Currency" => "货币",
|
||||
@@ -621,6 +623,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Series…" => "序列…",
|
||||
"Down" => "向下",
|
||||
"Up" => "向上",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "新建格式规则",
|
||||
"Edit Formatting Rule" => "编辑格式规则",
|
||||
"Select a Rule Type" => "选择规则类型",
|
||||
"Edit the Rule Description" => "编辑规则说明",
|
||||
"Format all cells based on their values" => "基于各自值设置所有单元格的格式",
|
||||
"Format only cells that contain" => "仅对包含以下内容的单元格设置格式",
|
||||
"Format only top or bottom ranked values" => "仅对排名靠前或靠后的数值设置格式",
|
||||
"Format only values that are above or below average" => "仅对高于或低于平均值的数值设置格式",
|
||||
"Format only unique or duplicate values" => "仅对唯一值或重复值设置格式",
|
||||
"Use a formula to determine which cells to format" => "使用公式确定要设置格式的单元格",
|
||||
"This rule type isn't available yet." => "此规则类型尚不可用。",
|
||||
"Format Style:" => "格式样式:",
|
||||
"2-Color Scale" => "双色刻度",
|
||||
"3-Color Scale" => "三色刻度",
|
||||
"Midpoint" => "中点",
|
||||
"Lowest value" => "最小值",
|
||||
"Highest value" => "最大值",
|
||||
"Percent" => "百分比",
|
||||
"Percentile" => "百分位",
|
||||
"Formula" => "公式",
|
||||
"Format values where this formula is true:" => "为符合此公式的值设置格式:",
|
||||
"with" => "格式:",
|
||||
"More Rules…" => "其他规则…",
|
||||
// Conditional formatting: the formatting presets the rule editor offers.
|
||||
"Light Red Fill with Dark Red Text" => "浅红填充色深红色文本",
|
||||
"Yellow Fill with Dark Yellow Text" => "黄填充色深黄色文本",
|
||||
"Green Fill with Dark Green Text" => "绿填充色深绿色文本",
|
||||
"Light Red Fill" => "浅红色填充",
|
||||
"Red Text" => "红色文本",
|
||||
"Red Border" => "红色边框",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -702,6 +702,7 @@ fn number_combo(app: &mut SheetApp, ui: &mut Ui, st: &Style) {
|
||||
}
|
||||
|
||||
fn cf_menu(app: &mut SheetApp, ui: &mut Ui) {
|
||||
let lang = app.ui.language;
|
||||
ui.menu_button("Highlight Cells Rules", |ui| {
|
||||
for (label, op) in [("Greater Than…", "greater"), ("Less Than…", "less"), ("Between…", "between"), ("Equal To…", "equal")] {
|
||||
if ui.button(label).clicked() {
|
||||
@@ -754,6 +755,10 @@ fn cf_menu(app: &mut SheetApp, ui: &mut Ui) {
|
||||
act(app, "home.conditionalFormat", json!({"rule": {"type": "colorScale", "colors": cols}}));
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button(lang.tr("More Rules…")).clicked() {
|
||||
app.open_dialog("newFormattingRule", json!({"style": "3color"}));
|
||||
}
|
||||
});
|
||||
ui.menu_button("Icon Sets", |ui| {
|
||||
for (label, set) in [
|
||||
@@ -771,7 +776,7 @@ fn cf_menu(app: &mut SheetApp, ui: &mut Ui) {
|
||||
});
|
||||
ui.separator();
|
||||
if ui.button("New Rule…").clicked() {
|
||||
app.open_dialog("cfQuick", json!({"type": "expression", "title": "New Formatting Rule"}));
|
||||
app.open_dialog("newFormattingRule", json!({}));
|
||||
}
|
||||
ui.menu_button("Clear Rules", |ui| {
|
||||
menu_items(
|
||||
@@ -815,3 +820,46 @@ mod accounting_symbol_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cf_menu_tests {
|
||||
use super::*;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
|
||||
#[test]
|
||||
fn new_rule_opens_the_rule_type_list_with_the_formula_entry() {
|
||||
let mut session = gridcraft_engine::Session::new();
|
||||
session.new_workbook();
|
||||
let app = SheetApp::new(session, Default::default());
|
||||
let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
cf_menu(app, ui);
|
||||
crate::dialogs::show(app, ui.ctx());
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(2);
|
||||
h.get_by_label("New Rule…").click();
|
||||
h.run_steps(2);
|
||||
let d = h.state().dialog.as_ref().expect("New Rule… opens a dialog");
|
||||
assert_eq!(d.name(), "newFormattingRule");
|
||||
assert_eq!(d.values.get("ruleType").and_then(serde_json::Value::as_str), Some("allCells"));
|
||||
// Formula rules stay reachable: New Rule… shows Excel's rule-type list, formula entry included.
|
||||
h.get_by_label("Use a formula to determine which cells to format");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn more_rules_follows_the_interface_language() {
|
||||
let mut session = gridcraft_engine::Session::new();
|
||||
session.new_workbook();
|
||||
let mut app = SheetApp::new(session, Default::default());
|
||||
app.run("app.language.set", serde_json::json!({"language": "es"})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state(|ui, app: &mut SheetApp| cf_menu(app, ui), app);
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Color Scales").click();
|
||||
h.run_steps(2);
|
||||
let more = crate::i18n::Language::Es.tr("More Rules…");
|
||||
assert_ne!(more, "More Rules…");
|
||||
assert!(h.query_all_by_label(more).next().is_some(), "More Rules… stays English");
|
||||
}
|
||||
}
|
||||
@@ -420,6 +420,11 @@ pub fn status_bar(app: &mut SheetApp, ui: &mut Ui) {
|
||||
gridcraft_engine::Mode::Point => "Point",
|
||||
};
|
||||
text(ui, egui::RichText::new(app.ui.language.tr(mode)).font(theme::ui_font(12.5)).color(t.text_dim));
|
||||
// F8 / Shift+F8 selection mode.
|
||||
if let Some(label) = app.grid.selection_mode.status_text() {
|
||||
ui.add_space(12.0);
|
||||
text(ui, egui::RichText::new(app.ui.language.tr(label)).font(theme::ui_font(12.5)).color(t.text_dim));
|
||||
}
|
||||
crate::macro_ui::status(app, ui);
|
||||
if let Some(d) = app.session.active() {
|
||||
if d.wb.vba_project.is_some() {
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
//! New Formatting Rule: the 2-/3-colour scale branch and in-place editing.
|
||||
|
||||
use egui::vec2;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_engine::model::{CfRule, CfValueKind, Color};
|
||||
use gridcraft_ui_egui::SheetApp;
|
||||
use gridcraft_ui_egui::i18n::Language;
|
||||
use serde_json::json;
|
||||
|
||||
fn harness() -> egui_kittest::Harness<'static, SheetApp> {
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
session.run("range.setValues", json!({"range": "A1:A3", "values": [[1], [2], [3]]})).unwrap();
|
||||
session.run("selection.set", json!({"range": "A1:A3"})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
app.logic(&ui.ctx().clone());
|
||||
app.ui(ui);
|
||||
},
|
||||
SheetApp::new(session, Default::default()),
|
||||
);
|
||||
h.run_steps(6);
|
||||
h
|
||||
}
|
||||
|
||||
fn stops(h: &egui_kittest::Harness<'static, SheetApp>) -> Vec<(CfValueKind, Color)> {
|
||||
let doc = h.state().session.active().unwrap();
|
||||
let rule = &doc.wb.active().unwrap().cond_formats[0].rule;
|
||||
match rule {
|
||||
CfRule::ColorScale { stops } => stops.clone(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creates_a_three_colour_scale_with_per_stop_thresholds() {
|
||||
let mut h = harness();
|
||||
h.state_mut().run("home.conditionalFormat", json!({})).unwrap();
|
||||
h.run_steps(6);
|
||||
assert_eq!(h.state().dialog.as_ref().map(|d| d.name.as_str()), Some("newFormattingRule"));
|
||||
|
||||
h.state_mut().dialog.as_mut().unwrap().values.insert(
|
||||
"stops".into(),
|
||||
json!([
|
||||
{"type": "min", "color": "#112233"},
|
||||
{"type": "percentile", "value": 90, "color": "#445566"},
|
||||
{"type": "max", "color": "#778899"},
|
||||
]),
|
||||
);
|
||||
h.run_steps(2);
|
||||
// The rule covers the sheet and range the dialog opened on, not the one shown at OK.
|
||||
h.state_mut().run("home.insertSheet", json!({"name": "Two"})).unwrap();
|
||||
h.state_mut().run("selection.set", json!({"range": "B1:B2"})).unwrap();
|
||||
h.run_steps(2);
|
||||
h.get_by_label(" OK ").click();
|
||||
h.run_steps(6);
|
||||
assert!(h.state().dialog.is_none());
|
||||
let two = h.state_mut().run("home.manageRules", json!({"sheet": "Two"})).unwrap();
|
||||
assert_eq!(two["rules"].as_array().map(Vec::len), Some(0), "the rule does not land on the sheet shown at OK");
|
||||
let list = h.state_mut().run("home.manageRules", json!({"sheet": "Sheet1"})).unwrap();
|
||||
assert_eq!(list["rules"][0]["ranges"], json!(["A1:A3"]));
|
||||
h.state_mut().run("sheet.activate", json!({"sheet": "Sheet1"})).unwrap();
|
||||
assert_eq!(
|
||||
stops(&h),
|
||||
vec![
|
||||
(CfValueKind::Min, Color::Rgb(0x112233)),
|
||||
(CfValueKind::Percentile(90.0), Color::Rgb(0x445566)),
|
||||
(CfValueKind::Max, Color::Rgb(0x778899)),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_an_existing_scale_in_place() {
|
||||
let mut h = harness();
|
||||
h.state_mut()
|
||||
.run(
|
||||
"home.conditionalFormat",
|
||||
json!({"rule": {"type": "colorScale", "stops": [
|
||||
{"type": "min", "color": "#112233"},
|
||||
{"type": "percentile", "value": 50, "color": "#445566"},
|
||||
{"type": "max", "color": "#778899"},
|
||||
]}}),
|
||||
)
|
||||
.unwrap();
|
||||
let rule = serde_json::to_value(&h.state().session.active().unwrap().wb.active().unwrap().cond_formats[0].rule).unwrap();
|
||||
h.state_mut().open_dialog("newFormattingRule", json!({"edit": 0, "rule": rule}));
|
||||
h.run_steps(6);
|
||||
h.state_mut().dialog.as_mut().unwrap().values.insert("style".into(), json!("2color"));
|
||||
h.state_mut().dialog.as_mut().unwrap().values.insert(
|
||||
"stops".into(),
|
||||
json!([
|
||||
{"type": "formula", "value": "$B$1", "color": "#ABCABC"},
|
||||
{"type": "max", "color": "#DEFDEF"},
|
||||
]),
|
||||
);
|
||||
h.run_steps(2);
|
||||
h.get_by_label(" OK ").click();
|
||||
h.run_steps(6);
|
||||
assert!(h.state().dialog.is_none());
|
||||
assert_eq!(stops(&h), vec![(CfValueKind::Formula("$B$1".into()), Color::Rgb(0xABCABC)), (CfValueKind::Max, Color::Rgb(0xDEFDEF))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_rule_still_creates_a_formula_rule() {
|
||||
let mut h = harness();
|
||||
h.state_mut().open_dialog("newFormattingRule", json!({}));
|
||||
h.run_steps(6);
|
||||
assert_eq!(h.state().dialog.as_ref().unwrap().values["ruleType"], json!("allCells"));
|
||||
|
||||
h.get_by_label("Use a formula to determine which cells to format").click();
|
||||
h.run_steps(4);
|
||||
assert_eq!(h.state().dialog.as_ref().unwrap().values["ruleType"], json!("formula"));
|
||||
h.state_mut().dialog.as_mut().unwrap().values.insert("formula".into(), json!("=A1>2"));
|
||||
h.run_steps(2);
|
||||
h.get_by_label(" OK ").click();
|
||||
h.run_steps(6);
|
||||
assert!(h.state().dialog.is_none());
|
||||
let rule = &h.state().session.active().unwrap().wb.active().unwrap().cond_formats[0].rule;
|
||||
let CfRule::Expression { formula, .. } = rule else { panic!("expected a formula rule, got {rule:?}") };
|
||||
assert_eq!(formula, "A1>2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_editor_widgets_drive_the_scale() {
|
||||
let mut h = harness();
|
||||
h.state_mut().open_dialog("newFormattingRule", json!({}));
|
||||
h.run_steps(6);
|
||||
|
||||
// Format Style: 3 -> 2 -> 3 through the combo itself.
|
||||
h.get_all_by_role(egui::accesskit::Role::ComboBox).next().expect("format style").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_label("2-Color Scale").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().dialog.as_ref().unwrap().values["stops"].as_array().unwrap().len(), 2);
|
||||
h.get_all_by_role(egui::accesskit::Role::ComboBox).next().expect("format style").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_label("3-Color Scale").click();
|
||||
h.run_steps(2);
|
||||
|
||||
// Midpoint: Percentile -> Number, then type a new threshold.
|
||||
h.get_all_by_role(egui::accesskit::Role::ComboBox).nth(2).expect("midpoint type").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Number").click();
|
||||
h.run_steps(2);
|
||||
h.get_all_by_role(egui::accesskit::Role::SpinButton).next().expect("midpoint threshold").click();
|
||||
h.run_steps(1);
|
||||
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
|
||||
h.key_press(egui::Key::Backspace);
|
||||
h.get_all_by_role(egui::accesskit::Role::SpinButton).next().expect("midpoint threshold").type_text("75");
|
||||
h.key_press(egui::Key::Tab);
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().dialog.as_ref().unwrap().values["stops"][1]["value"], json!(75.0));
|
||||
|
||||
h.get_by_label(" OK ").click();
|
||||
h.run_steps(6);
|
||||
assert_eq!(
|
||||
stops(&h),
|
||||
vec![(CfValueKind::Min, Color::Rgb(0xF8696B)), (CfValueKind::Number(75.0), Color::Rgb(0xFFEB84)), (CfValueKind::Max, Color::Rgb(0x63BE7B)),]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_three_to_two_to_three_uses_the_default_midpoint() {
|
||||
let mut h = harness();
|
||||
h.state_mut()
|
||||
.run(
|
||||
"home.conditionalFormat",
|
||||
json!({"rule": {"type": "colorScale", "stops": [
|
||||
{"type": "min", "color": "#112233"},
|
||||
{"type": "percentile", "value": 50, "color": "#445566"},
|
||||
{"type": "max", "color": "#778899"},
|
||||
]}}),
|
||||
)
|
||||
.unwrap();
|
||||
let rule = serde_json::to_value(&h.state().session.active().unwrap().wb.active().unwrap().cond_formats[0].rule).unwrap();
|
||||
h.state_mut().open_dialog("newFormattingRule", json!({"edit": 0, "rule": rule}));
|
||||
h.run_steps(6);
|
||||
|
||||
// The style combo drives these transitions in `new_formatting_rule`.
|
||||
h.state_mut().dialog.as_mut().unwrap().values.insert("style".into(), json!("2color"));
|
||||
h.run_steps(2);
|
||||
let two = h.state().dialog.as_ref().unwrap().values["stops"].as_array().unwrap().clone();
|
||||
assert_eq!(two.len(), 2);
|
||||
assert_eq!(two[0]["color"], json!("#112233"), "dropping the midpoint keeps the minimum's colour");
|
||||
assert_eq!(two[1]["color"], json!("#778899"), "dropping the midpoint keeps the maximum's colour");
|
||||
|
||||
h.state_mut().dialog.as_mut().unwrap().values.insert("style".into(), json!("3color"));
|
||||
h.run_steps(2);
|
||||
h.get_by_label(" OK ").click();
|
||||
h.run_steps(6);
|
||||
assert!(h.state().dialog.is_none());
|
||||
assert_eq!(
|
||||
stops(&h),
|
||||
vec![
|
||||
(CfValueKind::Min, Color::Rgb(0x112233)),
|
||||
(CfValueKind::Percentile(50.0), Color::Rgb(0xFFEB84)),
|
||||
(CfValueKind::Max, Color::Rgb(0x778899)),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_keeps_an_unchanged_theme_colour() {
|
||||
let mut h = harness();
|
||||
h.state_mut()
|
||||
.run(
|
||||
"home.conditionalFormat",
|
||||
json!({"rule": {"type": "colorScale", "stops": [
|
||||
{"type": "min", "color": {"theme": 4, "tint": 0}},
|
||||
{"type": "percentile", "value": 50, "color": {"theme": 2, "tint": 0}},
|
||||
{"type": "max", "color": {"theme": 6, "tint": 0}},
|
||||
]}}),
|
||||
)
|
||||
.unwrap();
|
||||
let rule = serde_json::to_value(&h.state().session.active().unwrap().wb.active().unwrap().cond_formats[0].rule).unwrap();
|
||||
h.state_mut().open_dialog("newFormattingRule", json!({"edit": 0, "rule": rule}));
|
||||
h.run_steps(6);
|
||||
h.get_by_label(" OK ").click();
|
||||
h.run_steps(6);
|
||||
assert!(h.state().dialog.is_none());
|
||||
assert_eq!(
|
||||
stops(&h),
|
||||
vec![(CfValueKind::Min, Color::Theme(4, 0)), (CfValueKind::Percentile(50.0), Color::Theme(2, 0)), (CfValueKind::Max, Color::Theme(6, 0)),]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_formula_keeps_ok_disabled() {
|
||||
let mut h = harness();
|
||||
h.state_mut().open_dialog("newFormattingRule", json!({}));
|
||||
h.run_steps(6);
|
||||
h.get_by_label("Use a formula to determine which cells to format").click();
|
||||
h.run_steps(4);
|
||||
assert_eq!(h.state().dialog.as_ref().unwrap().values["ruleType"], json!("formula"));
|
||||
// No formula typed: OK (and Enter) must do nothing, or the rule never applies.
|
||||
h.get_by_label(" OK ").click();
|
||||
h.run_steps(6);
|
||||
assert!(h.state().dialog.is_some(), "the dialog stays open for a formula");
|
||||
assert!(h.state().session.active().unwrap().wb.active().unwrap().cond_formats.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unparseable_formula_is_refused_with_a_message() {
|
||||
let mut h = harness();
|
||||
h.state_mut().open_dialog("newFormattingRule", json!({}));
|
||||
h.run_steps(6);
|
||||
h.get_by_label("Use a formula to determine which cells to format").click();
|
||||
h.run_steps(4);
|
||||
h.state_mut().dialog.as_mut().unwrap().values.insert("formula".into(), json!("=C1>"));
|
||||
h.run_steps(2);
|
||||
h.get_by_label(" OK ").click();
|
||||
h.run_steps(6);
|
||||
assert!(h.state().dialog.is_some(), "an invalid formula keeps the dialog open");
|
||||
let message = h.state().message.as_ref().map(|(_, m)| m.clone()).unwrap_or_default();
|
||||
assert!(message.contains("invalid") && message.contains("does not parse"), "{message}");
|
||||
assert!(h.state().session.active().unwrap().wb.active().unwrap().cond_formats.is_empty(), "no unopenable rule is stored");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_a_numeric_stop_to_formula_needs_a_formula() {
|
||||
let mut h = harness();
|
||||
h.state_mut().open_dialog("newFormattingRule", json!({}));
|
||||
h.run_steps(6);
|
||||
|
||||
// Switching a Number stop to Formula without touching the field: the editor must store the
|
||||
// field as a string rather than leave the old number in place, and OK must wait for one.
|
||||
h.state_mut().dialog.as_mut().unwrap().values.insert(
|
||||
"stops".into(),
|
||||
json!([
|
||||
{"type": "formula", "value": 7, "color": "#112233"},
|
||||
{"type": "max", "color": "#778899"},
|
||||
]),
|
||||
);
|
||||
h.run_steps(2);
|
||||
let stops_json = h.state().dialog.as_ref().unwrap().values["stops"].as_array().unwrap().clone();
|
||||
assert_eq!(stops_json[0]["value"], json!(""), "a numeric value is not a formula");
|
||||
h.get_by_label(" OK ").click();
|
||||
h.run_steps(6);
|
||||
assert!(h.state().dialog.is_some(), "a formula stop with no formula does not confirm");
|
||||
assert!(h.state().session.active().unwrap().wb.active().unwrap().cond_formats.is_empty());
|
||||
|
||||
// A blank formula is refused the same way.
|
||||
h.state_mut().dialog.as_mut().unwrap().values.insert(
|
||||
"stops".into(),
|
||||
json!([
|
||||
{"type": "formula", "value": " ", "color": "#112233"},
|
||||
{"type": "max", "color": "#778899"},
|
||||
]),
|
||||
);
|
||||
h.run_steps(2);
|
||||
h.get_by_label(" OK ").click();
|
||||
h.run_steps(6);
|
||||
assert!(h.state().dialog.is_some(), "a blank formula does not confirm");
|
||||
assert!(h.state().session.active().unwrap().wb.active().unwrap().cond_formats.is_empty());
|
||||
|
||||
// A real formula confirms.
|
||||
h.state_mut().dialog.as_mut().unwrap().values.insert("style".into(), json!("2color"));
|
||||
h.state_mut().dialog.as_mut().unwrap().values.insert(
|
||||
"stops".into(),
|
||||
json!([
|
||||
{"type": "formula", "value": "$Z$1", "color": "#112233"},
|
||||
{"type": "max", "color": "#778899"},
|
||||
]),
|
||||
);
|
||||
h.run_steps(2);
|
||||
h.get_by_label(" OK ").click();
|
||||
h.run_steps(6);
|
||||
assert!(h.state().dialog.is_none());
|
||||
assert_eq!(stops(&h), vec![(CfValueKind::Formula("$Z$1".into()), Color::Rgb(0x112233)), (CfValueKind::Max, Color::Rgb(0x778899))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rule_list_translates_its_edit_button() {
|
||||
let mut h = harness();
|
||||
h.state_mut()
|
||||
.run(
|
||||
"home.conditionalFormat",
|
||||
json!({"rule": {"type": "colorScale", "stops": [
|
||||
{"type": "min", "color": "#112233"},
|
||||
{"type": "max", "color": "#778899"},
|
||||
]}}),
|
||||
)
|
||||
.unwrap();
|
||||
h.state_mut().run("app.language.set", json!({"language": Language::Es.code()})).unwrap();
|
||||
h.state_mut().open_dialog("manageRules", json!({}));
|
||||
h.run_steps(6);
|
||||
let edit = Language::Es.tr("Edit");
|
||||
assert_ne!(edit, "Edit");
|
||||
assert!(h.query_all_by_label(edit).next().is_some(), "Edit stays English");
|
||||
}
|
||||
@@ -286,13 +286,16 @@ fn table_filter_autofit_works_through_command_and_header_double_click() {
|
||||
let cell = gridcraft_engine::core::CellRef::new(0, 0);
|
||||
let rect = geo.cell_rect(sheet, cell);
|
||||
let button = gridcraft_ui_egui::grid::filter_button_rect(&geo, sheet, cell);
|
||||
let style = app.session.active().unwrap().wb.styles.get(sheet.style_id(cell));
|
||||
// The heading as the grid draws it: in the table style's font, bold in the header row.
|
||||
// Measured as AutoFit measured it, with the app's fonts (they differ from machine to
|
||||
// machine). The app installs them before AutoFit runs; AutoFit without them, on the
|
||||
// engine's estimate, is `autofit_filter_buttons` in the engine's tests.
|
||||
let wb = &app.session.active().unwrap().wb;
|
||||
let table = sheet.table_at(cell).expect("A1 is the table's header");
|
||||
let font = gridcraft_engine::tables::table_cell_style(wb, wb.active_sheet(), table, cell).font;
|
||||
assert!(font.bold, "the table style draws its header bold");
|
||||
let measure = app.session.text_width.as_ref().expect("the app measures text with its fonts");
|
||||
let measured = measure("Quarterly Revenue", &style.font, true);
|
||||
let text_width = measured * geo.z;
|
||||
let text_width = measure("Quarterly Revenue", &font, true) * geo.z;
|
||||
assert!(rect.left() + text_width + 2.5 * geo.z < button.left(), "heading overlaps filter: zoom={zoom}, double_click={double_click}");
|
||||
assert_eq!(app.session.active().unwrap().undo.len(), 1);
|
||||
h.state_mut().session.execute("edit.undo", json!({})).unwrap();
|
||||
|
||||
@@ -1663,6 +1663,39 @@ fn general_numbers_fit_by_the_cells_own_font() {
|
||||
assert_eq!(texts.iter().filter(|t| t.starts_with('#')).count(), 1, "{texts:?}");
|
||||
}
|
||||
|
||||
/// #1077: after Increase Decimal and the other ribbon number formats the column widens enough for
|
||||
/// the real font, so the number is drawn instead of ####, at the default size and a large bold one.
|
||||
#[test]
|
||||
fn ribbon_number_formats_widen_the_column_enough_to_draw_the_number() {
|
||||
let mut s = blank();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[1.23456789, 1234567.891, 98765.4321], [0.5, 1, 2]]})).unwrap();
|
||||
s.execute("home.fontSize", json!({"range": "C1", "size": 20})).unwrap();
|
||||
s.execute("home.bold", json!({"range": "C1", "on": true})).unwrap();
|
||||
for _ in 0..4 {
|
||||
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
|
||||
}
|
||||
s.execute("home.comma", json!({"range": "B1"})).unwrap();
|
||||
s.execute("home.numberFormat", json!({"range": "C1", "format": "Currency"})).unwrap();
|
||||
s.execute("selection.set", json!({"cell": "E5"})).unwrap();
|
||||
let want: Vec<String> =
|
||||
["A1", "B1", "C1"].iter().map(|a| s.execute("cell.get", json!({"cell": a})).unwrap()["text"].as_str().unwrap().trim().to_string()).collect();
|
||||
assert_eq!(want, ["1.234567890000", "1,234,567.89", "$98,765.43"]);
|
||||
let h = harness(s);
|
||||
let texts: Vec<String> = h
|
||||
.output()
|
||||
.shapes
|
||||
.iter()
|
||||
.filter_map(|c| match &c.shape {
|
||||
egui::Shape::Text(t) => Some(t.galley.job.text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
for t in &want {
|
||||
assert!(texts.iter().any(|x| x.trim() == t), "{t} drawn in full: {texts:?}");
|
||||
}
|
||||
assert!(!texts.iter().any(|t| t.starts_with('#')), "no ####: {texts:?}");
|
||||
}
|
||||
|
||||
fn text_shapes(shape: &egui::Shape, clip: egui::Rect, out: &mut Vec<(egui::epaint::TextShape, egui::Rect)>) {
|
||||
match shape {
|
||||
egui::Shape::Text(t) => out.push((t.clone(), clip)),
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
//! Excel keyboard shortcuts (crate::keymap) dispatched through real egui key events.
|
||||
|
||||
use egui::{Event, Key, Modifiers};
|
||||
use egui::{Event, Key, Modifiers, PointerButton};
|
||||
use egui_kittest::kittest::Queryable as _;
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_engine::core::CellRef;
|
||||
use gridcraft_engine::model::BorderStyle;
|
||||
use gridcraft_ui_egui::SheetApp;
|
||||
use gridcraft_ui_egui::grid::{Geo, SelectionMode};
|
||||
use gridcraft_ui_egui::keymap::{Shortcut, lookup};
|
||||
use serde_json::json;
|
||||
|
||||
@@ -77,6 +79,210 @@ fn copy_formula_from_above_and_function_keys() {
|
||||
assert_eq!(h.state().session.active().unwrap().wb.sheets[0].zoom, 110);
|
||||
}
|
||||
|
||||
fn selection_a1(h: &Harness) -> String {
|
||||
h.state().session.active().unwrap().selection.a1()
|
||||
}
|
||||
|
||||
fn active_a1(h: &Harness) -> String {
|
||||
h.state().session.active().unwrap().selection.active.a1()
|
||||
}
|
||||
|
||||
fn mode(h: &Harness) -> SelectionMode {
|
||||
h.state().grid.selection_mode
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f8_extend_selection_extends_from_the_anchor_until_turned_off() {
|
||||
let mut h = harness(book("A1"));
|
||||
assert!(h.query_by_label("Extend Selection").is_none());
|
||||
key(&mut h, Key::F8, Modifiers::NONE);
|
||||
assert_eq!(mode(&h), SelectionMode::Extend);
|
||||
assert!(h.query_by_label("Extend Selection").is_some(), "the status bar shows the mode");
|
||||
key(&mut h, Key::ArrowRight, Modifiers::NONE);
|
||||
key(&mut h, Key::ArrowDown, Modifiers::NONE);
|
||||
assert_eq!(selection_a1(&h), "A1:B2");
|
||||
assert_eq!(active_a1(&h), "A1", "the active cell stays on the anchor");
|
||||
// Ctrl+arrow extends to the edge of the data, as Ctrl+Shift+arrow does.
|
||||
key(&mut h, Key::ArrowDown, CTRL);
|
||||
assert_eq!(selection_a1(&h), "A1:B3");
|
||||
// F8 again ends the mode: arrows move again.
|
||||
key(&mut h, Key::F8, Modifiers::NONE);
|
||||
assert_eq!(mode(&h), SelectionMode::Off);
|
||||
assert!(h.query_by_label("Extend Selection").is_none());
|
||||
key(&mut h, Key::ArrowRight, Modifiers::NONE);
|
||||
assert_eq!(selection_a1(&h), "B1");
|
||||
// Esc ends it too, and keeps the extended selection.
|
||||
key(&mut h, Key::F8, Modifiers::NONE);
|
||||
key(&mut h, Key::ArrowRight, Modifiers::NONE);
|
||||
key(&mut h, Key::Escape, Modifiers::NONE);
|
||||
assert_eq!(mode(&h), SelectionMode::Off);
|
||||
assert_eq!(selection_a1(&h), "B1:C1");
|
||||
key(&mut h, Key::ArrowDown, Modifiers::NONE);
|
||||
assert_eq!(selection_a1(&h), "B2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_f8_add_to_selection_builds_areas_with_arrow_keys() {
|
||||
let mut h = harness(book("A1:A2"));
|
||||
key(&mut h, Key::F8, Modifiers::SHIFT);
|
||||
assert_eq!(mode(&h), SelectionMode::Add);
|
||||
assert!(h.query_by_label("Add or Remove Selection").is_some(), "the status bar shows the mode");
|
||||
assert!(h.query_by_label("Extend Selection").is_none());
|
||||
// Arrows move the active cell and keep A1:A2; the next arrow moves the new cell again.
|
||||
key(&mut h, Key::ArrowRight, Modifiers::NONE);
|
||||
assert_eq!(selection_a1(&h), "A1:A2,B1");
|
||||
key(&mut h, Key::ArrowRight, Modifiers::NONE);
|
||||
assert_eq!(selection_a1(&h), "A1:A2,C1");
|
||||
assert_eq!(active_a1(&h), "C1");
|
||||
// Shift+arrow grows that area from it and keeps it.
|
||||
key(&mut h, Key::ArrowRight, Modifiers::SHIFT);
|
||||
assert_eq!(selection_a1(&h), "A1:A2,C1:D1");
|
||||
assert_eq!(active_a1(&h), "C1");
|
||||
// The next arrow starts a third area.
|
||||
key(&mut h, Key::ArrowDown, Modifiers::NONE);
|
||||
key(&mut h, Key::ArrowDown, Modifiers::NONE);
|
||||
assert_eq!(selection_a1(&h), "A1:A2,C1:D1,C3");
|
||||
// F8 switches to Extend mode, and Shift+F8 twice ends Add mode.
|
||||
key(&mut h, Key::F8, Modifiers::NONE);
|
||||
assert_eq!(mode(&h), SelectionMode::Extend);
|
||||
key(&mut h, Key::F8, Modifiers::SHIFT);
|
||||
assert_eq!(mode(&h), SelectionMode::Add);
|
||||
key(&mut h, Key::F8, Modifiers::SHIFT);
|
||||
assert_eq!(mode(&h), SelectionMode::Off);
|
||||
assert!(h.query_by_label("Add or Remove Selection").is_none());
|
||||
key(&mut h, Key::ArrowRight, Modifiers::NONE);
|
||||
assert_eq!(selection_a1(&h), "D3", "with the mode off an arrow drops the areas");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_a_cell_ends_the_selection_mode() {
|
||||
let mut h = harness(book("A1"));
|
||||
key(&mut h, Key::F8, Modifiers::NONE);
|
||||
key(&mut h, Key::F2, Modifiers::NONE);
|
||||
assert!(h.state().editor.is_some());
|
||||
assert_eq!(mode(&h), SelectionMode::Off);
|
||||
key(&mut h, Key::Escape, Modifiers::NONE);
|
||||
key(&mut h, Key::F8, Modifiers::SHIFT);
|
||||
h.input_mut().events.push(Event::Text("7".into()));
|
||||
h.run_steps(2);
|
||||
assert!(h.state().editor.is_some(), "typing starts an edit");
|
||||
assert_eq!(mode(&h), SelectionMode::Off);
|
||||
}
|
||||
|
||||
fn click(h: &mut Harness, a1: &str) {
|
||||
let at = {
|
||||
let app = h.state();
|
||||
let sheet = app.session.active().unwrap().wb.active().unwrap();
|
||||
Geo::new(sheet, app.grid.rect.unwrap(), app.view().scroll).cell_rect(sheet, CellRef::parse(a1).unwrap()).center()
|
||||
};
|
||||
h.input_mut().events.push(Event::PointerMoved(at));
|
||||
h.run_steps(1);
|
||||
for pressed in [true, false] {
|
||||
h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
|
||||
h.run_steps(1);
|
||||
}
|
||||
h.run_steps(1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicks_extend_or_add_in_the_selection_modes() {
|
||||
let mut h = harness(book("B2"));
|
||||
key(&mut h, Key::F8, Modifiers::NONE);
|
||||
click(&mut h, "D4");
|
||||
assert_eq!(selection_a1(&h), "B2:D4", "in Extend mode a click extends from the anchor");
|
||||
assert_eq!(mode(&h), SelectionMode::Extend, "the mode stays on");
|
||||
key(&mut h, Key::F8, Modifiers::SHIFT);
|
||||
click(&mut h, "F6");
|
||||
assert_eq!(selection_a1(&h), "B2:D4,F6", "in Add mode a click adds an area");
|
||||
// (Not a double-click: that would edit the cell.)
|
||||
h.state_mut().grid.last_click = None;
|
||||
click(&mut h, "F6");
|
||||
assert_eq!(selection_a1(&h), "B2:D4", "and a click on a selected area removes it");
|
||||
// An arrow after a click keeps the clicked areas.
|
||||
click(&mut h, "H8");
|
||||
key(&mut h, Key::ArrowDown, Modifiers::NONE);
|
||||
assert_eq!(selection_a1(&h), "B2:D4,H8,H9");
|
||||
// Moving back onto the kept H8 and off again keeps it.
|
||||
key(&mut h, Key::ArrowUp, Modifiers::NONE);
|
||||
assert_eq!(selection_a1(&h), "B2:D4,H8");
|
||||
key(&mut h, Key::ArrowDown, Modifiers::NONE);
|
||||
assert_eq!(selection_a1(&h), "B2:D4,H8,H9");
|
||||
}
|
||||
|
||||
/// A point in the column header band, above `col`'s cells.
|
||||
fn column_header_point(h: &Harness, col: &str) -> egui::Pos2 {
|
||||
let app = h.state();
|
||||
let sheet = app.session.active().unwrap().wb.active().unwrap();
|
||||
let geo = Geo::new(sheet, app.grid.rect.unwrap(), app.view().scroll);
|
||||
let x = geo.cell_rect(sheet, CellRef::parse(&format!("{col}1")).unwrap()).center().x;
|
||||
egui::pos2(x, geo.head_top() + 4.0)
|
||||
}
|
||||
|
||||
fn drag(h: &mut Harness, from: egui::Pos2, to: egui::Pos2) {
|
||||
h.input_mut().events.push(Event::PointerMoved(from));
|
||||
h.run_steps(1);
|
||||
h.input_mut().events.push(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
|
||||
h.run_steps(1);
|
||||
h.input_mut().events.push(Event::PointerMoved(to));
|
||||
h.run_steps(2);
|
||||
h.input_mut().events.push(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_mode_header_drag_keeps_the_earlier_areas() {
|
||||
let mut h = harness(book("B2"));
|
||||
key(&mut h, Key::F8, Modifiers::SHIFT);
|
||||
click(&mut h, "F6");
|
||||
assert_eq!(selection_a1(&h), "B2,F6");
|
||||
h.state_mut().grid.last_click = None;
|
||||
let (from, to) = (column_header_point(&h, "H"), column_header_point(&h, "J"));
|
||||
drag(&mut h, from, to);
|
||||
assert_eq!(selection_a1(&h), "B2,F6,H:J", "a header drag in Add mode adds its columns and keeps the areas already selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_mode_header_drag_replaces_only_the_provisional_area() {
|
||||
let mut h = harness(book("B2"));
|
||||
key(&mut h, Key::F8, Modifiers::SHIFT);
|
||||
key(&mut h, Key::ArrowRight, Modifiers::NONE);
|
||||
assert_eq!(selection_a1(&h), "B2,C2");
|
||||
h.state_mut().grid.last_click = None;
|
||||
let (from, to) = (column_header_point(&h, "H"), column_header_point(&h, "J"));
|
||||
drag(&mut h, from, to);
|
||||
assert_eq!(selection_a1(&h), "B2,H:J", "the header drag replaces the provisional area while retaining earlier areas");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_mode_shift_home_and_end_keep_the_earlier_areas() {
|
||||
let mut home = harness(book("B2"));
|
||||
key(&mut home, Key::F8, Modifiers::SHIFT);
|
||||
click(&mut home, "F6");
|
||||
key(&mut home, Key::Home, Modifiers::SHIFT);
|
||||
assert_eq!(selection_a1(&home), "B2,A6:F6", "Shift+Home extends the active area and keeps the earlier area");
|
||||
|
||||
let mut end = harness(book("B2"));
|
||||
key(&mut end, Key::F8, Modifiers::SHIFT);
|
||||
click(&mut end, "F6");
|
||||
key(&mut end, Key::End, CTRL_SHIFT);
|
||||
assert_eq!(selection_a1(&end), "B2,C3:F6", "Ctrl+Shift+End extends the active area and keeps the earlier area");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_mode_command_sets_and_reports_without_a_dialog() {
|
||||
let mut h = harness(book("A1"));
|
||||
assert_eq!(h.state_mut().run("ui.selectionMode", json!({})), Ok(json!({"mode": "off"})));
|
||||
assert_eq!(h.state_mut().run("ui.selectionMode", json!({"mode": "extend"})), Ok(json!({"mode": "extend"})));
|
||||
h.run_steps(2);
|
||||
assert!(h.query_by_label("Extend Selection").is_some());
|
||||
assert_eq!(h.state_mut().run("ui.selectionMode", json!({"mode": "add"})), Ok(json!({"mode": "add"})));
|
||||
assert!(h.state_mut().run("ui.selectionMode", json!({"mode": "sideways"})).is_err());
|
||||
assert!(h.state_mut().run("ui.selectionMode", json!({"mode": 3})).is_err());
|
||||
assert_eq!(mode(&h), SelectionMode::Add, "a bad mode changes nothing");
|
||||
assert_eq!(h.state_mut().run("ui.selectionMode", json!({"mode": "off"})), Ok(json!({"mode": "off"})));
|
||||
assert!(h.state().dialog.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_and_mac_variants() {
|
||||
let cmd = CTRL;
|
||||
|
||||
@@ -15,6 +15,8 @@ fn harness() -> Harness {
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "Executive Producer"})).unwrap();
|
||||
s.execute("home.formatCells", json!({"range": "A1", "style": shrink})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A2", "input": "Control Producer"})).unwrap();
|
||||
// Column A's width set by hand (to the default), so the numbers formatted below keep it.
|
||||
s.execute("home.columnWidth", json!({"cols": "A:A", "width": 64})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A4", "input": "123456789012"})).unwrap();
|
||||
s.execute("home.formatCells", json!({"range": "A4", "style": {"num_fmt": "#,##0", "align": {"shrink": true}}})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A5", "input": "123456789012"})).unwrap();
|
||||
|
||||
@@ -426,6 +426,7 @@ struct RawCol {
|
||||
max: u32,
|
||||
width: Option<f64>,
|
||||
custom_width: bool,
|
||||
best_fit: bool,
|
||||
hidden: bool,
|
||||
outline_level: u8,
|
||||
collapsed: bool,
|
||||
@@ -441,6 +442,9 @@ fn apply_col_entry(cx: &Ctx<'_>, c: RawCol, remaining: &mut u64, sheet: &mut She
|
||||
let mut info = LineInfo::default();
|
||||
if let Some(w) = c.width {
|
||||
let px = col_width_to_px(w);
|
||||
// Excel writes customWidth for every width it stores, and bestFit as well for one that
|
||||
// AutoFit or a number format sized: only customWidth without bestFit was set by hand.
|
||||
info.custom = c.custom_width && !c.best_fit;
|
||||
if c.custom_width || px != sheet.default_col_width {
|
||||
info.size = Some(px);
|
||||
}
|
||||
@@ -474,6 +478,7 @@ fn apply_craft_cols(cx: &Ctx<'_>, cols: &[craft_xlsx::Column], sheet: &mut Sheet
|
||||
max: c.last + 1,
|
||||
width: c.width,
|
||||
custom_width: c.custom_width,
|
||||
best_fit: c.best_fit,
|
||||
hidden: c.hidden,
|
||||
outline_level: c.outline_level,
|
||||
collapsed: c.collapsed,
|
||||
@@ -497,6 +502,7 @@ fn apply_xml_cols(cx: &Ctx<'_>, sp: &CraftSheetPart, sheet: &mut Sheet) -> Resul
|
||||
max: c.attr_u32("max").unwrap_or(0),
|
||||
width: c.attr_f64("width"),
|
||||
custom_width: c.flag("customWidth", false),
|
||||
best_fit: c.flag("bestFit", false),
|
||||
hidden: c.flag("hidden", false),
|
||||
outline_level: c.attr_u32("outlineLevel").unwrap_or(0).min(7) as u8,
|
||||
collapsed: c.flag("collapsed", false),
|
||||
|
||||
@@ -239,8 +239,10 @@ fn build_craft_cols(sheet: &Sheet, sid: &dyn Fn(gridcraft_model::StyleId) -> u32
|
||||
first: a,
|
||||
last: b,
|
||||
width: Some(px_to_col_width(w)),
|
||||
// As Excel writes them: a width that AutoFit or a number format sized is bestFit too, so
|
||||
// it keeps widening when the file is opened again; one set by hand is customWidth only.
|
||||
custom_width: i.size.is_some(),
|
||||
best_fit: false,
|
||||
best_fit: i.size.is_some() && !i.custom,
|
||||
hidden: i.hidden,
|
||||
outline_level: i.outline.min(7),
|
||||
collapsed: i.collapsed,
|
||||
|
||||
@@ -181,7 +181,9 @@ fn assert_sheet_settings(s: &gridcraft_model::Sheet) {
|
||||
assert!(s.cols.get(&2).unwrap().hidden);
|
||||
assert_eq!(s.cols.get(&2).unwrap().size, Some(145.0));
|
||||
assert_eq!(s.cols.get(&2).unwrap().outline, 1);
|
||||
assert!(s.cols.get(&2).unwrap().custom, "customWidth: a width set by hand");
|
||||
assert_ne!(s.cols.get(&3).unwrap().style, None);
|
||||
assert!(!s.cols.get(&3).unwrap().custom, "no customWidth: not set by hand");
|
||||
assert_eq!(s.rows.get(&0).unwrap().size, Some(40.0));
|
||||
let r2 = s.rows.get(&1).unwrap();
|
||||
assert!(r2.hidden);
|
||||
@@ -294,6 +296,27 @@ fn dxf_border_is_written_before_protection() {
|
||||
assert!(b.is_some() && p.is_some() && b < p, "{dx}");
|
||||
}
|
||||
|
||||
/// Which stored widths were set by hand, as Excel 16.0 treats them when a number format makes a
|
||||
/// number wider (#1077): only customWidth without bestFit keeps its width; the others widen.
|
||||
#[test]
|
||||
fn column_widths_set_by_hand() {
|
||||
let body = r#"<cols><col min="1" max="1" width="15"/><col min="2" max="2" width="15" customWidth="1"/>
|
||||
<col min="3" max="3" width="15" bestFit="1"/><col min="4" max="4" width="15" bestFit="1" customWidth="1"/>
|
||||
<col min="5" max="5" width="9.140625" customWidth="1"/></cols><sheetData/>"#;
|
||||
let (wb, _) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
|
||||
let s = wb.sheet(0).unwrap();
|
||||
let custom: Vec<bool> = (0..5).map(|c| s.cols.get(&c).is_some_and(|i| i.custom)).collect();
|
||||
assert_eq!(custom, [false, true, false, false, true]);
|
||||
assert_eq!(s.col_width(4), s.default_col_width, "E: the default width, but set by hand");
|
||||
// Written back the way Excel writes them.
|
||||
let bytes = crate::write_xlsx(&wb).unwrap();
|
||||
let mut pkg = crate::package::Package::open(&bytes).unwrap();
|
||||
let sheet = pkg.read_xml("xl/worksheets/sheet1.xml").unwrap().unwrap();
|
||||
let flags: Vec<(bool, bool)> =
|
||||
sheet.child("cols").unwrap().kids("col").map(|c| (c.flag("customWidth", false), c.flag("bestFit", false))).collect();
|
||||
assert_eq!(flags, [(true, true), (true, false), (true, true), (true, false)], "C and D are one run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_namespace_and_shared_strings() {
|
||||
let ct = super::CT;
|
||||
|
||||
@@ -112,7 +112,8 @@ fn sample() -> Workbook {
|
||||
s.spill.insert(at("H3"), Value::Number(3.0));
|
||||
|
||||
s.cols.insert(0, LineInfo { size: Some(100.0), ..Default::default() });
|
||||
s.cols.insert(1, LineInfo { size: Some(100.0), ..Default::default() });
|
||||
// Column B was sized by hand (customWidth), A widened by itself; both come back as they were.
|
||||
s.cols.insert(1, LineInfo { size: Some(100.0), custom: true, ..Default::default() });
|
||||
s.cols.insert(3, LineInfo { hidden: true, outline: 1, ..Default::default() });
|
||||
s.cols.insert(5, LineInfo { style: Some(money), ..Default::default() });
|
||||
s.rows.insert(0, LineInfo { size: Some(30.0), ..Default::default() });
|
||||
|
||||
@@ -794,6 +794,19 @@ fn xls_window2_right_to_left_sheet_opens_right_to_left() {
|
||||
assert_eq!(view(&one_sheet_with(&window2(0x0001 | 0x0002 | 0x0010))), (false, true, false, true, true));
|
||||
}
|
||||
|
||||
/// COLINFO's fUserSet marks a width set by hand, which a wider number format leaves alone (#1077).
|
||||
/// craft-xls does not report fBestFit, so fUserSet with fBestFit also reads as set by hand.
|
||||
#[test]
|
||||
fn xls_column_widths_set_by_hand() {
|
||||
let colinfo = |col: u16, flags: u16| rec(0x007D, &u16s(&[col, col, 20 * 256, 0, flags, 0]));
|
||||
let file = one_sheet_with(&cat(&[&colinfo(0, 0x0002), &colinfo(1, 0), &colinfo(2, 0x0006)]));
|
||||
let (wb, _) = read_xls(&file).unwrap();
|
||||
let sh = &wb.sheets[0];
|
||||
let custom: Vec<bool> = (0..3).map(|c| sh.cols.get(&c).is_some_and(|i| i.custom)).collect();
|
||||
assert_eq!(custom, [true, false, true]);
|
||||
assert!((0..3).all(|c| sh.col_width(c) > sh.default_col_width), "all three keep their stored width");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xls_short_window2_is_ignored() {
|
||||
for payload in [&[][..], &[0x40][..], &[0x40, 0][..], &[0x40, 0, 0, 0, 0, 0, 0, 0, 0][..]] {
|
||||
|
||||
@@ -227,11 +227,13 @@ fn sheet_of(s: &x::Sheet, styles: &[StyleId], unparsed: &mut bool) -> Sheet {
|
||||
let px = col_width_to_px(f64::from(c.width) / 256.0);
|
||||
let info = LineInfo {
|
||||
size: (c.custom_width || px != sheet.default_col_width).then_some(px),
|
||||
// fUserSet. craft-xls does not expose fBestFit, so a width AutoFit stored with both
|
||||
// flags also counts as set by hand here (#1077).
|
||||
custom: c.custom_width,
|
||||
hidden: c.hidden,
|
||||
outline: c.outline,
|
||||
collapsed: c.collapsed,
|
||||
style: c.format.map(|f| style(Some(f))).filter(|&id| id != StyleId::DEFAULT),
|
||||
..LineInfo::default()
|
||||
};
|
||||
if info != LineInfo::default() {
|
||||
sheet.cols.insert(u32::from(col), info);
|
||||
|
||||
@@ -127,3 +127,35 @@ so there the caps and the fuzzed input space are the protection. `crates/math/te
|
||||
gate on every test run, so a version bump has to pass it. RaTeX positions glyphs with KaTeX
|
||||
font metrics; GridCraft never bundles the KaTeX fonts, so glyphs are drawn with system fonts
|
||||
and a glyph no font has is drawn as a `[?]` box.
|
||||
|
||||
## Number formats widen columns that weren't sized by hand (#1077)
|
||||
|
||||
Increase/Decrease Decimal, the ribbon's other number formats (the Number Format list, Accounting,
|
||||
Percent, Comma) and a number format set in Format Cells widen a column so the formatted numbers in
|
||||
the target fit, instead of showing `####`.
|
||||
Microsoft's support article "Stop showing rounded numbers" says only that "the column width adjusts
|
||||
automatically", so the rule comes from observing Excel 16.0 (build 17932, Windows) with synthetic
|
||||
workbooks:
|
||||
|
||||
- A column at the default width, AutoFitted, or widened this way before widens to the widest number
|
||||
in the formatted range, also with Wrap Text and a large bold font. It never narrows.
|
||||
- A width set with Column Width (or by dragging the border) stays, even when it equals the default:
|
||||
the number shows `####`. AutoFit makes such a column automatic again.
|
||||
- Hidden columns, text, General numbers (they round to fit instead), merged cells and shrink-to-fit
|
||||
cells don't widen.
|
||||
- In XLSX, Excel writes `customWidth="1"` for every width it stores and adds `bestFit="1"` for widths
|
||||
that AutoFit or a number format set. Only `customWidth` without `bestFit` is read as set by hand: a
|
||||
width with no flags, `bestFit` alone, or both, keeps widening after the file is opened again.
|
||||
|
||||
`LineInfo::custom`, already used for rows set by hand, now marks columns set by hand too; GridCraft
|
||||
writes and reads the two flags as Excel does. In `.xls`, COLINFO's fUserSet marks a column set by
|
||||
hand; the shared craft-xls reader does not report fBestFit, so a `.xls` width with both flags also
|
||||
counts as set by hand.
|
||||
Files that earlier GridCraft versions saved have `customWidth` without `bestFit` on every stored
|
||||
width, so those columns open as set by hand and keep their width.
|
||||
|
||||
The engine has no font metrics, so the width is the same estimate AutoFit Column Width uses, which
|
||||
errs on the wide side; a UI test checks that the real font then draws the number, not `####`.
|
||||
Excel doesn't widen when a value is entered into a cell that already has the format (observed through
|
||||
the `Value` property: the cell shows `####`), and neither does GridCraft. Typing into such a cell
|
||||
wasn't observed.
|
||||
@@ -1,6 +1,6 @@
|
||||
# File-format parity
|
||||
|
||||
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-14 · **Change:** minor (a protection password set in GridCraft keeps both its XLSX form and the SHA-256 digest OpenDocument stores; earlier: the style model keeps a cell's padding, for OpenDocument; XLSX and XLS have none, so they read none and the XLSX writer leaves it out; not drawn yet; earlier: XLSX fonts keep outlined letters, `<outline/>`, through open and save; GridCraft draws them solid; earlier: PDF honours cell reading direction and mirrors right-to-left sheets; earlier: Arabic PDF export no longer fails when a character or the Arabic font is missing; earlier: Arabic PDF text is shaped with embedded Noto Arabic glyphs beside the non-embedded standard, Symbol and CID fonts; earlier: .xls data validation is read; earlier: .xls is read by the shared craft-xls crate: the workbook opens on the sheet it was saved on, and rich-text (RString) cells are read; earlier: form controls: buttons, scroll bars and spin buttons read and written; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-14 · **Change:** minor (XLSX and `.xls` column widths keep whether they were set by hand, so automatic ones still widen for wider number formats, #1077; earlier: a protection password set in GridCraft keeps both its XLSX form and the SHA-256 digest OpenDocument stores; earlier: the style model keeps a cell's padding, for OpenDocument; XLSX and XLS have none, so they read none and the XLSX writer leaves it out; not drawn yet; earlier: XLSX fonts keep outlined letters, `<outline/>`, through open and save; GridCraft draws them solid; earlier: PDF honours cell reading direction and mirrors right-to-left sheets; earlier: Arabic PDF export no longer fails when a character or the Arabic font is missing; earlier: Arabic PDF text is shaped with embedded Noto Arabic glyphs beside the non-embedded standard, Symbol and CID fonts; earlier: .xls data validation is read; earlier: .xls is read by the shared craft-xls crate: the workbook opens on the sheet it was saved on, and rich-text (RString) cells are read; earlier: form controls: buttons, scroll bars and spin buttons read and written; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
|
||||
Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests.
|
||||
Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h**
|
||||
@@ -194,6 +194,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here.
|
||||
| 2026-10-26 | minor | PDF honors cell Context/LTR/RTL, preserves paragraph direction across wrapping, and mirrors RTL sheet geometry without reversing glyphs |
|
||||
| 2026-10-26 | minor | Arabic PDF export embeds licensed glyph outlines, joins letters and marks, preserves logical text and reports unsupported glyphs before writing; Arabic runs take the embedded faces ahead of the CJK CID font, and CJK inside Arabic text is set in the CID font instead of failing the export |
|
||||
| 2026-10-26 | minor | Alignment readingOrder 0/1/2 survives cell, named-style and differential-style round-trips; Format Cells exposes reading direction and CF priority preserves unspecified inheritance |
|
||||
| 2026-10-22 | minor | XLSX column widths: `customWidth` without `bestFit` is a width set by hand, others (AutoFit, widened by a number format) are automatic, as Excel 16.0 reads them; written the same way (`bestFit="1" customWidth="1"` for automatic widths). `.xls` reads COLINFO's fUserSet as set by hand (the shared craft-xls reader does not report fBestFit) (#1077) |
|
||||
| 2026-10-21 | minor | HTML (Save as Web Page) writes pictures (`data:` URI `<img>`) and charts (inline SVG from the chart crate's drawing primitives, text included) at their anchors; the table uses the sheet's column widths and row heights when the sheet has either, and output for sheets without pictures or charts is unchanged |
|
||||
| 2026-10-20 | trivial | XLSX shared strings: Japanese phonetic runs (ふりがな, `<rPh sb="…" eb="…">` with `<phoneticPr>`) are read into the workbook and written back next to the string with the same text, so an open + save no longer deletes them; bad offsets and readings are dropped with a warning, a `<phoneticPr>` without runs is kept on its own, and when duplicate `<si>` items share a text but not a reading only the first reading is written (reported on open) (`phonetic_tests.rs`) |
|
||||
| 2026-10-20 | minor | A workbook theme's major/minor per-script typefaces (`<a:font script="Arab" typeface="…"/>`, also Hebr, Jpan and the rest) are read and written back in file order after `<a:cs>`; they were dropped before. A hostile file is held to 64 entries of 256 characters |
|
||||
|
||||
@@ -211,6 +211,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
|
||||
| 2026-10-22 | minor | §20: a native window per workbook window, New Window on the same workbook and Arrange All on the desktop; left: Arrange All across monitors, the web's one window, pen pressure (estimate 10–14 h → 5–8 h) |
|
||||
| 2026-10-20 | minor | §11: the Japanese catalog covers the dialogs, messages and menus — 943 keys (~43%), matching the pt-BR coverage; a test keeps the two catalogs in step |
|
||||
| 2026-10-17 | minor | §6: the five reports it tracked are closed and their PRs merged (#57, #133, #139, #140, #134; PRs #148, #155, #156, #157); the entry stays open for §15's oracle suite |
|
||||
| 2026-10-17 | minor | Conditional formatting: the 2-/3-colour scale branch of the New Formatting Rule dialog edits per-stop type/value/colour and updates rules in place (part of #1165) |
|
||||
| 2026-10-15 | minor | §6: Maximum Iterations and Maximum Change in File › Options › Formulas; dropped the stale "no Options dialog yet" |
|
||||
| 2026-10-15 | minor | §13: Solver prepares reports before committing the solution, model and report sheets together; report refusal preserves the workbook and Undo/Redo (#1050) |
|
||||
| 2026-10-13 | minor | §3: Excel 2010 conditional formats (`x14:conditionalFormattings`, cross-sheet rules) read, evaluated and written back in the extension |
|
||||
|
||||
@@ -295,7 +295,8 @@ The inventory carried over from the 2026-10-07 ROADMAP.md, updated for what land
|
||||
the fill handle explains how to fill versus select cells.
|
||||
- Formatting: fonts, fills, all border styles, alignment (wrap, indent, rotation, merge), number
|
||||
formats, 47 cell styles, 60 table styles, conditional formatting (cell rules, text, dates,
|
||||
duplicates, top/bottom, averages, data bars, colour scales, icon sets, formulas), automatic
|
||||
duplicates, top/bottom, averages, data bars, colour scales with per-stop type/value/colour
|
||||
editors, icon sets, formulas), automatic
|
||||
row heights, autofit, hide/unhide, freeze panes.
|
||||
Border presets include visual diagrams; Format Cells previews draft borders before applying.
|
||||
- Data: sort (multi-level, by colour, custom lists), AutoFilter (values, custom, top 10,
|
||||
|
||||
+9
-4
@@ -1,6 +1,6 @@
|
||||
# UI parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (a leading + or - starts a formula, #2023; earlier: AutoSum on one cell proposes its range in the editor, #1834; earlier: Quick Analysis, Ctrl+Q (#791); earlier: validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (AutoFit Column Width measures a table's header in the table style's bold font; earlier: ribbon number formats widen columns nobody sized by hand, #1077; earlier: a leading + or - starts a formula, #2023; earlier: AutoSum on one cell proposes its range in the editor, #1834; earlier: Quick Analysis, Ctrl+Q (#791); earlier: validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
|
||||
Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md).
|
||||
**UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured
|
||||
@@ -92,7 +92,7 @@ this logic, with one undo step.
|
||||
| Shortcuts bound to commands | 200+ documented shortcuts per platform | audited below (#110): shortcuts whose feature exists are bound, with the exceptions listed; the rest wait for their features |
|
||||
| Ctrl+arrow, Ctrl+Shift+arrow, Ctrl+Home/End, Ctrl+Shift+Home/End, Page Up/Down, Alt+Page | yes | done |
|
||||
| Ctrl+1, Ctrl+; and Ctrl+Shift+; , Ctrl+D/R, Ctrl+E, Ctrl+T/L, Ctrl+K, Ctrl+Shift+L, Ctrl+Shift+~!@#$%^&_ | yes | done |
|
||||
| F2, F3, F4, F5, F7, F9 family, Shift+F2/F3/F10/F11, F12 | yes | done; F11 chart sheet, F8 extend mode, F4 Repeat missing |
|
||||
| F2, F3, F4, F5, F7, F9 family, Shift+F2/F3/F10/F11, F12 | yes | done; F8 / Shift+F8 extend and add modes with their status bar text; F11 chart sheet, F4 Repeat missing |
|
||||
| Mac-specific (Cmd variants, Control variants, Fn keys) | yes | done where a feature exists (`keymap.rs` picks the Mac variant) |
|
||||
| Sequential Alt access keys (Alt, H, N, …) on every ribbon tab | yes | 364-sequence keytip table for all tabs: per-control badges, prefix waiting, dropdowns open for editing (type/arrows/Enter), pending bindings for not-yet-built commands; letters also work with left Alt held (Alt+H, O, A), as in Excel; each Borders letter (H, B, …) draws its own preset, H, B, M opens Format Cells on the Border tab, and Erase Border, Line Color and Line Style are reserved; QAT/Backstage excluded |
|
||||
| Requests | — | #110 (more shortcuts and hot keys), #33 (sequential Alt; initial support landed in #43) |
|
||||
@@ -147,8 +147,9 @@ A character egui has no key for (`č`, `ö`, `<`) falls back to the key's positi
|
||||
| Shift+F10, Alt+Shift+F10, Ctrl+F1 | Shift+F10, Cmd+Option+R | context menu, Error Checking, ribbon | **added** |
|
||||
| Ctrl+Alt+Shift+P | Cmd+Option+Shift+P | Python mode on or off | **added** |
|
||||
| F3 | not checked | Paste Name dialog, only when the workbook has names: OK puts the name at the caret of the formula being edited (or starts `=Name`), Paste List writes each name and what it refers to from the active cell (`formulas.pasteName`) | **added** |
|
||||
| F1, F4 (repeat), F6 / Shift+F6, F8 / Shift+F8, F11, End mode | same | help, Repeat, pane cycling, extend/add mode, chart sheet | missing (no such feature yet) |
|
||||
| F1, F3, F4 (repeat), F6 / Shift+F6, F8 / Shift+F8, F11, End mode | same | help, Paste Name, Repeat, pane cycling, extend/add mode, chart sheet | missing (no such feature yet) |
|
||||
| F8, Shift+F8 | same | Extend Selection (arrows, Page keys, Ctrl+arrows, Home and clicks extend from the anchor) and Add or Remove Selection (arrows move the active cell and keep the areas, Shift+arrows grow a new area, a click adds or removes an area); the status bar names the mode; the key again, Esc or editing a cell ends it (`ui.selectionMode`) | **added** |
|
||||
| F1, F4 (repeat), F6 / Shift+F6, F11, End mode | same | help, Repeat, pane cycling, chart sheet | missing (no such feature yet) |
|
||||
| F1, F3, F4 (repeat), F6 / Shift+F6, F11, End mode | same | help, Paste Name, Repeat, pane cycling, chart sheet | missing (no such feature yet) |
|
||||
| Ctrl+Q | Control+Q (Cmd+Q stays Quit) | Quick Analysis | **added** (#791) |
|
||||
| Ctrl+A after a function name, Ctrl+Alt+P | same | Function Arguments, tooltips | missing |
|
||||
| Ctrl+Shift+A after a function name | Control+Shift+A | argument names: `=SUMIF(` becomes `=SUMIF(range,criteria,sum_range)`, the `(` added when missing; one Undo takes them back | **added** |
|
||||
@@ -327,6 +328,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
|
||||
| 2026-10-24 | minor | Outline Settings (Data ▸ Outline ▸ Settings, `data.outlineSettings`): clearing Summary rows below detail or Summary columns to right of detail puts the − / + buttons on the line above or left of each group, and Hide Detail, Show Detail and the level buttons mark that line collapsed. Changing a direction moves the marks of collapsed groups. Read and written as `outlinePr summaryBelow` / `summaryRight` |
|
||||
| 2026-10-23 | minor | F3, Formulas › Use in Formula › Paste Names… and Alt+M, S, P open the Paste Name dialog (F3 only when the workbook has names). It lists the workbook's names and the active sheet's own in alphabetical order, hidden names left out; OK or a double-click puts the selected name at the caret of the formula being edited, in place of selected text, or starts `=Name` in the active cell (`formulas.pasteName` `{name}`), and Paste List writes each name and the text of what it refers to in two columns from the active cell (`{list: true}`). While a dialog is open over the edit, the cell editor takes no keys, and Cancel leaves the selected text selected. The Use in Formula menu lists the same names and inserts at the caret too (`formulas.useInFormula`); it used to list hidden names and other sheets' names, the menu added the name at the end of the text, and the command replaced the text being edited |
|
||||
| 2026-10-23 | minor | Conditional Formatting ▸ New Rule, formula: clicking a cell on the grid writes its absolute reference at the formula box's caret (`=$B$2`, an empty box starts with `=`), a drag writes a range (`$B$2:$C$4`) and a second click replaces the reference just written, as in Excel ("Selecting cells on the worksheet inserts absolute cell references"). The selection the rule applies to doesn't move, and the box keeps the keyboard. After an operand (`=A1>5`) the click does nothing (#2348) |
|
||||
| 2026-10-15 | minor | F8 Extend Selection and Shift+F8 Add or Remove Selection modes, shown in the status bar (`ui.selectionMode`) |
|
||||
| 2026-10-23 | minor | Frozen panes: Page Up, Ctrl+Up and Shift variants that move from the scrolled rows into the frozen ones bring the scrolled rows back to the top, so the rows in between are seen again (Page Up from far down used to end on row 1 with the view still a page down); Ctrl+Left and Alt+Page Up do the same for frozen columns. Other ways of selecting a frozen cell (click, Find, Go To, Undo, formula pointing) leave the view where it is |
|
||||
| 2026-10-23 | minor | After a left-drag of the fill handle an Auto Fill Options button sits below the filled cells; its menu redoes the fill as Copy Cells, Fill Series, Fill Formatting Only or Fill Without Formatting (undoes the drag's fill, then `edit.autoFill` in that mode). It goes away when the workbook changes or the selection moves (#1403) |
|
||||
| 2026-10-24 | minor | When the fill starts from a date, the right-drag fill menu and the Auto Fill Options button also offer Fill Days, Fill Weekdays (Saturday and Sunday skipped), Fill Months and Fill Years (`edit.autoFill` with `mode` set to `days`, `weekdays`, `months` or `years`). A lone date steps by one unit; two or more dates step by the difference between the first two in that unit, or one unit when they fall in the same one. Fill Months and Fill Years keep the day of the month, clamped to the month's last day. Every fill by months or years (these two, a drag of dates a month apart, and Series by Month or Year) keeps the time of day of a date with a time, which used to be dropped |
|
||||
@@ -336,6 +338,8 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
|
||||
| 2026-10-22 | minor | One native window per workbook window on the desktop: per-window drafts, dialogs and ribbons; menu bar commands go to the focused window; closing one of several windows on a workbook doesn't ask; Quit asks in each unsaved workbook's window; the last window closed quits (Windows, Linux) or leaves macOS running |
|
||||
| 2026-10-22 | minor | New Window opens a second window on the same workbook instead of a copy that saved over the original; windows keep their own selection, sheet and scroll; titles Name:1 / Name:2; Switch Windows, Hide and Unhide work by window; File › Close closes one window of several without asking |
|
||||
| 2026-10-22 | minor | New workbook no longer loses the first one: the cell being typed is entered into its own workbook before any File or window command (an entry the workbook refuses stays open and the command doesn't run; an untouched F2 draft changes nothing), the editor is tied to its workbook, View › Switch Windows and the macOS Window menu list the open workbooks, and the macOS Quit item asks about unsaved workbooks like the close button |
|
||||
| 2026-10-22 | minor | AutoFit Column Width measures a table's cells in the font the table style draws them in, so a bold header row is fitted bold; it measured the cell's own, plain font and could leave a bold heading too narrow |
|
||||
| 2026-10-22 | minor | Increase/Decrease Decimal, the ribbon's other number formats (Number Format list, Accounting, Percent, Comma) and Format Cells' number formats widen a column nobody sized by hand so the numbers fit, instead of showing #### (#1077). As observed in Excel 16.0: AutoFit counts as automatic, Column Width or dragging the border as by hand; hidden columns, text, General numbers, merged and shrink-to-fit cells don't widen, and columns never narrow |
|
||||
| 2026-10-21 | minor | Typing into a cell with an in-cell list validation shows the list filtered to entries with a word starting with the typed text (case and Latin accents ignored, Vietnamese included, list order kept, only visible rows drawn); Up/Down move the highlight, Enter/Tab/click commit it with the list's spelling, Escape hides the list before cancelling. Column AutoComplete is off for those cells. New query command `data.validationList` |
|
||||
| 2026-10-21 | minor | Background error checking, first part (#1994): a constant whose text would be a number if typed (signs, thousands, currency, percent, exponent, parenthesised negative) gets Excel's green corner triangle; the active cell then shows a warning button whose menu names the problem and offers Convert to Number for the selection (`formulas.convertToNumber`). Dates, times and fractions kept as text and formula results are not flagged, as in Excel |
|
||||
| 2026-10-21 | minor | Paste Special laid out as Excel's: Paste and Operation options each in two columns inside a frame, Skip blanks and Transpose side by side, Paste Link as a button that pastes references at once; labels translated (the generic form didn't translate them) and the window no longer runs past the screen |
|
||||
@@ -346,6 +350,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
|
||||
| 2026-10-18 | minor | Keytip letters typed with left Alt held continue the sequence (Alt+H, O, A / Alt+H, O, I ran nothing before: Alt+letter cancelled keytips); other Alt combinations, AltGr and macOS Option are unchanged (#1846) |
|
||||
| 2026-10-14 | minor | Punctuation shortcuts follow the character the keyboard layout types, digits keep their position: on a Croatian or German keyboard Ctrl+Shift+, (`;`) inserts the date instead of decreasing the font size, Ctrl+Shift+. (`:`) the time, Ctrl++ opens Insert, Ctrl+' copies the formula above, and Ctrl+Shift+0 (`=`) unhides columns instead of opening Insert |
|
||||
| 2026-10-17 | minor | A Ctrl+Alt+letter key that types a character (a user-defined Windows hotkey such as Ctrl+Alt+A for `ä`) types it instead of running the Ctrl+letter shortcut, e.g. Select All (#1530) |
|
||||
| 2026-10-17 | minor | Conditional formatting: 2-/3-colour scale editor with per-stop type/value/colour, reached from New Rule… → Format all cells based on their values and Color Scales › More Rules…; Manage Rules edits a scale in place (part of #1165) |
|
||||
| 2026-10-16 | minor | Right-drag on the fill handle opens the fill menu on release: Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, Series…; Esc cancels the drag or closes the menu without filling |
|
||||
| 2026-10-16 | minor | With the active cell in a Table whose header row is scrolled out of view, the column headings show the header names and their filter buttons in place of the letters (#1423) |
|
||||
| 2026-10-16 | minor | Custom Sort dialog: Sort by columns are a dropdown of the header names (Column A, B… without headers), Order follows the data (A to Z or Smallest to Largest), levels can be added, deleted, copied and reordered, the window moves and resizes, the grid selection follows "My list has headers" and is restored on close |
|
||||
|
||||
Reference in new issue
Block a user