mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-27 02:23:56 +00:00
Paste: a copied table in a table cell inserts rows or overwrites cells, as Word does (#6742)
Part of #6739. Default Paste with the caret in a table cell inserts the copied rows above (first column, same width) or overwrites cells from the caret's cell; over a cell selection it overwrites from the top-left. Paste as Nested Table (edit.pasteNestedTable) keeps the old nesting, which is also the fallback for cases this does not cover. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
6c6ac698ca
commit
44719ece99
@@ -151,6 +151,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-24: Pasting a plain table over selected cells overwrites from the selection's top-left, even when the copy is wider than the selection (#6742).
|
||||
- 2026-11-21: Layout: strict column balancing measures a kept paragraph again in each candidate column, so a float in one column does not make the paragraph skip another where it fits (#6821). Readiness estimates unchanged.
|
||||
|
||||
- 2026-11-20: `wordcraft-cli mcp` starts only with both `--automation-read-root` and `--automation-write-root` (shared rule 18, #7124); without them it stops with an error naming the two flags, where it used to serve with access to every file the user can reach. `mcp --connect` is refused until the desktop app confines its control channel to the same roots (#3695, #5819). The help, `docs/mcp.md`, the README and `AGENTS.md` pass both roots in every example.
|
||||
|
||||
@@ -33,6 +33,7 @@ pub mod packs;
|
||||
pub mod page;
|
||||
pub mod para;
|
||||
pub mod paste;
|
||||
pub mod paste_cells;
|
||||
pub mod phonetic;
|
||||
pub mod protect;
|
||||
pub mod references;
|
||||
|
||||
@@ -295,7 +295,13 @@ pub(crate) fn member_command(s: &mut Session, id: &str, _: &Value) -> Option<Cmd
|
||||
let replaces = (id.starts_with("text.") && id != "text.overtype")
|
||||
|| matches!(
|
||||
id,
|
||||
"edit.paste" | "edit.pasteText" | "edit.pasteMerge" | "edit.pasteSpecial" | "edit.pasteClipboardItem" | "edit.pasteAllClipboard"
|
||||
"edit.paste"
|
||||
| "edit.pasteText"
|
||||
| "edit.pasteMerge"
|
||||
| "edit.pasteNestedTable"
|
||||
| "edit.pasteSpecial"
|
||||
| "edit.pasteClipboardItem"
|
||||
| "edit.pasteAllClipboard"
|
||||
);
|
||||
if !replaces && !matches!(id, "edit.cut" | "edit.copy") {
|
||||
return None;
|
||||
|
||||
@@ -182,6 +182,9 @@ pub(crate) fn dispatch(s: &mut Session, id: &str, mutates: bool, run: fn(&mut Se
|
||||
_ if cells && (id.starts_with("table.") || matches!(id, "text.tab" | "text.backTab")) => run(s, v),
|
||||
// Copy and Cut of whole cells take a table of them (#1744).
|
||||
"edit.copy" | "edit.cut" if cells => run(s, v),
|
||||
// Paste can lay a copied table over the selected cells. Let it inspect the selection
|
||||
// before the ordinary column replacement deletes it.
|
||||
"edit.paste" if cells => run(s, v),
|
||||
"edit.copy" => copy(s, &segs),
|
||||
"edit.cut" => {
|
||||
let r = copy(s, &segs)?;
|
||||
@@ -209,6 +212,16 @@ pub(crate) fn dispatch(s: &mut Session, id: &str, mutates: bool, run: fn(&mut Se
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete the pieces of a selected cell rectangle for an ordinary Paste replacement.
|
||||
pub(super) fn delete_cell_segments(s: &mut Session) -> Result<(), CmdError> {
|
||||
if s.cell_range().is_some()
|
||||
&& let Some(segments) = s.column_segments().map(<[(Pos, Pos)]>::to_vec)
|
||||
{
|
||||
delete(s, &segments)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Copy: one paragraph per block row (formatting kept); the plain text joins rows with newlines.
|
||||
fn copy(s: &mut Session, segs: &[(Pos, Pos)]) -> CmdResult {
|
||||
let mut blocks = Vec::new();
|
||||
|
||||
@@ -89,6 +89,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("edit.paste", "Paste", "Home › Clipboard", paste)
|
||||
.key("Mod+V / Shift+Insert")
|
||||
.params(r#"{"text"?: string, "html"?: string, "rtf"?: string, "privateClipboard"?: bool}"#),
|
||||
CommandSpec::new("edit.pasteNestedTable", "Paste as Nested Table", "Home › Clipboard › Paste", paste_nested)
|
||||
.params(r#"{"text"?: string, "html"?: string, "rtf"?: string, "privateClipboard"?: bool} (a copied table with the caret in a table cell nests in that cell; Paste instead inserts its rows or overwrites the cells from the caret's)"#),
|
||||
CommandSpec::new("edit.pasteText", "Paste: Keep Text Only", "Home › Clipboard › Paste", paste_text)
|
||||
.params(r#"{"text"?: string}"#)
|
||||
.key("Mod+Shift+Alt+V"),
|
||||
@@ -301,13 +303,30 @@ fn insert_spike(s: &mut Session, _: &Value) -> CmdResult {
|
||||
/// else another program's HTML or RTF (#687). The system clipboard's text has none, so it pastes
|
||||
/// as Keep Text Only does.
|
||||
fn paste(s: &mut Session, v: &Value) -> CmdResult {
|
||||
match super::paste::paste_content(s, v)? {
|
||||
let pasted = super::paste::paste_content(s, v)?;
|
||||
if let super::paste::Pasted::Fragment(frag) = &pasted
|
||||
&& super::paste_cells::paste_over_selection(s, frag)?
|
||||
{
|
||||
return sel_result(s);
|
||||
}
|
||||
super::column::delete_cell_segments(s)?;
|
||||
match pasted {
|
||||
super::paste::Pasted::Fragment(frag) => super::paste::insert(s, frag)?,
|
||||
super::paste::Pasted::Text(text) => super::paste::insert_text(s, &text)?,
|
||||
}
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Paste as Nested Table: like Paste, but a copied table goes inside the cell the caret is in
|
||||
/// instead of laying its rows or cells over the table (#6739).
|
||||
fn paste_nested(s: &mut Session, v: &Value) -> CmdResult {
|
||||
match super::paste::paste_content(s, v)? {
|
||||
super::paste::Pasted::Fragment(frag) => super::paste::insert_as_is(s, frag)?,
|
||||
super::paste::Pasted::Text(text) => super::paste::insert_text(s, &text)?,
|
||||
}
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Merge Formatting: the pasted text takes the destination's formatting, keeping its emphasis.
|
||||
fn paste_merge(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let mut frag = super::paste::paste_fragment(s, v)?;
|
||||
@@ -444,11 +463,17 @@ fn paste_clip_item(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// Every collected item, in the order they were copied (one undo step).
|
||||
fn paste_all_clips(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let all: Vec<Fragment> = s.clip_history.items.iter().rev().map(|x| x.fragment.clone()).collect();
|
||||
let mut r = sel_result(s)?;
|
||||
let multiple = all.len() > 1;
|
||||
for f in all {
|
||||
r = paste_clip(s, f)?;
|
||||
if multiple {
|
||||
// Insert each item at the end of the last one. Cell paste can overwrite a
|
||||
// previous item or insert rows ahead of it.
|
||||
super::paste::insert_as_is(s, f)?;
|
||||
} else {
|
||||
return paste_clip(s, f);
|
||||
}
|
||||
}
|
||||
Ok(r)
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
fn paste_text(s: &mut Session, v: &Value) -> CmdResult {
|
||||
|
||||
@@ -365,8 +365,19 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace the selection with `frag`, marking it as an insertion under Track Changes.
|
||||
pub fn insert(s: &mut Session, mut frag: Fragment) -> Result<(), CmdError> {
|
||||
/// Paste `frag` at the selection. A copied table pasted with the caret in a table cell goes the way
|
||||
/// Word's Paste does it (rows inserted or cells overwritten, #6739; see [`super::paste_cells`]);
|
||||
/// anything else is [`insert_as_is`].
|
||||
pub fn insert(s: &mut Session, frag: Fragment) -> Result<(), CmdError> {
|
||||
if super::paste_cells::paste_cells(s, &frag)? {
|
||||
return Ok(());
|
||||
}
|
||||
insert_as_is(s, frag)
|
||||
}
|
||||
|
||||
/// Replace the selection with `frag`, marking it as an insertion under Track Changes. A table pasted
|
||||
/// with the caret in a cell nests in that cell (Word's Paste as Nested Table).
|
||||
pub fn insert_as_is(s: &mut Session, mut frag: Fragment) -> Result<(), CmdError> {
|
||||
// The pasted text keeps its own formatting; what Backspace carried over is not for after it (#6518).
|
||||
s.forget_carried();
|
||||
super::controls::prepare_edit(s)?;
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
//! Paste with the caret inside a table cell (#6739). Word does not nest a copied table there (that
|
||||
//! is its Paste as Nested Table, `edit.pasteNestedTable` here); observed black-box with synthetic
|
||||
//! tables:
|
||||
//!
|
||||
//! - a copied table (or whole rows) whose caret is in the first column of a table of the same
|
||||
//! width: its rows are inserted above the caret's row;
|
||||
//! - otherwise the copied cells overwrite the cells from the caret's cell rightwards and down,
|
||||
//! adding the rows and columns they need (new cells empty).
|
||||
//!
|
||||
//! With a cell selection, Paste overwrites from its top-left, including when the copy is wider
|
||||
//! than the selection.
|
||||
//!
|
||||
//! Pasted cells take the destination's cell formatting (Word's default keeps the source's; not
|
||||
//! done yet). What this does not cover falls back to the old behaviour, a nested table (see
|
||||
//! [`paste_cells`]).
|
||||
|
||||
use wordcraft_doc::edit::Fragment;
|
||||
use wordcraft_doc::props::VMerge;
|
||||
use wordcraft_doc::table::{MAX_COLS, MAX_ROWS};
|
||||
use wordcraft_doc::{Block, Cell, InlineObject, Path, Pos, Row, StoryRef, Table};
|
||||
|
||||
use crate::{CmdError, Selection, Session};
|
||||
|
||||
/// The fragment's table when it is one table and nothing else (empty paragraphs around it aside).
|
||||
fn lone_table(frag: &Fragment) -> Option<&Table> {
|
||||
let mut table = None;
|
||||
for b in &frag.blocks {
|
||||
match b {
|
||||
Block::Table(t) if table.is_none() => table = Some(t),
|
||||
Block::Para(p) if p.is_empty() && p.objects.is_empty() => {}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
table
|
||||
}
|
||||
|
||||
/// The width of a rectangular table that can be pasted cell by cell. Merges, offsets,
|
||||
/// objects and content control wrappers require preserving the table structure.
|
||||
fn plain_source(t: &Table) -> Option<usize> {
|
||||
let cols = t.rows.first()?.cells.len();
|
||||
let simple = |c: &Cell| {
|
||||
c.span() == 1
|
||||
&& c.props.vmerge == VMerge::None
|
||||
&& !c.blocks.is_empty()
|
||||
&& c.controls.is_empty()
|
||||
&& c.blocks.iter().all(|b| matches!(&**b, Block::Para(p) if p.objects.is_empty() && p.section.is_none()))
|
||||
};
|
||||
let ok = cols > 0
|
||||
&& t.controls.is_empty()
|
||||
&& t.rows.iter().all(|r| {
|
||||
r.cells.len() == cols
|
||||
&& r.first_grid() == 0
|
||||
&& r.grid_after() == 0
|
||||
&& r.props.exceptions.is_none()
|
||||
&& r.controls.is_empty()
|
||||
&& r.cells.iter().all(simple)
|
||||
});
|
||||
ok.then_some(cols)
|
||||
}
|
||||
|
||||
/// Whether the destination table's rows are a plain grid: one cell per grid column, no merges,
|
||||
/// offsets or row exceptions.
|
||||
fn plain_destination(t: &Table) -> bool {
|
||||
let cols = t.grid.len();
|
||||
cols > 0
|
||||
&& t.rows.iter().all(|r| {
|
||||
r.cells.len() == cols
|
||||
&& r.first_grid() == 0
|
||||
&& r.grid_after() == 0
|
||||
&& r.props.exceptions.is_none()
|
||||
&& r.cells.iter().all(|c| c.span() == 1 && c.props.vmerge == VMerge::None)
|
||||
})
|
||||
}
|
||||
|
||||
/// How deep [`has_control`] looks into tables nested in a cell; a deeper cell counts as holding a
|
||||
/// control, so a hostile document can't make the walk recurse without bound.
|
||||
const MAX_CONTROL_DEPTH: usize = 16;
|
||||
|
||||
/// Whether a cell holds a content control, or a control's start or end in its text, at any depth
|
||||
/// of nested tables, or a text box anchor (whose story may hold one): overwriting the cell
|
||||
/// replaces all of its blocks, which could remove a locked control (the caret's own cell is
|
||||
/// checked by the caller's edit rules).
|
||||
fn has_control(c: &Cell) -> bool {
|
||||
cell_has_control(c, 0)
|
||||
}
|
||||
|
||||
fn cell_has_control(c: &Cell, depth: usize) -> bool {
|
||||
if !c.controls.is_empty() || depth > MAX_CONTROL_DEPTH {
|
||||
return true;
|
||||
}
|
||||
c.blocks.iter().any(|b| match &**b {
|
||||
// A text box (or a group holding one) anchored here has its own story, which may hold a locked
|
||||
// control; it is not walked, so a cell with one counts as holding a control.
|
||||
Block::Para(p) => {
|
||||
p.objects.iter().any(|o| matches!(o, InlineObject::ControlStart { .. } | InlineObject::ControlEnd) || !o.text_boxes().is_empty())
|
||||
}
|
||||
Block::Table(t) => {
|
||||
!t.controls.is_empty() || t.rows.iter().any(|r| !r.controls.is_empty() || r.cells.iter().any(|c| cell_has_control(c, depth + 1)))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// What a paste into a cell does with the copied table `src` at (`row0`, `col0`) of `dest`.
|
||||
enum Plan {
|
||||
/// Insert the copy's rows above `row0`.
|
||||
InsertRows,
|
||||
/// Lay the copy's cells over the table from the cell.
|
||||
Overwrite,
|
||||
}
|
||||
|
||||
/// How `src` goes into `dest` at (`row0`, `col0`), or `None` when it can't be laid over it (the
|
||||
/// paste nests the table instead).
|
||||
fn plan(dest: &Table, src: &Table, src_cols: usize, row0: usize, col0: usize, allow_row_insertion: bool) -> Option<Plan> {
|
||||
if !plain_destination(dest) || col0 >= dest.grid.len() || row0 >= dest.rows.len() {
|
||||
return None;
|
||||
}
|
||||
let (src_rows, dest_cols) = (src.rows.len(), dest.grid.len());
|
||||
// A one-column table is a layout wrapper more often than a grid: a wider copy nests in it.
|
||||
if dest_cols == 1 && src_cols > 1 {
|
||||
return None;
|
||||
}
|
||||
// Word inserts whole rows above the caret's row when the caret is in the first column and
|
||||
// the rows are as wide as the table; a one-column table can't tell rows from a cell.
|
||||
if allow_row_insertion && col0 == 0 && src_cols == dest_cols && dest_cols > 1 {
|
||||
return (dest.rows.len().saturating_add(src_rows) <= MAX_ROWS).then_some(Plan::InsertRows);
|
||||
}
|
||||
if dest.rows.len().max(row0.saturating_add(src_rows)) > MAX_ROWS || dest_cols.max(col0.saturating_add(src_cols)) > MAX_COLS {
|
||||
return None;
|
||||
}
|
||||
// A wrapper may open before the first overwritten row or cell and close after the last.
|
||||
// Use ordinary paste for wrapped grids so an overwrite cannot bypass a structural control.
|
||||
if !dest.controls.is_empty() || dest.rows.iter().any(|row| !row.controls.is_empty() || row.cells.iter().any(|cell| !cell.controls.is_empty())) {
|
||||
return None;
|
||||
}
|
||||
let hit = |r: usize| dest.rows.get(r).is_some_and(|row| row.cells.iter().skip(col0).take(src_cols).any(has_control));
|
||||
(!(row0..row0.saturating_add(src_rows).min(dest.rows.len())).any(hit)).then_some(Plan::Overwrite)
|
||||
}
|
||||
|
||||
/// Overwrite cells from the top-left of a selection while it still identifies a rectangle.
|
||||
pub(super) fn paste_over_selection(s: &mut Session, frag: &Fragment) -> Result<bool, CmdError> {
|
||||
let Some(range) = s.cell_range() else { return Ok(false) };
|
||||
if s.doc.settings.track_changes || s.doc.control_at(&s.sel.ordered().0).is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(src) = lone_table(frag) else { return Ok(false) };
|
||||
let Some(src_cols) = plain_source(src) else { return Ok(false) };
|
||||
let (row, col) = (range.rows.0, range.cols.0);
|
||||
let story = range.story;
|
||||
let table = range.table.clone();
|
||||
let Some(dest) = s.doc.table(story, &table) else { return Ok(false) };
|
||||
let Some(edit) = plan(dest, src, src_cols, row, col, false) else { return Ok(false) };
|
||||
apply_plan(s, src, story, &table, row, col, edit)?;
|
||||
s.column = None;
|
||||
s.goal_x = None;
|
||||
s.pending = None;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// A copied table pasted with the caret in a table cell, as Word's default Paste does it.
|
||||
/// `false` (nothing done; the caller pastes as before, nesting the table) when:
|
||||
/// - the selection is not a caret in a cell, or the clipboard is not one table;
|
||||
/// - Track Changes is on (the cell edits aren't tracked here);
|
||||
/// - the copied table has merged cells, ragged rows, empty cells, pictures or other objects,
|
||||
/// a paragraph with a section break, or a control wrapping the table, a row or a cell;
|
||||
/// - the destination table has merged cells or offset rows, or an overwrite would affect a
|
||||
/// destination with structural wrappers or a cell containing a control in its blocks;
|
||||
/// - the caret is in a content control that shows its placeholder (the ordinary paste replaces
|
||||
/// the placeholder);
|
||||
/// - the destination has one column and the copy more (a layout wrapper), or the paste would pass
|
||||
/// the limits on a table's rows or columns.
|
||||
pub fn paste_cells(s: &mut Session, frag: &Fragment) -> Result<bool, CmdError> {
|
||||
if s.doc.settings.track_changes || !s.sel.is_collapsed() || s.cell_range().is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(src) = lone_table(frag) else { return Ok(false) };
|
||||
let Some(src_cols) = plain_source(src) else { return Ok(false) };
|
||||
let Some((tp, row0, col0)) = s.sel.focus.path.cell() else { return Ok(false) };
|
||||
let Some(dest) = s.doc.table(s.sel.focus.story, &tp) else { return Ok(false) };
|
||||
if plan(dest, src, src_cols, row0, col0, true).is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
// A caret in a control that shows its placeholder: the edit rules would select the
|
||||
// placeholder to replace it, which the row insertion would not do. The ordinary paste does.
|
||||
// This also covers a caret at the edge of such a control (drop-down, check box): rows used to
|
||||
// be inserted there, now the table nests. Overwrite already declined for cells with controls.
|
||||
if s.doc.control_at(&s.sel.focus).is_some_and(|r| r.control.showing_placeholder) {
|
||||
return Ok(false);
|
||||
}
|
||||
// Pasting ends Backspace's carried formatting, as in the ordinary paste path.
|
||||
s.forget_carried();
|
||||
// Protection: the edit rules may move the caret (to where typing goes) or refuse.
|
||||
if super::controls::prepare_edit(s)?.is_some() {
|
||||
// Normalizing the caret can enter a control and select its placeholder.
|
||||
// Let ordinary paste replace that selection.
|
||||
return Ok(false);
|
||||
}
|
||||
let at = s.sel.focus.clone();
|
||||
let Some((tp, row0, col0)) = at.path.cell() else { return Ok(false) };
|
||||
let story = at.story;
|
||||
let Some(dest) = s.doc.table(story, &tp) else { return Ok(false) };
|
||||
let Some(edit) = plan(dest, src, src_cols, row0, col0, true) else { return Ok(false) };
|
||||
apply_plan(s, src, story, &tp, row0, col0, edit)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn apply_plan(s: &mut Session, src: &Table, story: StoryRef, tp: &Path, row0: usize, col0: usize, plan: Plan) -> Result<(), CmdError> {
|
||||
let t = s.doc.table_mut(story, tp)?;
|
||||
let first = match plan {
|
||||
Plan::InsertRows => insert_source_rows(t, src, row0),
|
||||
Plan::Overwrite => overwrite_cells(t, src, row0, col0),
|
||||
};
|
||||
super::table::touch_cells(s, tp)?;
|
||||
let mut path = tp.0.clone();
|
||||
path.extend([first.0 as u32, first.1 as u32, 0]);
|
||||
s.sel = Selection::caret(Pos { story, path: Path(path), off: 0 });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Insert the rows of `src` above row `at` of `t` (same column count), formatted as that row.
|
||||
/// Returns the (row, cell) of the first pasted cell.
|
||||
fn insert_source_rows(t: &mut Table, src: &Table, at: usize) -> (usize, usize) {
|
||||
let Some(template) = t.rows.get(at) else { return (at, 0) };
|
||||
let new_rows: Vec<Row> = src
|
||||
.rows
|
||||
.iter()
|
||||
.map(|sr| {
|
||||
let mut row = Row { props: template.props.clone(), ..Row::default() };
|
||||
row.props.header = false;
|
||||
row.cells = template
|
||||
.cells
|
||||
.iter()
|
||||
.zip(&sr.cells)
|
||||
.map(|(dc, sc)| {
|
||||
let mut c = Cell::empty();
|
||||
c.props = dc.props.clone();
|
||||
c.blocks = sc.blocks.clone();
|
||||
c
|
||||
})
|
||||
.collect();
|
||||
row
|
||||
})
|
||||
.collect();
|
||||
t.rows.splice(at..at, new_rows);
|
||||
(at, 0)
|
||||
}
|
||||
|
||||
/// Lay the cells of `src` over those of `t` from (`row0`, column `col0`), adding the rows and
|
||||
/// columns they need. Returns the (row, cell) of the first pasted cell.
|
||||
fn overwrite_cells(t: &mut Table, src: &Table, row0: usize, col0: usize) -> (usize, usize) {
|
||||
let src_cols = src.rows.first().map_or(0, |r| r.cells.len());
|
||||
while t.grid.len() < col0.saturating_add(src_cols) && t.grid.len() < MAX_COLS {
|
||||
t.insert_col(t.grid.len());
|
||||
}
|
||||
while t.rows.len() < row0.saturating_add(src.rows.len()) && t.rows.len() < MAX_ROWS {
|
||||
let at = t.rows.len();
|
||||
t.insert_row(at, at.saturating_sub(1));
|
||||
}
|
||||
for (i, sr) in src.rows.iter().enumerate() {
|
||||
let Some(row) = t.rows.get_mut(row0 + i) else { break };
|
||||
for (j, sc) in sr.cells.iter().enumerate() {
|
||||
if let Some(dc) = row.cells.get_mut(col0 + j) {
|
||||
dc.blocks = sc.blocks.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
(row0, col0)
|
||||
}
|
||||
@@ -20,6 +20,7 @@ mod fonts;
|
||||
mod ime_noop;
|
||||
mod page_number_formats_in_lists;
|
||||
mod para_tools;
|
||||
mod paste_table_in_cell;
|
||||
mod revision_checks;
|
||||
mod typing;
|
||||
mod wordart;
|
||||
@@ -3000,11 +3001,19 @@ fn tables_nest_only_as_deep_as_a_json_save_reads() {
|
||||
let e = s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap_err();
|
||||
assert!(e.to_string().contains(&format!("{MAX_TABLE_DEPTH} deep")), "{e}");
|
||||
assert_eq!(s.doc, before);
|
||||
run(&mut s, "edit.paste", json!({"text": "b", "html": "<table><tr><td>b</td></tr></table>"}));
|
||||
// Paste as Nested Table is the path the depth guard sits on: the table's text comes as paragraphs.
|
||||
run(&mut s, "edit.pasteNestedTable", json!({"text": "b", "html": "<table><tr><td>b</td></tr></table>"}));
|
||||
let cell = s.sel.focus.path.clone();
|
||||
let blocks: Vec<_> = (0..).map_while(|i| s.doc.block(StoryRef::Body, &cell.with_last(i))).collect();
|
||||
assert!(blocks.iter().all(|b| b.as_table().is_none()), "no table below the limit");
|
||||
assert!(blocks.iter().any(|b| b.as_para().is_some_and(|p| p.text.contains('b'))), "the pasted text is there");
|
||||
// Paste lays a one-cell table over the cell (#6739): no new level either.
|
||||
run(&mut s, "edit.paste", json!({"text": "c", "html": "<table><tr><td>c</td></tr></table>"}));
|
||||
let cell = s.sel.focus.path.clone();
|
||||
let blocks: Vec<_> = (0..).map_while(|i| s.doc.block(StoryRef::Body, &cell.with_last(i))).collect();
|
||||
assert!(blocks.iter().all(|b| b.as_table().is_none()), "no table below the limit");
|
||||
assert!(blocks.iter().any(|b| b.as_para().is_some_and(|p| p.text.contains('c'))), "the pasted text is there");
|
||||
assert_eq!(s.sel.focus.path.depth(), MAX_TABLE_DEPTH);
|
||||
}
|
||||
|
||||
/// #3618: a text box story sits two JSON levels below the body, and its deepest cell still reads
|
||||
|
||||
@@ -0,0 +1,532 @@
|
||||
//! #6739: a copied table pasted with the caret in a table cell does what Word's Paste does (rows
|
||||
//! inserted above, or cells overwritten from the caret's), and nests only when asked to.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use wordcraft_doc::edit::Fragment;
|
||||
use wordcraft_doc::{Block, Cell, Document, Paragraph, Path, Pos, StoryRef, Table, para_block};
|
||||
|
||||
use crate::cmd::table::cell_text;
|
||||
use crate::{Selection, Session};
|
||||
|
||||
/// A table of `rows` x `cols` cells whose texts are `<prefix><row><col>` (from 1), 100 pt wide cells.
|
||||
fn table(prefix: &str, rows: usize, cols: usize) -> Table {
|
||||
let mut t = Table::new(rows, cols, 100.0 * cols as f32);
|
||||
for (r, row) in t.rows.iter_mut().enumerate() {
|
||||
for (c, cell) in row.cells.iter_mut().enumerate() {
|
||||
cell.blocks = Cell::with_text(&format!("{prefix}{}{}", r + 1, c + 1)).blocks;
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// A document of the 3 x 3 table d11..d33 and an empty paragraph, the caret in cell (`row`, `col`).
|
||||
fn dest(row: usize, col: usize) -> Session {
|
||||
let mut d = Document::new();
|
||||
d.body = vec![Arc::new(Block::Table(table("d", 3, 3))), para_block(Paragraph::new())];
|
||||
let mut s = Session::new(d);
|
||||
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, row as u32, col as u32, 0]), 0));
|
||||
s
|
||||
}
|
||||
|
||||
fn copy(s: &mut Session, t: Table) {
|
||||
s.clipboard = Some(Fragment { blocks: vec![Block::Table(t)], ..Default::default() });
|
||||
}
|
||||
|
||||
fn paste(s: &mut Session) {
|
||||
s.run("edit.paste", &json!({})).unwrap();
|
||||
}
|
||||
|
||||
fn t0(s: &Session) -> &Table {
|
||||
s.doc.body[0].as_table().expect("the table")
|
||||
}
|
||||
|
||||
/// The texts of the table's rows, a nested table shown as `[nested]`.
|
||||
fn grid(t: &Table) -> Vec<Vec<String>> {
|
||||
t.rows
|
||||
.iter()
|
||||
.map(|r| r.cells.iter().map(|c| if c.blocks.iter().any(|b| b.as_table().is_some()) { "[nested]".into() } else { cell_text(c) }).collect())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn rows(spec: &[&str]) -> Vec<Vec<String>> {
|
||||
spec.iter().map(|r| r.split(',').map(str::to_string).collect()).collect()
|
||||
}
|
||||
|
||||
fn nested(t: &Table) -> bool {
|
||||
t.rows.iter().flat_map(|r| &r.cells).any(|c| c.blocks.iter().any(|b| b.as_table().is_some()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_all_keeps_tables_in_copy_order_inside_the_cell() {
|
||||
for col in [0, 1] {
|
||||
let mut s = dest(1, col);
|
||||
for prefix in ["first", "second"] {
|
||||
copy(&mut s, table(prefix, 1, 3));
|
||||
let frag = s.clipboard.as_ref().unwrap();
|
||||
s.clip_history.push(frag, &frag.clipboard_text());
|
||||
}
|
||||
s.run("edit.pasteAllClipboard", &json!({})).unwrap();
|
||||
let pasted: Vec<_> = t0(&s).rows[1].cells[col].blocks.iter().filter_map(|b| b.as_table()).map(|t| cell_text(&t.rows[0].cells[0])).collect();
|
||||
assert_eq!(pasted, ["first11", "second11"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copied_table_over_selected_cells_overwrites_from_the_top_left() {
|
||||
for (source_cols, expected) in
|
||||
[(2, rows(&["s11,s12,d13", "s21,s22,d23", "d31,d32,d33"])), (3, rows(&["s11,s12,s13", "s21,s22,s23", "d31,d32,d33"]))]
|
||||
{
|
||||
let mut s = dest(1, 1);
|
||||
crate::cmd::table::extend_selection(&mut s, Pos::new(StoryRef::Body, Path(vec![0, 0, 0, 0]), 0));
|
||||
let range = s.cell_range().unwrap();
|
||||
assert_eq!((range.rows, range.cols, range.stream), ((0, 1), (0, 1), false));
|
||||
copy(&mut s, table("s", 2, source_cols));
|
||||
paste(&mut s);
|
||||
assert_eq!(grid(t0(&s)), expected, "source width {source_cols}");
|
||||
assert_eq!(s.sel, Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, 0, 0, 0]), 0)));
|
||||
assert!(s.cell_range().is_none());
|
||||
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(grid(t0(&s)), grid(&table("d", 3, 3)));
|
||||
s.run("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(grid(t0(&s)), expected);
|
||||
let reopened = wordcraft_docx::read(&wordcraft_docx::write(&s.doc).unwrap()).unwrap();
|
||||
assert_eq!(grid(reopened.body[0].as_table().unwrap()), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_text_paste_still_replaces_a_cell_rectangle() {
|
||||
let mut s = dest(0, 0);
|
||||
crate::cmd::table::extend_selection(&mut s, Pos::new(StoryRef::Body, Path(vec![0, 1, 1, 0]), 0));
|
||||
s.run("edit.paste", &json!({"text": "replacement"})).unwrap();
|
||||
assert_eq!(grid(t0(&s)), rows(&["replacement,,d13", ",,d23", "d31,d32,d33"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_table_with_the_caret_in_the_first_column_inserts_its_rows_above() {
|
||||
for (row, want) in [
|
||||
(1, rows(&["d11,d12,d13", "s11,s12,s13", "s21,s22,s23", "s31,s32,s33", "d21,d22,d23", "d31,d32,d33"])),
|
||||
(0, rows(&["s11,s12,s13", "s21,s22,s23", "s31,s32,s33", "d11,d12,d13", "d21,d22,d23", "d31,d32,d33"])),
|
||||
] {
|
||||
let mut s = dest(row, 0);
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
paste(&mut s);
|
||||
assert_eq!(grid(t0(&s)), want, "caret in row {row}");
|
||||
assert!(!nested(t0(&s)));
|
||||
assert_eq!(s.doc.body.iter().filter(|b| b.as_table().is_some()).count(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_table_with_the_caret_further_right_overwrites_cells_and_grows_the_table() {
|
||||
let mut s = dest(1, 2);
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
paste(&mut s);
|
||||
let want = rows(&["d11,d12,d13,,", "d21,d22,s11,s12,s13", "d31,d32,s21,s22,s23", ",,s31,s32,s33"]);
|
||||
assert_eq!(grid(t0(&s)), want);
|
||||
assert_eq!(t0(&s).grid.len(), 5);
|
||||
assert!(t0(&s).rows.iter().all(|r| r.cells.len() == 5));
|
||||
// The last cell of the last row: the table grows two columns and two rows.
|
||||
let mut s = dest(2, 2);
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
paste(&mut s);
|
||||
let want = rows(&["d11,d12,d13,,", "d21,d22,d23,,", "d31,d32,s11,s12,s13", ",,s21,s22,s23", ",,s31,s32,s33"]);
|
||||
assert_eq!(grid(t0(&s)), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cells_copied_from_part_of_a_table_overwrite_from_the_caret_in_any_column() {
|
||||
// Two cells of one column (Word: s12, s22 into the cells below the caret).
|
||||
let mut s = dest(1, 0);
|
||||
copy(&mut s, table("s", 2, 1));
|
||||
paste(&mut s);
|
||||
assert_eq!(grid(t0(&s)), rows(&["d11,d12,d13", "s11,d22,d23", "s21,d32,d33"]));
|
||||
// At the last row a row is added.
|
||||
let mut s = dest(2, 0);
|
||||
copy(&mut s, table("s", 2, 1));
|
||||
paste(&mut s);
|
||||
assert_eq!(grid(t0(&s)), rows(&["d11,d12,d13", "d21,d22,d23", "s11,d32,d33", "s21,,"]));
|
||||
// Two columns wide, from the middle column: it fits the table.
|
||||
let mut s = dest(0, 1);
|
||||
copy(&mut s, table("s", 2, 2));
|
||||
paste(&mut s);
|
||||
assert_eq!(grid(t0(&s)), rows(&["d11,s11,s12", "d21,s21,s22", "d31,d32,d33"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_copied_cell_replaces_the_cell_it_is_pasted_in() {
|
||||
for (r, c) in [(0, 0), (1, 2), (2, 2)] {
|
||||
let mut s = dest(r, c);
|
||||
copy(&mut s, table("s", 1, 1));
|
||||
paste(&mut s);
|
||||
let mut want = grid(&table("d", 3, 3));
|
||||
want[r][c] = "s11".into();
|
||||
assert_eq!(grid(t0(&s)), want, "cell ({r}, {c})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_caret_goes_to_the_first_pasted_cell() {
|
||||
let mut s = dest(1, 0);
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
paste(&mut s);
|
||||
assert_eq!(s.sel.focus.path, Path(vec![0, 1, 0, 0]));
|
||||
assert!(s.sel.is_collapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_as_nested_table_nests_the_table_in_the_cell() {
|
||||
let mut s = dest(1, 0);
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
s.run("edit.pasteNestedTable", &json!({})).unwrap();
|
||||
let t = t0(&s);
|
||||
assert_eq!(t.rows.len(), 3, "no rows inserted");
|
||||
assert!(t.rows[1].cells[0].blocks.iter().any(|b| b.as_table().is_some()), "a table nests in the cell");
|
||||
assert_eq!(cell_text(&t.rows[1].cells[1]), "d22");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasting_a_wrapped_table_keeps_its_source_controls() {
|
||||
use wordcraft_doc::{ContentControl, ControlKind};
|
||||
|
||||
for on_row in [false, true] {
|
||||
// A same-width copy can insert rows at column zero or overwrite cells further right.
|
||||
for col in [0, 1] {
|
||||
let mut s = dest(1, col);
|
||||
let mut source = table("s", 2, 3);
|
||||
let controls = if on_row { &mut source.rows[0].controls } else { &mut source.controls };
|
||||
let mut wrapper = ContentControl::new(ControlKind::RichText);
|
||||
wrapper.tag = "source wrapper".into();
|
||||
controls.open.push(wrapper);
|
||||
controls.close = 1;
|
||||
let expected = controls.clone();
|
||||
|
||||
copy(&mut s, source);
|
||||
paste(&mut s);
|
||||
|
||||
let pasted = t0(&s).rows[1].cells[col]
|
||||
.blocks
|
||||
.iter()
|
||||
.find_map(|b| b.as_table())
|
||||
.unwrap_or_else(|| panic!("the wrapped source should nest (row wrapper: {on_row}, column: {col})"));
|
||||
let controls = if on_row { &pasted.rows[0].controls } else { &pasted.controls };
|
||||
assert_eq!(controls, &expected, "row wrapper: {on_row}, column: {col}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_cannot_be_laid_over_the_cells_nests_as_before() {
|
||||
let nests = |s: &mut Session| {
|
||||
paste(s);
|
||||
assert!(nested(t0(s)), "nested");
|
||||
assert_eq!(t0(s).rows.len(), 3);
|
||||
};
|
||||
// Merged cells in the copy.
|
||||
let mut merged = table("s", 2, 3);
|
||||
merged.rows[0].cells[0].props.span = 2;
|
||||
merged.rows[0].cells.remove(1);
|
||||
let mut s = dest(1, 0);
|
||||
copy(&mut s, merged);
|
||||
nests(&mut s);
|
||||
// Ragged rows in the copy.
|
||||
let mut ragged = table("s", 2, 3);
|
||||
ragged.rows[1].cells.pop();
|
||||
let mut s = dest(1, 0);
|
||||
copy(&mut s, ragged);
|
||||
nests(&mut s);
|
||||
// More columns than a table may have.
|
||||
let mut s = dest(1, 2);
|
||||
copy(&mut s, table("s", 1, 62));
|
||||
nests(&mut s);
|
||||
// A table inside a copied cell.
|
||||
let mut inner = table("s", 1, 1);
|
||||
inner.rows[0].cells[0].blocks = vec![Arc::new(Block::Table(table("n", 1, 1)))];
|
||||
let mut s = dest(1, 0);
|
||||
copy(&mut s, inner);
|
||||
nests(&mut s);
|
||||
// Merged cells in the destination.
|
||||
let mut s = dest(1, 0);
|
||||
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
|
||||
t.rows[1].cells[0].props.span = 2;
|
||||
t.rows[1].cells.remove(1);
|
||||
}
|
||||
copy(&mut s, table("s", 1, 1));
|
||||
nests(&mut s);
|
||||
// A copied cell without any block (hostile fragment): nothing to lay over the cell.
|
||||
let mut hollow = table("s", 1, 1);
|
||||
hollow.rows[0].cells[0].blocks.clear();
|
||||
let mut s = dest(1, 0);
|
||||
copy(&mut s, hollow);
|
||||
let _ = s.run("edit.paste", &json!({}));
|
||||
assert_eq!(t0(&s).rows.len(), 3, "nothing laid over the cells");
|
||||
// A wider copy into a one-column table (a layout wrapper) nests instead of widening it.
|
||||
let mut s = dest(1, 0);
|
||||
s.doc.body[0] = Arc::new(Block::Table(table("w", 3, 1)));
|
||||
copy(&mut s, table("s", 2, 3));
|
||||
paste(&mut s);
|
||||
assert!(nested(t0(&s)));
|
||||
assert_eq!(t0(&s).grid.len(), 1);
|
||||
// A content control in a cell the copy would overwrite.
|
||||
let mut s = dest(1, 0);
|
||||
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
|
||||
t.rows[2].cells[0].controls.close = 1;
|
||||
}
|
||||
copy(&mut s, table("s", 3, 1));
|
||||
nests(&mut s);
|
||||
// Row exceptions on the destination.
|
||||
let mut s = dest(1, 0);
|
||||
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
|
||||
t.rows[0].props.exceptions = Some(Default::default());
|
||||
}
|
||||
copy(&mut s, table("s", 1, 1));
|
||||
nests(&mut s);
|
||||
// Track Changes on.
|
||||
let mut s = dest(1, 0);
|
||||
s.doc.settings.track_changes = true;
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
nests(&mut s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_shapes_never_panic() {
|
||||
// An empty table, a table with empty rows, 30,000 columns and 30,000 rows in a copy.
|
||||
let mut wide = table("s", 1, 1);
|
||||
wide.grid = vec![1.0; 30_000];
|
||||
wide.rows[0].cells = (0..30_000).map(|_| Cell::empty()).collect();
|
||||
let mut tall = table("s", 1, 2);
|
||||
tall.rows = (0..30_000).map(|_| tall.rows[0].clone()).collect();
|
||||
let mut no_rows = table("s", 1, 1);
|
||||
no_rows.rows.clear();
|
||||
let mut no_cells = table("s", 1, 1);
|
||||
no_cells.rows[0].cells.clear();
|
||||
// 30,000 columns and empty tables can't be laid over the cells: they nest (the old path).
|
||||
for t in [wide, no_rows, no_cells] {
|
||||
for (r, c) in [(0, 0), (2, 2)] {
|
||||
let mut s = dest(r, c);
|
||||
copy(&mut s, t.clone());
|
||||
let _ = s.run("edit.paste", &json!({}));
|
||||
assert_eq!((t0(&s).rows.len(), t0(&s).grid.len()), (3, 3), "unchanged table");
|
||||
}
|
||||
}
|
||||
// 30,000 rows are laid over the cells: rows are added up to the limit, never past it.
|
||||
for (r, c) in [(0, 0), (2, 1)] {
|
||||
let mut s = dest(r, c);
|
||||
copy(&mut s, tall.clone());
|
||||
s.run("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(t0(&s).rows.len(), r + 30_000);
|
||||
assert!(t0(&s).rows.iter().all(|row| row.cells.len() == t0(&s).grid.len()));
|
||||
}
|
||||
// More rows than a table may have nest instead.
|
||||
let mut huge = table("s", 1, 2);
|
||||
huge.rows = (0..wordcraft_doc::table::MAX_ROWS).map(|_| huge.rows[0].clone()).collect();
|
||||
let mut s = dest(1, 1);
|
||||
copy(&mut s, huge);
|
||||
let _ = s.run("edit.paste", &json!({}));
|
||||
assert_eq!(t0(&s).rows.len(), 3);
|
||||
// A caret path that is not a cell of the table.
|
||||
let mut s = dest(0, 0);
|
||||
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, 9, 9, 0]), 0));
|
||||
copy(&mut s, table("s", 1, 1));
|
||||
let _ = s.run("edit.paste", &json!({}));
|
||||
assert_eq!(t0(&s).rows.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copied_table_with_empty_paragraphs_around_it_is_laid_over_the_cells_too() {
|
||||
let mut s = dest(1, 0);
|
||||
s.clipboard = Some(Fragment {
|
||||
blocks: vec![Block::Para(Paragraph::new()), Block::Table(table("s", 1, 3)), Block::Para(Paragraph::new())],
|
||||
..Default::default()
|
||||
});
|
||||
paste(&mut s);
|
||||
assert_eq!(grid(t0(&s)), rows(&["d11,d12,d13", "s11,s12,s13", "d21,d22,d23", "d31,d32,d33"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_takes_the_paste_back_in_one_step_and_redo_does_it_again() {
|
||||
for (row, col) in [(1, 0), (1, 2)] {
|
||||
let mut s = dest(row, col);
|
||||
let before = t0(&s).clone();
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
paste(&mut s);
|
||||
let after = t0(&s).clone();
|
||||
assert_ne!(after, before);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(t0(&s), &before, "one undo restores the table ({row}, {col})");
|
||||
s.run("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(t0(&s), &after);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pasted_rows_survive_saving_and_reopening_as_docx() {
|
||||
let mut s = dest(1, 0);
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
paste(&mut s);
|
||||
let bytes = crate::io::save_bytes("t.docx", &s.doc).unwrap();
|
||||
let back = crate::io::open_bytes("t.docx", &bytes).unwrap();
|
||||
let t = back.body.iter().find_map(|b| b.as_table()).expect("a table");
|
||||
assert_eq!(grid(t), grid(t0(&s)));
|
||||
let mut s = dest(1, 2);
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
paste(&mut s);
|
||||
let back = crate::io::open_bytes("t.docx", &crate::io::save_bytes("t.docx", &s.doc).unwrap()).unwrap();
|
||||
let t = back.body.iter().find_map(|b| b.as_table()).expect("a table");
|
||||
assert_eq!((t.rows.len(), t.grid.len()), (4, 5));
|
||||
assert_eq!(grid(t), grid(t0(&s)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paste_into_a_cell_of_a_table_inside_a_cell_works_on_that_table() {
|
||||
let mut inner_host = table("o", 1, 1);
|
||||
inner_host.rows[0].cells[0].blocks = vec![Arc::new(Block::Table(table("d", 3, 3))), para_block(Paragraph::new())];
|
||||
let mut d = Document::new();
|
||||
d.body = vec![Arc::new(Block::Table(inner_host)), para_block(Paragraph::new())];
|
||||
let mut s = Session::new(d);
|
||||
// Body table 0, row 0, cell 0, its block 0 (the inner table), row 1, cell 0, block 0.
|
||||
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, 0, 0, 0, 1, 0, 0]), 0));
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
paste(&mut s);
|
||||
let inner = t0(&s).rows[0].cells[0].blocks[0].as_table().expect("the inner table").clone();
|
||||
assert_eq!(grid(&inner).len(), 6);
|
||||
assert!(!nested(&inner));
|
||||
}
|
||||
|
||||
/// A locked control in a table nested in a cell the copy would overwrite is not deleted: the
|
||||
/// paste nests instead (#6739 review).
|
||||
#[test]
|
||||
fn a_locked_control_in_a_nested_table_of_an_overwritten_cell_is_kept() {
|
||||
use wordcraft_doc::{ContentControl, ControlKind, ControlLock};
|
||||
let mut s = dest(0, 0);
|
||||
let mut inner = table("n", 1, 1);
|
||||
let mut ctl = ContentControl::new(ControlKind::RichText);
|
||||
ctl.lock = ControlLock::SdtContentLocked;
|
||||
inner.rows[0].cells[0].controls.open.push(ctl);
|
||||
inner.rows[0].cells[0].controls.close = 1;
|
||||
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
|
||||
t.rows[1].cells[0].blocks = vec![Arc::new(Block::Table(inner)), para_block(Paragraph::new())];
|
||||
}
|
||||
let before = t0(&s).rows[1].cells[0].clone();
|
||||
// Copy one cell, caret above the cell with the nested table: it would be overwritten.
|
||||
copy(&mut s, table("s", 2, 1));
|
||||
paste(&mut s);
|
||||
let kept = |t: &Table| t.rows.iter().flat_map(|r| &r.cells).any(|c| c.blocks == before.blocks);
|
||||
assert!(kept(t0(&s)), "the cell with the locked control survives");
|
||||
}
|
||||
|
||||
/// A caret in a control that shows its placeholder: no rows are inserted above the caret's row;
|
||||
/// the table nests in the cell as the ordinary paste does (#6739 review).
|
||||
#[test]
|
||||
fn a_control_showing_its_placeholder_gets_the_ordinary_paste_not_inserted_rows() {
|
||||
let mut s = dest(1, 0);
|
||||
s.run("developer.plainText", &json!({})).unwrap();
|
||||
let before = s.doc.body[0].as_table().map(|t| t.rows.len());
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
paste(&mut s);
|
||||
assert_eq!(t0(&s).rows.len(), before.unwrap_or(0), "no rows inserted above the caret's row");
|
||||
assert!(nested(t0(&s)), "the table nests in the cell");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_from_before_a_block_control_replaces_its_placeholder() {
|
||||
let mut s = dest(1, 0);
|
||||
let start = s.sel.focus.clone();
|
||||
s.run("developer.plainText", &json!({})).unwrap();
|
||||
let range = s.doc.control_at(&s.sel.focus).unwrap();
|
||||
assert_eq!(range.start, start);
|
||||
assert!(range.control.showing_placeholder);
|
||||
let placeholder = s.doc.para_at(&start).unwrap().text[range.content_start().off..range.end.off].to_owned();
|
||||
assert!(!placeholder.is_empty());
|
||||
s.doc.control_mut(&start).unwrap().block = true;
|
||||
s.sel = Selection::caret(start);
|
||||
copy(&mut s, table("s", 1, 3));
|
||||
paste(&mut s);
|
||||
assert_eq!(t0(&s).rows.len(), 3);
|
||||
assert!(nested(t0(&s)));
|
||||
assert!(!cell_text(&t0(&s).rows[1].cells[0]).contains(&placeholder));
|
||||
}
|
||||
|
||||
/// A locked control in a text box anchored in a cell the copy would overwrite is not lost: the
|
||||
/// paste nests instead (#6739 review).
|
||||
#[test]
|
||||
fn a_locked_control_in_a_text_box_of_an_overwritten_cell_is_kept() {
|
||||
use wordcraft_doc::para::ShapeKind;
|
||||
use wordcraft_doc::{ContentControl, ControlKind, ControlLock, InlineObject, PartKind};
|
||||
let mut s = dest(0, 0);
|
||||
let mut ctl = ContentControl::new(ControlKind::RichText);
|
||||
ctl.lock = ControlLock::SdtContentLocked;
|
||||
let mut inner = Paragraph::with_text("Locked", Default::default());
|
||||
inner.insert_object(0, InlineObject::ControlStart { control: Box::new(ctl) }, &Default::default()).unwrap();
|
||||
let end = inner.text.chars().count();
|
||||
inner.insert_object(end, InlineObject::ControlEnd, &Default::default()).unwrap();
|
||||
let id = s.doc.add_part(PartKind::TextBox, vec![para_block(inner)]);
|
||||
let shape = InlineObject::Shape {
|
||||
kind: ShapeKind::TextBox,
|
||||
w: 72.0,
|
||||
h: 36.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 0.75,
|
||||
float: Default::default(),
|
||||
story: Some(id),
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: Default::default(),
|
||||
};
|
||||
let mut anchor = Paragraph::with_text("Box", Default::default());
|
||||
anchor.insert_object(0, shape, &Default::default()).unwrap();
|
||||
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
|
||||
t.rows[1].cells[0].blocks = vec![para_block(anchor)];
|
||||
}
|
||||
let before = t0(&s).rows[1].cells[0].blocks.clone();
|
||||
// One column of two cells from the caret in the top cell: the cell with the box is overwritten.
|
||||
copy(&mut s, table("s", 2, 1));
|
||||
paste(&mut s);
|
||||
let kept = |t: &Table| t.rows.iter().flat_map(|r| &r.cells).any(|c| c.blocks == before);
|
||||
assert!(kept(t0(&s)), "the cell anchoring the text box survives");
|
||||
assert!(nested(t0(&s)), "the table nests in the cell instead");
|
||||
}
|
||||
|
||||
/// A row-level content control on a row the copy would overwrite is not bypassed: the paste nests
|
||||
/// instead (#6739 review).
|
||||
#[test]
|
||||
fn a_row_level_control_on_an_overwritten_row_declines_the_overwrite() {
|
||||
use wordcraft_doc::{ContentControl, ControlKind, ControlLock};
|
||||
let mut s = dest(0, 0);
|
||||
let mut ctl = ContentControl::new(ControlKind::RichText);
|
||||
ctl.lock = ControlLock::SdtContentLocked;
|
||||
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
|
||||
t.rows[1].controls.open.push(ctl);
|
||||
t.rows[1].controls.close = 1;
|
||||
}
|
||||
let before = grid(t0(&s));
|
||||
copy(&mut s, table("s", 2, 1));
|
||||
paste(&mut s);
|
||||
assert_eq!(grid(t0(&s))[1], before[1], "the row under the control is not overwritten");
|
||||
assert!(nested(t0(&s)), "the table nests in the cell instead");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_overwrite_inside_a_spanning_row_control_preserves_the_row() {
|
||||
use wordcraft_doc::{ContentControl, ControlKind, ControlLock};
|
||||
|
||||
let mut s = dest(1, 1);
|
||||
let mut control = ContentControl::new(ControlKind::RichText);
|
||||
control.lock = ControlLock::SdtContentLocked;
|
||||
let destination = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
|
||||
destination.rows[0].controls.open.push(control);
|
||||
destination.rows[2].controls.close = 1;
|
||||
copy(&mut s, table("s", 1, 1));
|
||||
paste(&mut s);
|
||||
|
||||
let table = t0(&s);
|
||||
let cell = &table.rows[1].cells[1];
|
||||
assert!(cell_text(cell).lines().any(|line| line == "d22"));
|
||||
assert!(cell.blocks.iter().any(|block| block.as_table().is_some()));
|
||||
assert_eq!(table.rows[0].controls.open[0].lock, ControlLock::SdtContentLocked);
|
||||
assert_eq!(table.rows[2].controls.close, 1);
|
||||
}
|
||||
@@ -157,6 +157,7 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
("Paste", "edit.paste"),
|
||||
("Keep Text Only", "edit.pasteText"),
|
||||
("Merge Formatting", "edit.pasteMerge"),
|
||||
("Paste as Nested Table", "edit.pasteNestedTable"),
|
||||
("Paste Special…", "edit.pasteSpecial"),
|
||||
] {
|
||||
MenuItem::command(CommandRef::new(id)).label(tl!(label).to_string()).show(ui);
|
||||
|
||||
@@ -24,7 +24,7 @@ const MAX_PIXELS: usize = 50_000_000;
|
||||
|
||||
/// The commands that paste the clipboard.
|
||||
pub(crate) fn is_paste(id: &str) -> bool {
|
||||
matches!(id, "edit.paste" | "edit.pasteText" | "edit.pasteMerge" | "edit.pasteSpecial")
|
||||
matches!(id, "edit.paste" | "edit.pasteText" | "edit.pasteMerge" | "edit.pasteNestedTable" | "edit.pasteSpecial")
|
||||
}
|
||||
|
||||
/// Most format names an error lists.
|
||||
|
||||
+2
-1
File diff suppressed because one or more lines are too long
+2
-1
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user