mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-03 08:51:30 -06:00
Merge current main into PR2597 for hosted validation
This commit is contained in:
@@ -46,7 +46,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Values",
|
||||
[],
|
||||
None,
|
||||
"{range?: \"A1\", values: [[...]] (rows of numbers/strings/bools/null; strings starting with = are formulas), parse?: bool (default true: a string goes through typed input, so \"05.04.2026\" becomes a date and \"2.500\" a number, by en-US rules; false stores every other string as the text it is, so a dd.mm.yyyy date or a thousands separator survives)}",
|
||||
"{range?: \"A1\", values: [[...]] (rows of numbers/strings/bools/null; strings starting with = are formulas), parse?: bool (default true: a string goes through typed input, so \"05.04.2026\" becomes a date and \"2.500\" a number, by en-US rules; false stores every other string as the text it is, so a dd.mm.yyyy date or a thousands separator survives, a leading ' is kept and an empty string clears the cell)} → {cells, convertedCount, converted: [{cell, input, stored}] (up to 20 of the strings typed input read as a number, date, time, boolean or error, so a script can notice)}",
|
||||
has_doc,
|
||||
range_set_values
|
||||
),
|
||||
|
||||
@@ -183,6 +183,22 @@ pub(crate) fn json_to_input(v: &Json) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many converted strings `range.setValues` reports back, and how much of each input and
|
||||
/// stored text: the report is a diagnostic, so a big write must not put a second copy of its data
|
||||
/// in the result.
|
||||
const MAX_REPORTED_CONVERSIONS: usize = 20;
|
||||
const MAX_REPORTED_CHARS: usize = 32;
|
||||
|
||||
/// `text` cut to [`MAX_REPORTED_CHARS`] characters for the conversion report, with `…` when it was
|
||||
/// cut. Counting characters keeps a multi-byte input whole.
|
||||
fn clipped(text: &str) -> String {
|
||||
let mut out: String = text.chars().take(MAX_REPORTED_CHARS).collect();
|
||||
if out.len() < text.len() {
|
||||
out.push('…');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(super) fn range_set_values(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let start = target_range(s, p)?.start;
|
||||
@@ -200,6 +216,10 @@ pub(super) fn range_set_values(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
return Err(bad("range.setValues", "too many rows"));
|
||||
}
|
||||
let mut count = 0;
|
||||
// The strings typed input read as something other than the text given, for the result: a
|
||||
// caller can notice a "05.04.2026" that became a date without reading the file back (#2255).
|
||||
let mut converted: Vec<(CellRef, String)> = Vec::new();
|
||||
let mut converted_count = 0;
|
||||
edit(s, |cx| {
|
||||
for (ri, row) in rows.iter().enumerate() {
|
||||
let cols: Vec<&Json> = match row.as_array() {
|
||||
@@ -222,15 +242,35 @@ pub(super) fn range_set_values(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
// text rather than the marker that makes it text. A formula is still a
|
||||
// formula, which is what the ticket asks for and what `=` means in a cell.
|
||||
Json::String(text) if !parse && !text.starts_with('=') => {
|
||||
let mut style = cx.wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default();
|
||||
// Line breaks still turn on Wrap Text, as typed input does.
|
||||
if text.contains('\n') && !cx.wb.styles.get(style).align.wrap {
|
||||
style = cx.wb.styles.derive(style, |s| s.align.wrap = true);
|
||||
if text.is_empty() {
|
||||
// An empty string clears the cell, as `null` and the default path do:
|
||||
// an empty text cell is not blank, and a script clearing cells with
|
||||
// `""` would leave cells `COUNTA` counts. The cell keeps its formatting.
|
||||
input_to_cell("", sheet, at, &mut cx.wb)?
|
||||
} else {
|
||||
let mut style = cx.wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default();
|
||||
// Line breaks still turn on Wrap Text, as typed input does.
|
||||
if text.contains('\n') && !cx.wb.styles.get(style).align.wrap {
|
||||
style = cx.wb.styles.derive(style, |s| s.align.wrap = true);
|
||||
}
|
||||
Some(Cell { value: Value::Text(text.as_str().into()), formula: None, style })
|
||||
}
|
||||
Some(Cell { value: Value::Text(text.as_str().into()), formula: None, style })
|
||||
}
|
||||
_ => input_to_cell(&input, sheet, at, &mut cx.wb)?,
|
||||
};
|
||||
// A string that became a formula was written as one (`=`), which is deliberate;
|
||||
// only a number (dates and times included), boolean or error is a reading of the
|
||||
// string and worth reporting.
|
||||
if let Some(c) = &cell
|
||||
&& matches!(v, Json::String(_))
|
||||
&& c.formula.is_none()
|
||||
&& matches!(c.value, Value::Number(_) | Value::Bool(_) | Value::Error(_))
|
||||
{
|
||||
converted_count += 1;
|
||||
if converted.len() < MAX_REPORTED_CONVERSIONS {
|
||||
converted.push((at, input.clone()));
|
||||
}
|
||||
}
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
match cell {
|
||||
Some(c) => sh.set_cell(at, c),
|
||||
@@ -245,7 +285,17 @@ pub(super) fn range_set_values(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"cells": count}))
|
||||
let d = s.doc()?;
|
||||
let reported: Vec<Json> =
|
||||
d.wb.sheet(sheet)
|
||||
.map(|sh| {
|
||||
converted
|
||||
.iter()
|
||||
.map(|(at, input)| json!({"cell": at.a1(), "input": clipped(input), "stored": clipped(&crate::display::cell_text(&d.wb, sh, *at))}))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
Ok(json!({"cells": count, "convertedCount": converted_count, "converted": reported}))
|
||||
}
|
||||
|
||||
pub(super) fn range_fill(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
@@ -192,6 +192,74 @@ fn set_values_can_store_strings_as_the_text_they_are() {
|
||||
assert!(d.wb.styles.get(sh.style_id(CellRef::parse("A9").unwrap())).align.wrap);
|
||||
}
|
||||
|
||||
/// The result names the strings typed input read as something else, so a script notices without
|
||||
/// reading the file back (#2255). A formula and a leading apostrophe are not conversions.
|
||||
#[test]
|
||||
fn set_values_reports_the_strings_typed_input_read() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let row = json!(["05.04.2026", "02/11/2026", "2.500", "4.25 %", "=1+1", "'keep"]);
|
||||
let r = s.execute("range.setValues", json!({"range": "A1", "values": [row.clone()]})).unwrap();
|
||||
assert_eq!(r["cells"], 6, "{r}");
|
||||
assert_eq!(r["convertedCount"], 4, "{r}");
|
||||
assert_eq!(r["converted"][0], json!({"cell": "A1", "input": "05.04.2026", "stored": "5/4/2026"}), "{r}");
|
||||
assert_eq!(r["converted"][1], json!({"cell": "B1", "input": "02/11/2026", "stored": "2/11/2026"}), "{r}");
|
||||
assert_eq!(r["converted"][2], json!({"cell": "C1", "input": "2.500", "stored": "2.5"}), "{r}");
|
||||
assert_eq!(r["converted"][3], json!({"cell": "D1", "input": "4.25 %", "stored": "4.25%"}), "{r}");
|
||||
// The report is a diagnostic, not a second copy of the data: a long input is cut.
|
||||
let long = s.execute("range.setValues", json!({"range": "J1", "values": [["9".repeat(100)]]})).unwrap();
|
||||
assert_eq!(long["convertedCount"], 1, "{long}");
|
||||
let input = long["converted"][0]["input"].as_str().unwrap_or_default();
|
||||
assert_eq!(input.chars().count(), 33, "32 characters and the ellipsis: {input}");
|
||||
assert!(input.ends_with('…'), "{input}");
|
||||
// Nothing is read with `parse: false`, so nothing is reported.
|
||||
let verbatim = s.execute("range.setValues", json!({"range": "A3", "parse": false, "values": [row]})).unwrap();
|
||||
assert_eq!(verbatim["convertedCount"], 0, "{verbatim}");
|
||||
assert_eq!(verbatim["converted"], json!([]), "{verbatim}");
|
||||
}
|
||||
|
||||
/// An empty string clears the cell with `parse: false` too, as `null` and the default path do: a
|
||||
/// script clearing cells with "" must not leave cells `COUNTA` counts.
|
||||
#[test]
|
||||
fn set_values_parse_false_clears_an_empty_string() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1:B1", "values": [["keep", "keep"]]})).unwrap();
|
||||
s.execute("home.bold", json!({"range": "A1"})).unwrap();
|
||||
s.execute("range.setValues", json!({"range": "A1", "parse": false, "values": [["", ""]]})).unwrap();
|
||||
let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap();
|
||||
assert_eq!(get(&mut s, "A1")["type"], "empty");
|
||||
assert_eq!(get(&mut s, "B1")["type"], "empty");
|
||||
let d = s.doc().unwrap();
|
||||
let sh = d.wb.sheet(0).unwrap();
|
||||
assert!(d.wb.styles.get(sh.style_id(CellRef::parse("A1").unwrap())).font.bold, "clearing with \"\" keeps the formatting");
|
||||
assert_eq!(s.execute("formulas.evaluate", json!({"formula": "=COUNTA(A1:B1)"})).unwrap(), json!(0.0));
|
||||
}
|
||||
|
||||
/// The text `parse: false` stores is still text after the workbook is saved and reopened, and the
|
||||
/// default's reading of a date survives as a date (#2255).
|
||||
#[test]
|
||||
fn set_values_text_survives_an_xlsx_roundtrip() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let values = json!([["05.04.2026", "2.500", "4.25 %", "=1+1", 3, true]]);
|
||||
s.execute("range.setValues", json!({"range": "A1", "parse": false, "values": values})).unwrap();
|
||||
s.execute("range.setValues", json!({"range": "A3", "values": [["05.04.2026"]]})).unwrap();
|
||||
let bytes = crate::io::save_bytes(&s.doc().unwrap().wb, "book.xlsx").unwrap();
|
||||
let (wb, _) = crate::io::open_bytes("book.xlsx", &bytes).unwrap();
|
||||
let sh = wb.sheet(0).unwrap();
|
||||
for (col, want) in [(0, "05.04.2026"), (1, "2.500"), (2, "4.25 %")] {
|
||||
assert_eq!(sh.value(CellRef::new(0, col)), Value::text(want), "column {col} is the text it was given");
|
||||
}
|
||||
assert_eq!(sh.value(CellRef::new(0, 3)), Value::number(2.0), "=1+1 is still a formula");
|
||||
assert_eq!(sh.value(CellRef::new(0, 4)), Value::number(3.0));
|
||||
assert_eq!(sh.value(CellRef::new(0, 5)), Value::Bool(true));
|
||||
// The default read the date, and the file keeps it as one.
|
||||
let at = CellRef::new(2, 0);
|
||||
assert_eq!(crate::display::cell_text(&wb, sh, at), "5/4/2026");
|
||||
assert_eq!(wb.styles.get(sh.style_id(at)).num_fmt.as_str(), "m/d/yyyy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_array_entry() {
|
||||
let mut s = Session::new();
|
||||
|
||||
Reference in New Issue
Block a user