diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs index 0034645f8..5d0ad0237 100644 --- a/crates/engine/src/cmd/table.rs +++ b/crates/engine/src/cmd/table.rs @@ -1,7 +1,7 @@ //! Table Design and Table Layout tabs. use deckcraft_geom::{Affine, Point, Rect}; -use deckcraft_model::{Shape, ShapeKind, Table}; +use deckcraft_model::{Cell, Shape, ShapeKind, Table}; use serde_json::{Value, json}; use super::{ @@ -24,18 +24,24 @@ pub fn specs() -> Vec { "rowBelow", "table.insertRowBelow" )), - cmd!("table.insertColumnLeft", "Insert Left", ["Table Layout", "Rows & Columns"], None, "{col?, id?}", has_selection, |s, p| rows_cols( - s, - p, - "colLeft", - "table.insertColumnLeft" - )), - cmd!("table.insertColumnRight", "Insert Right", ["Table Layout", "Rows & Columns"], None, "{col?, id?}", has_selection, |s, p| rows_cols( - s, - p, - "colRight", - "table.insertColumnRight" - )), + cmd!( + "table.insertColumnLeft", + "Insert Left", + ["Table Layout", "Rows & Columns"], + None, + "{col?, keepWidth?: bool (default false, as in PowerPoint: the table grows by the new column and the other widths stay; true: the other columns shrink in proportion so the table keeps its width), id?} the new column takes the width and cell formatting (fill, margins, anchor, text properties) of the column it is inserted beside", + has_selection, + |s, p| rows_cols(s, p, "colLeft", "table.insertColumnLeft") + ), + cmd!( + "table.insertColumnRight", + "Insert Right", + ["Table Layout", "Rows & Columns"], + None, + "{col?, keepWidth?: bool (default false, as in PowerPoint: the table grows by the new column and the other widths stay; true: the other columns shrink in proportion so the table keeps its width), id?} the new column takes the width and cell formatting (fill, margins, anchor, text properties) of the column it is inserted beside", + has_selection, + |s, p| rows_cols(s, p, "colRight", "table.insertColumnRight") + ), cmd!("table.deleteRow", "Delete Rows", ["Table Layout", "Rows & Columns"], None, "{row?, id?}", has_selection, |s, p| rows_cols( s, p, @@ -322,6 +328,15 @@ 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 { let (r, c) = at(s, p, name)?; + // 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")) { + (_, None) | (_, Some(Value::Null)) => false, + (_, Some(Value::Bool(b))) => *b, + ("colLeft", Some(_)) => return Err(bad("table.insertColumnLeft", "`keepWidth` must be true or false")), + ("colRight", Some(_)) => return Err(bad("table.insertColumnRight", "`keepWidth` must be true or false")), + _ => false, + }; let op = op.to_string(); with_table(s, p, name, move |t| { match op.as_str() { @@ -329,8 +344,8 @@ fn rows_cols(s: &mut Session, p: &Value, op: &str, name: &'static str) -> Result let ok = match op.as_str() { "rowAbove" => t.insert_row(r), "rowBelow" => t.insert_row(r.saturating_add(1)), - "colLeft" => t.insert_col(c), - _ => t.insert_col(c.saturating_add(1)), + "colLeft" => insert_col_like(t, c, c, keep_width), + _ => insert_col_like(t, c.saturating_add(1), c, keep_width), }; if !ok { return Err(bad(name, format!("the table is at its {}-cell limit", deckcraft_model::table::MAX_CELLS))); @@ -351,6 +366,90 @@ fn rows_cols(s: &mut Session, p: &Value, op: &str, name: &'static str) -> Result }) } +/// Insert a column before `at` that looks like column `neighbour` (the one it is inserted beside): +/// its width, and in every row the neighbour cell's explicit formatting with no text. With +/// `keep_width` the columns then shrink in proportion so the table keeps its total width; +/// otherwise (PowerPoint's behaviour) the table grows by the new column and the widths stay. +/// Returns false, leaving the table as it was, when the column would take it past the cell limit. +fn insert_col_like(t: &mut Table, at: usize, neighbour: usize, keep_width: bool) -> bool { + let total = t.width(); + let neighbour = neighbour.min(t.cols.len().saturating_sub(1)); + let w = t.cols.get(neighbour).copied(); + // A neighbour covered by a merge (horizontally or vertically) is formatted as its anchor, which is what shows. + let covered = |r: usize, c: usize| t.rows.get(r).and_then(|row| row.cells.get(c)).is_some_and(|x| x.h_merge || x.v_merge); + let templates: Vec> = (0..t.rows.len()) + .map(|r0| { + let (mut r, mut n) = (r0, neighbour); + while covered(r, n) { + let cell = &t.rows[r].cells[n]; + if cell.h_merge && n > 0 { + n -= 1; + } else if cell.v_merge && r > 0 { + r -= 1; + } else { + break; + } + } + // Only the formatting is kept: the anchor's text is not copied once per covered row. + t.rows[r].cells.get(n).map(|src| { + let mut tpl = Cell::new(""); + copy_cell_format(&mut tpl, src); + tpl + }) + }) + .collect(); + if !t.insert_col(at) { + return false; + } + let at = at.min(t.cols.len().saturating_sub(1)); + if let (Some(w), Some(slot)) = (w, t.cols.get_mut(at)) { + *slot = w; + } + for (row, tpl) in t.rows.iter_mut().zip(templates) { + if let (Some(cell), Some(tpl)) = (row.cells.get_mut(at), tpl) { + copy_cell_format(cell, &tpl); + } + } + let grown = t.width(); + if keep_width && total > 1e-9 && grown > 1e-9 { + let k = total / grown; + for cw in &mut t.cols { + *cw *= k; + } + } + true +} + +/// `dst` takes `src`'s formatting (fill, borders, margins, anchor, text direction and the text +/// properties of its first paragraph, kept on the end mark of an empty paragraph) and keeps its +/// own spans and merge cover. Hyperlinks are not copied. +fn copy_cell_format(dst: &mut Cell, src: &Cell) { + dst.fill.clone_from(&src.fill); + dst.borders.clone_from(&src.borders); + dst.diag_down.clone_from(&src.diag_down); + dst.diag_up.clone_from(&src.diag_up); + dst.margins = src.margins; + dst.anchor = src.anchor; + dst.vertical = src.vertical; + dst.anchor_ctr = src.anchor_ctr; + dst.horz_overflow = src.horz_overflow; + let para = src.text.paragraphs.first().map(|p0| { + let mut end_props = p0.runs.first().map_or_else(|| p0.end_props.clone(), |r| r.props.clone()); + end_props.link = None; + end_props.hover = None; + let mut def_props = p0.def_props.clone(); + def_props.link = None; + def_props.hover = None; + deckcraft_model::text::Paragraph { level: p0.level, props: p0.props.clone(), runs: vec![], def_props, end_props } + }); + let mut list_style = src.text.list_style.clone(); + for l in list_style.levels.iter_mut().flatten() { + l.run.link = None; + l.run.hover = None; + } + dst.text = deckcraft_model::text::TextBody { body: src.text.body.clone(), list_style, paragraphs: vec![para.unwrap_or_default()] }; +} + fn merge(s: &mut Session, p: &Value) -> Result { let sel = s.doc()?.selection.cells; let from = cell_param(p, "from", "table.merge")?.or(sel.map(|c| c.1)).ok_or_else(|| bad("table.merge", "missing `from`"))?; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7d0f92259..5ad0ac5ec 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7328,6 +7328,160 @@ fn master_body_placeholder_format_keeps_per_level_formatting() { assert_eq!(shown(&s), vec![Some(28.0), Some(24.0)]); } +/// A `keepWidth` that is not a bool is refused, naming it, and the table is left alone, not read +/// as the default (the table growing by the new column). +#[test] +fn table_insert_column_refuses_a_keep_width_that_is_not_a_bool() { + let mut s = session(); + let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"]])); + for (cmd, bad) in [("table.insertColumnRight", json!("false")), ("table.insertColumnLeft", json!(0))] { + let err = s.execute(cmd, &json!({"id": id.0, "col": 1, "keepWidth": bad})).unwrap_err().to_string(); + assert!(err.contains("keepWidth") && err.contains(cmd), "{err}"); + let t = table_of(&s, id); + assert_eq!(t.n_cols(), 3, "{cmd} changed the table: {:?}", t.cols); + assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width()); + } +} + +#[test] +fn table_insert_column_with_keep_width_keeps_the_table_width_and_copies_the_neighbour_format() { + let mut s = session(); + let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"], ["d", "e", "f"]])); + s.execute("table.cellFill", &json!({"id": id.0, "color": "#FF0000", "cells": [[0, 2], [1, 2]]})).unwrap(); + s.execute("table.cellMargins", &json!({"id": id.0, "left": 20, "right": 20, "top": 5, "bottom": 5, "cells": [[0, 2]]})).unwrap(); + s.execute("table.cellAlign", &json!({"id": id.0, "anchor": "bottom", "cells": [[0, 2]]})).unwrap(); + s.execute("edit.select", &json!({"ids": [id.0]})).unwrap(); + s.execute("table.selectCells", &json!({"from": [0, 2], "to": [1, 2]})).unwrap(); + s.execute("format.bold", &json!({"on": true})).unwrap(); + // Right of the last column: four columns in the same 840 pt, the new one as wide as its + // neighbour, the others shrunk to make room. + s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 2, "keepWidth": true})).unwrap(); + let t = table_of(&s, id); + assert_eq!(t.n_cols(), 4); + assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width()); + assert!(t.cols.iter().all(|w| (w - 210.0).abs() < 1e-6), "{:?}", t.cols); + let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap(); + assert!((x.w - 840.0).abs() < 1e-6, "frame {}", x.w); + // The new cells take the neighbour's explicit formatting. + let new = t.cell(0, 3).unwrap(); + assert_eq!(new.fill, Some(deckcraft_model::Fill::solid(deckcraft_model::ColorRef::rgb(deckcraft_color::Rgba::rgb(255, 0, 0))))); + assert_eq!(new.margins, Some([20.0, 20.0, 5.0, 5.0])); + assert_eq!(new.anchor, Some(deckcraft_model::text::Anchor::Bottom)); + assert_eq!(new.text.text(), "", "the new cell is empty"); + let bold = new.text.paragraphs.first().map(|p| p.end_props.bold.or(p.def_props.bold)); + assert_eq!(bold, Some(Some(true)), "the neighbour's bold carries over: {:?}", new.text); + assert_eq!(t.cell(1, 3).unwrap().fill, t.cell(1, 2).unwrap().fill); + // Left of the first column: the neighbour is the old first column. + s.execute("table.insertColumnLeft", &json!({"id": id.0, "col": 0, "keepWidth": true})).unwrap(); + let t = table_of(&s, id); + assert_eq!(t.n_cols(), 5); + assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width()); + assert_eq!(t.cell(0, 1).unwrap().text.text(), "a"); + assert_eq!(t.cell(0, 0).unwrap().fill, None); + // keepWidth: false grows the table by the neighbour's width, as before. + s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 4, "keepWidth": false})).unwrap(); + let t = table_of(&s, id); + assert_eq!(t.n_cols(), 6); + assert!((t.width() - 840.0 - 168.0).abs() < 1e-6, "width {}", t.width()); + // The insertion is journaled as called, and each one is a single undo step back to the table + // as it was: the columns, their widths and the frame. + let (jid, jp) = s.journal.last().cloned().unwrap(); + assert_eq!(jid, "table.insertColumnRight"); + assert_eq!(jp["keepWidth"], json!(false), "{jp}"); + s.execute("edit.undo", &json!({})).unwrap(); + let t = table_of(&s, id); + assert_eq!(t.n_cols(), 5); + assert!((t.width() - 840.0).abs() < 1e-6, "width {}", t.width()); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let t = table_of(&s, id); + assert_eq!(t.n_cols(), 3); + assert!(t.cols.iter().all(|w| (w - 280.0).abs() < 1e-6), "{:?}", t.cols); + assert_eq!(t.cell(0, 2).unwrap().text.text(), "c"); + let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap(); + assert!((x.w - 840.0).abs() < 1e-6, "frame {}", x.w); +} + +#[test] +fn table_insert_column_beside_a_merge_copies_the_anchor_format() { + let mut s = session(); + let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"], ["d", "e", "f"]])); + s.execute("table.cellFill", &json!({"id": id.0, "color": "#FF0000", "cells": [[0, 0]]})).unwrap(); + s.execute("table.merge", &json!({"id": id.0, "from": [0, 0], "to": [0, 1]})).unwrap(); + // Right of the merge: the neighbour column holds the covered cell, but the anchor shows. + s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 1})).unwrap(); + let t = table_of(&s, id); + assert!(t.cell(0, 1).unwrap().h_merge, "the merge stays put"); + assert_eq!(t.cell(0, 2).unwrap().fill, t.cell(0, 0).unwrap().fill); + assert!(t.cell(0, 2).unwrap().fill.is_some()); +} + +#[test] +fn table_insert_column_beside_a_two_row_merge_copies_the_anchor_format() { + let mut s = session(); + let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"], ["d", "e", "f"]])); + s.execute("table.cellFill", &json!({"id": id.0, "color": "#FF0000", "cells": [[0, 0]]})).unwrap(); + s.execute("table.merge", &json!({"id": id.0, "from": [0, 0], "to": [1, 1]})).unwrap(); + s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 1})).unwrap(); + let t = table_of(&s, id); + assert!(t.cell(1, 1).unwrap().h_merge && t.cell(1, 1).unwrap().v_merge, "the merge stays put"); + assert!(t.cell(0, 2).unwrap().fill.is_some()); + assert_eq!(t.cell(1, 2).unwrap().fill, t.cell(0, 0).unwrap().fill); +} + +/// A table near the slide's right edge, with no room for another column: by default an inserted +/// column widens it past the edge, as PowerPoint's Insert Right does (the frame keeps its left and +/// grows), and `keepWidth: true` keeps it on the slide. +#[test] +fn table_insert_column_near_the_slide_edge_grows_past_it_unless_it_keeps_its_width() { + let mut s = session(); + let id = table_at(&mut s, &[280.0, 280.0, 280.0], json!([["a", "b", "c"]])); + let slide_w = s.doc().unwrap().doc.slide_size.width; + let frame = |s: &Session| s.doc().unwrap().shape(id).unwrap().xfrm.unwrap(); + let before = frame(&s); + assert!(before.x + before.w <= slide_w && before.x + before.w + 280.0 > slide_w, "another column won't fit: {before:?}"); + s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 2})).unwrap(); + assert_eq!(table_of(&s, id).n_cols(), 4); + let grown = frame(&s); + assert!((grown.x - before.x).abs() < 1e-6 && (grown.w - 1120.0).abs() < 1e-6, "{grown:?}"); + assert!(grown.x + grown.w > slide_w, "past the edge"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("table.insertColumnRight", &json!({"id": id.0, "col": 2, "keepWidth": true})).unwrap(); + let kept = frame(&s); + assert_eq!(table_of(&s, id).n_cols(), 4); + assert!((kept.x - before.x).abs() < 1e-6 && (kept.w - before.w).abs() < 1e-6, "{kept:?}"); + assert!(kept.x + kept.w <= slide_w, "still on the slide"); +} + +/// PowerPoint inserts a column as wide as its neighbour and widens the table by that amount; the +/// other widths stay. Deleting a column narrows the table by its width, the others untouched. +#[test] +fn table_insert_and_delete_column_leave_other_widths_alone() { + let mut s = session(); + let id = table_at(&mut s, &[160.0, 234.0, 235.0, 235.0], json!([["a", "b", "c", "d"]])); + for (cmd, col, at, wide) in [("table.insertColumnRight", 0, 1, 160.0), ("table.insertColumnLeft", 3, 3, 235.0)] { + let before = table_of(&s, id).cols.clone(); + let w0 = table_of(&s, id).width(); + s.execute(cmd, &json!({"id": id.0, "col": col})).unwrap(); + let t = table_of(&s, id); + let mut want = before.clone(); + want.insert(at, wide); + assert_eq!(t.cols, want, "{cmd}"); + assert!((t.width() - w0 - wide).abs() < 1e-6, "{cmd} width {}", t.width()); + let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap(); + assert!((x.w - t.width()).abs() < 1e-6, "{cmd} frame {}", x.w); + } + let before = table_of(&s, id).cols.clone(); + s.execute("table.deleteColumn", &json!({"id": id.0, "col": 1})).unwrap(); + let t = table_of(&s, id); + let mut want = before.clone(); + let gone = want.remove(1); + assert_eq!(t.cols, want); + assert!((t.width() - (before.iter().sum::() - gone)).abs() < 1e-6); + let x = s.doc().unwrap().shape(id).unwrap().xfrm.unwrap(); + assert!((x.w - t.width()).abs() < 1e-6, "frame {}", x.w); +} + #[test] fn table_edits_past_the_cell_cap_are_refused_not_trimmed() { use deckcraft_model::table::{MAX_CELLS, Row};