DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge tested main 0f4f382b0eb6 into PR #456
sanyamsingh00184bcbe2f01a2
diff --cc crates/doc/src/edit.rsindex e532823a5,7b2168e30..a6ac764d8--- a/crates/doc/src/edit.rs+++ b/crates/doc/src/edit.rs@@@ -216,67 -218,186 +218,186 @@@ impl Documentif ts == Some(fs) {return Err(DocError::Invalid("frames are already in the same story".into()));}- if let Some(ts) = ts {- let other = self.stories.remove(&ts).ok_or(DocError::NoStory(ts))?;- let other = Arc::unwrap_or_clone(other);- // Frames of the other story after `to` follow along; frames before it are left as empty new stories.- let pos_to = other.frames.iter().position(|f| *f == to).unwrap_or(0);- let before: Vec<ItemId> = other.frames[..pos_to].to_vec();- let after: Vec<ItemId> = other.frames[pos_to..].to_vec();- {- let st = self.story_mut(fs).ok_or(DocError::NoStory(fs))?;- if !other.text.is_empty() {- st.text.push('\n');- st.text.push_str(&other.text);- st.paras.extend(other.paras.iter().cloned());- // Char runs: '\n' takes the last run's format, then the other story's runs.- if let Some(last) = st.chars.last_mut() {- last.len += 1;- }- st.chars.extend(other.chars.iter().filter(|r| r.len > 0).cloned());- st.tables.extend(other.tables.iter().map(|(k, v)| (*k, v.clone())));- for n in &other.notes {- let id = st.next_note_id();- st.notes.push(Arc::new(crate::Footnote { id, text: n.text.clone() }));- }- st.anchors.extend(other.anchors.iter().cloned());- st.xrefs.extend(other.xrefs.iter().cloned());- st.index_refs.extend(other.index_refs.iter().cloned());- st.objects.extend(other.objects.iter().cloned());- st.rev = st.rev.wrapping_add(1);- }- let at = st.frames.iter().position(|f| *f == from).map_or(st.frames.len(), |p| p + 1);- for (k, f) in after.iter().enumerate() {- st.frames.insert(at + k, *f);- }+ let Some(ts) = ts else {+ let st = self.story_mut(fs).ok_or(DocError::NoStory(fs))?;+ let at = st.frames.iter().position(|f| *f == from).map_or(st.frames.len(), |p| p + 1);+ st.frames.insert(at, to);- st.rev += 1;++ st.rev = st.rev.wrapping_add(1);+ let it = self.item_mut(to).ok_or(DocError::NoItem(to))?;+ it.content = Content::Text(TextFrame { story: fs, options: TextFrameOptions::default() });+ return Ok(());+ };+ let mut other = Arc::unwrap_or_clone(self.stories.remove(&ts).ok_or(DocError::NoStory(ts))?);+ // Frames of the other story from `to` on follow along; frames before it are left as an empty new story.+ let pos_to = other.frames.iter().position(|f| *f == to).unwrap_or(0);+ let after = other.frames.split_off(pos_to);+ let before = std::mem::take(&mut other.frames);+ let (vertical, direction) = (other.vertical, other.direction);+ let offset;+ {+ let st = self.story_mut(fs).ok_or(DocError::NoStory(fs))?;+ offset = if st.text.is_empty() { 0 } else { st.text.len().saturating_add(1) };+ // The story keeps its own direction, even when it was empty and takes the other's text.+ let own = (st.vertical, st.direction);+ st.append_story(other);+ (st.vertical, st.direction) = own;+ let at = st.frames.iter().position(|f| *f == from).map_or(st.frames.len(), |p| p + 1);+ for (k, f) in after.iter().enumerate() {+ st.frames.insert(at + k, *f);+ }- st.rev += 1;++ st.rev = st.rev.wrapping_add(1);+ }+ self.remap_thread_story_refs(ts, fs, offset);+ for f in &after {+ if let Some(t) = self.item_mut(*f).and_then(Item::text_frame_mut) {+ t.story = fs;}- for f in &after {+ }+ if !before.is_empty() {+ let nid = StoryId(self.alloc());+ let mut ns = Story::new(nid);+ ns.frames = before.clone();+ ns.vertical = vertical;+ ns.direction = direction;+ for f in &before {if let Some(t) = self.item_mut(*f).and_then(Item::text_frame_mut) {- t.story = fs;+ t.story = nid;}}- if !before.is_empty() {- let nid = StoryId(self.alloc());- let mut ns = Story::new(nid);- ns.frames = before.clone();- ns.vertical = other.vertical;- ns.direction = other.direction;- for f in &before {- if let Some(t) = self.item_mut(*f).and_then(Item::text_frame_mut) {- t.story = nid;- }- }- self.stories.insert(nid, Arc::new(ns));+ self.stories.insert(nid, Arc::new(ns));+ }+ Ok(())+ }++ /// [`Document::thread`], except that an empty `from` alone in its story, threaded in front of+ /// the first frame of `to`'s story, joins that story: the story with the text keeps its id+ /// (and whatever refers to it).+ pub fn thread_keeping_story(&mut self, from: ItemId, to: ItemId) -> Result<()> {+ let fs = self.frame_story(from)?;+ let from_empty = fs.is_none_or(|fs| self.story(fs).is_some_and(|s| s.text.is_empty() && s.frames == [from]));+ let ts = self.frame_story(to)?;+ let to_first = ts.and_then(|ts| self.story(ts)).is_some_and(|s| s.frames.first() == Some(&to));+ let (Some(ts), true, true) = (ts, from_empty, to_first && from != to) else { return self.thread(from, to) };+ self.check_thread_links(from, to, true)?;+ if let Some(fs) = fs {+ self.stories.remove(&fs);+ self.remap_thread_story_refs(fs, ts, 0);+ }+ let st = self.story_mut(ts).ok_or(DocError::NoStory(ts))?;+ st.frames.insert(0, from);- st.rev += 1;++ st.rev = st.rev.wrapping_add(1);+ let it = self.item_mut(from).ok_or(DocError::NoItem(from))?;+ match it.text_frame_mut() {+ Some(t) => t.story = ts,+ None => it.content = Content::Text(TextFrame { story: ts, options: TextFrameOptions::default() }),+ }+ Ok(())+ }++ /// Story-external text addresses move with the incoming text when threading merges stories.+ /// Linked children follow the surviving whole story, including for an empty removed parent;+ /// their copied content stays unchanged until an explicit Update Link.+ fn remap_thread_story_refs(&mut self, from: StoryId, to: StoryId, offset: usize) {+ // The child's old snapshot is not a snapshot of the newly merged parent. Force it+ // out of date even when the old and surviving revision numbers happen to coincide.+ let stale_rev = self.story(to).map_or(0, |st| st.rev.wrapping_sub(1));+ for st in self.stories.values_mut() {+ if st.link.is_some_and(|(parent, _)| parent == from) {+ Arc::make_mut(st).link = Some((to, stale_rev));+ }+ }+ for link in &mut self.hyperlinks {+ if let crate::HyperlinkSource::Text { story, start, end } = &mut link.source+ && *story == from+ {+ *story = to;+ *start = start.saturating_add(offset);+ *end = end.saturating_add(offset);}+ }+ for placeholder in &mut self.data_merge.placeholders {+ if let crate::PlaceholderAnchor::Text { story, start, end } = &mut placeholder.anchor+ && *story == from+ {+ *story = to;+ *start = start.saturating_add(offset);+ *end = end.saturating_add(offset);+ }+ }+ if self.settings.primary_story == Some(from) {+ self.settings.primary_story = Some(to);+ }+ }++ /// A linked child is replaced wholesale on update. Only empty, unlinked frame+ /// extensions can join it without losing a link or newly appended body text.+ fn check_thread_links(&self, from: ItemId, to: ItemId, keep_to: bool) -> Result<()> {+ let fs = self.frame_story(from)?;+ let ts = self.frame_story(to)?;+ let first = fs.and_then(|id| self.story(id));+ let second = ts.and_then(|id| self.story(id));+ let incompatible = if keep_to {+ first.is_some_and(|st| st.link.is_some()) || second.is_some_and(|st| st.link.is_some_and(|(parent, _)| Some(parent) == fs))} else {- let st = self.story_mut(fs).ok_or(DocError::NoStory(fs))?;- let at = st.frames.iter().position(|f| *f == from).map_or(st.frames.len(), |p| p + 1);- st.frames.insert(at, to);- let it = self.item_mut(to).ok_or(DocError::NoItem(to))?;- it.content = Content::Text(TextFrame { story: fs, options: TextFrameOptions::default() });+ second.is_some_and(|st| st.link.is_some())+ || first.is_some_and(|st| {+ st.link.is_some()+ && second.is_some_and(|incoming| !incoming.text.is_empty() || st.link.is_some_and(|(parent, _)| parent == incoming.id))+ })+ };+ if incompatible {+ return Err(DocError::Invalid("unlink the linked story before merging its text".into()));}- if let Some(st) = self.story_mut(fs) {- st.rev = st.rev.wrapping_add(1);+ Ok(())+ }++ /// Can a user thread `from` → `to`? Both are text frames or empty frames (not lines), on+ /// document spreads or on the same parent spread, not in one story already, and no frame+ /// threads into `to` yet. [`Document::thread`] itself is less strict (import and autoflow).+ pub fn check_thread(&self, from: ItemId, to: ItemId) -> Result<()> {+ if from == to {+ return Err(DocError::Invalid("cannot thread a frame to itself".into()));+ }+ for id in [from, to] {+ let it = self.item(id).ok_or(DocError::NoItem(id))?;+ if !matches!(it.content, Content::Text(_) | Content::Unassigned) || it.shape == Shape::GraphicLine {+ return Err(DocError::Invalid(format!("{id} is not a text frame or an empty frame")));+ }+ if it.locked || self.layer(it.layer).is_some_and(|l| l.locked) {+ return Err(DocError::Invalid(format!("{id} is locked or on a locked layer")));+ }+ }+ let (Some(fl), Some(tl)) = (self.find(from), self.find(to)) else { return Err(DocError::NoItem(to)) };+ let same_place = match (fl.spread, tl.spread) {+ (SpreadRef::Doc(_), SpreadRef::Doc(_)) => true,+ (a, b) => a == b,+ };+ if !same_place {+ return Err(DocError::Invalid("frames on a parent spread thread only to frames on the same parent".into()));+ }+ let story = |id: ItemId| self.item(id).and_then(|i| i.text_frame()).map(|t| t.story);+ if story(from).is_some() && story(from) == story(to) {+ return Err(DocError::Invalid("the frames are already in the same thread".into()));+ }+ // Generated text is rebuilt from its source data. Merging body text into it would+ // silently discard that text on the next update (endnotes update after every edit).+ let generated = |sid| {+ self.endnote_story == Some(sid)+ || self.toc.as_ref().is_some_and(|t| t.story == sid)+ || self.index.as_ref().is_some_and(|i| i.story == sid)+ };+ let (fs, ts) = (story(from), story(to));+ if fs.is_some_and(generated) && ts.and_then(|sid| self.story(sid)).is_some_and(|st| !st.text.is_empty()) {+ return Err(DocError::Invalid("cannot merge body text into a generated story".into()));+ }+ if ts.is_some_and(generated) && fs.and_then(|sid| self.story(sid)).is_some_and(|st| !st.text.is_empty() || st.frames != [from]) {+ return Err(DocError::Invalid("a generated story can only take a new empty first frame".into()));+ }+ let keep_to = fs.is_none_or(|sid| self.story(sid).is_some_and(|st| st.text.is_empty() && st.frames == [from]))+ && ts.and_then(|sid| self.story(sid)).is_some_and(|st| st.frames.first() == Some(&to));+ self.check_thread_links(from, to, keep_to)?;+ if self.prev_frame(to).is_some() {+ return Err(DocError::Invalid(format!("text already flows into {to} from another frame: break that thread first")));}Ok(())}@@@ -309,6 -451,30 +451,30 @@@Ok(())}+ /// Take `frame` out of its thread: the frames before and after it join up and keep the text,+ /// `frame` stays on the page with a new empty story.+ pub fn remove_from_thread(&mut self, frame: ItemId) -> Result<()> {+ let sid = self.item(frame).and_then(|i| i.text_frame()).map(|t| t.story).ok_or(DocError::NoItem(frame))?;+ let (vertical, direction) = {+ let st = self.story_mut(sid).ok_or(DocError::NoStory(sid))?;+ if st.frames.len() < 2 {+ return Err(DocError::Invalid(format!("frame {frame} is not threaded to another frame")));+ }+ st.frames.retain(|f| *f != frame);- st.rev += 1;++ st.rev = st.rev.wrapping_add(1);+ (st.vertical, st.direction)+ };+ let nid = StoryId(self.alloc());+ let mut ns = Story::new(nid);+ ns.frames = vec![frame];+ ns.vertical = vertical;+ ns.direction = direction;+ self.stories.insert(nid, Arc::new(ns));+ let t = self.item_mut(frame).and_then(Item::text_frame_mut).ok_or(DocError::NoItem(frame))?;+ t.story = nid;+ Ok(())+ }+/// Next / previous frame in a thread.pub fn next_frame(&self, frame: ItemId) -> Option<ItemId> {let st = self.story(self.item(frame)?.text_frame()?.story)?;diff --cc crates/doc/src/slice.rsindex 7020f4cf1,ebf59b6a8..58d35cd80--- a/crates/doc/src/slice.rs+++ b/crates/doc/src/slice.rs@@@ -123,9 -123,69 +123,69 @@@ impl Story}self.fix_tables();}- self.rev += 1;+ self.rev = self.rev.wrapping_add(1);end}++ /// Append the whole of `other` as new paragraphs after this story's text (threading two+ /// stories merges them this way). Its formatting, notes, endnotes, editorial notes, markers,+ /// anchored objects and tables come along; footnotes, endnotes, editorial notes and tables get+ /// ids that are free in this story. An empty story simply takes `other`'s content. Frames stay.+ pub fn append_story(&mut self, mut other: Story) {+ if other.text.is_empty() {+ return;+ }+ if self.text.is_empty() {+ let (id, frames, rev, link) = (self.id, std::mem::take(&mut self.frames), self.rev, self.link.take());- *self = Story { id, frames, rev: rev.saturating_add(1), link, ..other };++ *self = Story { id, frames, rev: rev.wrapping_add(1), link, ..other };+ return;+ }+ if !other.tables.is_empty() {+ let mut ids = std::collections::HashMap::new();+ let mut next = crate::ids::next_local_id(self.tables.keys().copied());+ for (old, t) in std::mem::take(&mut other.tables) {+ let new = next;+ let mut t = Arc::unwrap_or_clone(t);+ t.id = new;+ ids.insert(old, new);+ self.tables.insert(new, Arc::new(t));+ // Continue through free ids without rescanning the table map for its maximum.+ // On exhaustion wrap to gaps; an allocated map cannot occupy every u64 id.+ next = next.checked_add(1).unwrap_or(1);+ while self.tables.contains_key(&next) {+ next = next.checked_add(1).unwrap_or(1);+ }+ }+ for p in &mut other.paras {+ p.table = p.table.and_then(|id| ids.get(&id).copied());+ }+ }+ self.text.push('\n');+ self.text.push_str(&other.text);+ // The paragraph end takes the last run's format.+ if let Some(last) = self.chars.last_mut() {+ last.len += 1;+ }+ self.chars.extend(other.chars.into_iter().filter(|r| r.len > 0));+ self.paras.extend(other.paras);+ for n in other.notes {+ let id = self.next_note_id();+ self.notes.push(Arc::new(crate::notes::Footnote { id, text: n.text.clone() }));+ }+ for n in other.endnotes {+ let id = crate::ids::next_local_id(self.endnotes.iter().map(|x| x.id));+ self.endnotes.push(Arc::new(crate::notes::Footnote { id, text: n.text.clone() }));+ }+ for n in other.editorial {+ let id = crate::ids::next_local_id(self.editorial.iter().map(|x| x.id));+ self.editorial.push(Arc::new(crate::endnotes::EditorialNote { id, ..(*n).clone() }));+ }+ self.anchors.extend(other.anchors);+ self.xrefs.extend(other.xrefs);+ self.index_refs.extend(other.index_refs);+ self.objects.extend(other.objects);- self.rev = self.rev.saturating_add(1);++ self.rev = self.rev.wrapping_add(1);+ }}#[cfg(test)]@@@ -159,4 -219,52 +219,71 @@@ mod testsassert_eq!(part.notes.len(), 1);assert!(a.extract(2..8).notes.is_empty());}++ #[test]+ fn append_tables_preserves_sparse_and_wrapping_ids() {+ for existing in [vec![1, 3, u64::MAX], vec![1, 3, u64::MAX - 1], vec![1, 3, 8]] {+ let story = |id, ids: &[u64]| {+ let mut s = Story::with_text(StoryId(id), &vec![crate::TABLE_ANCHOR.to_string(); ids.len()].join("\n"), ParaFormat::default());+ for (p, &tid) in s.paras.iter_mut().zip(ids) {+ p.table = Some(tid);+ let mut t = crate::table::Table::new(tid, 1, 1, 0, 0, 100.0);+ t.cells[0].text = Story::with_text(StoryId(0), &format!("{id}:{tid}"), ParaFormat::default());+ s.tables.insert(tid, Arc::new(t));+ }+ s+ };+ let mut a = story(1, &existing);+ let b = story(2, &[1, 2, 3]);+ a.check().unwrap();+ b.check().unwrap();+ a.append_story(b);+ a.check().unwrap();+ assert_eq!(a.tables.len(), 6);+ for (p, tid) in a.paras.iter().take(3).zip(&existing) {+ assert_eq!(p.table, Some(*tid));+ assert_eq!(a.tables[tid].cells[0].text.text, format!("1:{tid}"));+ }+ for (p, tid) in a.paras.iter().skip(3).zip(1..=3) {+ assert_eq!(a.tables[&p.table.unwrap()].cells[0].text.text, format!("2:{tid}"));+ }+ }+ }++ #[test]+ fn append_story_with_maximal_ids_does_not_overflow() {+ let mut a = Story::with_text(StoryId(1), "Alpha", ParaFormat::default());+ a.tables.insert(u64::MAX, Arc::new(crate::table::Table::new(u64::MAX, 1, 1, 0, 0, 100.0)));+ let note = |id| Arc::new(crate::notes::Footnote { id, text: Story::with_text(StoryId(0), "n", ParaFormat::default()) });+ a.endnotes.push(note(u64::MAX));+ a.notes.push(note(u64::MAX));+ a.rev = u64::MAX;+ let mut b = Story::with_text(StoryId(2), "Beta", ParaFormat::default());+ b.tables.insert(1, Arc::new(crate::table::Table::new(1, 1, 1, 0, 0, 100.0)));+ b.endnotes.push(note(1));+ b.notes.push(note(1));+ a.append_story(b);+ assert_eq!(a.text, "Alpha\nBeta");++ assert_eq!(a.rev, 0);+ assert_eq!(a.endnotes.len(), 2);+ assert_eq!(a.notes.len(), 2);+ }++++ #[test]++ fn append_to_empty_story_wraps_revision_and_keeps_identity() {++ let mut a = Story::new(StoryId(1));++ a.frames = vec![crate::ItemId(3)];++ a.link = Some((StoryId(4), 7));++ a.rev = u64::MAX;++ let mut b = Story::with_text(StoryId(2), "Incoming", ParaFormat::default());++ b.format_chars(0..8, |f| f.over.size = Some(18.0));++ a.append_story(b);++ assert_eq!(a.rev, 0);++ assert_eq!(a.id, StoryId(1));++ assert_eq!(a.frames, [crate::ItemId(3)]);++ assert_eq!(a.link, Some((StoryId(4), 7)));++ assert_eq!(a.text, "Incoming");++ assert_eq!(a.char_format_at(0).over.size, Some(18.0));++ a.check().unwrap();++ }}diff --cc crates/engine/src/cmd/text.rsindex ee09a59cf,e928ce472..b3364f462--- a/crates/engine/src/cmd/text.rs+++ b/crates/engine/src/cmd/text.rs@@@ -854,6 -1065,30 +1065,30 @@@ pub(crate) fn format_chars(s: &mut Sess})}+ /// Character attributes `a` (and the overrides `cleared` removed) over each target's text.+ pub(crate) fn apply_char_attrs(d: &mut designcraft_doc::Document, targets: &[Target], a: &CharAttrs, cleared: &[String]) {+ for t in targets {+ let r = &t.range;+ let Some(st) = d.text_story_mut(t.story, t.cell) else { continue };+ if r.is_empty() {+ // An empty story: its one (empty) run is the format typing takes.+ if st.is_empty()+ && let Some(run) = st.chars.first_mut()+ {+ run.format.over.merge(a);- st.rev += 1;++ st.rev = st.rev.wrapping_add(1);+ }+ continue;+ }+ st.format_chars(r.clone(), |f| {+ f.over.merge(a);+ for k in cleared {+ let _ = f.over.set_json(k, &Value::Null);+ }+ });+ }+ }+pub(crate) fn format_paras(s: &mut Session, attrs: &Value) -> Result<Value> {let empty = serde_json::Map::new();let obj = attrs.as_object().unwrap_or(&empty);diff --cc crates/engine/tests/text_thread_regressions.rsindex 000000000,2bca1b06d..ce7ffbd99mode 000000,100644..100644--- a/crates/engine/tests/text_thread_regressions.rs+++ b/crates/engine/tests/text_thread_regressions.rs@@@ -1,0 -1,277 +1,342 @@@+ use designcraft_doc::{ParaFormat, Story, StoryId};+ use designcraft_engine::Session;+ use serde_json::{Value, json};+ use std::sync::Arc;+ fn setup() -> Session {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s+ }+ fn frame(s: &mut Session, text: &str) -> (u64, u64) {+ let r = s.execute("frame.create", &json!({"rect":[72,72,300,300],"content":"text","text":text,"caret":false})).unwrap();+ (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap())+ }+ fn snapshot(s: &Session) -> Value {+ let d = s.doc().unwrap();+ json!({"doc":d.doc,"selection":d.selection,"revision":d.revision,"dirty":d.is_dirty(),"undo":d.history.undo.len(),"redo":d.history.redo.len(),"journal":s.journal})+ }+ #[test]+ fn rejected_thread_is_atomic_with_new_frame_and_redo() {+ let mut s = setup();+ let (a, _) = frame(&mut s, "hello");+ frame(&mut s, "undo");+ s.execute("edit.undo", &json!({})).unwrap();+ let before = snapshot(&s);+ assert!(s.execute("text.thread", &json!({"from":999999,"rect":[0,0,100,100]})).is_err());+ assert_eq!(snapshot(&s), before);+ assert!(s.execute("text.thread", &json!({"from":a,"rect":[0,0,100,100],"spread":999})).is_err());+ assert_eq!(snapshot(&s), before);+ }+ #[test]+ fn locked_frame_cannot_be_unthreaded() {+ let mut s = setup();+ let (a, _) = frame(&mut s, "hello");+ let (b, _) = frame(&mut s, "");+ s.execute("text.thread", &json!({"from":a,"to":b})).unwrap();+ s.execute("object.lock", &json!({"ids":[a]})).unwrap();+ let before = snapshot(&s);+ let r = s.execute("text.unthread", &json!({"frame":a}));+ assert!(r.is_err(), "unthread accepted locked frame: {r:?}");+ assert_eq!(snapshot(&s), before);+ }+ #[test]+ fn locked_frame_cannot_be_removed_from_thread() {+ let mut s = setup();+ let (a, _) = frame(&mut s, "hello");+ let (b, _) = frame(&mut s, "");+ s.execute("text.thread", &json!({"from":a,"to":b})).unwrap();+ s.execute("object.lock", &json!({"ids":[a]})).unwrap();+ let before = snapshot(&s);+ let r = s.execute("text.removeFromThread", &json!({"frame":a}));+ assert!(r.is_err(), "remove accepted locked frame: {r:?}");+ assert_eq!(snapshot(&s), before);+ }+ #[test]+ fn rejected_selection_preserves_pending_typing() {+ let mut s = setup();+ let (_, sid) = frame(&mut s, "hello");+ s.execute("text.select", &json!({"story":sid,"anchor":3})).unwrap();+ s.execute("type.char", &json!({"attrs":{"size":30}})).unwrap();+ let before = s.execute("type.selectionAttrs", &json!({})).unwrap();+ assert!(s.execute("text.select", &json!({"story":999999,"anchor":0})).is_err());+ let after = s.execute("type.selectionAttrs", &json!({})).unwrap();+ assert_eq!(after, before, "rejected selection reset pending typing");+ }+ #[test]+ fn append_max_id_preserves_both_tables() {+ use designcraft_doc::table::Table;+ let mut a = Story::with_text(StoryId(1), &designcraft_doc::TABLE_ANCHOR.to_string(), ParaFormat::default());+ let mut b = Story::with_text(StoryId(2), &designcraft_doc::TABLE_ANCHOR.to_string(), ParaFormat::default());+ let mut ta = Table::new(u64::MAX, 1, 1, 0, 0, 100.);+ ta.cells[0].text = Story::with_text(StoryId(0), "ORIGINAL", ParaFormat::default());+ a.tables.insert(u64::MAX, Arc::new(ta));+ let mut tb = Table::new(1, 1, 1, 0, 0, 100.);+ tb.cells[0].text = Story::with_text(StoryId(0), "INCOMING", ParaFormat::default());+ b.tables.insert(1, Arc::new(tb));+ a.paras[0].table = Some(u64::MAX);+ b.paras[0].table = Some(1);+ a.check().unwrap();+ b.check().unwrap();+ a.append_story(b);+ let contents: Vec<_> = a.tables.values().map(|t| t.cells[0].text.text.clone()).collect();+ assert!(contents.contains(&"ORIGINAL".into()) && contents.contains(&"INCOMING".into()), "table loss: {contents:?}");+ }+ #[test]+ fn idml_dropcap_detail_preserves_inherited_other_bit() {+ use designcraft_doc::{Document, ParaAttrs, ParagraphStyle, build::NewDocument};+ let mut d = Document::new(&NewDocument::default());+ let parent = ParagraphStyle {+ name: "Parent".into(),+ based_on: None,+ next_style: None,+ para: ParaAttrs { drop_cap_align_left: Some(false), drop_cap_scale_descenders: Some(true), ..Default::default() },+ chars: Default::default(),+ shortcut: String::new(),+ };+ let child = ParagraphStyle {+ name: "Child".into(),+ based_on: Some("Parent".into()),+ next_style: None,+ para: ParaAttrs { drop_cap_scale_descenders: Some(false), ..Default::default() },+ chars: Default::default(),+ shortcut: String::new(),+ };+ d.styles_mut().paragraph.extend([parent, child]);+ let before = d.styles.resolve_para_style("Child").0;+ let bytes = designcraft_idml::export_idml(&d);+ let back = designcraft_idml::import_idml(&bytes).unwrap();+ let after = back.styles.resolve_para_style("Child").0;+ assert_eq!(+ (after.drop_cap_align_left, after.drop_cap_scale_descenders),+ (before.drop_cap_align_left, before.drop_cap_scale_descenders),+ "IDML export resets inherited align-left bit"+ );+ }+ #[test]+ fn threading_preserves_incoming_text_hyperlink() {+ let mut s = setup();+ let (a, sa) = frame(&mut s, "First");+ let (b, sb) = frame(&mut s, "Second");+ s.execute("text.select", &json!({"story":sb,"anchor":0,"focus":6})).unwrap();+ s.execute("hyperlink.create", &json!({"url":"https://example.com"})).unwrap();+ s.execute("text.thread", &json!({"from":a,"to":b})).unwrap();+ let d = &s.doc().unwrap().doc;+ let back = designcraft_format::load(&designcraft_format::save(d).unwrap()).unwrap();+ match &back.hyperlinks[0].source {+ designcraft_doc::HyperlinkSource::Text { story, start, end } => {+ assert_eq!(story.0, sa, "hyperlink points to deleted incoming story");+ assert_eq!((*start, *end), (6, 12));+ }+ _ => panic!("wrong source"),+ };+ }+ #[test]+ fn thread_cannot_destroy_body_by_joining_generated_endnotes() {+ let mut s = setup();+ let (body, sid) = frame(&mut s, "KEEP THIS BODY");+ s.execute("text.select", &json!({"story":sid,"anchor":14})).unwrap();+ let e = s.execute("endnote.insert", &json!({"text":"a note"})).unwrap();+ let ef = e["frame"].as_u64().unwrap();+ let before = snapshot(&s);+ let r = s.execute("text.thread", &json!({"from":ef,"to":body}));+ assert!(+ r.is_err(),+ "thread into generated endnotes accepted: {r:?}; stories: {:?}",+ s.doc().unwrap().doc.stories.values().map(|s| &s.text).collect::<Vec<_>>()+ );+ assert_eq!(snapshot(&s), before);+ }+ #[test]+ fn generated_endnotes_accept_empty_extensions_but_reject_reverse_body_merge() {+ let mut s = setup();+ let (body, sid) = frame(&mut s, "Body");+ s.execute("text.select", &json!({"story":sid,"anchor":4})).unwrap();+ let r = s.execute("endnote.insert", &json!({"text":"note"})).unwrap();+ let ef = r["frame"].as_u64().unwrap();+ let esid = s.doc().unwrap().doc.endnote_story.unwrap();+ let before = snapshot(&s);+ assert!(s.execute("text.thread", &json!({"from":body,"to":ef})).is_err());+ assert_eq!(snapshot(&s), before);+ s.execute("text.thread", &json!({"from":ef,"rect":[72,72,300,300]})).unwrap();+ assert_eq!(s.doc().unwrap().doc.endnote_story, Some(esid));+ s.execute("text.thread", &json!({"to":ef,"rect":[72,72,300,300]})).unwrap();+ assert_eq!(s.doc().unwrap().doc.endnote_story, Some(esid));+ assert_eq!(s.doc().unwrap().doc.story(esid).unwrap().frames.len(), 3);+ assert!(s.doc().unwrap().doc.story(StoryId(sid)).unwrap().text.starts_with("Body"));+ s.doc().unwrap().doc.check().unwrap();+ }+ #[test]+ fn threading_moves_data_placeholders_and_primary_story_with_text() {+ use designcraft_doc::{Placeholder, PlaceholderAnchor, PlaceholderRole};+ let mut s = setup();+ let (a, sa) = frame(&mut s, "First");+ let (b, sb) = frame(&mut s, "<<name>>");+ s.edit(|d, _| {+ d.settings.primary_story = Some(StoryId(sb));+ d.data_merge.placeholders.push(Placeholder {+ id: 123,+ source_id: 0,+ field: "name".into(),+ role: PlaceholderRole::Text,+ anchor: PlaceholderAnchor::Text { story: StoryId(sb), start: 0, end: 8 },+ });+ Ok(())+ })+ .unwrap();+ let before = s.doc().unwrap().doc.clone();+ s.execute("text.thread", &json!({"from":a,"to":b})).unwrap();+ let d = &s.doc().unwrap().doc;+ assert_eq!(d.settings.primary_story, Some(StoryId(sa)));+ assert_eq!(d.data_merge.placeholders.len(), 1);+ assert_eq!(d.data_merge.placeholders[0].anchor, PlaceholderAnchor::Text { story: StoryId(sa), start: 6, end: 14 });+ let after = d.clone();+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc, before);+ s.execute("edit.redo", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc, after);+ }+ #[test]+ fn append_max_ids_preserves_addressable_footnotes_and_endnotes() {+ let mut a = Story::with_text(StoryId(1), "A", ParaFormat::default());+ let mut b = Story::with_text(StoryId(2), "B", ParaFormat::default());+ a.insert_note(1, "original footnote", ParaFormat::default());+ b.insert_note(1, "incoming footnote", ParaFormat::default());+ Arc::make_mut(&mut a.notes[0]).id = u64::MAX;+ a.insert_endnote(1, "original endnote", ParaFormat::default());+ b.insert_endnote(1, "incoming endnote", ParaFormat::default());+ Arc::make_mut(&mut a.endnotes[0]).id = u64::MAX;+ a.check().unwrap();+ b.check().unwrap();+ a.append_story(b);+ a.check().unwrap();+ assert_ne!(a.notes[0].id, a.notes[1].id);+ assert_ne!(a.endnotes[0].id, a.endnotes[1].id);+ assert_eq!(a.notes[0].text.text, "original footnote");+ assert_eq!(a.endnotes[1].text.text, "incoming endnote");+ }+ #[test]+ fn locked_layer_and_neighbour_reject_unthread_atomically() {+ for lock_layer in [false, true] {+ let mut s = setup();+ let (a, _) = frame(&mut s, "A");+ let (b, _) = frame(&mut s, "B");+ s.execute("text.thread", &json!({"from":a,"to":b})).unwrap();+ if lock_layer {+ let lid = s.doc().unwrap().active_layer.0;+ s.execute("layer.set", &json!({"id":lid,"locked":true})).unwrap();+ } else {+ s.execute("object.lock", &json!({"ids":[b]})).unwrap();+ }+ let before = snapshot(&s);+ assert!(s.execute("text.unthread", &json!({"frame":a})).is_err());+ assert_eq!(snapshot(&s), before);+ }+ }+ #[test]+ fn idml_partial_dropcap_bits_resolve_both_style_and_paragraph_inheritance() {+ use designcraft_doc::{Document, ParaAttrs, ParagraphStyle, SpreadRef, build::NewDocument};+ use designcraft_geom::Rect;+ for parent_align in [false, true] {+ for parent_scale in [false, true] {+ for local_align in [false, true] {+ let mut d = Document::new(&NewDocument::default());+ d.styles_mut().paragraph.push(ParagraphStyle {+ name: "Parent".into(),+ based_on: None,+ next_style: None,+ para: ParaAttrs { drop_cap_align_left: Some(parent_align), drop_cap_scale_descenders: Some(parent_scale), ..Default::default() },+ chars: Default::default(),+ shortcut: String::new(),+ });+ let layer = d.default_layer();+ let (_, sid) = d+ .add_text_frame(+ SpreadRef::Doc(0),+ Rect::new(10., 10., 200., 200.),+ layer,+ "Body",+ ParaFormat {+ style: "Parent".into(),+ para: ParaAttrs { drop_cap_align_left: Some(local_align), ..Default::default() },+ ..Default::default()+ },+ )+ .unwrap();+ let bytes = designcraft_idml::export_idml(&d);+ let back = designcraft_idml::import_idml(&bytes).unwrap();+ let st = back.stories.values().find(|s| s.text == "Body").unwrap();+ let actual = back.styles.resolve_para(&st.paras[0]).0;+ let expected = d.styles.resolve_para(&d.story(sid).unwrap().paras[0]).0;+ assert_eq!(+ (actual.drop_cap_align_left, actual.drop_cap_scale_descenders),+ (expected.drop_cap_align_left, expected.drop_cap_scale_descenders)+ );+ }+ }+ }+ }++++#[test]++fn thread_extensions_and_removal_wrap_saved_revisions() {++ let mut s = setup();++ let (body, sid) = frame(&mut s, "Body");++ let sid = StoryId(sid);++ let (prefix, prefix_story) = frame(&mut s, "");++ let extra = s.execute("frame.create", &json!({"rect":[72,320,300,500],"content":"unassigned"})).unwrap()["id"].as_u64().unwrap();++ Arc::make_mut(&mut s.doc_mut().unwrap().doc).story_mut(sid).unwrap().rev = u64::MAX;++ s.execute("text.thread", &json!({"from":body,"to":extra})).unwrap();++ let st = s.doc().unwrap().doc.story(sid).unwrap();++ assert_eq!(st.rev, 0);++ assert_eq!(st.text, "Body");++ assert_eq!(st.frames, [designcraft_doc::ItemId(body), designcraft_doc::ItemId(extra)]);++++ Arc::make_mut(&mut s.doc_mut().unwrap().doc).story_mut(sid).unwrap().rev = u64::MAX;++ s.execute("text.thread", &json!({"from":prefix,"to":body})).unwrap();++ let d = &s.doc().unwrap().doc;++ assert!(d.story(StoryId(prefix_story)).is_none());++ let st = d.story(sid).unwrap();++ assert_eq!(st.rev, 0);++ assert_eq!(st.text, "Body");++ assert_eq!(st.frames, [designcraft_doc::ItemId(prefix), designcraft_doc::ItemId(body), designcraft_doc::ItemId(extra)]);++ d.check().unwrap();++++ Arc::make_mut(&mut s.doc_mut().unwrap().doc).story_mut(sid).unwrap().rev = u64::MAX;++ let before = s.doc().unwrap().doc.clone();++ s.execute("text.removeFromThread", &json!({"frame":extra})).unwrap();++ let d = &s.doc().unwrap().doc;++ let st = d.story(sid).unwrap();++ assert_eq!(st.rev, 0);++ assert_eq!(st.text, "Body");++ assert_eq!(st.frames, [designcraft_doc::ItemId(prefix), designcraft_doc::ItemId(body)]);++ let detached = d.item(designcraft_doc::ItemId(extra)).unwrap().text_frame().unwrap().story;++ assert_ne!(detached, sid);++ assert!(d.story(detached).unwrap().text.is_empty());++ d.check().unwrap();++ let after = d.clone();++ s.execute("edit.undo", &json!({})).unwrap();++ assert_eq!(s.doc().unwrap().doc, before);++ s.execute("edit.redo", &json!({})).unwrap();++ assert_eq!(s.doc().unwrap().doc, after);++}++++#[test]++fn empty_story_character_format_wraps_saved_revision_and_undoes() {++ let mut s = setup();++ let (_, sid) = frame(&mut s, "");++ s.execute("text.select", &json!({"story":sid,"anchor":0})).unwrap();++ let sid = StoryId(sid);++ Arc::make_mut(&mut s.doc_mut().unwrap().doc).story_mut(sid).unwrap().rev = u64::MAX;++ let before = s.doc().unwrap().doc.clone();++ s.execute("type.char", &json!({"attrs":{"size":18.0}})).unwrap();++ let d = &s.doc().unwrap().doc;++ let st = d.story(sid).unwrap();++ assert_eq!(st.rev, 0);++ assert!(st.text.is_empty());++ assert_eq!(st.chars[0].format.over.size, Some(18.0));++ d.check().unwrap();++ let after = d.clone();++ s.execute("edit.undo", &json!({})).unwrap();++ assert_eq!(s.doc().unwrap().doc, before);++ s.execute("edit.redo", &json!({})).unwrap();++ assert_eq!(s.doc().unwrap().doc, after);++}diff --cc crates/engine/tests/thread_color_safety.rsindex 000000000,501df92b9..1457d01c1mode 000000,100644..100644--- a/crates/engine/tests/thread_color_safety.rs+++ b/crates/engine/tests/thread_color_safety.rs@@@ -1,0 -1,223 +1,276 @@@+ //! Linked-story threading and text-color transaction safety.+ use designcraft_doc::{ParaFormat, Story, StoryId, table::Table};+ use designcraft_engine::Session;+ use serde_json::{Value, json};+ use std::sync::Arc;++ fn setup() -> Session {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s+ }+ fn frame(s: &mut Session, text: &str) -> (u64, StoryId) {+ let f = s.execute("frame.create", &json!({"rect":[36,36,200,100],"content":"text","text":text,"caret":false})).unwrap();+ (f["id"].as_u64().unwrap(), StoryId(f["story"].as_u64().unwrap()))+ }+ fn child(s: &mut Session, parent: StoryId) -> (u64, StoryId) {+ let f = s.execute("story.placeAndLink", &json!({"story":parent.0,"rect":[36,150,200,100]})).unwrap();+ (f["id"].as_u64().unwrap(), StoryId(f["story"].as_u64().unwrap()))+ }+ fn state(s: &Session) -> Value {+ let d = s.doc().unwrap();+ json!({"doc":d.doc,"selection":d.selection,"revision":d.revision,"dirty":d.is_dirty(),"undo":format!("{:?}",d.history),"journal":s.journal})+ }+ fn link(s: &mut Session, sid: StoryId) -> Value {+ s.execute("story.links", &json!({})).unwrap().as_array().unwrap().iter().find(|l| l["story"] == sid.0).unwrap().clone()+ }++ #[test]+ fn safety_linked_parent_follows_merge_and_updates_after_native_reopen() {+ let mut s = setup();+ let (first, survivor) = frame(&mut s, "PREFIX");+ let (incoming, parent) = frame(&mut s, "PARENT");+ let (_, linked) = child(&mut s, parent);+ // A coincident old parent revision must not hide the change of parent identity/content.+ let future_rev = s.doc().unwrap().doc.story(survivor).unwrap().rev + 2;+ s.edit(|d, _| {+ d.story_mut(linked).unwrap().link = Some((parent, future_rev));+ Ok(())+ })+ .unwrap();+ s.execute("text.thread", &json!({"from":first,"to":incoming})).unwrap();+ assert_eq!(link(&mut s, linked)["parent"], survivor.0);+ assert_eq!(link(&mut s, linked)["outOfDate"], true);+ assert_eq!(s.doc().unwrap().doc.story(linked).unwrap().text, "PARENT");+ let bytes = s.execute("file.serialize", &json!({})).unwrap();+ let mut reopened = Session::new();+ reopened.execute("file.openBytes", &json!({"name":"links.designcraft","base64":bytes["base64"]})).unwrap();+ assert_eq!(link(&mut reopened, linked)["parent"], survivor.0);+ reopened.execute("story.updateLink", &json!({"story":linked.0})).unwrap();+ assert_eq!(reopened.doc().unwrap().doc.story(linked).unwrap().text, "PREFIX\nPARENT");+ assert_eq!(link(&mut reopened, linked)["outOfDate"], false);+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(link(&mut s, linked)["parent"], parent.0);+ s.execute("edit.redo", &json!({})).unwrap();+ assert_eq!(link(&mut s, linked)["parent"], survivor.0);+ }++ #[test]+ fn safety_linked_child_cannot_merge_body_text_in_either_direction() {+ for reverse in [false, true] {+ let mut s = setup();+ let (_, parent) = frame(&mut s, "SOURCE");+ let (linked, child) = child(&mut s, parent);+ let (body, _) = frame(&mut s, "BODY");+ let (from, to) = if reverse { (body, linked) } else { (linked, body) };+ let before = state(&s);+ let error = s.execute("text.thread", &json!({"from":from,"to":to})).unwrap_err();+ assert!(error.to_string().contains("linked story"));+ assert_eq!(state(&s), before);+ s.execute("story.updateLink", &json!({"story":child.0})).unwrap();+ assert!(s.doc().unwrap().doc.stories.values().any(|st| st.text == "BODY"));+ }+ }++ #[test]+ fn safety_linked_child_allows_empty_extensions_in_both_directions() {+ for reverse in [false, true] {+ let mut s = setup();+ let (_, parent) = frame(&mut s, "SOURCE");+ let (linked, child) = child(&mut s, parent);+ let (empty, _) = frame(&mut s, "");+ let (from, to) = if reverse { (empty, linked) } else { (linked, empty) };+ s.execute("text.thread", &json!({"from":from,"to":to})).unwrap();+ assert_eq!(link(&mut s, child)["parent"], parent.0);+ s.execute("story.setText", &json!({"story":parent.0,"text":"UPDATED"})).unwrap();+ assert_eq!(link(&mut s, child)["outOfDate"], true);+ s.execute("story.updateLink", &json!({"story":child.0})).unwrap();+ let st = s.doc().unwrap().doc.story(child).unwrap();+ assert_eq!(st.text, "UPDATED");+ assert_eq!(st.frames.len(), 2);+ assert_eq!(link(&mut s, child)["outOfDate"], false);+ }+ }++ #[test]+ fn safety_linked_empty_parent_cannot_be_merged_into_its_child() {+ let mut s = setup();+ let (parent_frame, parent) = frame(&mut s, "");+ let (linked, _) = child(&mut s, parent);+ let before = state(&s);+ assert!(s.execute("text.thread", &json!({"from":parent_frame,"to":linked})).is_err());+ assert_eq!(state(&s), before);+ }++ #[test]+ fn safety_text_color_without_target_is_atomic_and_carets_remain_valid() {+ let mut s = setup();+ let f = s.execute("frame.create", &json!({"rect":[36,36,200,100]})).unwrap();+ s.execute("selection.set", &json!({"ids":[f["id"]]})).unwrap();+ let before = state(&s);+ assert!(s.execute("object.color", &json!({"color":"#123456","text":true})).is_err());+ assert_eq!(state(&s), before);+ for text in ["", "Words"] {+ let (_, sid) = frame(&mut s, text);+ s.execute("text.select", &json!({"story":sid.0,"anchor":0})).unwrap();+ let color = s.execute("object.color", &json!({"color":"#654321","text":true})).unwrap();+ s.execute("text.insert", &json!({"text":"X"})).unwrap();+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().format_after(0).over.fill.as_deref(), color["swatch"].as_str());+ }+ }++ fn nested_story(depth: usize, name: &str) -> Story {+ let mut st = Story::with_text(StoryId(0), "leaf", ParaFormat::default());+ st.chars[0].format.over.fill = Some(name.into());+ for _ in 0..depth {+ let mut outer = Story::with_text(StoryId(0), &designcraft_doc::TABLE_ANCHOR.to_string(), ParaFormat::default());+ let mut t = Table::new(1, 1, 1, 0, 0, 100.);+ t.cells[0].text = st;+ outer.tables.insert(1, Arc::new(t));+ outer.paras[0].table = Some(1);+ st = outer;+ }+ st+ }++ #[test]+ fn safety_deep_swatch_rename_rejects_atomically_with_pending_color() {+ // A small boundary probe, never an attempted stack-overflow reproduction.+ for depth in [33, 34] {+ let mut s = setup();+ let (_, sid) = frame(&mut s, "root");+ s.execute("text.select", &json!({"story":sid.0,"anchor":0})).unwrap();+ let old = s.execute("object.color", &json!({"color":"#123456"})).unwrap()["swatch"].as_str().unwrap().to_string();+ s.edit(|d, _| {+ let st = d.story_mut(sid).unwrap();+ let frames = st.frames.clone();+ *st = nested_story(depth, &old);+ st.id = sid;+ st.frames = frames;+ Ok(())+ })+ .unwrap();+ let pending = s.execute("type.selectionAttrs", &json!({})).unwrap();+ let before = state(&s);+ let doc = s.doc().unwrap().doc.clone();+ let error = s.execute("swatch.addToSwatches", &json!({"swatch":old,"name":"Brand"})).unwrap_err();+ assert!(error.to_string().contains("nesting"));+ assert!(Arc::ptr_eq(&doc, &s.doc().unwrap().doc));+ assert_eq!(state(&s), before);+ assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap(), pending);+ }+ }++ #[test]+ fn safety_swatch_rename_reaches_last_supported_depth() {+ let mut s = setup();+ let (_, sid) = frame(&mut s, "root");+ s.execute("text.select", &json!({"story":sid.0,"anchor":0})).unwrap();+ let old = s.execute("object.color", &json!({"color":"#123456"})).unwrap()["swatch"].as_str().unwrap().to_string();+ s.edit(|d, _| {+ let st = d.story_mut(sid).unwrap();+ let frames = st.frames.clone();+ *st = nested_story(32, &old);+ st.id = sid;+ st.frames = frames;+ Ok(())+ })+ .unwrap();+ s.execute("swatch.addToSwatches", &json!({"swatch":old,"name":"Brand"})).unwrap();+ let mut st = s.doc().unwrap().doc.story(sid).unwrap();+ for _ in 0..32 {+ st = &st.tables[&1].cells[0].text;+ }+ assert_eq!(st.format_after(0).over.fill.as_deref(), Some("Brand"));+ assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["fill"], "Brand");+ }++ #[test]+ fn safety_empty_linked_parent_follows_survivor_only_on_explicit_update() {+ for incoming_empty in [false, true] {+ for alternate_layout in [false, true] {+ let mut s = setup();+ let (empty, parent) = frame(&mut s, "");+ let linked = if alternate_layout {+ s.execute("layout.createAlternate", &json!({"name":"Alternate","width":600,"height":800})).unwrap();+ let links = s.execute("story.links", &json!({})).unwrap();+ StoryId(links.as_array().unwrap().iter().find(|l| l["parent"] == parent.0).unwrap()["story"].as_u64().unwrap())+ } else {+ child(&mut s, parent).1+ };+ let (body, survivor) = frame(&mut s, "BODY");+ let (from, to) = if incoming_empty { (body, empty) } else { (empty, body) };+ s.execute("text.thread", &json!({"from":from,"to":to})).unwrap();+ assert!(s.doc().unwrap().doc.story(parent).is_none());+ assert_eq!(link(&mut s, linked)["parent"], survivor.0);+ assert_eq!(link(&mut s, linked)["outOfDate"], true);+ assert_eq!(s.doc().unwrap().doc.story(linked).unwrap().text, "");+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(link(&mut s, linked)["parent"], parent.0);+ assert_eq!(s.doc().unwrap().doc.story(linked).unwrap().text, "");+ s.execute("edit.redo", &json!({})).unwrap();+ assert_eq!(link(&mut s, linked)["parent"], survivor.0);+ let bytes = s.execute("file.serialize", &json!({})).unwrap();+ let mut reopened = Session::new();+ reopened.execute("file.openBytes", &json!({"name":"empty-parent.designcraft","base64":bytes["base64"]})).unwrap();+ assert_eq!(link(&mut reopened, linked)["outOfDate"], true);+ assert_eq!(reopened.doc().unwrap().doc.story(linked).unwrap().text, "");+ reopened.execute("story.updateLink", &json!({"story":linked.0})).unwrap();+ assert_eq!(reopened.doc().unwrap().doc.story(linked).unwrap().text, "BODY");+ assert_eq!(link(&mut reopened, linked)["outOfDate"], false);+ }+ }+ }++++#[test]++fn safety_thread_revision_wrap_keeps_link_stale_through_native_reopen() {++ let mut s = setup();++ let (first, survivor) = frame(&mut s, "PREFIX");++ let (incoming, parent) = frame(&mut s, "PARENT");++ // The copied parent's token will coincide with the merged survivor's final revision.++ Arc::make_mut(&mut s.doc_mut().unwrap().doc).story_mut(parent).unwrap().rev = 1;++ let (_, linked) = child(&mut s, parent);++ Arc::make_mut(&mut s.doc_mut().unwrap().doc).story_mut(survivor).unwrap().rev = u64::MAX;++ assert_eq!(link(&mut s, linked)["outOfDate"], false);++ let bytes = s.execute("file.serialize", &json!({})).unwrap();++ let mut reopened = Session::new();++ reopened.execute("file.openBytes", &json!({"name":"rollover.designcraft","base64":bytes["base64"]})).unwrap();++ let mut s = reopened;++ assert_eq!(s.doc().unwrap().doc.story(survivor).unwrap().rev, u64::MAX);++ assert_eq!(s.doc().unwrap().doc.story(linked).unwrap().link, Some((parent, 1)));++ let before = s.doc().unwrap().doc.clone();++ let child_frames = before.story(linked).unwrap().frames.clone();++++ s.execute("text.thread", &json!({"from":first,"to":incoming})).unwrap();++ let d = &s.doc().unwrap().doc;++ let st = d.story(survivor).unwrap();++ assert_eq!(st.rev, 1, "append wraps MAX to 0, then threading increments to 1");++ assert_eq!(st.text, "PREFIX\nPARENT");++ assert_eq!(st.frames, [designcraft_doc::ItemId(first), designcraft_doc::ItemId(incoming)]);++ assert!(d.story(parent).is_none());++ assert_eq!(d.story(linked).unwrap().link, Some((survivor, 0)));++ assert_eq!(d.story(linked).unwrap().text, "PARENT");++ assert_eq!(d.story(linked).unwrap().frames, child_frames);++ d.check().unwrap();++ let after = d.clone();++ assert_eq!(link(&mut s, linked)["outOfDate"], true);++++ let bytes = s.execute("file.serialize", &json!({})).unwrap();++ let mut reopened = Session::new();++ reopened.execute("file.openBytes", &json!({"name":"merged-rollover.designcraft","base64":bytes["base64"]})).unwrap();++ assert_eq!(reopened.doc().unwrap().doc.story(survivor).unwrap().rev, 1);++ assert_eq!(reopened.doc().unwrap().doc.story(linked).unwrap().link, Some((survivor, 0)));++ assert_eq!(link(&mut reopened, linked)["outOfDate"], true);++ reopened.execute("story.updateLink", &json!({"story":linked.0})).unwrap();++ let st = reopened.doc().unwrap().doc.story(linked).unwrap();++ assert_eq!(st.id, linked);++ assert_eq!(st.frames, child_frames);++ assert_eq!(st.text, "PREFIX\nPARENT");++ assert_eq!(st.link, Some((survivor, 1)));++ assert_eq!(link(&mut reopened, linked)["outOfDate"], false);++++ s.execute("edit.undo", &json!({})).unwrap();++ assert_eq!(s.doc().unwrap().doc, before);++ s.execute("edit.redo", &json!({})).unwrap();++ assert_eq!(s.doc().unwrap().doc, after);++}