Compare commits

...
1 Commits
Author SHA1 Message Date
e2df2d64cd Tables in a header or footer: borders, handles, selection arrows, pen and eraser work while it is edited (#5558) (#5576)
Lands #5576 rebased onto main; only docs conflicts were resolved (both sides kept).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: D13GOOOO <106814760+D13GOOOO@users.noreply.github.com>
2026-11-17 04:04:48 +00:00
11 changed files with 485 additions and 97 deletions
+3 -1
View File
File diff suppressed because one or more lines are too long
+54 -26
View File
@@ -9,9 +9,10 @@ use wordcraft_doc::props::{HeightRule, VMerge};
use wordcraft_doc::table::{MAX_COLS, MAX_ROWS};
use wordcraft_doc::{Block, Cell, Path, Pos, StoryRef, Table, para_block};
use wordcraft_geom::Rect;
use wordcraft_layout::{DocLayout, Placed};
use wordcraft_layout::DocLayout;
use super::sel_result;
use super::table_resize::Reach;
use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
/// A drag shorter than this (points) both ways isn't a rectangle.
@@ -29,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
r#"{"page": n, "x0": pt, "y0": pt, "x1": pt, "y1": pt, "story"?: StoryRef} (a pen stroke in page points, 0-based page: a rectangle at least 12 pt each way outside any table inserts a one-cell table of that size at the paragraph under its start; a straight vertical or horizontal line inside a table splits the cells it crosses there. In the app the button turns the pen on.)"#,
),
CommandSpec::new("table.eraser", "Eraser", "Table Layout › Draw", eraser).params(
r#"{"page": n, "x": pt, "y": pt} (removes the border between two cells within 4 pt of the point: cells that make one rectangle merge, including cells merged down the same rows; otherwise the border is hidden along the whole edge. In the app the button turns the eraser on.)"#,
r#"{"page": n, "x": pt, "y": pt, "story"?: StoryRef} (removes the border between two cells within 4 pt of the point, of a table in `story` (default: the caret's; a header's or footer's while one is edited): cells that make one rectangle merge, including cells merged down the same rows; otherwise the border is hidden along the whole edge. In the app the button turns the eraser on.)"#,
),
]
}
@@ -55,16 +56,12 @@ struct CellBox {
cell: usize,
}
fn cell_boxes(l: &DocLayout, page: usize) -> Vec<CellBox> {
let Some(pg) = l.pages.get(page) else { return Vec::new() };
pg.items
.iter()
.filter_map(|it| match it {
Placed::Cell { rect, table, row, cell, story, .. } => {
Some(CellBox { rect: *rect, table: table.clone(), story: *story, row: *row, cell: *cell })
}
_ => None,
})
/// The table cells on a page the pen and eraser reach ([`Reach`]: a header's and footer's while
/// one of them is edited, #5558).
fn cell_boxes(l: &DocLayout, page: usize, reach: Reach) -> Vec<CellBox> {
super::table_resize::cell_boxes_in(l, page, reach)
.into_iter()
.map(|b| CellBox { rect: b.rect, table: b.table, story: b.story, row: b.row, cell: b.cell })
.collect()
}
@@ -79,13 +76,22 @@ fn table_at(boxes: &[CellBox], x: f32, y: f32) -> Option<(StoryRef, Path)> {
/// Classify a pen stroke: a straight line inside a table, a rectangle outside one, else `None`.
pub fn stroke(l: &DocLayout, page: usize, x0: f32, y0: f32, x1: f32, y1: f32) -> Option<Stroke> {
stroke_in(l, page, Reach::Body, x0, y0, x1, y1)
}
/// [`stroke`] while `editing` is edited: across a header's or footer's tables then (#5558).
pub fn stroke_in(l: &DocLayout, page: usize, tables: Reach, x0: f32, y0: f32, x1: f32, y1: f32) -> Option<Stroke> {
stroke_among(&cell_boxes(l, page, tables), x0, y0, x1, y1)
}
/// [`stroke`] across the tables of `boxes`.
fn stroke_among(boxes: &[CellBox], x0: f32, y0: f32, x1: f32, y1: f32) -> Option<Stroke> {
if ![x0, y0, x1, y1].iter().all(|v| v.is_finite()) {
return None;
}
let (dx, dy) = ((x1 - x0).abs(), (y1 - y0).abs());
let boxes = cell_boxes(l, page);
let (mx, my) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
if table_at(&boxes, x0, y0).is_some() || table_at(&boxes, mx, my).is_some() {
if table_at(boxes, x0, y0).is_some() || table_at(boxes, mx, my).is_some() {
if dy >= dx && dy >= MIN_LINE && dx <= MIN_RECT.max(dy * 0.2) {
return Some(Stroke::Vertical { x: mx, y0: y0.min(y1), y1: y0.max(y1) });
}
@@ -97,6 +103,19 @@ pub fn stroke(l: &DocLayout, page: usize, x0: f32, y0: f32, x1: f32, y1: f32) ->
(dx >= MIN_RECT && dy >= MIN_RECT).then(|| Stroke::Rect(Rect::new(x0.min(x1), y0.min(y1), dx, dy)))
}
/// The cells a pen or eraser command reaches: those of the tables its `story` (default: the
/// caret's) reaches ([`Reach`]), and of those only `story`'s own when the command names one: a
/// caller that names a story means its tables, not a table of another drawn there.
fn command_boxes(s: &Session, l: &DocLayout, v: &Value, page: usize) -> Vec<CellBox> {
let story = super::story_param(s, v);
let boxes = cell_boxes(l, page, Reach::of(l, &s.doc, story, page));
let named = v.get("story").and_then(|x| serde_json::from_value::<StoryRef>(x.clone()).ok());
match named {
Some(named) => boxes.into_iter().filter(|b| b.story == named).collect(),
None => boxes,
}
}
fn page_param(v: &Value) -> Result<usize, CmdError> {
p::u64(v, "page").map(|n| usize::try_from(n).unwrap_or(usize::MAX)).ok_or_else(|| CmdError::Params("`page` (number) is required".into()))
}
@@ -108,10 +127,11 @@ fn draw(s: &mut Session, v: &Value) -> CmdResult {
if l.pages.get(page).is_none() {
return Err(CmdError::Params(format!("no page {page}")));
}
match stroke(&l, page, x0, y0, x1, y1) {
let boxes = command_boxes(s, &l, v, page);
match stroke_among(&boxes, x0, y0, x1, y1) {
Some(Stroke::Rect(r)) => draw_table(s, v, &l, page, (x0, y0), r),
Some(Stroke::Vertical { x, y0, y1 }) => split_columns(s, &l, page, x, (y0, y1)),
Some(Stroke::Horizontal { y, x0, x1 }) => split_rows(s, &l, page, y, (x0, x1)),
Some(Stroke::Vertical { x, y0, y1 }) => split_columns(s, &boxes, x, (y0, y1)),
Some(Stroke::Horizontal { y, x0, x1 }) => split_rows(s, &boxes, y, (x0, x1)),
None => Err(CmdError::Failed(
"draw a rectangle (at least 12 pt each way) outside a table, or a straight horizontal or vertical line across table cells".into(),
)),
@@ -276,13 +296,12 @@ fn hide_edge(t: &mut Table, vertical: bool, line: usize, (lo, hi): (usize, usize
}
/// A vertical line at page `x`: split each crossed cell into two columns there.
fn split_columns(s: &mut Session, l: &DocLayout, page: usize, x: f32, (ya, yb): (f32, f32)) -> CmdResult {
let boxes = cell_boxes(l, page);
fn split_columns(s: &mut Session, boxes: &[CellBox], x: f32, (ya, yb): (f32, f32)) -> CmdResult {
let hit = |r: &Rect| {
let overlap = yb.min(r.bottom()) - ya.max(r.y);
x > r.x + SNAP && x < r.right() - SNAP && overlap >= r.h * 0.5
};
let Some((story, tp, cells)) = crossed(&boxes, (x, (ya + yb) / 2.0), hit) else {
let Some((story, tp, cells)) = crossed(boxes, (x, (ya + yb) / 2.0), hit) else {
return Err(CmdError::Failed("the line doesn't cross a table cell".into()));
};
let Some(&(r0, c0, rect0)) = cells.first() else { return Err(CmdError::Failed("the line doesn't cross a table cell".into())) };
@@ -372,13 +391,12 @@ fn split_columns(s: &mut Session, l: &DocLayout, page: usize, x: f32, (ya, yb):
/// A horizontal line at page `y`: split the row it crosses there. Crossed cells become two;
/// the row's other cells span both rows (a vertical merge).
fn split_rows(s: &mut Session, l: &DocLayout, page: usize, y: f32, (xa, xb): (f32, f32)) -> CmdResult {
let boxes = cell_boxes(l, page);
fn split_rows(s: &mut Session, boxes: &[CellBox], y: f32, (xa, xb): (f32, f32)) -> CmdResult {
let hit = |r: &Rect| {
let overlap = xb.min(r.right()) - xa.max(r.x);
y > r.y + SNAP && y < r.bottom() - SNAP && overlap >= r.w * 0.5
};
let Some((story, tp, cells)) = crossed(&boxes, ((xa + xb) / 2.0, y), hit) else {
let Some((story, tp, cells)) = crossed(boxes, ((xa + xb) / 2.0, y), hit) else {
return Err(CmdError::Failed("the line doesn't cross a table cell".into()));
};
let Some(&(r, c0, _)) = cells.first() else { return Err(CmdError::Failed("the line doesn't cross a table cell".into())) };
@@ -459,17 +477,26 @@ pub struct EraseTarget {
/// The border between two cells nearest page point (`x`, `y`), within [`ERASER_REACH`].
pub fn erase_target(l: &DocLayout, page: usize, x: f32, y: f32) -> Option<EraseTarget> {
erase_target_in(l, page, Reach::Body, x, y)
}
/// [`erase_target`] while `editing` is edited: a header's or footer's tables then (#5558).
pub fn erase_target_in(l: &DocLayout, page: usize, tables: Reach, x: f32, y: f32) -> Option<EraseTarget> {
erase_among(&cell_boxes(l, page, tables), x, y)
}
/// [`erase_target`] among the tables of `boxes`.
fn erase_among(boxes: &[CellBox], x: f32, y: f32) -> Option<EraseTarget> {
if !x.is_finite() || !y.is_finite() {
return None;
}
let boxes = cell_boxes(l, page);
let mut best: Option<(f32, usize, EraseTarget)> = None;
let mut offer = |d: f32, depth: usize, e: EraseTarget| {
if d <= ERASER_REACH && best.as_ref().is_none_or(|(bd, bdepth, _)| d < *bd - 0.01 || (d <= *bd + 0.01 && depth > *bdepth)) {
best = Some((d, depth, e));
}
};
for a in &boxes {
for a in boxes {
let (ar, ab) = (a.rect.right(), a.rect.bottom());
let same = |b: &&CellBox| b.story == a.story && b.table == a.table;
// The border on a's right, shared with the next cell of its row.
@@ -518,7 +545,7 @@ fn eraser(s: &mut Session, v: &Value) -> CmdResult {
if l.pages.get(page).is_none() {
return Err(CmdError::Params(format!("no page {page}")));
}
let e = erase_target(&l, page, x, y).ok_or_else(|| CmdError::Failed("there's no border between two cells there".into()))?;
let e = erase_among(&command_boxes(s, &l, v, page), x, y).ok_or_else(|| CmdError::Failed("there's no border between two cells there".into()))?;
let (story, tp) = (e.story, e.table.clone());
let t = s.doc.table_mut(story, &tp)?;
let ((r, c), (r2, c2)) = (e.first, e.second);
@@ -581,6 +608,7 @@ fn eraser(s: &mut Session, v: &Value) -> CmdResult {
mod tests {
use super::*;
use serde_json::json;
use wordcraft_layout::Placed;
/// Each row's cell spans.
fn shape(t: &Table) -> Value {
+21 -16
View File
@@ -16,7 +16,7 @@ use wordcraft_doc::{Document, Path, Pos, StoryRef, Table};
use wordcraft_geom::{Point, Rect};
use wordcraft_layout::{DocLayout, Placed};
use super::table_resize::{self, CellBox, Edge, REACH, ResizeTarget};
use super::table_resize::{self, CellBox, Edge, REACH, Reach, ResizeTarget};
use super::{sel_result, table};
use crate::{CellRange, CmdError, CmdResult, CommandSpec, Selection, Session, p};
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
r#"{"page": n, "x": pt, "y": pt, "toX": pt, "toY": pt, "reach"?: pt} (a drag from the move handle past a table's top-left corner: the table floats where it's dropped, the text wrapping around it; tables in the main text only)"#,
),
CommandSpec::new("table.fitColumn", "AutoFit Column by Double-Clicking", "Table Layout › Cell Size", fit_column).params(
r#"{"page": n, "x": pt, "y": pt, "reach"?: pt} (a double-click on a column border: the column left of it fits its contents and the columns right of it keep their widths, moving with the border, so the table narrows or widens (up to the right margin), as in Word)"#,
r#"{"page": n, "x": pt, "y": pt, "reach"?: pt} (a double-click on a column border of a table in the caret's story: the column left of it fits its contents and the columns right of it keep their widths, moving with the border, so the table narrows or widens (up to the right margin), as in Word)"#,
),
]
}
@@ -205,11 +205,12 @@ pub fn target_at(l: &DocLayout, doc: &Document, story: StoryRef, page: usize, x:
return None;
}
let reach = clean_reach(reach);
if table_resize::resize_target(l, doc, page, x, y, reach).is_some() {
let tables = Reach::of(l, doc, story, page);
if table_resize::resize_target_in(l, doc, page, x, y, reach, tables).is_some() {
return None;
}
let boxes = table_resize::cell_boxes(l, page);
table_resize::tables_on(l, doc, page)
let boxes = table_resize::cell_boxes_in(l, page, tables);
table_resize::tables_on_in(l, doc, page, tables)
.into_iter()
.filter(|g| g.story == story)
.filter_map(|geom| {
@@ -226,7 +227,7 @@ pub fn handle_table(l: &DocLayout, doc: &Document, story: StoryRef, page: usize,
return None;
}
let pad = clean_reach(reach) / 2.0;
table_resize::tables_on(l, doc, page)
table_resize::tables_on_in(l, doc, page, Reach::of(l, doc, story, page))
.into_iter()
.filter(|g| {
let h = handle(g);
@@ -242,7 +243,7 @@ pub fn caret_handles(l: &DocLayout, doc: &Document, story: StoryRef, table: &Pat
let rows = doc.table(story, table).map_or(0, |t| t.rows.len());
let has_row = |p: usize, r: usize| {
l.pages.get(p).is_some_and(|pg| {
pg.items.iter().any(|it| matches!(it, Placed::Cell { table: t, story: st, row, .. } if *st == story && t == table && *row == r))
pg.story_items(story).any(|it| matches!(it, Placed::Cell { table: t, story: st, row, .. } if *st == story && t == table && *row == r))
})
};
// A repeated header row, or a row running on to the next page, is drawn on more than one
@@ -253,7 +254,9 @@ pub fn caret_handles(l: &DocLayout, doc: &Document, story: StoryRef, table: &Pat
return (None, None);
}
// The table's geometry on this page that the pointer handles are drawn and grabbed from.
let Some(g) = table_resize::tables_on(l, doc, page).into_iter().find(|g| g.story == story && g.table == *table) else {
let Some(g) =
table_resize::tables_on_in(l, doc, page, Reach::of(l, doc, story, page)).into_iter().find(|g| g.story == story && g.table == *table)
else {
return (None, None);
};
(first.then(|| handle(&g)), last.then(|| g.handle()))
@@ -298,7 +301,7 @@ pub fn cell_rects(l: &DocLayout, doc: &Document, range: &CellRange) -> Vec<(usiz
let picked: std::collections::BTreeSet<(usize, usize)> = range.cells(t).into_iter().collect();
let mut out = Vec::new();
for (pi, pg) in l.pages.iter().enumerate() {
for it in &pg.items {
for it in pg.story_items(range.story) {
// A vertically merged cell's box spans its rows (#640); its continuation rows'
// `covered` boxes would shade it twice.
if let Placed::Cell { rect, table, row, cell, story, covered: false, .. } = it
@@ -326,7 +329,7 @@ pub fn selection_rects(l: &DocLayout, doc: &Document, a: &Pos, b: &Pos, page_hin
let mut seen = BTreeMap::new();
let mut cells = Vec::new();
for (pi, pg) in l.pages.iter().enumerate() {
for it in &pg.items {
for it in pg.story_items(a.story) {
// A vertically merged cell's box spans its rows (#640), as in `cell_rects`.
if let Placed::Cell { rect, table, row, story, covered: false, .. } = it
&& *story == a.story
@@ -510,7 +513,7 @@ fn insert_at(s: &mut Session, v: &Value) -> CmdResult {
/// Where table `table` of `story` is first drawn: its page and top-left corner.
pub fn corner(l: &DocLayout, story: StoryRef, table: &Path) -> Option<(usize, f32, f32)> {
l.pages.iter().enumerate().find_map(|(pi, pg)| {
let cells = pg.items.iter().filter_map(|it| match it {
let cells = pg.story_items(story).filter_map(|it| match it {
Placed::Cell { rect, table: t, story: st, .. } if *st == story && t == table => Some(*rect),
_ => None,
});
@@ -565,10 +568,12 @@ fn move_drag(s: &mut Session, v: &Value) -> CmdResult {
fn fit_column(s: &mut Session, v: &Value) -> CmdResult {
let (page, x, y, reach) = point(v)?;
let l = s.layout();
let Some((target, line)) = table_resize::resize_target(&l, &s.doc, page, x, y, reach).and_then(|t| match t.edge {
Edge::Column(line) => Some((t, line)),
_ => None,
}) else {
let Some((target, line)) = table_resize::resize_target_in(&l, &s.doc, page, x, y, reach, Reach::of(&l, &s.doc, s.sel.focus.story, page))
.and_then(|t| match t.edge {
Edge::Column(line) => Some((t, line)),
_ => None,
})
else {
return Err(CmdError::Failed("there's no column border there".into()));
};
let t = s.doc.table(target.story, &target.table).ok_or_else(|| CmdError::Failed("there's no table there".into()))?;
@@ -595,7 +600,7 @@ fn room_right(l: &DocLayout, doc: &Document, page: usize, target: &ResizeTarget)
let margin = l.pages.get(page).map_or(target.right(), |pg| pg.body.right());
let Some((outer, row, cell)) = target.table.cell() else { return margin };
let Some(t) = doc.table(target.story, &outer) else { return margin };
let boxes = table_resize::cell_boxes(l, page);
let boxes = table_resize::story_cell_boxes(l, page, target.story);
let Some(b) = boxes.iter().find(|b| b.story == target.story && b.table == outer && b.row == row && b.cell == cell) else {
return margin;
};
+77 -19
View File
@@ -9,7 +9,7 @@
use serde_json::Value;
use wordcraft_doc::props::{Align, HeightRule, VMerge};
use wordcraft_doc::table::MAX_COLS;
use wordcraft_doc::{Cell, Document, Path, StoryRef, Table};
use wordcraft_doc::{Cell, Document, PartKind, Path, StoryRef, Table};
use wordcraft_geom::Rect;
use wordcraft_layout::{DocLayout, Placed};
@@ -29,7 +29,7 @@ const MAX_LEN: f32 = 1584.0;
pub fn specs() -> Vec<CommandSpec> {
vec![CommandSpec::new("table.resizeDrag", "Resize Table by Dragging", "Table Layout › Cell Size", resize_drag).params(
r#"{"page": n, "x": pt, "y": pt, "toX": pt, "toY": pt, "shift"?: bool, "ctrl"?: bool, "reach"?: pt} (a mouse drag in page points, 0-based page, starting on a table border or the resize handle: a column border moves (the column to its right gives or takes the difference, so the table keeps its width; with ctrl the columns right of it share it in proportion; with shift, or on the table's right edge, only the column left of it changes); the table's left edge moves a left-aligned table's indent, the first column making up the difference (a centred or right-aligned table keeps its alignment: only the first column changes); with cells of the table selected, a border of theirs moves only in their rows; a row's bottom border sets that row's height; the handle just outside the bottom-right corner scales every column and the rows on that page. `reach` (default 3) is how near the start has to be.)"#,
r#"{"page": n, "x": pt, "y": pt, "toX": pt, "toY": pt, "shift"?: bool, "ctrl"?: bool, "reach"?: pt} (a mouse drag in page points, 0-based page, starting on a border or the resize handle of a table in the caret's story (a header's or footer's tables while one is edited): a column border moves (the column to its right gives or takes the difference, so the table keeps its width; with ctrl the columns right of it share it in proportion; with shift, or on the table's right edge, only the column left of it changes); the table's left edge moves a left-aligned table's indent, the first column making up the difference (a centred or right-aligned table keeps its alignment: only the first column changes); with cells of the table selected, a border of theirs moves only in their rows; a row's bottom border sets that row's height; the handle just outside the bottom-right corner scales every column and the rows on that page. `reach` (default 3) is how near the start has to be.)"#,
)]
}
@@ -327,17 +327,53 @@ pub(crate) struct CellBox {
pub(crate) cell: usize,
}
pub(crate) fn cell_boxes(l: &DocLayout, page: usize) -> Vec<CellBox> {
/// Which of a page's tables the pointer reaches (#5558): the body's, with its text boxes' and
/// notes', while those are edited; a header's and footer's, with the text boxes in them, while
/// a header or footer (or a text box in one) is, and then not the dimmed body's.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reach {
Body,
HeaderFooter,
}
impl Reach {
/// The reach while `editing` is edited, around `page` (where a text box's host is looked for).
pub fn of(l: &DocLayout, doc: &Document, editing: StoryRef, page: usize) -> Reach {
let kind = |s: StoryRef| match s {
StoryRef::Part(id) => doc.parts.get(&id).map(|p| p.kind),
StoryRef::Body => None,
};
let host = match editing {
StoryRef::Part(id) if kind(editing) == Some(PartKind::TextBox) => l.text_box(id, page).map_or(editing, |o| o.story),
_ => editing,
};
if matches!(kind(host), Some(PartKind::Header | PartKind::Footer)) { Reach::HeaderFooter } else { Reach::Body }
}
}
/// The table cells on a page that the pointer reaches ([`Reach`]).
pub(crate) fn cell_boxes_in(l: &DocLayout, page: usize, reach: Reach) -> Vec<CellBox> {
let Some(pg) = l.pages.get(page) else { return Vec::new() };
pg.items
.iter()
.filter_map(|it| match it {
Placed::Cell { rect, table, row, cell, story, .. } => {
Some(CellBox { rect: *rect, table: table.clone(), story: *story, row: *row, cell: *cell })
}
_ => None,
})
.collect()
let items: Box<dyn Iterator<Item = &Placed>> = match reach {
Reach::Body => Box::new(pg.items.iter()),
Reach::HeaderFooter => Box::new(pg.header.iter().chain(pg.footer.iter())),
};
items.filter_map(cell_box).collect()
}
/// The cells of `story`'s tables on a page, wherever that story is drawn.
pub(crate) fn story_cell_boxes(l: &DocLayout, page: usize, story: StoryRef) -> Vec<CellBox> {
let Some(pg) = l.pages.get(page) else { return Vec::new() };
pg.story_items(story).filter_map(cell_box).filter(|b| b.story == story).collect()
}
fn cell_box(it: &Placed) -> Option<CellBox> {
match it {
Placed::Cell { rect, table, row, cell, story, .. } => {
Some(CellBox { rect: *rect, table: table.clone(), story: *story, row: *row, cell: *cell })
}
_ => None,
}
}
/// The drawn geometry of one table on a page, from its cells' boxes.
@@ -403,8 +439,14 @@ fn geometry(t: &Table, boxes: &[&CellBox]) -> Option<(Vec<f32>, Vec<DrawnRow>)>
}
/// Every table drawn on a page, with its geometry there (`edge` is a placeholder).
#[cfg(test)]
pub(crate) fn tables_on(l: &DocLayout, doc: &Document, page: usize) -> Vec<ResizeTarget> {
let boxes = cell_boxes(l, page);
tables_on_in(l, doc, page, Reach::Body)
}
/// Every table drawn on a page that the pointer reaches ([`Reach`]).
pub(crate) fn tables_on_in(l: &DocLayout, doc: &Document, page: usize, reach: Reach) -> Vec<ResizeTarget> {
let boxes = cell_boxes_in(l, page, reach);
let mut tables: Vec<(StoryRef, &Path)> = Vec::new();
for b in &boxes {
if !tables.iter().any(|(s, p)| *s == b.story && **p == b.table) {
@@ -431,11 +473,17 @@ fn on_handle(t: &ResizeTarget, x: f32, y: f32, reach: f32) -> bool {
/// The innermost table under page point (`x`, `y`) whose resize handle is on this page, or whose
/// handle is under the point: the one whose handle the app shows.
pub fn table_under(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, reach: f32) -> Option<ResizeTarget> {
table_under_in(l, doc, page, x, y, reach, Reach::Body)
}
/// [`table_under`] among the tables `tables` reaches: a header's or footer's while one is edited
/// (#5558).
pub fn table_under_in(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, reach: f32, tables: Reach) -> Option<ResizeTarget> {
if !x.is_finite() || !y.is_finite() {
return None;
}
let reach = if reach.is_finite() { reach.clamp(0.5, 24.0) } else { REACH };
tables_on(l, doc, page)
tables_on_in(l, doc, page, tables)
.into_iter()
.filter(|t| t.ends_here && ((x >= t.left() && x <= t.right() && y >= t.top() && y <= t.bottom()) || on_handle(t, x, y, reach)))
.max_by_key(|t| t.table.0.len())
@@ -444,12 +492,18 @@ pub fn table_under(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, r
/// The table border or resize handle within `reach` points of page point (`x`, `y`): the
/// nearest, and of nested tables the innermost.
pub fn resize_target(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, reach: f32) -> Option<ResizeTarget> {
resize_target_in(l, doc, page, x, y, reach, Reach::Body)
}
/// [`resize_target`] among the tables `tables` reaches: a header's or footer's while one is
/// edited (#5558).
pub fn resize_target_in(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, reach: f32, tables: Reach) -> Option<ResizeTarget> {
if !x.is_finite() || !y.is_finite() {
return None;
}
let reach = if reach.is_finite() { reach.clamp(0.5, 24.0) } else { REACH };
let mut best: Option<(f32, usize, ResizeTarget)> = None;
for mut target in tables_on(l, doc, page) {
for mut target in tables_on_in(l, doc, page, tables) {
let depth = target.table.0.len();
let mut offer = |d: f32, edge: Edge, target: &mut ResizeTarget| {
if d <= reach && best.as_ref().is_none_or(|(bd, bdepth, _)| d < *bd - 0.01 || (d <= *bd + 0.01 && depth > *bdepth)) {
@@ -500,8 +554,8 @@ fn resize_drag(s: &mut Session, v: &Value) -> CmdResult {
if l.pages.get(page).is_none() {
return Err(CmdError::Params(format!("no page {page}")));
}
let mut target =
resize_target(&l, &s.doc, page, x, y, reach).ok_or_else(|| CmdError::Failed("there's no table border or resize handle there".into()))?;
let mut target = resize_target_in(&l, &s.doc, page, x, y, reach, Reach::of(&l, &s.doc, s.sel.focus.story, page))
.ok_or_else(|| CmdError::Failed("there's no table border or resize handle there".into()))?;
target.limit_to_selection(s, y);
let plan = target.plan(to_x - x, to_y - y, share);
if plan.widths.is_none() && plan.heights.is_empty() && plan.cells.is_empty() {
@@ -647,7 +701,11 @@ fn regrid(t: &mut Table, cols: &[f32], rows: &[(usize, Vec<f32>)]) -> Result<(),
/// The page x of the target table's left edge on `page`, as drawn.
fn drawn_left(l: &DocLayout, page: usize, target: &ResizeTarget) -> Option<f32> {
cell_boxes(l, page).iter().filter(|b| b.story == target.story && b.table == target.table).map(|b| b.rect.x).min_by(f32::total_cmp)
story_cell_boxes(l, page, target.story)
.iter()
.filter(|b| b.story == target.story && b.table == target.table)
.map(|b| b.rect.x)
.min_by(f32::total_cmp)
}
/// Make `widths` (one per grid column) the table's column widths, as drawn: no preferred table
@@ -663,7 +721,7 @@ pub(crate) fn set_widths(t: &mut Table, widths: Vec<f32>) {
/// The drawn height of each of the target table's rows on `page`.
fn drawn_heights(l: &DocLayout, doc: &Document, page: usize, target: &ResizeTarget) -> Vec<(usize, f32)> {
tables_on(l, doc, page)
tables_on_in(l, doc, page, Reach::of(l, doc, target.story, page))
.into_iter()
.find(|t| t.story == target.story && t.table == target.table)
.map(|t| t.rows.iter().map(|r| (r.row, r.bottom - r.top)).collect())
+177
View File
@@ -13404,6 +13404,183 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
}
/// #5558: a table in the header is edited like one in the body (typing in its cells, Table
/// Layout's rows and columns), and a table copied from the body is pasted into the header as a
/// table, not as its text.
#[test]
fn a_header_table_is_edited_and_a_copied_table_pastes_into_the_header() {
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Body"}));
let id = run(&mut s, "insert.header", json!({"text": "Head"}))["story"].as_u64().unwrap() as u32;
let hf = StoryRef::Part(id);
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
assert_eq!(s.sel.focus.story, hf, "the caret stays in the header");
assert!(s.sel.focus.path.cell().is_some(), "the caret is in the new table: {:?}", s.sel.focus);
run(&mut s, "text.insert", json!({"text": "Cell"}));
run(&mut s, "table.insertRowBelow", json!({}));
run(&mut s, "table.insertColumnRight", json!({}));
let tables = |s: &Session| {
s.doc
.story(hf)
.map(|b| b.iter().filter_map(|b| b.as_table().map(|t| (t.rows.len(), t.rows[0].cells.len()))).collect::<Vec<_>>())
.unwrap_or_default()
};
assert_eq!(tables(&s), vec![(3, 3)]);
assert!(s.doc.plain_text(hf).contains("Cell"));
// Its column border drags, as a body table's does: the border is in the page's header.
let first = s.layout().pages[0].header.iter().find_map(|it| match it {
wordcraft_layout::Placed::Cell { rect, row: 0, cell: 0, story, .. } if *story == hf => Some(*rect),
_ => None,
});
let first = first.expect("the header's table is laid out");
let grid = |s: &Session| s.doc.story(hf).and_then(|b| b.iter().find_map(|b| b.as_table().map(|t| t.grid.clone()))).unwrap_or_default();
let before = grid(&s);
let (x, y) = (first.right(), first.y + first.h / 2.0);
run(&mut s, "table.resizeDrag", json!({"page": 0, "x": x, "y": y, "toX": x + 30.0, "toY": y}));
let after = grid(&s);
assert!(after[0] > before[0] + 20.0, "the header table's first column widened: {before:?} → {after:?}");
// While the body is edited, the dimmed header's table doesn't take the pointer.
assert!(crate::cmd::table_resize::resize_target_in(&s.layout(), &s.doc, 0, x, y, 4.0, crate::cmd::table_resize::Reach::Body).is_none());
// The Draw Table pen splits the header table's cell it crosses, as in the body.
let first = s.layout().pages[0].header.iter().find_map(|it| match it {
wordcraft_layout::Placed::Cell { rect, row: 0, cell: 0, story, .. } if *story == hf => Some(*rect),
_ => None,
});
let first = first.expect("the header's table is still laid out");
let mid = first.x + first.w / 2.0;
run(&mut s, "table.draw", json!({"page": 0, "x0": mid, "y0": first.y + 1.0, "x1": mid, "y1": first.bottom() - 1.0}));
assert_eq!(grid(&s).len(), 4, "the pen split a column of the header's table");
// A table copied from the body pastes into the header as a table.
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 4)}));
run(&mut s, "insert.table", json!({"rows": 1, "cols": 2}));
run(&mut s, "text.insert", json!({"text": "Copied"}));
run(&mut s, "table.selectTable", json!({}));
run(&mut s, "edit.copy", json!({}));
// The end of the header's "Head" paragraph, after its table.
let head = s.doc.story(hf).map_or(0, |b| b.len().saturating_sub(1));
let at = Pos { story: hf, path: wordcraft_doc::Path::top(head), off: 4 };
assert_eq!(s.doc.para_at(&at).map(|p| p.text.as_str()), Some("Head"));
run(&mut s, "caret.set", json!({"pos": at}));
run(&mut s, "edit.paste", json!({}));
let mut found = tables(&s);
found.sort();
assert_eq!(found, vec![(1, 2), (3, 4)], "{:?}", s.doc.story(hf));
assert!(s.doc.plain_text(hf).contains("Copied"));
}
/// #5558 review: a body text box and a footnote share the body's editing. With the caret in
/// one, the body's table still takes the pointer (border drags, the pen) and the dimmed header's
/// doesn't; with the caret in the footer, the footer's table takes it and the body's doesn't.
#[test]
fn body_tables_keep_the_pointer_from_a_text_box_or_a_note_and_a_footer_table_takes_it() {
use crate::cmd::table_resize::{Reach, resize_target_in};
use wordcraft_layout::Placed;
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Body"}));
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
let head = run(&mut s, "insert.header", json!({"text": "Head"}))["story"].as_u64().unwrap() as u32;
run(&mut s, "insert.table", json!({"rows": 1, "cols": 2}));
let foot = run(&mut s, "insert.footer", json!({"text": "Foot"}))["story"].as_u64().unwrap() as u32;
run(&mut s, "insert.table", json!({"rows": 1, "cols": 2}));
run(&mut s, "insert.closeHeader", json!({}));
// The middle of the right border of `story`'s first cell on page 1.
let border = |s: &mut Session, story: StoryRef| {
let l = s.layout();
let pg = &l.pages[0];
let r = pg.items.iter().chain(&pg.header).chain(&pg.footer).find_map(|it| match it {
Placed::Cell { rect, row: 0, cell: 0, story: st, .. } if *st == story => Some(*rect),
_ => None,
});
let r = r.unwrap_or_else(|| panic!("{story:?}'s table is laid out"));
(r.right(), r.y + r.h / 2.0, r)
};
let grabbed = |s: &mut Session, (x, y): (f32, f32)| {
let l = s.layout();
let reach = Reach::of(&l, &s.doc, s.sel.focus.story, 0);
resize_target_in(&l, &s.doc, 0, x, y, 4.0, reach).map(|t| t.story)
};
let grid = |s: &Session, story: StoryRef| {
s.doc.story(story).and_then(|b| b.iter().find_map(|b| b.as_table().map(|t| t.grid.clone()))).unwrap_or_default()
};
// A text box in the body (the borders are measured once it is in).
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
let boxed = run(&mut s, "insert.textBox", json!({"text": "in box"}))["story"].as_u64().unwrap() as u32;
assert_eq!(s.sel.focus.story, StoryRef::Part(boxed));
let (bx, by, _) = border(&mut s, StoryRef::Body);
let (hx, hy, _) = border(&mut s, StoryRef::Part(head));
assert_eq!(grabbed(&mut s, (bx, by)), Some(StoryRef::Body), "the body's table, from a body text box");
assert_eq!(grabbed(&mut s, (hx, hy)), None, "not the dimmed header's");
let before = grid(&s, StoryRef::Body);
run(&mut s, "table.resizeDrag", json!({"page": 0, "x": bx, "y": by, "toX": bx + 20.0, "toY": by}));
assert!(grid(&s, StoryRef::Body)[0] > before[0] + 10.0, "the drag widened the body's column");
// A footnote.
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 4)}));
run(&mut s, "references.footnote", json!({"text": "note"}));
let note = s.doc.parts.iter().find(|(_, p)| p.kind == wordcraft_doc::PartKind::Footnote).map(|(id, _)| *id).expect("the footnote's story");
run(&mut s, "caret.set", json!({"pos": Pos { story: StoryRef::Part(note), path: wordcraft_doc::Path::top(0), off: 0 }}));
let (bx, by, _) = border(&mut s, StoryRef::Body);
assert_eq!(grabbed(&mut s, (bx, by)), Some(StoryRef::Body), "the body's table, from a footnote");
assert_eq!(grabbed(&mut s, (hx, hy)), None);
// The pen still splits the body's cell it crosses instead of drawing a new table.
let (_, _, cell) = border(&mut s, StoryRef::Body);
let mid = cell.x + cell.w / 2.0;
let cols = grid(&s, StoryRef::Body).len();
run(&mut s, "table.draw", json!({"page": 0, "x0": mid, "y0": cell.y + 1.0, "x1": mid, "y1": cell.bottom() - 1.0}));
assert_eq!(grid(&s, StoryRef::Body).len(), cols + 1, "the pen split a body column");
// The footer, while it is edited: its table, not the body's.
run(&mut s, "caret.set", json!({"pos": Pos { story: StoryRef::Part(foot), path: wordcraft_doc::Path::top(0), off: 0 }}));
let (bx, by, _) = border(&mut s, StoryRef::Body);
let (fx, fy, _) = border(&mut s, StoryRef::Part(foot));
assert_eq!(grabbed(&mut s, (fx, fy)), Some(StoryRef::Part(foot)), "the footer's table, while the footer is edited");
assert_eq!(grabbed(&mut s, (bx, by)), None, "not the dimmed body's");
let before = grid(&s, StoryRef::Part(foot));
run(&mut s, "table.resizeDrag", json!({"page": 0, "x": fx, "y": fy, "toX": fx + 20.0, "toY": fy}));
assert!(grid(&s, StoryRef::Part(foot))[0] > before[0] + 10.0, "the drag widened the footer's column");
}
/// #5558 review: `table.eraser` and `table.draw` with a `story` work on that story's tables only:
/// a border of another story's table drawn there (a table in a body text box, among the body's
/// items) is left alone; the named story's own is erased.
#[test]
fn the_eraser_and_the_pen_keep_to_the_story_they_are_given() {
use wordcraft_layout::Placed;
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Body"}));
run(&mut s, "insert.table", json!({"rows": 1, "cols": 2}));
// A text box in the body with a table of its own.
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
let boxed = StoryRef::Part(run(&mut s, "insert.textBox", json!({"text": "Box"}))["story"].as_u64().unwrap() as u32);
run(&mut s, "insert.table", json!({"rows": 1, "cols": 2}));
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
let first = |s: &mut Session, story: StoryRef| {
let l = s.layout();
let r = l.pages[0].items.iter().find_map(|it| match it {
Placed::Cell { rect, row: 0, cell: 0, story: st, .. } if *st == story => Some(*rect),
_ => None,
});
r.unwrap_or_else(|| panic!("{story:?}'s table is laid out"))
};
let cols = |s: &Session, story: StoryRef| {
s.doc.story(story).and_then(|b| b.iter().find_map(|b| b.as_table().map(|t| t.rows[0].cells.len()))).unwrap_or(0)
};
let body = serde_json::to_value(StoryRef::Body).unwrap();
// Named the body: the text box's table, though drawn among the body's items, is left alone.
let b = first(&mut s, boxed);
let erase = json!({"page": 0, "x": b.right(), "y": b.y + b.h / 2.0, "story": body.clone()});
assert!(s.run("table.eraser", &erase).is_err(), "no body border there");
let mid = b.x + b.w / 2.0;
let line = json!({"page": 0, "x0": mid, "y0": b.y + 1.0, "x1": mid, "y1": b.bottom() - 1.0, "story": body.clone()});
assert!(s.run("table.draw", &line).is_err(), "no body table to split there");
assert_eq!(cols(&s, boxed), 2, "the text box's table is as it was");
// The body's own border is erased.
let t = first(&mut s, StoryRef::Body);
run(&mut s, "table.eraser", json!({"page": 0, "x": t.right(), "y": t.y + t.h / 2.0, "story": body}));
assert_eq!(cols(&s, StoryRef::Body), 1, "the body table's two cells merged");
}
/// A picture an OpenDocument file gives no size is shown at its own, fitted to the text as other
/// formats' are; one with a stated size keeps it, in line too.
#[test]
+10 -7
View File
@@ -264,18 +264,21 @@ impl<'a> PartPages<'a> {
/// The items of `page` that `story`'s pieces are among (each one looked at counted as a step of
/// [`crate::work`]).
fn items_of(page: &Page, story: StoryRef) -> Box<dyn Iterator<Item = &Placed> + '_> {
let items = story_items(page, story);
let items = page.story_items(story);
#[cfg(test)]
let items: Box<dyn Iterator<Item = &Placed> + '_> = Box::new(items.inspect(|_| crate::work::steps(1)));
items
}
fn story_items(page: &Page, story: StoryRef) -> Box<dyn Iterator<Item = &Placed> + '_> {
match story {
StoryRef::Body => Box::new(page.items.iter()),
// Headers and footers, and the text boxes in them, are drawn with the page's header and
// footer; everything else is in its items.
StoryRef::Part(_) => Box::new(page.header.iter().chain(page.footer.iter()).chain(page.items.iter())),
impl Page {
/// The items `story`'s pieces are among: the page's items for the body; for a header,
/// footer or text box, its header and footer too (they hold the header's and footer's
/// pieces, and the text boxes in them).
pub fn story_items(&self, story: StoryRef) -> Box<dyn Iterator<Item = &Placed> + '_> {
match story {
StoryRef::Body => Box::new(self.items.iter()),
StoryRef::Part(_) => Box::new(self.header.iter().chain(self.footer.iter()).chain(self.items.iter())),
}
}
}
+24 -22
View File
@@ -142,33 +142,35 @@ pub fn paint(app: &WordApp, painter: &egui::Painter, t: &Tokens, layout: &DocLay
let ink = Stroke::new(1.5, t.accent);
let hover = painter.ctx().input(|i| i.pointer.hover_pos());
match (tool, app.canvas.table_stroke) {
(TableTool::Draw, Some(st)) => match table_draw::stroke(layout, st.page, st.from.0, st.from.1, st.to.0, st.to.1) {
Some(Kind::Rect(r)) => {
if let (Some(a), Some(b)) = (to_screen(st.page, r.x, r.y), to_screen(st.page, r.right(), r.bottom())) {
painter.rect_stroke(Rect::from_two_pos(a, b), 0.0, ink, egui::StrokeKind::Middle);
(TableTool::Draw, Some(st)) => {
match table_draw::stroke_in(layout, st.page, crate::table_resize::reach(app, layout, st.page), st.from.0, st.from.1, st.to.0, st.to.1) {
Some(Kind::Rect(r)) => {
if let (Some(a), Some(b)) = (to_screen(st.page, r.x, r.y), to_screen(st.page, r.right(), r.bottom())) {
painter.rect_stroke(Rect::from_two_pos(a, b), 0.0, ink, egui::StrokeKind::Middle);
}
}
Some(Kind::Vertical { x, y0, y1 }) => {
if let (Some(a), Some(b)) = (to_screen(st.page, x, y0), to_screen(st.page, x, y1)) {
painter.line_segment([a, b], ink);
}
}
Some(Kind::Horizontal { y, x0, x1 }) => {
if let (Some(a), Some(b)) = (to_screen(st.page, x0, y), to_screen(st.page, x1, y)) {
painter.line_segment([a, b], ink);
}
}
// Not a table or a line yet: the drag's box, dashed and dim.
None => {
if let (Some(a), Some(b)) = (to_screen(st.page, st.from.0, st.from.1), to_screen(st.page, st.to.0, st.to.1)) {
dashed_rect(painter, Rect::from_two_pos(a, b), Stroke::new(1.0, t.text_dim));
}
}
}
Some(Kind::Vertical { x, y0, y1 }) => {
if let (Some(a), Some(b)) = (to_screen(st.page, x, y0), to_screen(st.page, x, y1)) {
painter.line_segment([a, b], ink);
}
}
Some(Kind::Horizontal { y, x0, x1 }) => {
if let (Some(a), Some(b)) = (to_screen(st.page, x0, y), to_screen(st.page, x1, y)) {
painter.line_segment([a, b], ink);
}
}
// Not a table or a line yet: the drag's box, dashed and dim.
None => {
if let (Some(a), Some(b)) = (to_screen(st.page, st.from.0, st.from.1), to_screen(st.page, st.to.0, st.to.1)) {
dashed_rect(painter, Rect::from_two_pos(a, b), Stroke::new(1.0, t.text_dim));
}
}
},
}
(TableTool::Erase, _) => {
if let Some(p) = hover
&& let Some((page, x, y)) = crate::canvas::page_at(pages, layout, scale, p)
&& let Some(e) = table_draw::erase_target(layout, page, x, y)
&& let Some(e) = table_draw::erase_target_in(layout, page, crate::table_resize::reach(app, layout, page), x, y)
&& let (Some(a), Some(b)) = (to_screen(page, e.from.0, e.from.1), to_screen(page, e.to.0, e.to.1))
{
painter.line_segment([a, b], Stroke::new(3.0, t.red));
+8 -3
View File
@@ -99,11 +99,16 @@ pub(crate) fn available(app: &WordApp) -> bool {
&& crate::ink::cursor(app).is_none()
}
/// Which tables the pointer reaches on `page`: a header's and footer's while one is edited (#5558).
pub(crate) fn reach(app: &WordApp, layout: &DocLayout, page: usize) -> table_resize::Reach {
table_resize::Reach::of(layout, &app.session.doc, app.session.sel.focus.story, page)
}
/// The border or handle under screen point `p`, if any.
fn target_at(app: &WordApp, layout: &DocLayout, rects: &[Rect], scale: f32, p: Pos2) -> Option<(usize, f32, f32, ResizeTarget)> {
let (page, x, y) = crate::canvas::page_at(rects, layout, scale, p)?;
let sc = page_scale(rects, layout, scale, page)?;
let t = table_resize::resize_target(layout, &app.session.doc, page, x, y, REACH_PX / sc)?;
let t = table_resize::resize_target_in(layout, &app.session.doc, page, x, y, REACH_PX / sc, reach(app, layout, page))?;
Some((page, x, y, t))
}
@@ -167,7 +172,7 @@ pub(crate) fn grab(app: &mut WordApp, layout: &DocLayout, page: usize, x: f32, y
if !available(app) {
return;
}
if let Some(mut target) = table_resize::resize_target(layout, &app.session.doc, page, x, y, 1.0) {
if let Some(mut target) = table_resize::resize_target_in(layout, &app.session.doc, page, x, y, 1.0, reach(app, layout, page)) {
target.limit_to_selection(&app.session, y);
app.canvas.table_resize = Some(ResizeDrag { page, from: (x, y), to: (x, y), target, ruler: true });
}
@@ -277,7 +282,7 @@ pub fn paint(app: &WordApp, painter: &egui::Painter, t: &Tokens, layout: &DocLay
let Some(p) = painter.ctx().input(|i| i.pointer.hover_pos()) else { return };
let Some((page, x, y)) = crate::canvas::page_at(rects, layout, scale, p) else { return };
let Some(sc) = page_scale(rects, layout, scale, page) else { return };
let Some(tg) = table_resize::table_under(layout, &app.session.doc, page, x, y, REACH_PX / sc) else { return };
let Some(tg) = table_resize::table_under_in(layout, &app.session.doc, page, x, y, REACH_PX / sc, reach(app, layout, page)) else { return };
let h = tg.handle();
if let (Some(a), Some(b)) = (s(page, h.x, h.y), s(page, h.right(), h.bottom())) {
let r = Rect::from_two_pos(a, b);
+105
View File
@@ -8430,6 +8430,111 @@ fn focus_hides_the_ribbon_and_escape_brings_it_back() {
assert!(h.state().session.view.read_mode && shown(&h, "Focus"), "Immersive Reader keeps the status bar");
}
/// #5558: while the header is edited, its table is edited like one in the body: a click puts
/// the caret in the cell under it, typing goes there, and a column border drags to a new width.
#[test]
fn a_table_in_the_header_is_clicked_typed_in_and_resized() {
let ctx = egui::Context::default();
let mut a = app();
a.run("text.insert", json!({"text": "Body text"})).unwrap();
a.run("insert.header", json!({"text": "Head"})).unwrap();
a.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
a.run("insert.closeHeader", json!({})).unwrap();
a.run("caret.docStart", json!({})).unwrap();
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0));
let mut t = 0.0;
let mut frame = |a: &mut WordApp, events: Vec<egui::Event>| {
t += 1.0 / 60.0;
let input = egui::RawInput { events, time: Some(t), screen_rect: Some(screen), ..Default::default() };
ctx.run_ui(input, |ui| {
a.logic(ui.ctx());
a.ui(ui);
})
.drop_without_applying_deltas();
};
let btn = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
for _ in 0..20 {
frame(&mut a, Vec::new());
}
a.run("insert.editHeader", json!({"page": 0})).unwrap();
for _ in 0..20 {
frame(&mut a, Vec::new());
}
let hf = a.session.sel.focus.story;
assert_ne!(hf, wordcraft_doc::StoryRef::Body, "editing the header");
let cells = |a: &mut WordApp| {
let l = a.session.layout();
let mut v: Vec<(usize, usize, wordcraft_geom::Rect)> = l.pages[0]
.header
.iter()
.filter_map(|it| match it {
wordcraft_layout::Placed::Cell { rect, row, cell, story, .. } if *story == hf => Some((*row, *cell, *rect)),
_ => None,
})
.collect();
v.sort_by_key(|c| (c.0, c.1));
v
};
let cs = cells(&mut a);
assert_eq!(cs.len(), 4, "the header's table is laid out: {cs:?}");
// A click in the second row's second cell puts the caret there.
let r = cs[3].2;
let at = canvas::page_to_screen(&mut a, 0, r.x + r.w / 2.0, r.y + r.h / 2.0).expect("on screen");
frame(&mut a, vec![egui::Event::PointerMoved(at)]);
frame(&mut a, vec![btn(at, true)]);
frame(&mut a, vec![btn(at, false)]);
for _ in 0..10 {
frame(&mut a, Vec::new());
}
let focus = a.session.sel.focus.clone();
assert_eq!(focus.story, hf);
assert_eq!(focus.path.cell().map(|(_, r, c)| (r, c)), Some((1, 1)), "the caret is in the clicked cell: {focus:?}");
frame(&mut a, vec![egui::Event::Text("X".into())]);
frame(&mut a, Vec::new());
assert!(a.session.doc.plain_text(hf).contains('X'), "typing goes into the cell");
// Dragging the border between the columns moves it.
let width = |a: &WordApp| {
let blocks = a.session.doc.story(hf).expect("the header");
blocks.iter().find_map(|b| b.as_table().map(|t| t.grid.clone())).expect("its table")
};
let before = width(&a);
let border = cs[0].2.right();
let y = cs[0].2.y + cs[0].2.h / 2.0;
let from = canvas::page_to_screen(&mut a, 0, border, y).expect("on screen");
let to = from + egui::vec2(60.0, 0.0);
frame(&mut a, vec![egui::Event::PointerMoved(from)]);
frame(&mut a, vec![btn(from, true)]);
for i in 1..=6 {
frame(&mut a, vec![egui::Event::PointerMoved(from + egui::vec2(10.0 * i as f32, 0.0))]);
}
frame(&mut a, vec![btn(to, false)]);
for _ in 0..5 {
frame(&mut a, Vec::new());
}
let after = width(&a);
assert!(after[0] > before[0] + 10.0, "the first column widened: {before:?} → {after:?}");
assert_eq!(a.session.sel.focus.story, hf, "still editing the header");
// A table copied from the body, pasted with Ctrl+V at the end of the header's text, is a
// table there too.
a.run("insert.closeHeader", json!({})).unwrap();
a.run("caret.docEnd", json!({})).unwrap();
a.run("insert.table", json!({"rows": 1, "cols": 3})).unwrap();
a.run("text.insert", json!({"text": "Copied"})).unwrap();
a.run("table.selectTable", json!({})).unwrap();
let copied = a.run("edit.copy", json!({})).unwrap()["text"].as_str().unwrap_or_default().to_string();
a.run("insert.editHeader", json!({"page": 0})).unwrap();
let blocks = a.session.doc.story(hf).map_or(0, |b| b.len());
let head = wordcraft_doc::Pos { story: hf, path: wordcraft_doc::Path::top(blocks.saturating_sub(1)), off: 4 };
a.run("caret.set", json!({"pos": head})).unwrap();
frame(&mut a, vec![egui::Event::Paste(copied)]);
for _ in 0..5 {
frame(&mut a, Vec::new());
}
let tables: Vec<usize> = a.session.doc.story(hf).expect("the header").iter().filter_map(|b| b.as_table().map(|t| t.cols())).collect();
assert_eq!(tables, vec![2, 3], "the pasted table is a table in the header");
assert_eq!(cells(&mut a).len(), 4 + 3, "and is drawn there");
}
#[test]
fn format_painter_single_click_formats_the_target_word_and_finishes() {
let mut a = app();
+2 -1
View File
File diff suppressed because one or more lines are too long
+4 -2
View File
File diff suppressed because one or more lines are too long