diff --git a/crates/engine/src/assets/library.rs b/crates/engine/src/assets/library.rs index d9107ad63..8b8be7e1b 100644 --- a/crates/engine/src/assets/library.rs +++ b/crates/engine/src/assets/library.rs @@ -1208,6 +1208,58 @@ fn merge_components( Ok(remote) } +/// Match the mains of `src` (a design app's paste) that nothing else covers with the components of +/// `doc` that carry the same Figma identity: the same `fig.guid` from the same file (`fig.file`, +/// both absent counts as the same), or the same library `fig.key` from anywhere. A hit links the +/// main and each of its layers carrying a `fig.guid` to the layer of `doc`'s component with that +/// guid, so instances and their per-layer sources point into the component already there. +fn relink_by_identity( + doc: &Document, + src: &Document, + mains: &BTreeSet, + map: &BTreeMap, + remote: &mut BTreeMap, +) { + let todo: Vec = mains + .iter() + .copied() + .filter(|m| !map.contains_key(m) && !remote.contains_key(m) && src.node(*m).is_some_and(|n| n.plugin_data.contains_key("fig.guid"))) + .collect(); + if todo.is_empty() { + return; + } + let pasted: BTreeSet = map.values().copied().collect(); + let mut by_guid: BTreeMap<(Option<&str>, &str), NodeId> = BTreeMap::new(); + let mut by_key: BTreeMap<&str, NodeId> = BTreeMap::new(); + for n in doc.nodes() { + if !matches!(n.kind, NodeKind::Component { .. } | NodeKind::ComponentSet { .. }) || pasted.contains(&n.id) || doc.is_remote(n.id) { + continue; + } + if let Some(g) = n.plugin_data.get("fig.guid") { + by_guid.entry((n.plugin_data.get("fig.file").map(String::as_str), g.as_str())).or_insert(n.id); + } + if let Some(k) = n.plugin_data.get("fig.key") { + by_key.entry(k.as_str()).or_insert(n.id); + } + } + for m in todo { + let Some(theirs) = src.node(m) else { continue }; + let guid = theirs.plugin_data.get("fig.guid").map(String::as_str).unwrap_or_default(); + let found = by_guid + .get(&(theirs.plugin_data.get("fig.file").map(String::as_str), guid)) + .or_else(|| theirs.plugin_data.get("fig.key").and_then(|k| by_key.get(k.as_str()))); + let Some(&mine) = found else { continue }; + let layers: BTreeMap<&str, NodeId> = + doc.subtree(mine).into_iter().filter_map(|i| Some((doc.node(i)?.plugin_data.get("fig.guid")?.as_str(), i))).collect(); + remote.insert(m, mine); + for l in src.subtree(m) { + if let Some(&target) = src.node(l).and_then(|n| n.plugin_data.get("fig.guid")).and_then(|g| layers.get(g.as_str())) { + remote.entry(l).or_insert(target); + } + } + } +} + /// When layers copied from another document `src` are pasted into `doc` (`map`: their ids → the /// pasted ids), point the instances among them at mains of `doc`: library copies are shared with /// (or brought along as) `doc`'s copies of the same library assets; components `src` publishes as @@ -1261,6 +1313,9 @@ pub fn adopt_pasted(doc: &mut Document, src: &Document, src_path: Option<&str>, } } } + // Mains copied from a design app that this file already holds (pasted earlier): found by the + // identity recorded on them, layer by layer. + relink_by_identity(doc, src, &mains, map, &mut remote); // Point the pasted layers at those mains; what stays behind gets ids of its own. let mut behind: BTreeMap = BTreeMap::new(); let mut follow = |doc: &mut Document, id: NodeId| -> NodeId { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index efcb0fc52..6985fc5eb 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -19,7 +19,7 @@ pub(crate) use props::{edit_region_fills, fill_regions}; mod select; pub(crate) use clipboard::apply_copied_props; -pub use clipboard::{CLIP_CLOSE, CLIP_OPEN, copy_to_clipboard, design_clipboard_buffer, paste_into}; +pub use clipboard::{CLIP_CLOSE, CLIP_OPEN, copy_to_clipboard, design_clipboard_buffer, design_clipboard_file, paste_into}; use clipboard::{copy, copy_props, copy_props_of, cut, paste, paste_design_layers, paste_over, paste_props, paste_replace}; use props::{ batch_rename, effect_add, effect_copy, effect_paste, find_replace, paint_copy, paint_list, paint_paste, paint_set, pattern_fill, reparent, set, diff --git a/crates/engine/src/cmd/edit/clipboard.rs b/crates/engine/src/cmd/edit/clipboard.rs index 150a3b577..dfdf8122e 100644 --- a/crates/engine/src/cmd/edit/clipboard.rs +++ b/crates/engine/src/cmd/edit/clipboard.rs @@ -89,6 +89,27 @@ pub fn design_clipboard_buffer(html: &str) -> Option> { figcraft_format::fig::is_fig(&bytes).then_some(bytes) } +/// The markers around the copy's metadata (base64 of a JSON object) in the clipboard's HTML. +const META_OPEN: &str = "(figmeta)"; + +const META_CLOSE: &str = "(/figmeta)"; + +/// The key of the file the layers were copied from, from the metadata span of the clipboard's +/// HTML; a copy's layer ids are only unique within that file. `None` when the HTML has none. +pub fn design_clipboard_file(html: &str) -> Option { + use base64::Engine as _; + let start = html.find(META_OPEN)? + META_OPEN.len(); + let len = html.get(start..)?.find(META_CLOSE)?; + let b64: String = html.get(start..start + len)?.chars().filter(|c| !c.is_ascii_whitespace()).collect(); + if b64.len() > 64 * 1024 { + return None; + } + let bytes = + base64::engine::general_purpose::STANDARD.decode(&b64).or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(&b64)).ok()?; + let meta: Value = serde_json::from_slice(&bytes).ok()?; + meta.get("fileKey").and_then(Value::as_str).filter(|k| !k.is_empty() && k.len() <= 128).map(str::to_string) +} + /// Paste design layers from clipboard HTML or base64 `data`: decode and reject missing, /// invalid or oversized data, load a temporary `.fig`, take its top-level page layers, /// store them as a foreign-file clipboard source with a bumped layers generation, then @@ -100,7 +121,20 @@ pub(super) fn paste_design_layers(s: &mut Session, p: &Value) -> Result { (None, Some(d)) => clip_base64(&d).ok_or_else(|| bad(CMD, "`data` is not base64 of at most 256 MB"))?, (None, None) => return Err(bad(CMD, "pass `html` or `data`")), }; - let other = crate::cmd::file::load_fig(&bytes, "Pasted layers").ok_or_else(|| bad(CMD, "the data is not copied design layers"))??; + let file_key = + string(p, "html").as_deref().and_then(design_clipboard_file).or_else(|| string(p, "fileKey").filter(|k| !k.is_empty() && k.len() <= 128)); + let mut other = crate::cmd::file::load_fig(&bytes, "Pasted layers").ok_or_else(|| bad(CMD, "the data is not copied design layers"))??; + if let Some(key) = &file_key { + // Layer ids are unique within one file only: mains keep the file they came from. + let ids: Vec = other.doc.ids().collect(); + for id in ids { + if let Ok(n) = other.doc.get_mut(id) + && n.plugin_data.contains_key("fig.guid") + { + n.plugin_data.insert("fig.file".into(), key.clone()); + } + } + } let doc = std::sync::Arc::new(other.doc); let tops: Vec = doc.pages.iter().filter_map(|pg| doc.node(*pg)).flat_map(|pg| pg.children.iter().copied()).collect(); if tops.is_empty() { @@ -139,8 +173,20 @@ pub(super) fn paste_design_layers(s: &mut Session, p: &Value) -> Result { if !missing.is_empty() { out["missingImages"] = json!(missing); } - if !other.issues.is_empty() { - out["warnings"] = json!(other.issues); + let mut warnings: Vec = other.issues.clone(); + { + let d = s.doc()?; + let unlinked = pasted + .iter() + .flat_map(|r| d.subtree(*r)) + .filter_map(|i| d.node(i)) + .any(|n| matches!(&n.kind, NodeKind::Instance { component, .. } if !d.contains(*component))); + if unlinked { + warnings.push("instances of components not in this file stay unlinked (paste their main components first)".into()); + } + } + if !warnings.is_empty() { + out["warnings"] = json!(warnings); } Ok(out) } diff --git a/crates/engine/src/design_paste_relink_tests.rs b/crates/engine/src/design_paste_relink_tests.rs new file mode 100644 index 000000000..3b652b2cd --- /dev/null +++ b/crates/engine/src/design_paste_relink_tests.rs @@ -0,0 +1,166 @@ +//! Instances pasted from another design app link to the mains pasted earlier (#2022). The paste +//! carries the mains the instances use in a hidden canvas; those mains are matched with the +//! components this file already holds by the identity recorded on them at their own paste (the +//! layer guid within one file, or the library key). Payloads are synthetic, built in code. + +use base64::Engine as _; +use figcraft_format::fig::kiwi::Kv; +use serde_json::json; + +use figcraft_doc::NodeKind; + +use super::{NodeId, Session, params}; +use crate::cmd::edit::{CLIP_CLOSE, CLIP_OPEN}; + +const B64: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD; + +type Fields = Vec<(&'static str, Kv<'static>)>; + +fn o(f: Fields) -> Kv<'static> { + Kv::Object(f) +} + +fn g(local: u64) -> Kv<'static> { + o(vec![("sessionID", Kv::Uint(1)), ("localID", Kv::Uint(local))]) +} + +fn xy(x: f32, y: f32) -> Kv<'static> { + o(vec![("x", Kv::Float(x)), ("y", Kv::Float(y))]) +} + +fn node(id: u64, parent: Option<(u64, &str)>, ty: &'static str, name: &str, mut more: Fields) -> Kv<'static> { + let mut v = vec![("guid", if id == 0 { o(vec![("sessionID", Kv::Uint(0)), ("localID", Kv::Uint(0))]) } else { g(id) })]; + if let Some((p, pos)) = parent { + let pg = if p == 0 { o(vec![("sessionID", Kv::Uint(0)), ("localID", Kv::Uint(0))]) } else { g(p) }; + v.push(("parentIndex", o(vec![("guid", pg), ("position", Kv::Str(pos.into()))]))); + } + v.push(("type", Kv::Enum(ty))); + v.push(("name", Kv::Str(name.into()))); + v.append(&mut more); + o(v) +} + +fn main_nodes(parent: u64, id: u64, key: Option<&'static str>) -> Vec> { + let mut f = vec![("size", xy(40.0, 20.0))]; + if let Some(k) = key { + f.push(("key", Kv::Str(k.into()))); + } + vec![node(id, Some((parent, "!")), "SYMBOL", "Button", f), node(id + 1, Some((id, "!")), "RECTANGLE", "Face", vec![("size", xy(40.0, 20.0))])] +} + +/// A paste of the main alone, as the first copy. +fn payload_main(id: u64, key: Option<&'static str>) -> Vec> { + let mut v = vec![node(0, None, "DOCUMENT", "Document", vec![]), node(1, Some((0, "!")), "CANVAS", "Page", vec![])]; + v.extend(main_nodes(1, id, key)); + v +} + +/// A paste of an instance of the main `id`, whose definition travels in the hidden canvas. +fn payload_instance(id: u64, key: Option<&'static str>, with_main: bool) -> Vec> { + let mut v = vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page", vec![]), + node(2, Some((0, "~")), "CANVAS", "Internal", vec![("internalOnly", Kv::Bool(true))]), + node(30, Some((1, "!")), "INSTANCE", "Copy", vec![("size", xy(40.0, 20.0)), ("symbolData", o(vec![("symbolID", g(id))]))]), + ]; + if with_main { + v.extend(main_nodes(2, id, key)); + } + v +} + +fn html(nodes: Vec>, file: &str) -> String { + let bytes = figcraft_format::fig::pack_canvas(&schema(), &o(vec![("nodeChanges", Kv::Array(nodes))])).expect("packs"); + let meta = B64.encode(json!({"fileKey": file}).to_string()); + format!( + r#""#, + B64.encode(bytes) + ) +} + +fn paste(s: &mut Session, html: String) -> serde_json::Value { + // A paste goes into the selected frame: the main just pasted is not a place for its instances. + s.execute("select.set", &json!({"ids": []})).expect("clears"); + s.execute("edit.pasteDesignLayers", &json!({ "html": html })).expect("pastes") +} + +fn ids(r: &serde_json::Value) -> Vec { + r["ids"].as_array().unwrap().iter().filter_map(params::id_of).collect() +} + +fn components(s: &Session) -> Vec { + s.doc().unwrap().nodes().filter(|n| matches!(n.kind, NodeKind::Component { .. })).map(|n| n.id).collect() +} + +fn instance_main(s: &Session, instance: NodeId) -> NodeId { + match &s.doc().unwrap().node(instance).unwrap().kind { + NodeKind::Instance { component, .. } => *component, + k => panic!("not an instance: {k:?}"), + } +} + +#[test] +fn instances_pasted_after_their_mains_link_to_them() { + let mut s = Session::new(); + let a = paste(&mut s, html(payload_main(20, None), "F1")); + let main = ids(&a)[0]; + assert_eq!(components(&s), [main]); + let r = paste(&mut s, html(payload_instance(20, None, true), "F1")); + let copy = ids(&r)[0]; + assert_eq!(instance_main(&s, copy), main, "the instance shows the main pasted first"); + assert_eq!(components(&s), [main], "no second component came along"); + let doc = s.doc().unwrap(); + let face = doc.node(copy).unwrap().children[0]; + let source = doc.node(face).unwrap().source.expect("the layer is linked to the main's layer"); + assert!(doc.is_ancestor(main, source), "inside the main"); + assert!(r.get("warnings").is_none_or(|w| w.as_array().is_some_and(|w| w.is_empty())), "{r}"); + s.execute("select.set", &json!({"ids": [copy]})).unwrap(); + s.execute("component.goToMain", &json!({"id": copy})).expect("goToMain succeeds"); +} + +#[test] +fn one_undo_removes_the_pasted_instance_and_keeps_the_main() { + let mut s = Session::new(); + let main = ids(&paste(&mut s, html(payload_main(20, None), "F1")))[0]; + let copy = ids(&paste(&mut s, html(payload_instance(20, None, true), "F1")))[0]; + assert!(s.undo().unwrap()); + let doc = s.doc().unwrap(); + assert!(!doc.contains(copy)); + assert!(doc.contains(main)); + assert_eq!(components(&s), [main]); +} + +#[test] +fn a_main_from_another_figma_file_is_not_matched_by_guid_alone() { + let mut s = Session::new(); + let main = ids(&paste(&mut s, html(payload_main(20, None), "F1")))[0]; + let r = paste(&mut s, html(payload_instance(20, None, true), "F2")); + let copy = ids(&r)[0]; + assert_ne!(instance_main(&s, copy), main, "the same guid in another file is another component"); +} + +#[test] +fn the_same_library_key_links_whatever_the_guids() { + let mut s = Session::new(); + let main = ids(&paste(&mut s, html(payload_main(20, Some("btn")), "F1")))[0]; + let r = paste(&mut s, html(payload_instance(77, Some("btn"), true), "F2")); + let copy = ids(&r)[0]; + assert_eq!(instance_main(&s, copy), main); +} + +#[test] +fn an_instance_whose_main_never_arrives_stays_as_today() { + let mut s = Session::new(); + let r = paste(&mut s, html(payload_instance(20, None, true), "F1")); + let copy = ids(&r)[0]; + let main = instance_main(&s, copy); + assert!(!s.doc().unwrap().contains(main), "the main stayed behind"); + let warnings = r["warnings"].to_string(); + assert!(warnings.contains("stay unlinked"), "{warnings}"); + s.execute("component.restoreMain", &json!({"id": copy})).expect("the main can be restored"); +} + +/// The export schema, with the library `key` field the payloads of a library's components carry. +fn schema() -> String { + figcraft_format::fig::EXPORT_SCHEMA.replacen("message NodeChange ", "message NodeChange string key=9999, ", 1) +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 302e7053e..54d14bae8 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -279,6 +279,8 @@ mod datafill_tests; #[cfg(test)] mod default_props_tests; #[cfg(test)] +mod design_paste_relink_tests; +#[cfg(test)] mod design_paste_tests; #[cfg(test)] mod dev_measurements_tests; diff --git a/crates/format/src/fig.rs b/crates/format/src/fig.rs index f7547c3d0..21c3ada49 100644 --- a/crates/format/src/fig.rs +++ b/crates/format/src/fig.rs @@ -34,6 +34,8 @@ mod map; mod missing_image_tests; mod network; #[cfg(test)] +mod paste_relink_tests; +#[cfg(test)] mod paste_style_tests; #[cfg(test)] mod prop_value_tests; @@ -68,7 +70,7 @@ use std::sync::Arc; use figcraft_doc::{Document, FileKind}; -pub use export::export; +pub use export::{SCHEMA as EXPORT_SCHEMA, export, pack_canvas}; use crate::FormatError; use kiwi::{Kv, Schema}; diff --git a/crates/format/src/fig/export.rs b/crates/format/src/fig/export.rs index f00de3606..364fbd7bc 100644 --- a/crates/format/src/fig/export.rs +++ b/crates/format/src/fig/export.rs @@ -69,7 +69,7 @@ const AUX: u32 = 2; /// The schema written into every file: `enum Name A=value …`, `struct Name type field, …` (every /// field, in order) and `message Name type field=id, …`, with the names, kinds and numbers the /// format gives them. Only what the export writes. -pub(super) const SCHEMA: &str = " +pub const SCHEMA: &str = " enum MessageType JOIN_START=0 NODE_CHANGES=1 enum NodePhase CREATED=0 REMOVED=1 enum NodeType NONE=0 DOCUMENT=1 CANVAS=2 GROUP=3 FRAME=4 BOOLEAN_OPERATION=5 VECTOR=6 STAR=7 LINE=8 ELLIPSE=9 RECTANGLE=10 REGULAR_POLYGON=11 ROUNDED_RECTANGLE=12 TEXT=13 SLICE=14 SYMBOL=15 INSTANCE=16 SECTION=25 VARIABLE=28 VARIABLE_SET=31 @@ -199,11 +199,7 @@ message Message MessageType type=1, uint sessionID=2, NodeChange[] nodeChanges=4 pub fn export(doc: &Document, thumbnail: Option<&[u8]>) -> Result<(Vec, Vec), FormatError> { let mut x = Exporter::new(doc); let message = x.message(); - let fail = |e: super::kiwi::KiwiError| FormatError::Io(format!(".fig export: {e}")); - let schema = Schema::parse(SCHEMA).map_err(fail)?; - let root = schema.find("Message").ok_or_else(|| FormatError::Io(".fig export: the schema has no Message".into()))?; - let body = encode::message(&schema, root, &message).map_err(fail)?; - let canvas = canvas(&encode::schema(&schema), &body)?; + let canvas = pack_canvas(SCHEMA, &message)?; let background = doc.pages.first().and_then(|p| doc.node(*p)).and_then(|p| match &p.kind { NodeKind::Page { background, .. } => Some(*background), _ => None, @@ -212,6 +208,17 @@ pub fn export(doc: &Document, thumbnail: Option<&[u8]>) -> Result<(Vec, Vec< Ok((bytes, x.warnings)) } +/// A `canvas.fig` holding `message` (a `Message` of the kiwi schema `schema_source`, normally +/// [`SCHEMA`]), as the design apps put it on the clipboard. Lets synthetic payloads be built +/// outside this crate. +pub fn pack_canvas(schema_source: &str, message: &Kv) -> Result, FormatError> { + let fail = |e: super::kiwi::KiwiError| FormatError::Io(format!(".fig export: {e}")); + let schema = Schema::parse(schema_source).map_err(fail)?; + let root = schema.find("Message").ok_or_else(|| FormatError::Io(".fig export: the schema has no Message".into()))?; + let body = encode::message(&schema, root, message).map_err(fail)?; + canvas(&encode::schema(&schema), &body) +} + fn too_large() -> FormatError { FormatError::Io("the document is too large for a .fig file".into()) } diff --git a/crates/format/src/fig/export/layer.rs b/crates/format/src/fig/export/layer.rs index b4fda9138..51aeffe1c 100644 --- a/crates/format/src/fig/export/layer.rs +++ b/crates/format/src/fig/export/layer.rs @@ -306,7 +306,7 @@ impl<'d> Exporter<'d> { { self.warn("Dev Mode annotations, statuses, resources, measurements and code links were left out"); } - if !n.plugin_data.is_empty() { + if n.plugin_data.keys().any(|k| !k.starts_with("fig.")) { self.warn("plugin data was left out"); } } diff --git a/crates/format/src/fig/export_tests.rs b/crates/format/src/fig/export_tests.rs index 9651a1025..3e9ac1994 100644 --- a/crates/format/src/fig/export_tests.rs +++ b/crates/format/src/fig/export_tests.rs @@ -754,6 +754,8 @@ fn canon(doc: &Document) -> Vec { .map(|id| { let mut n = doc.node(*id).unwrap().clone(); normalize(&mut n, &ix); + // The identity the import keeps of a file's components (#2022) is not written back. + n.plugin_data.retain(|k, _| !k.starts_with("fig.")); let mut v = serde_json::to_value(&n).unwrap(); // Written even when it's the identity: near-identity read back must compare. v["transform"] = serde_json::json!(n.transform.as_coeffs()); diff --git a/crates/format/src/fig/map/layer.rs b/crates/format/src/fig/map/layer.rs index e3de96368..8dbad0e01 100644 --- a/crates/format/src/fig/map/layer.rs +++ b/crates/format/src/fig/map/layer.rs @@ -184,6 +184,8 @@ impl<'a> Mapper<'a> { if own == "SYMBOL" && inst.is_none() { self.mapped_mains.insert(id.to_string()); } + let is_main = inst.is_none() && (own == "SYMBOL" || (own == "FRAME" && view.flag("isStateGroup") == Some(true))); + let lib_key = view.str("key").filter(|k| is_main && !k.is_empty() && k.len() <= 256); let mut o = Obj::new(); o.insert("id".into(), json!(rest_id)); // Private provenance for the .fig importer; ordinary REST import ignores it. @@ -197,6 +199,8 @@ impl<'a> Mapper<'a> { "slotContent": inst.is_some_and(|i| i.slot_content), // A size the instance gives this layer itself (kept when the instance relays out). "sizeOverride": entries.iter().any(|e| e.entry == Entry::Override && e.row.get("size").is_some()), + // The library key of a published main (components pasted later match by it). + "key": lib_key, }), ); o.insert("type".into(), json!(ty)); diff --git a/crates/format/src/fig/paste_relink_tests.rs b/crates/format/src/fig/paste_relink_tests.rs new file mode 100644 index 000000000..38ed48242 --- /dev/null +++ b/crates/format/src/fig/paste_relink_tests.rs @@ -0,0 +1,55 @@ +//! Layers pasted from another design app keep the identity they had there (#2022): a main's guid +//! (and its library key) lands in its plugin data, on the main and on every layer in it, so +//! instances pasted later can link to it. Built in code from synthetic payloads. + +use figcraft_doc::{Document, Node, NodeKind}; + +use super::kiwi::Kv; +use super::tests::{arr, canvas, g, node, o, s, schema, xy}; +use super::try_import; + +fn import(nodes: Vec>) -> Document { + let bytes = canvas(&schema(), &o(vec![("nodeChanges", arr(nodes))])); + try_import(&bytes, "Pasted layers").expect("design data").expect("it imports").0 +} + +fn named<'a>(doc: &'a Document, name: &str) -> &'a Node { + doc.nodes().find(|n| n.name == name).expect(name) +} + +#[test] +fn a_pasted_main_records_its_figma_identity() { + let doc = import(vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page", vec![]), + node(20, Some((1, "!")), "SYMBOL", "Button", vec![("size", xy(40.0, 20.0)), ("key", s("btn"))]), + node(21, Some((20, "!")), "RECTANGLE", "Face", vec![("size", xy(40.0, 20.0))]), + node(30, Some((1, "\"")), "RECTANGLE", "Loose", vec![("size", xy(5.0, 5.0))]), + ]); + let main = named(&doc, "Button"); + assert!(matches!(main.kind, NodeKind::Component { .. })); + assert_eq!(main.plugin_data.get("fig.guid").map(String::as_str), Some("1:20")); + assert_eq!(main.plugin_data.get("fig.key").map(String::as_str), Some("btn")); + let face = named(&doc, "Face"); + assert_eq!(face.plugin_data.get("fig.guid").map(String::as_str), Some("1:21"), "every layer of a main"); + assert!(!face.plugin_data.contains_key("fig.key")); + assert!(named(&doc, "Loose").plugin_data.is_empty(), "layers outside mains record nothing"); +} + +#[test] +fn a_cached_main_in_the_internal_canvas_is_an_instance_main_in_the_store() { + let doc = import(vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page", vec![]), + node(2, Some((0, "~")), "CANVAS", "Internal", vec![("internalOnly", Kv::Bool(true))]), + node(30, Some((1, "!")), "INSTANCE", "Copy", vec![("size", xy(40.0, 20.0)), ("symbolData", o(vec![("symbolID", g(20))]))]), + node(20, Some((2, "!")), "SYMBOL", "Button", vec![("size", xy(40.0, 20.0))]), + node(21, Some((20, "!")), "RECTANGLE", "Face", vec![("size", xy(40.0, 20.0))]), + ]); + let copy = doc.nodes().find(|n| n.name == "Copy").expect("the instance"); + let NodeKind::Instance { component, .. } = ©.kind else { panic!("the top is not an instance: {:?}", copy.kind) }; + assert!(doc.is_remote(*component), "its main is in the library store"); + let main = doc.node(*component).expect("main"); + assert_eq!(main.plugin_data.get("fig.guid").map(String::as_str), Some("1:20")); + assert_eq!(copy.plugin_data.get("fig.main").map(String::as_str), Some("1:20")); +} diff --git a/crates/format/src/rest.rs b/crates/format/src/rest.rs index 99acbab2f..ded2d27de 100644 --- a/crates/format/src/rest.rs +++ b/crates/format/src/rest.rs @@ -593,6 +593,9 @@ impl<'a> Ctx<'a> { if let Some(sources) = &mut self.fig_sources { sources.record(id, j, primary); } + if primary && self.fig_sources.is_some() { + self.record_identity(id, rid, ty, j); + } } match ty { "INSTANCE" => self.instances.push((id, j)), @@ -1131,6 +1134,40 @@ impl<'a> Ctx<'a> { } } + /// Keep the file's own identity of a main (and of every layer in it) in the layer's plugin data, + /// so instances pasted later can find mains pasted earlier: `fig.guid` (unique within one + /// file), `fig.key` (a library component's key, unique everywhere). Instances keep their + /// main's guid as `fig.main`. Only layers the file really holds (not the copies an instance + /// expands) are recorded. + fn record_identity(&mut self, id: NodeId, rest_id: &str, ty: &str, j: &Value) { + let meta = j.get(FIG_SOURCE_FIELD); + if meta.and_then(|m| m.get("expanded")).and_then(Value::as_bool) != Some(false) || rest_id.starts_with('I') || rest_id.len() > 41 { + return; + } + let is_main = matches!(ty, "COMPONENT" | "COMPONENT_SET"); + let in_main = is_main + || self + .doc + .ancestors(id) + .into_iter() + .any(|a| self.doc.node(a).is_some_and(|n| matches!(n.kind, NodeKind::Component { .. } | NodeKind::ComponentSet { .. }))); + let main = (ty == "INSTANCE").then(|| text(j, "componentId")).flatten().filter(|m| m.len() <= 41); + if !in_main && main.is_none() { + return; + } + let key = meta.and_then(|m| m.get("key")).and_then(Value::as_str).filter(|k| is_main && !k.is_empty()); + let Some(n) = self.doc.node_mut(id) else { return }; + if in_main { + n.plugin_data.insert("fig.guid".into(), rest_id.into()); + } + if let Some(k) = key { + n.plugin_data.insert("fig.key".into(), k.into()); + } + if let Some(m) = main { + n.plugin_data.insert("fig.main".into(), m.into()); + } + } + fn resolve_swap_defaults(&mut self) { for (owner, name, rest_id) in std::mem::take(&mut self.swap_defaults) { let Some(c) = self.component(&rest_id) else { diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index a90038427..bc0017f71 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (`.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (pasting an instance copied from a design app links it to its main component when that main was pasted earlier, matched by the identity kept on the main (#2022); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of `/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's @@ -39,8 +39,8 @@ and prototype interactions are still unchecked there. | BMP | — | yes | | — | | MP4, MOV, WebM (video fills, paid plans) | yes | **no** | shortcut: decoding H.264/HEVC/VP9 needs non-Rust libraries (FFmpeg or each platform's media framework); presenter playback would reuse the animated GIF clock | 4–8 | | Images over 4096 px | downscaled to 4096 | kept | | — | -| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`), never with a real clipboard from other software | with `.fig` | -| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), never with a real clipboard from other software | with `.fig` | +| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). A pasted main keeps the identity it had in its file (layer guid, and library key when it has one) in its plugin data (`fig.*` keys), together with the file key from the clipboard's metadata; an instance pasted later whose main is one of those components links to it (and its layers to the main's layers) instead of showing "Main component deleted": a guid matches only within the same file, a library key matches across files; an instance whose main was never pasted stays as before (restorable) with a note in the paste result, and pasting the main after the instance does not relink it yet (#2022). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`), never with a real clipboard from other software | with `.fig` | +| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). A pasted main keeps the identity it had in its file (layer guid, and library key when it has one) in its plugin data (`fig.*` keys), together with the file key from the clipboard's metadata; an instance pasted later whose main is one of those components links to it (and its layers to the main's layers) instead of showing "Main component deleted": a guid matches only within the same file, a library key matches across files; an instance whose main was never pasted stays as before (restorable) with a note in the paste result, and pasting the main after the instance does not relink it yet (#2022). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), never with a real clipboard from other software | with `.fig` | ## Export @@ -196,6 +196,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-09 | minor | M6, #2022: instances copied from a design app link to mains pasted earlier. The importer records each main's layer guids (and its library key) as `fig.*` plugin data, the paste reads the file key from the clipboard metadata, and the paste matches the mains an instance uses with components already in the file by guid within the same file or by library key, linking the instance and its layers to them; before, the main came along as a library copy the paste dropped, so the instance showed "Main component deleted". No match keeps the old result with a note. `fig.*` plugin data is not named in the `.fig` export's plugin-data note. Mains pasted after their instances are not relinked yet. | | 2026-11-08 | minor | M6, #2097 follow-up: per-point vector corner radii take the scale of the row supplying `vectorData`, including nested instance rows; override and derived rows are not scaled twice. Network caching distinguishes the instance scale even when resizing gives two vectors the same final box. Synthetic tests cover missing/unit factors, half/double scale, derived size alone, overridden and derived vector data, nested scale and equal-size cache separation. Layer-radius fallback remains the separate #2115 change. Numbers unchanged. | | 2026-11-08 | patch | #2097 / #2100: scaled-instance lengths reset to the unscaled main value survive export/import as explicit overrides. Dimensionless values and zero do not gain scale overrides. Exported factors stay within the importer's 0.001–1000 range; larger or smaller ratios use explicit values instead. Effect/grid payload rows above an inherited style link take precedence at their own scale, including nested instances and empty-list clears, without detaching styles. Synthetic regressions cover corners, dashes/shadows, layout/grids and bounds, typography and styled runs, linked text and nested styles. Numbers unchanged. | | 2026-11-07 | minor | `.fig` import, #2091 item 1: an instance scaled with the Scale tool stores `symbolData.uniformScaleFactor`, which the import never read, so the layers of a 128 px instance of a 256 px component came in at 256 px with the main's radii, strokes and spacing. The layers of an instance now take the main's lengths times the factor (composed through nested instances, so 0.5 inside 0.5 is 0.25 for the inner layers), the lengths the Scale tool scales: sizes and places, corner radii, stroke weights and dashes, effect radii, spreads and offsets, auto layout gaps and paddings, grid gaps, min and max sizes, layout grids, font sizes, pixel line heights and letter spacings, paragraph spacing and indent. A value an override or derived row gives is taken as written, already at the instance's scale; the instance's own size is the file's; a missing, non-finite, non-positive or out-of-range factor (outside 0.001 to 1000) changes nothing. Not scaled: vector outline paths (a network's points follow the layer's size), per-point corner radii, fixed grid tracks, image tile scales and glass effects. Tests: `fig::tests::a_scaled_instance_draws_its_layers_at_the_factor` and `fig::scale_factor_tests`. Numbers unchanged |