table: identify the source of out-of-range resize indices (#2560)

This commit is contained in:
Zaxaerith
2026-12-03 04:43:24 +08:00
parent e7b67fb029
commit 239f293ca7
2 changed files with 77 additions and 9 deletions
+41 -9
View File
@@ -267,12 +267,31 @@ fn cell_param(p: &Value, key: &str, cmd: &str) -> Result<Option<(usize, usize)>>
}
}
/// The table's row/col to act on: params, the edited cell, or the selected cells.
/// A present but invalid `row`/`col` is an error; only an absent one falls back.
fn at(s: &Session, p: &Value, cmd: &str) -> Result<(usize, usize)> {
enum TableIndex {
Explicit(usize),
Selected(usize),
Default,
}
impl TableIndex {
fn value(&self) -> usize {
match *self {
Self::Explicit(i) | Self::Selected(i) => i,
Self::Default => 0,
}
}
}
/// Resolve each axis from its parameter, the edited or selected cell, then index zero.
/// Invalid parameters are rejected before any fallback.
fn at(s: &Session, p: &Value, cmd: &str) -> Result<(TableIndex, TableIndex)> {
let st = s.active();
let cell = st.and_then(|d| d.selection.text.as_ref().and_then(|t| t.cell)).or_else(|| st.and_then(|d| d.selection.cells.map(|c| c.1)));
Ok((opt_usize_param(p, "row", cmd)?.or(cell.map(|c| c.0)).unwrap_or(0), opt_usize_param(p, "col", cmd)?.or(cell.map(|c| c.1)).unwrap_or(0)))
let resolve = |key, selected: Option<usize>| -> Result<TableIndex> {
let explicit = opt_usize_param(p, key, cmd)?;
Ok(explicit.map(TableIndex::Explicit).or(selected.map(TableIndex::Selected)).unwrap_or(TableIndex::Default))
};
Ok((resolve("row", cell.map(|c| c.0))?, resolve("col", cell.map(|c| c.1))?))
}
fn with_table(s: &mut Session, p: &Value, cmd: &str, f: impl Fn(&mut Table) -> Result<()>) -> Result<Value> {
@@ -328,6 +347,7 @@ fn with_table(s: &mut Session, p: &Value, cmd: &str, f: impl Fn(&mut Table) -> R
fn rows_cols(s: &mut Session, p: &Value, op: &str, name: &'static str) -> Result<Value> {
let (r, c) = at(s, p, name)?;
let (r, c) = (r.value(), c.value());
// Absent: the table grows, as in PowerPoint; present, it must be a bool, so a mistyped value is refused
// rather than silently taken as the default.
let keep_width = match (op, p.get("keepWidth")) {
@@ -465,7 +485,10 @@ fn merge(s: &mut Session, p: &Value) -> Result<Value> {
fn split(s: &mut Session, p: &Value) -> Result<Value> {
let cell = match cell_param(p, "cell", "table.split")? {
Some(c) => c,
None => at(s, p, "table.split")?,
None => {
let (r, c) = at(s, p, "table.split")?;
(r.value(), c.value())
}
};
with_table(s, p, "table.split", move |t| if t.split(cell.0, cell.1) { Ok(()) } else { Err(bad("table.split", "that cell isn't merged")) })
}
@@ -727,8 +750,17 @@ fn distribute(s: &mut Session, p: &Value, rows: bool) -> Result<Value> {
/// A row or column the table doesn't have is an error, like a malformed index (#2260): checked
/// inside the edit, so a refused resize changes nothing and adds no undo step.
fn index_in_table(cmd: &str, key: &str, i: usize, n: usize, what: &str) -> Result<()> {
if i < n { Ok(()) } else { Err(bad(cmd, format!("`{key}` {i} is out of range: the table has {n} {what}"))) }
fn index_in_table(cmd: &str, key: &str, index: &TableIndex, n: usize, axis: &str) -> Result<usize> {
let i = index.value();
if i < n {
return Ok(i);
}
let source = match index {
TableIndex::Explicit(_) => format!("`{key}` {i}"),
TableIndex::Selected(_) => format!("the selected cell's {axis} {i}"),
TableIndex::Default => format!("the default {axis} {i}"),
};
Err(bad(cmd, format!("{source} is out of range: the table has {n} {axis}s")))
}
fn column_width(s: &mut Session, p: &Value) -> Result<Value> {
@@ -736,7 +768,7 @@ fn column_width(s: &mut Session, p: &Value) -> Result<Value> {
let w = f64_param(p, "width").ok_or_else(|| bad("table.columnWidth", "missing `width`"))?.clamp(4.0, 4000.0);
let keep_total = bool_or(p, "keepTotal", false);
with_table(s, p, "table.columnWidth", move |t| {
index_in_table("table.columnWidth", "col", c, t.n_cols(), "columns")?;
let c = index_in_table("table.columnWidth", "col", &c, t.n_cols(), "column")?;
// Keeping the table's width, the column to the right gives or takes the difference (dragging
// an inner border). The last column has none: the table gets wider or narrower.
let pair = t.cols.get(c).zip(t.cols.get(c.saturating_add(1))).map(|(a, b)| a.max(0.0) + b.max(0.0)).filter(|x| x.is_finite());
@@ -765,7 +797,7 @@ fn row_height(s: &mut Session, p: &Value) -> Result<Value> {
let (r, _) = at(s, p, "table.rowHeight")?;
let h = f64_param(p, "height").ok_or_else(|| bad("table.rowHeight", "missing `height`"))?.clamp(4.0, 4000.0);
with_table(s, p, "table.rowHeight", move |t| {
index_in_table("table.rowHeight", "row", r, t.n_rows(), "rows")?;
let r = index_in_table("table.rowHeight", "row", &r, t.n_rows(), "row")?;
if let Some(x) = t.rows.get_mut(r) {
x.height = h;
}
+36
View File
@@ -6128,6 +6128,8 @@ fn table_resize_rejects_a_row_or_column_past_the_table() {
let (undo, redo) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().history.redo.len());
let e = s.execute(cmd, &params).expect_err(&format!("{cmd} {params} should be rejected"));
assert!(e.to_string().contains(cmd), "the error should name {cmd}: {e}");
let key = if params.get("row").is_some() { "row" } else { "col" };
assert!(e.to_string().contains(&format!("`{key}`")), "the error should name the explicit parameter: {e}");
assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &doc), "{cmd} {params} must leave the presentation unchanged");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{cmd} {params} must not add an undo step");
assert_eq!(s.doc().unwrap().history.redo.len(), redo, "{cmd} {params} must keep the redo step");
@@ -6137,6 +6139,40 @@ fn table_resize_rejects_a_row_or_column_past_the_table() {
assert_eq!(table_of(&s, id).rows.first().map(|r| r.height), Some(30.0), "the redo step is still the row height");
}
#[test]
fn table_resize_names_the_source_of_an_out_of_range_implicit_index() {
let mut s = session();
let source = table_at(&mut s, &[100.0, 100.0], json!([["a", "b"], ["c", "d"]]));
let target = table_at(&mut s, &[100.0], json!([["e"]]));
let check = |s: &mut Session, row_error: &str, column_error: &str| {
let before = s.doc().unwrap();
let doc = before.doc.clone();
let history = (before.history.undo.len(), before.history.redo.len());
for (cmd, params, expected) in [
("table.rowHeight", json!({"id": target.0, "height": 50.0}), row_error),
("table.columnWidth", json!({"id": target.0, "width": 50.0}), column_error),
] {
let err = s.execute(cmd, &params).unwrap_err().to_string();
assert!(err.contains(expected), "{cmd}: {err}");
let after = s.doc().unwrap();
assert!(std::sync::Arc::ptr_eq(&after.doc, &doc), "{cmd} must leave the presentation unchanged");
assert_eq!((after.history.undo.len(), after.history.redo.len()), history);
}
};
s.execute("table.selectCells", &json!({"id": source.0, "from": [1, 1]})).unwrap();
check(&mut s, "the selected cell's row 1 is out of range", "the selected cell's column 1 is out of range");
s.execute("edit.deselect", &json!({})).unwrap();
// A table without rows or columns has no index zero to fall back to.
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let slide = std::sync::Arc::make_mut(&mut doc.slides[0]);
let deckcraft_model::ShapeKind::Table(table) = &mut slide.shape_mut(target).unwrap().kind else { panic!("not a table") };
table.rows.clear();
table.cols.clear();
check(&mut s, "the default row 0 is out of range", "the default column 0 is out of range");
}
#[test]
fn table_resize_in_range_still_works() {
let mut s = session();