mirror of
https://github.com/storytold/figcraft.git
synced 2026-12-05 22:58:51 +00:00
M6: instances pasted from Figma link to mains pasted earlier (#2022)
The .fig import now keeps each main's Figma identity (layer guid on the main and every layer in it, library key when present) in the node's plugin data as fig.* keys, and instances keep their main's guid as fig.main. The paste reads the file key from the clipboard's figmeta span and stamps it as fig.file. When the mains an instance uses are not in the pasted layers, adopt_pasted matches them with components the file already holds (same guid and file, or same library key) and links the instance and its layers to them. No match keeps today's result with one warning in the paste result. fig.* keys are not named in the .fig export's plugin-data note. Reverse order (mains pasted after their instances) is deferred. pack_canvas (and the export schema) are exposed so engine tests can build synthetic payloads. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Model-Effort: Opus 5.5 drove; Fable 5.1 briefed; Sonnet 5.5 wrote at medium
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
970cdfe664
commit
d2c4567eb0
@@ -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<NodeId>,
|
||||
map: &BTreeMap<NodeId, NodeId>,
|
||||
remote: &mut BTreeMap<NodeId, NodeId>,
|
||||
) {
|
||||
let todo: Vec<NodeId> = 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<NodeId> = 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<NodeId, NodeId> = BTreeMap::new();
|
||||
let mut follow = |doc: &mut Document, id: NodeId| -> NodeId {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -89,6 +89,27 @@ pub fn design_clipboard_buffer(html: &str) -> Option<Vec<u8>> {
|
||||
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<String> {
|
||||
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<Value> {
|
||||
(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<NodeId> = 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<NodeId> = 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<Value> {
|
||||
if !missing.is_empty() {
|
||||
out["missingImages"] = json!(missing);
|
||||
}
|
||||
if !other.issues.is_empty() {
|
||||
out["warnings"] = json!(other.issues);
|
||||
let mut warnings: Vec<String> = 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)
|
||||
}
|
||||
|
||||
@@ -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<Kv<'static>> {
|
||||
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<Kv<'static>> {
|
||||
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<Kv<'static>> {
|
||||
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<Kv<'static>>, 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#"<meta charset="utf-8"><span data-metadata="<!--(figmeta){meta}(/figmeta)-->"></span><span data-buffer="<!--{CLIP_OPEN}{}{CLIP_CLOSE}-->"></span>"#,
|
||||
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<NodeId> {
|
||||
r["ids"].as_array().unwrap().iter().filter_map(params::id_of).collect()
|
||||
}
|
||||
|
||||
fn components(s: &Session) -> Vec<NodeId> {
|
||||
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)
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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<u8>, Vec<String>), 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<u8>, 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<Vec<u8>, 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())
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -754,6 +754,8 @@ fn canon(doc: &Document) -> Vec<Value> {
|
||||
.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());
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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<Kv<'static>>) -> 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"));
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user