diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index eb4cabb5a..21a883a91 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -21,6 +21,10 @@ use crate::EngineError; pub struct Maps { pub items: HashMap, pub stories: HashMap, + /// Each source text frame's place in its story's thread, for the stories copied so far. + source_ranks: HashMap, + /// The same place, by the id of the frame's copy. + frame_ranks: HashMap, } #[derive(Clone, Debug, PartialEq)] @@ -104,6 +108,7 @@ fn renumber_in(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Docum } } designcraft_doc::remap_story_assets(&mut st, &assets); + maps.source_ranks.extend(st.frames.iter().enumerate().map(|(i, f)| (*f, i))); st.frames.clear(); // Mapped first: the map is the seen-set that stops story recursion. maps.stories.insert(tf.story, n); @@ -112,8 +117,13 @@ fn renumber_in(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Docum n }; tf.story = new_sid; + // Frames are copied in page and nesting order, which can differ from the thread order: + // each copy goes where its source frame is in the source story's thread. + let rank = maps.source_ranks.get(&old).copied().unwrap_or(usize::MAX); + maps.frame_ranks.insert(new_id, rank); if let Some(st) = dst.story_mut(new_sid) { - st.frames.push(new_id); + let at = st.frames.partition_point(|f| maps.frame_ranks.get(f).is_some_and(|r| *r <= rank)); + st.frames.insert(at, new_id); } } Content::Graphic(g) => { @@ -130,16 +140,20 @@ fn renumber_in(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Docum } } -/// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes (#1522). +/// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes, and +/// the cells and notes inside those at any depth (#1522). The texts are walked with a stack, so a deeply +/// nested file can't exhaust the call stack. fn renumber_anchored(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Document, st: &mut Story, maps: &mut Maps) { - let mut fresh = |t: &mut Story| { - for o in &mut t.objects { + let mut texts = vec![st]; + while let Some(t) = texts.pop() { + let Story { objects, tables, notes, endnotes, .. } = t; + for o in objects.iter_mut() { renumber_in(dst, src, &mut Arc::make_mut(o).item, maps, false); } - }; - st.for_each_text_mut(&mut fresh); - for n in &mut st.endnotes { - Arc::make_mut(n).text.for_each_text_mut(&mut fresh); + for table in tables.values_mut() { + texts.extend(Arc::make_mut(table).cells.iter_mut().map(|c| &mut c.text)); + } + texts.extend(notes.iter_mut().chain(endnotes.iter_mut()).map(|n| &mut Arc::make_mut(n).text)); } } diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index afafb43d6..0d777cefa 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -1567,6 +1567,103 @@ fn merged_records_give_anchored_objects_their_own_ids() { designcraft_format::load(&designcraft_format::save(doc).unwrap()).unwrap(); } +/// A record's copy gives the objects anchored in an endnote of a table cell or of a footnote ids of +/// their own, and maps them, so placeholders on them follow the copy. +#[test] +fn record_copies_renumber_objects_anchored_in_nested_endnotes() { + use designcraft_doc::{AnchoredObject, ItemId, SpreadRef}; + use std::sync::Arc; + + let mut s = Session::new(); + new_doc(&mut s, 1); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 300.0], "Body", None); + let (frame, sid) = (ItemId(made["id"].as_u64().unwrap()), StoryId(made["story"].as_u64().unwrap())); + let a = exec(&mut s, "frame.create", json!({"rect": [450, 450, 474, 490]}))["id"].as_u64().unwrap(); + let b = exec(&mut s, "frame.create", json!({"rect": [480, 450, 504, 490]}))["id"].as_u64().unwrap(); + let mut src = s.doc().unwrap().doc.as_ref().clone(); + let d = &mut src; + let take = |d: &mut designcraft_doc::Document, id: u64| { + let it = d.item(ItemId(id)).cloned().unwrap(); + Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != id); + AnchoredObject::new(it, Default::default()) + }; + let in_cell = take(d, a); + let in_footnote = take(d, b); + let mut table = designcraft_doc::Table::new(d.alloc(), 1, 1, 0, 0, 40.0); + let cell = &mut table.cells[0].text; + cell.insert_endnote(cell.len(), "Cell endnote", Default::default()).unwrap(); + Arc::make_mut(&mut cell.endnotes[0]).text.insert_object(0, in_cell); + let st = d.story_mut(sid).unwrap(); + st.insert_note(st.len(), "Footnote", Default::default()).unwrap(); + let note = &mut Arc::make_mut(&mut st.notes[0]).text; + note.insert_endnote(note.len(), "Footnote endnote", Default::default()).unwrap(); + Arc::make_mut(&mut note.endnotes[0]).text.insert_object(0, in_footnote); + st.insert_table(0, table); + src.check().unwrap(); + + let mut dst = src.clone(); + let it = src.item(frame).cloned().unwrap(); + let mut maps = super::fill::Maps::default(); + super::fill::copy_item(&mut dst, &src, &it, SpreadRef::Doc(0), designcraft_geom::Vec2::new(0.0, 0.0), &mut maps).unwrap(); + let ids: Vec = dst.anchored_items().into_iter().map(|(_, i)| i.id.0).collect(); + let unique: std::collections::BTreeSet<_> = ids.iter().collect(); + assert_eq!((ids.len(), unique.len()), (4, 4), "the copies have ids of their own: {ids:?}"); + for old in [a, b] { + assert!(maps.items.contains_key(&ItemId(old)), "object {old} is mapped to its copy"); + } + dst.check().unwrap(); +} + +/// A story threaded through anchored text frames in two table cells keeps its thread order in a +/// record's copy, so its text flows through the copied frames in the same order, whichever cell +/// holds the first frame. +#[test] +fn record_copies_keep_the_thread_order_of_frames_anchored_in_cells() { + for first_in_first_cell in [true, false] { + thread_order_of_frames_anchored_in_cells(first_in_first_cell); + } +} + +fn thread_order_of_frames_anchored_in_cells(first_in_first_cell: bool) { + use designcraft_doc::{AnchoredObject, ItemId, SpreadRef}; + use std::sync::Arc; + + let mut s = Session::new(); + new_doc(&mut s, 1); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 300.0], "Body", None); + let (frame, sid) = (ItemId(made["id"].as_u64().unwrap()), StoryId(made["story"].as_u64().unwrap())); + let first = text_frame(&mut s, [450.0, 450.0, 500.0, 490.0], "Threaded text", None); + let second = text_frame(&mut s, [450.0, 500.0, 500.0, 540.0], "", None); + exec(&mut s, "text.thread", json!({"from": first["id"], "to": second["id"]})); + let (a, b) = (first["id"].as_u64().unwrap(), second["id"].as_u64().unwrap()); + let thread = StoryId(first["story"].as_u64().unwrap()); + let mut src = s.doc().unwrap().doc.as_ref().clone(); + assert_eq!(src.story(thread).unwrap().frames, vec![ItemId(a), ItemId(b)]); + let d = &mut src; + let take = |d: &mut designcraft_doc::Document, id: u64| { + let it = d.item(ItemId(id)).cloned().unwrap(); + Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != id); + AnchoredObject::new(it, Default::default()) + }; + let in_first = take(d, a); + let in_second = take(d, b); + let mut table = designcraft_doc::Table::new(d.alloc(), 1, 2, 0, 0, 80.0); + let (left, right) = if first_in_first_cell { (in_first, in_second) } else { (in_second, in_first) }; + table.cells[0].text.insert_object(0, left); + table.cells[1].text.insert_object(0, right); + d.story_mut(sid).unwrap().insert_table(0, table); + src.check().unwrap(); + + let mut dst = src.clone(); + let it = src.item(frame).cloned().unwrap(); + let mut maps = super::fill::Maps::default(); + super::fill::copy_item(&mut dst, &src, &it, SpreadRef::Doc(0), designcraft_geom::Vec2::new(0.0, 0.0), &mut maps).unwrap(); + let copy = maps.stories[&thread]; + let expected = vec![maps.items[&ItemId(a)], maps.items[&ItemId(b)]]; + assert_eq!(dst.story(copy).unwrap().frames, expected, "the copy's frames keep the thread order ({first_in_first_cell})"); + dst.check().unwrap(); +} + /// A record previewed into an image placeholder whose frame wraps with an Alpha Channel contour /// gets the image's outline, as an edit would. #[test]