From 34abd7da2dba055c4ea87e10bfcee80f8b4f42b7 Mon Sep 17 00:00:00 2001 From: ViktorBystrov72 <18964918+ViktorBystrov72@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:25:06 +0500 Subject: [PATCH] Components: report and find orphaned instances (#2183) --- crates/engine/src/cmd/edit.rs | 26 ++++++++++++++++++++++++-- crates/engine/src/node_find_tests.rs | 27 +++++++++++++++++++++++++++ crates/engine/src/session/exec.rs | 10 +++++++--- 3 files changed, 58 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index cc2391ef5..4ab96755d 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -72,6 +72,7 @@ fn node_find(s: &mut Session, p: &Value) -> Result { let text = filter("text")?; let component = filter("component")?; let kind = filter("type")?; + let orphaned = get(p, "orphaned").map(|v| v.as_bool().ok_or_else(|| bad(cmd, "`orphaned` must be a boolean"))).transpose()?; if let Some(kind) = &kind && !LAYER_TYPES.iter().any(|t| t.eq_ignore_ascii_case(kind)) { @@ -100,6 +101,7 @@ fn node_find(s: &mut Session, p: &Value) -> Result { || component.as_ref().is_some_and( |q| !matches!(&n.kind, NodeKind::Instance { component, .. } if doc.node(*component).is_some_and(|c| fold(&c.name).contains(q))), ) + || orphaned.is_some_and(|want| !matches!(&n.kind, NodeKind::Instance { component, .. } if doc.contains(*component) != want)) { continue; } @@ -115,7 +117,7 @@ pub fn specs() -> Vec { vec![ spec!("edit.undo", "Undo", "{}", false, |s, _| Ok(json!({"undone": s.undo()?}))), spec!("edit.redo", "Redo", "{}", false, |s, _| Ok(json!({"redone": s.redo()?}))), - spec!("edit.delete", "Delete", "{ids?}", true, delete), + spec!("edit.delete", "Delete", "{ids?} → {deleted, hidden, orphaned? (surviving instances that lost their main)}", true, delete), spec!( "edit.duplicate", "Duplicate", @@ -347,7 +349,7 @@ pub fn specs() -> Vec { spec!( "node.find", "Find layers", - "{root? (strict descendants; default current page), name?, type? (canonical layer type), text?, component? (main component name), limit? (0-10000; default 100)}: every filter must match; name, text and component are case-insensitive substrings, type is exact (any case); returns {ids, total} and does not select", + "{root? (strict descendants; default current page), name?, type? (canonical layer type), text?, component? (main component name), orphaned?: bool (instances without a main if true, with a main if false), limit? (0-10000; default 100)}: every filter must match; name, text and component are case-insensitive substrings, type is exact (any case); returns {ids, total} and does not select", false, node_find ), @@ -616,6 +618,26 @@ fn delete(s: &mut Session, p: &Value) -> Result { Ok(json!({"deleted": ids, "hidden": hidden})) } +/// Add only instances that still exist after the delete and instance synchronisation. +pub(crate) fn report_orphaned_instances(result: &mut Value, before: &Document, after: &Document) { + let removed: BTreeSet<_> = after + .changed_ids(before, usize::MAX) + .unwrap_or_default() + .into_iter() + .filter(|&id| !after.contains(id) && matches!(before.node(id).map(|n| &n.kind), Some(NodeKind::Component { .. }))) + .collect(); + if removed.is_empty() { + return; + } + let orphaned: Vec<_> = + after.nodes().filter(|n| matches!(&n.kind, NodeKind::Instance { component, .. } if removed.contains(component))).map(|n| n.id).collect(); + if !orphaned.is_empty() + && let Some(result) = result.as_object_mut() + { + result.insert("orphaned".into(), json!(orphaned)); + } +} + /// Layers duplicated last (Duplicate or Alt-drag) and their copies, in the same order. While the /// copies are the selection, Duplicate places the next copies as far from them as they are from /// their sources, measured then (their move and turn, not their size): so moving or turning the diff --git a/crates/engine/src/node_find_tests.rs b/crates/engine/src/node_find_tests.rs index bb892ad5a..cb56d8139 100644 --- a/crates/engine/src/node_find_tests.rs +++ b/crates/engine/src/node_find_tests.rs @@ -99,6 +99,33 @@ fn node_find_instances_match_main_name_and_visit_actual_children_only() { found(&mut s, json!({"root": inst, "text": "original"}), &[]); found(&mut s, json!({"root": inst, "text": "changed"}), &[child]); found(&mut s, json!({}), &[main, original, inst, child, broken]); + found(&mut s, json!({"orphaned": true}), &[broken]); + found(&mut s, json!({"orphaned": false}), &[inst]); + found(&mut s, json!({"orphaned": true, "name": "other"}), &[]); + assert!(s.execute("node.find", &json!({"orphaned": "true"})).is_err()); +} + +#[test] +fn deleting_a_component_reports_only_the_instances_it_leaves_orphaned() { + let mut s = Session::new(); + let page = s.page().unwrap(); + let frame = add(&mut s, page, NodeKind::Frame, "With a main"); + let main = add(&mut s, frame, NodeKind::Component { description: String::new(), props: Default::default(), prop_order: Vec::new() }, "Main"); + let other_main = + add(&mut s, page, NodeKind::Component { description: String::new(), props: Default::default(), prop_order: Vec::new() }, "Other"); + let deleted = idv(&ex(&mut s, "instance.create", json!({"component": main, "parent": frame}))); + let survivor = idv(&ex(&mut s, "instance.create", json!({"component": main}))); + let linked = idv(&ex(&mut s, "instance.create", json!({"component": other_main}))); + + let first = ex(&mut s, "edit.delete", json!({"ids": [other_main]})); + assert_eq!(first["orphaned"], json!([linked])); + let result = ex(&mut s, "edit.delete", json!({"ids": [frame]})); + assert_eq!(result["orphaned"], json!([survivor])); + assert!(!s.doc().unwrap().contains(deleted)); + found(&mut s, json!({"orphaned": true}), &[survivor, linked]); + + ex(&mut s, "edit.undo", json!({})); + found(&mut s, json!({"orphaned": true}), &[linked]); } #[test] diff --git a/crates/engine/src/session/exec.rs b/crates/engine/src/session/exec.rs index 73f2d7d16..d709e45f5 100644 --- a/crates/engine/src/session/exec.rs +++ b/crates/engine/src/session/exec.rs @@ -107,9 +107,9 @@ impl Session { .and_then(|v| self.check_live_access(id, &before).map(|()| v)) .and_then(|v| self.check_finite_geometry(id, &before).map(|()| v)) // Normalising is part of the command: a panic in it rolls the edit back too (#1085). - .and_then(|v| { + .and_then(|mut v| { guard::run(id, || { - self.normalize_edit(spec, &before); + self.normalize_edit(spec, &before, &mut v); Ok(v) }) }); @@ -229,13 +229,17 @@ impl Session { /// Normalise what a command changed in the document it ran on (text boxes, groups, instances, /// auto layout…). - fn normalize_edit(&mut self, spec: &CommandSpec, before: &Option<(Arc, Vec, NodeId, u64)>) { + fn normalize_edit(&mut self, spec: &CommandSpec, before: &Option<(Arc, Vec, NodeId, u64)>, result: &mut Value) { let Some((bdoc, _, _, uid)) = before else { return }; + let deletes = spec.id == "edit.delete" || (spec.id == "edit.repeat" && self.last_command.as_ref().is_some_and(|(id, _)| id == "edit.delete")); let Some(ds) = self.docs.iter_mut().find(|d| d.uid == *uid) else { return }; // Saving may adopt the chosen filename as the document title. The encoded snapshot is // already final; normalising it again would detach it from the saved baseline. if !Arc::ptr_eq(&ds.doc, bdoc) && !matches!(spec.id, "file.save" | "file.saveAs") { normalize(ds.doc_mut(), bdoc); + if deletes { + cmd::edit::report_orphaned_instances(result, bdoc, &ds.doc); + } } }