DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge group-nested-panic: Objects: group siblings inside a group; refuse mixed levels and spreads
aionggcf0ff4a03406
diff --cc crates/engine/src/cmd/object.rsindex 0ab566d84,e3502f1fc..aa51cd046--- a/crates/engine/src/cmd/object.rs+++ b/crates/engine/src/cmd/object.rs@@@ -1356,192 -1303,85 +1357,243 @@@ fn arrange(s: &mut Session, p: &Value)})}+/// An optional non-negative integer parameter; any other value is an error.+fn opt_u64(p: &Value, cmd: &str, key: &str) -> Result<Option<u64>> {+ match p.get(key) {+ None | Some(Value::Null) => Ok(None),+ Some(v) => v.as_u64().map(Some).ok_or_else(|| bad(cmd, format!("{key} must be a non-negative integer"))),+ }+}++/// The sibling list under the group at `parent` (the spread's top level when empty).+fn siblings_mut<'a>(d: &'a mut Document, r: SpreadRef, parent: &[usize]) -> Option<&'a mut Vec<Arc<Item>>> {+ let mut items = &mut d.spread_mut(r)?.items;+ for &i in parent {+ items = Arc::make_mut(items.get_mut(i)?).children_mut()?;+ }+ Some(items)+}++fn reorder(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "object.reorder";+ let mut ids = targets(s, p)?;+ let mut seen = HashSet::new();+ ids.retain(|i| seen.insert(*i));+ let Some(&first) = ids.first() else { return Err(bad(C, "no objects")) };+ let above = opt_u64(p, C, "above")?.map(ItemId);+ let below = opt_u64(p, C, "below")?.map(ItemId);+ let index = opt_u64(p, C, "index")?;+ let layer = opt_u64(p, C, "layer")?.map(designcraft_doc::LayerId);+ if [above.is_some(), below.is_some(), index.is_some()].into_iter().filter(|b| *b).count() > 1 {+ return Err(bad(C, "give only one of above, below and index"));+ }+ let target = above.map(|t| (t, true)).or(below.map(|t| (t, false)));+ let d = s.doc()?.doc.clone();+ let (spread, parent, new_items) = {+ let no_object = |id: ItemId| bad(C, format!("no object {}", id.0));+ let loc = d.find(first).ok_or_else(|| no_object(first))?;+ let Some((_, parent)) = loc.path.split_last() else { return Err(no_object(first)) };+ let parent = parent.to_vec();+ let sibling = |id: ItemId| d.find(id).is_some_and(|l| l.spread == loc.spread && l.path.split_last().is_some_and(|(_, pp)| pp == parent));+ for id in &ids {+ if d.find(*id).is_none() {+ return Err(no_object(*id));+ }+ if !sibling(*id) {+ return Err(bad(C, "the objects must be on one spread and in one group"));+ }+ }+ let in_group = !parent.is_empty();+ let group_layer = if in_group {+ let g = d.item_at(&designcraft_doc::ItemLoc { spread: loc.spread, path: parent.clone() }).ok_or_else(|| no_object(first))?;+ if !g.states.is_empty() {+ return Err(bad(C, "the states of a multi-state object are reordered in the Object States panel"));+ }+ Some(g.layer)+ } else {+ None+ };+ let own_layer = d.item(first).map(|i| i.layer).ok_or_else(|| no_object(first))?;+ let target_layer = match target {+ Some((t, _)) => {+ if ids.contains(&t) {+ return Err(bad(C, "an object can't move next to itself"));+ }+ if d.find(t).is_none() {+ return Err(no_object(t));+ }+ if !sibling(t) {+ return Err(bad(C, "the target must be on the same spread and in the same group"));+ }+ let tl = d.item(t).map(|i| i.layer).ok_or_else(|| no_object(t))?;+ if layer.is_some_and(|l| l != tl) {+ return Err(bad(C, "layer differs from the target's layer"));+ }+ if in_group { own_layer } else { tl }+ }+ None => layer.unwrap_or(own_layer),+ };+ if d.layer(target_layer).is_none() {+ return Err(bad(C, "no such layer"));+ }+ if let Some(gl) = group_layer+ && layer.is_some_and(|l| l != gl)+ {+ return Err(bad(C, "group members stay on their group's layer"));+ }+ let items = d.spread(loc.spread).map(|sp| sp.items.clone()).ok_or_else(|| no_object(first))?;+ let items = parent.iter().try_fold(items, |items, &i| items.get(i).map(|g| g.children().to_vec())).ok_or_else(|| no_object(first))?;+ // Moved objects keep their relative stacking order.+ let moved: Vec<Arc<Item>> = items.iter().filter(|i| ids.contains(&i.id)).cloned().collect();+ let rest: Vec<Arc<Item>> = items.iter().filter(|i| !ids.contains(&i.id)).cloned().collect();+ let at = match target {+ Some((t, front)) => {+ let i = rest.iter().position(|x| x.id == t).ok_or_else(|| no_object(t))?;+ if front { i + 1 } else { i }+ }+ None => {+ let k = usize::try_from(index.unwrap_or(0)).map_err(|_| bad(C, "index out of range"))?;+ // Positions of the layer's objects (all siblings in a group), topmost first.+ let stack: Vec<usize> = rest.iter().enumerate().filter(|(_, x)| in_group || x.layer == target_layer).map(|(i, _)| i).rev().collect();+ if k > stack.len() {+ return Err(bad(C, format!("index {k} out of range (0..={})", stack.len())));+ }+ match (stack.get(k), stack.last()) {+ (Some(&i), _) => i + 1,+ (None, Some(&backmost)) => backmost,+ (None, None) => rest.len(),+ }+ }+ };+ let (back, front) = rest.split_at(at.min(rest.len()));+ let moved = moved.into_iter().map(|mut it| {+ if !in_group && it.layer != target_layer {+ set_layer_deep(Arc::make_mut(&mut it), target_layer, 0);+ }+ it+ });+ let new_items: Vec<Arc<Item>> = back.iter().cloned().chain(moved).chain(front.iter().cloned()).collect();+ if new_items.iter().zip(items.iter()).all(|(a, b)| a.id == b.id && a.layer == b.layer) {+ return ok();+ }+ (loc.spread, parent, new_items)+ };+ s.edit(|d, _| {+ let items = siblings_mut(d, spread, &parent).ok_or_else(|| bad(C, "the objects moved"))?;+ *items = new_items;+ ok()+ })+}++/// Sets the layer of `it` and its group members (nesting is bounded).+fn set_layer_deep(it: &mut Item, l: designcraft_doc::LayerId, depth: usize) {+ it.layer = l;+ if depth < 64+ && let Some(kids) = it.children_mut()+ {+ for k in kids {+ set_layer_deep(Arc::make_mut(k), l, depth + 1);+ }+ }+}++/// `object.setLayer`: moves the objects, or the top-level groups of group members, to a layer.+fn set_layer(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "object.setLayer";+ let l = designcraft_doc::LayerId(p.get("layer").and_then(Value::as_u64).ok_or_else(|| bad(C, "missing layer"))?);+ let ids = targets(s, p)?;+ s.edit(|d, _| {+ if d.layer(l).is_none() {+ return Err(bad(C, "no such layer"));+ }+ let mut tops: Vec<ItemId> = Vec::new();+ for id in &ids {+ if let Some(t) = d.top_level_of(*id)+ && !tops.contains(&t)+ {+ tops.push(t);+ }+ }+ for t in &tops {+ if let Some(it) = d.item_mut(*t) {+ set_layer_deep(it, l, 0);+ }+ }+ Ok(json!({"changed": tops.len()}))+ })+}++ /// Where a group of `ids` goes: their spread, the path of the group holding them (empty at top+ /// level), and their indices in that list, back to front.+ struct GroupPlan {+ spread: SpreadRef,+ parent: Vec<usize>,+ indices: Vec<usize>,+ }++ /// Objects can be grouped when they share a spread and a parent: all top-level, or all in the+ /// same group (which then holds the new group). A multi-state object keeps one state per child,+ /// so objects inside one stay as they are.+ fn group_plan(d: &Document, ids: &[ItemId]) -> std::result::Result<GroupPlan, String> {+ let mut seen = HashSet::new();+ let mut locs = Vec::new();+ for id in ids {+ if seen.insert(*id) {+ locs.push(d.find(*id).ok_or_else(|| format!("no object with id {}", id.0))?);+ }+ }+ if locs.len() < 2 {+ return Err("select at least two objects".into());+ }+ let mut plan: Option<GroupPlan> = None;+ for loc in locs {+ let Some((&i, parent)) = loc.path.split_last() else { return Err("object not found".into()) };+ match &mut plan {+ None => plan = Some(GroupPlan { spread: loc.spread, parent: parent.to_vec(), indices: vec![i] }),+ Some(p) if p.spread == loc.spread && p.parent == parent => p.indices.push(i),+ Some(_) => return Err(GROUP_SAME_LEVEL.into()),+ }+ }+ let Some(mut plan) = plan else { return Err("select at least two objects".into()) };+ if !plan.parent.is_empty() && d.item_at(&ItemLoc { spread: plan.spread, path: plan.parent.clone() }).is_some_and(|g| !g.states.is_empty()) {+ return Err("objects inside a multi-state object can't be grouped".into());+ }+ plan.indices.sort_unstable();+ Ok(plan)+ }++ const GROUP_SAME_LEVEL: &str = "objects to group must be on the same spread and at the same level (all top-level, or all in the same group)";+-/// The list that holds the objects a [`GroupPlan`] groups.-fn siblings_mut<'a>(d: &'a mut Document, plan: &GroupPlan) -> Option<&'a mut Vec<Arc<Item>>> {- if plan.parent.is_empty() {- return Some(&mut d.spread_mut(plan.spread)?.items);- }- d.item_mut_at(&ItemLoc { spread: plan.spread, path: plan.parent.clone() })?.children_mut()-}-+ /// Menu state of Object › Group: the selection must be groupable.+ fn can_group(s: &Session) -> std::result::Result<(), String> {+ has_selection(s)?;+ let st = s.active().ok_or_else(|| "no document open".to_string())?;+ group_plan(&st.doc, &st.selection.items).map(|_| ()).map_err(|_| super::CANT_GROUP_SELECTION.into())+ }+fn group(s: &mut Session, p: &Value) -> Result<Value> {let ids = targets(s, p)?;- if ids.len() < 2 {- return Err(bad("object.group", "select at least two objects"));- }s.edit(|d, sel| {- let sr = d.find(ids[0]).map(|l| l.spread).ok_or(designcraft_doc::DocError::NoItem(ids[0]))?;- // Keep stacking order: collect in z-order.- let order: Vec<ItemId> = d.spread(sr).map(|sp| sp.items.iter().map(|i| i.id).filter(|i| ids.contains(i)).collect()).unwrap_or_default();- let front = d.spread(sr).and_then(|sp| sp.items.iter().position(|i| Some(&i.id) == order.last())).unwrap_or(0);- let layer = d.item(order[0]).map(|i| i.layer).unwrap_or_default();- let mut kids = Vec::new();- for id in &order {- kids.push(d.remove_item_keep_story(*id)?);- }+ let plan = group_plan(d, &ids).map_err(|e| bad("object.group", e))?;+ let missing = || bad("object.group", "the objects to group are gone");- let siblings = siblings_mut(d, &plan).ok_or_else(missing)?;++ let siblings = siblings_mut(d, plan.spread, &plan.parent).ok_or_else(missing)?;+ let (Some(&back), Some(&front)) = (plan.indices.first(), plan.indices.last()) else { return Err(missing()) };+ let layer = siblings.get(back).ok_or_else(missing)?.layer;+ // Keep stacking order: remove front to back, then restore back-to-front order.+ let mut kids = Vec::with_capacity(plan.indices.len());+ for &i in plan.indices.iter().rev() {+ if i >= siblings.len() {+ return Err(missing());+ }+ kids.push(siblings.remove(i));+ }+ kids.reverse();let gid = ItemId(d.alloc());let mut g = Item::new(gid, layer, Shape::Group, designcraft_geom::PathData::default());- g.content = Content::Group { items: kids.into_iter().map(Arc::new).collect() };- let at = front + 1 - order.len();- d.insert_item(sr, g, Some(at))?;+ let at = (front + 1).saturating_sub(kids.len());+ g.content = Content::Group { items: kids };- let siblings = siblings_mut(d, &plan).ok_or_else(missing)?;++ let siblings = siblings_mut(d, plan.spread, &plan.parent).ok_or_else(missing)?;+ siblings.insert(at.min(siblings.len()), Arc::new(g));*sel = Selection::items(vec![gid]);Ok(json!({"id": gid.0}))})@@@ -2996,176 -2775,110 +3048,284 @@@ mod blend_mode_tests}}+#[cfg(test)]+mod reorder_tests {+ use super::*;++ fn frame(s: &mut Session) -> u64 {+ s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap()+ }++ /// Top-level objects of the first spread on `layer`, topmost first.+ fn stack(s: &Session, layer: u64) -> Vec<u64> {+ let d = &s.doc().unwrap().doc;+ d.spreads[0].items.iter().rev().filter(|i| i.layer.0 == layer).map(|i| i.id.0).collect()+ }++ #[test]+ fn reorder_within_and_across_layers_validates_and_undoes() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let l1 = s.doc().unwrap().doc.layers[0].id.0;+ let l2 = s.execute("layer.new", &json!({"name": "Art"})).unwrap()["id"].as_u64().unwrap();+ s.execute("layer.activate", &json!({"id": l1})).unwrap();+ let (a, b, c) = (frame(&mut s), frame(&mut s), frame(&mut s));+ s.execute("layer.activate", &json!({"id": l2})).unwrap();+ let (x, y) = (frame(&mut s), frame(&mut s));+ assert_eq!(stack(&s, l1), [c, b, a]);+ s.execute("object.reorder", &json!({"ids": [a], "above": c})).unwrap();+ assert_eq!(stack(&s, l1), [a, c, b]);+ s.execute("object.reorder", &json!({"ids": [b], "index": 0})).unwrap();+ assert_eq!(stack(&s, l1), [b, a, c]);+ // To another layer at a position.+ s.execute("object.reorder", &json!({"ids": [a], "layer": l2, "index": 1})).unwrap();+ assert_eq!((stack(&s, l1), stack(&s, l2)), (vec![b, c], vec![y, a, x]));+ s.execute("object.reorder", &json!({"ids": [x, y], "below": c})).unwrap();+ assert_eq!((stack(&s, l1), stack(&s, l2)), (vec![b, c, y, x], vec![a]));+ // Bad input is an error and changes nothing.+ let before = s.doc().unwrap().doc.clone();+ for bad in [+ json!({"ids": [999], "index": 0}),+ json!({"ids": [b], "index": 4}),+ json!({"ids": [b], "above": b}),+ json!({"ids": [b], "above": 999}),+ json!({"ids": [b], "layer": 999}),+ json!({"ids": [b], "layer": l2, "above": c}),+ json!({"ids": [b], "above": c, "index": 0}),+ json!({"ids": [b], "index": "top"}),+ json!({"ids": []}),+ ] {+ assert!(s.execute("object.reorder", &bad).is_err(), "{bad}");+ assert_eq!(*s.doc().unwrap().doc, *before, "{bad}");+ }+ // The bottom of a layer is index = its count.+ s.execute("object.reorder", &json!({"ids": [b], "index": 3})).unwrap();+ assert_eq!(stack(&s, l1), [c, y, x, b]);+ // A reorder that changes nothing adds no undo step.+ let undo = |s: &Session| s.doc().unwrap().history.undo.len();+ let steps = undo(&s);+ s.execute("object.reorder", &json!({"ids": [x], "index": 2})).unwrap();+ s.execute("object.reorder", &json!({"ids": [y], "above": x})).unwrap();+ s.execute("object.reorder", &json!({"ids": [c], "layer": l1, "index": 0})).unwrap();+ assert_eq!(stack(&s, l1), [c, y, x, b]);+ assert_eq!(undo(&s), steps);+ // One undo step per reorder.+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(stack(&s, l1), [b, c, y, x]);+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!((stack(&s, l1), stack(&s, l2)), (vec![b, c], vec![y, a, x]));+ }++ #[test]+ fn group_members_reorder_only_within_their_group() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let (a, b, c) = (frame(&mut s), frame(&mut s), frame(&mut s));+ let g = s.execute("object.group", &json!({"ids": [a, b]})).unwrap()["id"].as_u64().unwrap();+ let kids = |s: &Session| s.doc().unwrap().doc.item(ItemId(g)).unwrap().children().iter().map(|i| i.id.0).collect::<Vec<_>>();+ assert_eq!(kids(&s), [a, b]);+ s.execute("object.reorder", &json!({"ids": [a], "above": b})).unwrap();+ assert_eq!(kids(&s), [b, a]);+ s.execute("object.reorder", &json!({"ids": [a], "index": 1})).unwrap();+ assert_eq!(kids(&s), [a, b]);+ let before = s.doc().unwrap().doc.clone();+ assert!(s.execute("object.reorder", &json!({"ids": [a], "above": c})).is_err(), "out of the group");+ assert!(s.execute("object.reorder", &json!({"ids": [c], "above": a})).is_err(), "into the group");+ assert!(s.execute("object.reorder", &json!({"ids": [a, c], "index": 0})).is_err(), "mixed parents");+ assert_eq!(*s.doc().unwrap().doc, *before);+ }++ #[test]+ fn moving_a_group_member_to_a_layer_moves_its_group() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let (a, b) = (frame(&mut s), frame(&mut s));+ let g = s.execute("object.group", &json!({"ids": [a, b]})).unwrap()["id"].as_u64().unwrap();+ let art = s.execute("layer.new", &json!({"name": "Art"})).unwrap()["id"].as_u64().unwrap();+ let r = s.execute("object.setLayer", &json!({"ids": [a, b], "layer": art})).unwrap();+ assert_eq!(r["changed"], 1, "the group, once");+ let d = &s.doc().unwrap().doc;+ assert!([g, a, b].iter().all(|i| d.item(ItemId(*i)).unwrap().layer.0 == art));+ assert!(s.execute("object.setLayer", &json!({"ids": [a], "layer": 999})).is_err());+ }+}++#[cfg(test)]+mod content_move_tests {+ use super::*;++ /// A session with a 40×20 image placed in a frame at (100, 100)–(300, 300).+ fn placed() -> (Session, ItemId) {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png();+ let f = s.execute("frame.create", &json!({"rect": [100, 100, 300, 300], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();+ s.execute("place.load", &json!({"base64": super::super::base64_encode(&png)})).unwrap();+ s.execute("place.drop", &json!({"frame": f})).unwrap();+ (s, ItemId(f))+ }++ /// Spread bounds of the frame and of its graphic.+ fn boxes(s: &Session, id: ItemId) -> (Rect, Rect) {+ let it = s.doc().unwrap().doc.item(id).unwrap().clone();+ let g = it.graphic().unwrap();+ (it.bounds(), (it.xf * g.xf).transform_rect_bbox(Rect::new(0.0, 0.0, g.size.0, g.size.1)))+ }++ fn near(a: Rect, b: Rect) -> bool {+ [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 1e-6)+ }++ #[test]+ fn content_moves_inside_the_frame_in_one_undo_step() {+ let (mut s, f) = placed();+ let (frame0, g0) = boxes(&s, f);+ s.execute("selection.set", &json!({"ids": [f.0], "content": true})).unwrap();+ s.execute("transform.move", &json!({"dx": 10, "dy": -5})).unwrap();+ let (frame1, g1) = boxes(&s, f);+ assert!(near(frame1, frame0), "the frame stays");+ assert!(near(g1, g0 + Vec2::new(10.0, -5.0)), "{g1:?}");+ s.execute("edit.undo", &json!({})).unwrap();+ assert!(near(boxes(&s, f).1, g0));+ // Explicit ids with `content` act on the content whatever the selection is.+ s.execute("selection.set", &json!({"ids": [f.0]})).unwrap();+ s.execute("transform.move", &json!({"ids": [f.0], "content": true, "dx": 3})).unwrap();+ assert!(near(boxes(&s, f).0, frame0) && near(boxes(&s, f).1, g0 + Vec2::new(3.0, 0.0)));+ // A frame selection moves frame and content together.+ s.execute("transform.move", &json!({"dx": 4})).unwrap();+ assert!(near(boxes(&s, f).0, frame0 + Vec2::new(4.0, 0.0)) && near(boxes(&s, f).1, g0 + Vec2::new(7.0, 0.0)));+ }++ #[test]+ fn content_moves_on_the_page_axes_in_a_rotated_frame_and_pasted_items_move_too() {+ let (mut s, f) = placed();+ s.execute("transform.rotate", &json!({"ids": [f.0], "angle": 90})).unwrap();+ let (frame0, g0) = boxes(&s, f);+ s.execute("transform.move", &json!({"ids": [f.0], "content": true, "dx": 10})).unwrap();+ let (frame1, g1) = boxes(&s, f);+ assert!(near(frame1, frame0) && near(g1, g0 + Vec2::new(10.0, 0.0)), "{g0:?} → {g1:?}");+ // Items pasted into a frame are its content.+ let a = s.execute("frame.create", &json!({"rect": [400, 100, 420, 120], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": [a]})).unwrap();+ s.execute("edit.copy", &json!({})).unwrap();+ let b = s.execute("frame.create", &json!({"rect": [400, 300, 500, 400], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": [b]})).unwrap();+ s.execute("edit.pasteInto", &json!({})).unwrap();+ let kids = |s: &Session| {+ let it = s.doc().unwrap().doc.item(ItemId(b)).unwrap().clone();+ (it.bounds(), it.children().iter().map(|c| it.xf.transform_rect_bbox(c.bounds())).collect::<Vec<_>>())+ };+ let (fb0, k0) = kids(&s);+ s.execute("transform.move", &json!({"ids": [b], "content": true, "dx": 5, "dy": 6})).unwrap();+ let (fb1, k1) = kids(&s);+ assert!(near(fb1, fb0) && near(k1[0], k0[0] + Vec2::new(5.0, 6.0)), "{k0:?} → {k1:?}");+ }+}+++ #[cfg(test)]+ mod group_tests {+ use super::*;++ fn frame(s: &mut Session, rect: [f64; 4], spread: usize) -> ItemId {+ ItemId(s.execute("frame.create", &json!({"rect": rect, "spread": spread})).unwrap()["id"].as_u64().unwrap())+ }++ fn group_ids(s: &mut Session, ids: &[ItemId]) -> Result<ItemId> {+ let r = s.execute("object.group", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))?;+ Ok(ItemId(r["id"].as_u64().unwrap()))+ }++ fn children(s: &Session, id: ItemId) -> Vec<ItemId> {+ s.doc().unwrap().doc.item(id).unwrap().children().iter().map(|c| c.id).collect()+ }++ fn world(s: &Session, id: ItemId) -> Affine {+ let d = &s.doc().unwrap().doc;+ let loc = d.find(id).unwrap();+ d.parent_xf(&loc) * d.item(id).unwrap().xf+ }++ fn group_enabled(s: &Session) -> bool {+ super::super::find_command("object.group").unwrap().info(s).enabled+ }++ #[test]+ fn grouping_objects_already_in_a_group_does_not_panic() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 1})).unwrap();+ let a = frame(&mut s, [36.0, 36.0, 136.0, 136.0], 0);+ let b = frame(&mut s, [200.0, 36.0, 300.0, 136.0], 0);+ let g = group_ids(&mut s, &[a, b]).unwrap();+ let inner = group_ids(&mut s, &[a, b]).unwrap();+ assert_eq!(children(&s, g), vec![inner]);+ assert_eq!(children(&s, inner), vec![a, b]);++ // The same through the selection, and through Convert to Multi-State Object.+ s.execute("selection.set", &json!({"ids": [a.0, b.0], "content": true})).unwrap();+ assert!(group_enabled(&s));+ let inner2 = ItemId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());+ assert_eq!(children(&s, inner), vec![inner2]);+ let st = ItemId(s.execute("states.create", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap());+ assert_eq!(children(&s, inner2), vec![st]);+ assert_eq!(s.doc().unwrap().doc.item(st).unwrap().states.len(), 2);+ }++ #[test]+ fn grouping_siblings_inside_a_group_nests_them_and_undo_restores() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 1})).unwrap();+ let a = frame(&mut s, [0.0, 0.0, 10.0, 10.0], 0);+ let b = frame(&mut s, [20.0, 0.0, 30.0, 10.0], 0);+ let c = frame(&mut s, [40.0, 0.0, 50.0, 10.0], 0);+ let g = group_ids(&mut s, &[a, b, c]).unwrap();+ s.execute("transform.rotate", &json!({"ids": [g.0], "angle": 30})).unwrap();+ let before = (world(&s, a), world(&s, c));++ let inner = group_ids(&mut s, &[c, a]).unwrap();+ assert_eq!(children(&s, g), vec![b, inner], "the new group takes the frontmost object's place");+ assert_eq!(children(&s, inner), vec![a, c], "stacking order kept");+ assert_eq!((world(&s, a), world(&s, c)), before, "nothing moves");+ assert_eq!(s.doc().unwrap().selection.items, vec![inner]);++ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(children(&s, g), vec![a, b, c]);+ assert!(s.doc().unwrap().doc.find(inner).is_none());+ }++ #[test]+ fn grouping_across_levels_or_spreads_is_refused_and_changes_nothing() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap();+ let a = frame(&mut s, [0.0, 0.0, 10.0, 10.0], 0);+ let b = frame(&mut s, [20.0, 0.0, 30.0, 10.0], 0);+ let top = frame(&mut s, [40.0, 0.0, 50.0, 10.0], 0);+ let other = frame(&mut s, [0.0, 0.0, 10.0, 10.0], 1);+ let other2 = frame(&mut s, [20.0, 0.0, 30.0, 10.0], 1);+ let g = group_ids(&mut s, &[a, b]).unwrap();+ let doc = s.doc().unwrap().doc.clone();++ for ids in [[a, top], [top, a], [a, other], [top, other], [g, a]] {+ let e = group_ids(&mut s, &ids).unwrap_err().to_string();+ assert!(e.contains("same spread and at the same level"), "{ids:?}: {e}");+ let e = s.execute("states.create", &json!({"ids": [ids[0].0, ids[1].0]})).unwrap_err().to_string();+ assert!(e.contains("same spread and at the same level"), "states.create {ids:?}: {e}");+ assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &doc), "{ids:?} changed the document");+ }+ assert!(group_ids(&mut s, &[a, ItemId(999_999)]).is_err());++ s.execute("selection.set", &json!({"ids": [a.0, other.0], "content": true})).unwrap();+ assert!(!group_enabled(&s), "Group is disabled for objects on different spreads");+ s.execute("selection.set", &json!({"ids": [other.0, other2.0]})).unwrap();+ assert!(group_enabled(&s));+ // Named objects win over a selection that can't be grouped.+ s.execute("selection.set", &json!({"ids": [a.0, other.0], "content": true})).unwrap();+ assert!(group_ids(&mut s, &[other, other2]).is_ok());++ // A multi-state object keeps one state per object.+ let ms = ItemId(s.execute("states.create", &json!({"ids": [g.0]})).unwrap()["id"].as_u64().unwrap());+ assert_eq!(ms, g);+ let e = group_ids(&mut s, &[a, b]).unwrap_err().to_string();+ assert!(e.contains("multi-state"), "{e}");+ assert_eq!(children(&s, g), vec![a, b]);+ }+ }