From 6b625a0d465992be204e7fda314450e2d9a3c10e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 19 Nov 2026 01:28:57 +0700 Subject: [PATCH] M6: .fig export writes ruler guides (#2336) (#2337) The change from #2337 by @TrevorBrown-dev, as one commit. --- crates/format/src/fig.rs | 2 + crates/format/src/fig/export.rs | 23 +++- crates/format/src/fig/export/common.rs | 24 +++- crates/format/src/fig/export/layer.rs | 8 +- crates/format/src/fig/guides_tests.rs | 162 +++++++++++++++++++++++++ docs/file-format-parity.md | 8 +- 6 files changed, 212 insertions(+), 15 deletions(-) create mode 100644 crates/format/src/fig/guides_tests.rs diff --git a/crates/format/src/fig.rs b/crates/format/src/fig.rs index 033d4f22d..db799ca70 100644 --- a/crates/format/src/fig.rs +++ b/crates/format/src/fig.rs @@ -25,6 +25,8 @@ mod export; #[cfg(test)] mod export_tests; #[cfg(test)] +mod guides_tests; +#[cfg(test)] mod interop_tests; #[cfg(test)] mod layer_cap_tests; diff --git a/crates/format/src/fig/export.rs b/crates/format/src/fig/export.rs index c0de279c1..d2f548abd 100644 --- a/crates/format/src/fig/export.rs +++ b/crates/format/src/fig/export.rs @@ -154,6 +154,7 @@ message VectorData uint vectorNetworkBlob=1, Vector normalizedSize=2, NodeChange message TextPathStart float tValue=1, bool forward=2 message ArcData float startingAngle=1, float endingAngle=2, float innerRadius=3 message OptionalVector Vector value=1 +message Guide Axis axis=1, float offset=2, GUID guid=3 message LayoutGrid LayoutGridType type=1, Axis axis=2, bool visible=3, int numSections=4, float offset=5, float sectionSize=6, float gutterSize=7, Color color=8, LayoutGridPattern pattern=9, VariableData numSectionsVar=10, VariableData offsetVar=11, VariableData sectionSizeVar=12, VariableData gutterSizeVar=13 struct ExportConstraint ExportConstraintType type, float value message ExportSettings string suffix=1, ImageType imageType=2, ExportConstraint constraint=3 @@ -191,7 +192,7 @@ message GridTrackSizingFunction GridTrackSizingType type=1, float value=2 message GridTrackSize GridTrackSizingFunction minSizing=1, GridTrackSizingFunction maxSizing=2 message GUIDGridTrackSizeMapEntry GUID id=1, GridTrackSize trackSize=2 message GUIDGridTrackSizeMap GUIDGridTrackSizeMapEntry[] entries=1 -message NodeChange GUID guid=1, NodePhase phase=2, ParentIndex parentIndex=3, NodeType type=4, string name=5, bool visible=6, bool locked=7, float opacity=8, BlendMode blendMode=9, Vector size=11, Matrix transform=12, bool mask=16, MaskType maskType=317, float backgroundOpacity=19, bool backgroundEnabled=15, bool internalOnly=142, string description=318, StyleType styleType=163, string sortPosition=320, StyleId styleIdForFill=332, StyleId styleIdForStrokeFill=333, StyleId styleIdForText=334, StyleId styleIdForEffect=335, StyleId styleIdForGrid=336, VariableDataMap variableConsumptionMap=307, VariableModeBySetMap variableModeBySetMap=316, VariableSetMode[] variableSetModes=312, VariableSetID variableSetID=313, VariableResolvedDataType variableResolvedType=314, VariableDataValues variableDataValues=315, VariableScope[] variableScopes=353, DocumentColorProfile documentColorProfile=349, Paint[] fillPaints=38, Paint[] strokePaints=39, float strokeWeight=26, StrokeAlign strokeAlign=29, StrokeJoin strokeJoin=31, StrokeCap strokeCap=30, float[] dashPattern=13, float miterLimit=25, bool borderStrokeWeightsIndependent=299, float borderTopWeight=295, float borderRightWeight=298, float borderBottomWeight=296, float borderLeftWeight=297, Effect[] effects=43, float cornerRadius=20, float cornerSmoothing=160, bool rectangleCornerRadiiIndependent=149, float rectangleTopLeftCornerRadius=145, float rectangleTopRightCornerRadius=146, float rectangleBottomRightCornerRadius=148, float rectangleBottomLeftCornerRadius=147, ConstraintType horizontalConstraint=28, ConstraintType verticalConstraint=37, bool frameMaskDisabled=115, bool resizeToFit=117, bool isStateGroup=225, StateGroupPropertyValueOrder[] stateGroupPropertyValueOrders=238, bool sectionContentsHidden=283, Color backgroundColor=50, StackMode stackMode=105, float stackSpacing=107, float stackCounterSpacing=324, StackWrap stackWrap=323, StackCounterAlignContent stackCounterAlignContent=343, float stackHorizontalPadding=209, float stackVerticalPadding=210, float stackPaddingRight=233, float stackPaddingBottom=234, StackJustify stackPrimaryAlignItems=230, StackAlign stackCounterAlignItems=231, StackSize stackPrimarySizing=229, StackSize stackCounterSizing=221, bool bordersTakeSpace=294, bool stackReverseZIndex=271, float gridColumnGap=438, float gridRowGap=437, GUIDPositionMap gridColumns=436, GUIDPositionMap gridRows=435, GUIDGridTrackSizeMap gridColumnsSizing=474, GUIDGridTrackSizeMap gridRowsSizing=475, float stackChildPrimaryGrow=232, StackCounterAlign stackChildAlignSelf=236, StackPositioning stackPositioning=269, OptionalVector minSize=325, OptionalVector maxSize=326, GUID gridColumnAnchor=440, GUID gridRowAnchor=439, uint gridColumnSpan=442, uint gridRowSpan=441, LayoutGrid[] layoutGrids=47, ExportSettings[] exportSettings=45, TextData textData=42, FontName fontName=41, float fontSize=21, Number lineHeight=40, Number letterSpacing=165, TextCase textCase=34, TextDecoration textDecoration=35, TextAlignHorizontal textAlignHorizontal=32, TextAlignVertical textAlignVertical=33, TextAutoResize textAutoResize=46, TextTruncation textTruncation=280, int maxLines=351, float paragraphSpacing=23, float paragraphIndent=22, float listSpacing=264, LeadingTrim leadingTrim=322, bool hangingPunctuation=337, bool hangingList=339, Hyperlink hyperlink=223, bool autoRename=14, bool fontVariantCommonLigatures=127, bool fontVariantContextualLigatures=128, string fontVersion=202, uint textUserLayoutVersion=203, uint textExplicitLayoutVersion=396, uint textBidiVersion=279, float textTracking=27, bool textDecorationSkipInk=412, EmojiImageSet emojiImageSet=391, uint styleID=49, Path[] fillGeometry=51, Path[] strokeGeometry=52, VectorData vectorData=48, TextPathStart textPathStart=432, VectorMirror handleMirroring=44, uint count=10, float starInnerScale=24, ArcData arcData=195, BooleanOperation booleanOperation=36, string symbolDescription=144, VariableWidthPoint[] variableWidthPoints=447, PluginData[] pluginData=204, SymbolData symbolData=113, NodeChange[] derivedSymbolData=125, GUID overriddenSymbolID=143, ComponentPropDef[] componentPropDefs=266, ComponentPropRef[] componentPropRefs=267, ComponentPropAssignment[] componentPropAssignments=268, VariantPropSpec[] variantPropSpecs=483, VariableDataMap parameterConsumptionMap=445, GUIDPath guidPath=111, PrototypeInteraction[] prototypeInteractions=226, PrototypeStartingPoint prototypeStartingPoint=249, ScrollDirection scrollDirection=159, ScrollBehavior scrollBehavior=186, OverlayPositionType overlayPositionType=198, OverlayBackgroundInteraction overlayBackgroundInteraction=200, OverlayBackgroundAppearance overlayBackgroundAppearance=201, Color prototypeBackgroundColor=141 +message NodeChange GUID guid=1, NodePhase phase=2, ParentIndex parentIndex=3, NodeType type=4, string name=5, bool visible=6, bool locked=7, float opacity=8, BlendMode blendMode=9, Vector size=11, Matrix transform=12, bool mask=16, MaskType maskType=317, float backgroundOpacity=19, bool backgroundEnabled=15, bool internalOnly=142, string description=318, StyleType styleType=163, string sortPosition=320, StyleId styleIdForFill=332, StyleId styleIdForStrokeFill=333, StyleId styleIdForText=334, StyleId styleIdForEffect=335, StyleId styleIdForGrid=336, VariableDataMap variableConsumptionMap=307, VariableModeBySetMap variableModeBySetMap=316, VariableSetMode[] variableSetModes=312, VariableSetID variableSetID=313, VariableResolvedDataType variableResolvedType=314, VariableDataValues variableDataValues=315, VariableScope[] variableScopes=353, DocumentColorProfile documentColorProfile=349, Paint[] fillPaints=38, Paint[] strokePaints=39, float strokeWeight=26, StrokeAlign strokeAlign=29, StrokeJoin strokeJoin=31, StrokeCap strokeCap=30, float[] dashPattern=13, float miterLimit=25, bool borderStrokeWeightsIndependent=299, float borderTopWeight=295, float borderRightWeight=298, float borderBottomWeight=296, float borderLeftWeight=297, Effect[] effects=43, float cornerRadius=20, float cornerSmoothing=160, bool rectangleCornerRadiiIndependent=149, float rectangleTopLeftCornerRadius=145, float rectangleTopRightCornerRadius=146, float rectangleBottomRightCornerRadius=148, float rectangleBottomLeftCornerRadius=147, ConstraintType horizontalConstraint=28, ConstraintType verticalConstraint=37, bool frameMaskDisabled=115, bool resizeToFit=117, bool isStateGroup=225, StateGroupPropertyValueOrder[] stateGroupPropertyValueOrders=238, bool sectionContentsHidden=283, Color backgroundColor=50, StackMode stackMode=105, float stackSpacing=107, float stackCounterSpacing=324, StackWrap stackWrap=323, StackCounterAlignContent stackCounterAlignContent=343, float stackHorizontalPadding=209, float stackVerticalPadding=210, float stackPaddingRight=233, float stackPaddingBottom=234, StackJustify stackPrimaryAlignItems=230, StackAlign stackCounterAlignItems=231, StackSize stackPrimarySizing=229, StackSize stackCounterSizing=221, bool bordersTakeSpace=294, bool stackReverseZIndex=271, float gridColumnGap=438, float gridRowGap=437, GUIDPositionMap gridColumns=436, GUIDPositionMap gridRows=435, GUIDGridTrackSizeMap gridColumnsSizing=474, GUIDGridTrackSizeMap gridRowsSizing=475, float stackChildPrimaryGrow=232, StackCounterAlign stackChildAlignSelf=236, StackPositioning stackPositioning=269, OptionalVector minSize=325, OptionalVector maxSize=326, GUID gridColumnAnchor=440, GUID gridRowAnchor=439, uint gridColumnSpan=442, uint gridRowSpan=441, LayoutGrid[] layoutGrids=47, ExportSettings[] exportSettings=45, TextData textData=42, FontName fontName=41, float fontSize=21, Number lineHeight=40, Number letterSpacing=165, TextCase textCase=34, TextDecoration textDecoration=35, TextAlignHorizontal textAlignHorizontal=32, TextAlignVertical textAlignVertical=33, TextAutoResize textAutoResize=46, TextTruncation textTruncation=280, int maxLines=351, float paragraphSpacing=23, float paragraphIndent=22, float listSpacing=264, LeadingTrim leadingTrim=322, bool hangingPunctuation=337, bool hangingList=339, Hyperlink hyperlink=223, bool autoRename=14, bool fontVariantCommonLigatures=127, bool fontVariantContextualLigatures=128, string fontVersion=202, uint textUserLayoutVersion=203, uint textExplicitLayoutVersion=396, uint textBidiVersion=279, float textTracking=27, bool textDecorationSkipInk=412, EmojiImageSet emojiImageSet=391, uint styleID=49, Path[] fillGeometry=51, Path[] strokeGeometry=52, VectorData vectorData=48, TextPathStart textPathStart=432, VectorMirror handleMirroring=44, uint count=10, float starInnerScale=24, ArcData arcData=195, BooleanOperation booleanOperation=36, string symbolDescription=144, VariableWidthPoint[] variableWidthPoints=447, PluginData[] pluginData=204, SymbolData symbolData=113, NodeChange[] derivedSymbolData=125, GUID overriddenSymbolID=143, ComponentPropDef[] componentPropDefs=266, ComponentPropRef[] componentPropRefs=267, ComponentPropAssignment[] componentPropAssignments=268, VariantPropSpec[] variantPropSpecs=483, VariableDataMap parameterConsumptionMap=445, GUIDPath guidPath=111, PrototypeInteraction[] prototypeInteractions=226, PrototypeStartingPoint prototypeStartingPoint=249, ScrollDirection scrollDirection=159, ScrollBehavior scrollBehavior=186, OverlayPositionType overlayPositionType=198, OverlayBackgroundInteraction overlayBackgroundInteraction=200, OverlayBackgroundAppearance overlayBackgroundAppearance=201, Color prototypeBackgroundColor=141, Guide[] guides=138 struct Blob byte[] bytes message Message MessageType type=1, uint sessionID=2, NodeChange[] nodeChanges=4, Blob[] blobs=6 "; @@ -418,6 +419,8 @@ struct Exporter<'d> { /// Grid tracks of written grid frames: (columns, rows) local ids (session [`AUX`]). tracks: BTreeMap, Vec)>, aux: u32, + /// Session of the last guide's GUID: guides count from the session after [`AUX`], one session each, local id 1. + guide_session: u32, overlays: BTreeMap, trigger_size: [f64; 2], /// Flow starting points: layer → (order, name). @@ -458,6 +461,7 @@ impl<'d> Exporter<'d> { child_defs: BTreeMap::new(), tracks: BTreeMap::new(), aux: 0, + guide_session: AUX, overlays: BTreeMap::new(), trigger_size: [0.0, 0.0], starts: BTreeMap::new(), @@ -475,6 +479,23 @@ impl<'d> Exporter<'d> { } } + /// A node's ruler `guides` field: Y is a horizontal guide and X a vertical one, the offset the ruler's reading (a + /// page's in page coordinates, a frame's in the frame's own). + fn guides(&mut self, guides: &[figcraft_doc::Guide], f: &mut Fields) { + // A guide whose offset isn't finite shows nowhere in the document: it is left out, not written at 0. + let list: Vec> = guides + .iter() + .filter(|g| g.offset.is_finite()) + .map(|g| { + self.guide_session = self.guide_session.saturating_add(1); + o(vec![("axis", e(if g.vertical { "X" } else { "Y" })), ("offset", fl(g.offset)), ("guid", guid(self.guide_session, 1))]) + }) + .collect(); + if !list.is_empty() { + f.push(("guides", arr(list))); + } + } + fn next_aux(&mut self) -> u32 { self.aux += 1; self.aux diff --git a/crates/format/src/fig/export/common.rs b/crates/format/src/fig/export/common.rs index a28951cf8..3ca682682 100644 --- a/crates/format/src/fig/export/common.rs +++ b/crates/format/src/fig/export/common.rs @@ -111,11 +111,22 @@ pub(super) fn scaled(a: &Kv<'static>, b: &Kv<'static>, k: f64, slack: f64) -> bo } } +/// A `guides` list without its guids. Every guide written has a guid of its own, so two layers' guides are the same +/// when their axes and offsets are. +fn bare_guides(v: &Kv<'static>) -> Vec> { + let bare = |g: &Kv<'static>| match g { + Kv::Object(f) => o(f.iter().filter(|(k, _)| *k != "guid").cloned().collect()), + other => other.clone(), + }; + v.list().iter().map(bare).collect() +} + /// The fields of `mine` that differ from `theirs` (a layer and the main's layer it mirrors), and /// the ones only `theirs` has at their empty values. pub(super) fn changed(mine: Fields, theirs: &Fields) -> Fields { + let same = |k: &str, a: &Kv<'static>, b: &Kv<'static>| a == b || (k == "guides" && bare_guides(a) == bare_guides(b)); let cleared: Fields = theirs.iter().filter(|(k, _)| !mine.iter().any(|(mk, _)| mk == k)).filter_map(|(k, _)| Some((*k, unset(k)?))).collect(); - let mut out: Fields = mine.into_iter().filter(|(k, v)| !theirs.iter().any(|(tk, tv)| tk == k && tv == v)).collect(); + let mut out: Fields = mine.into_iter().filter(|(k, v)| !theirs.iter().any(|(tk, tv)| tk == k && same(k, tv, v))).collect(); out.extend(cleared); out } @@ -181,9 +192,14 @@ fn unset(key: &str) -> Option> { } "variableConsumptionMap" | "variableModeBySetMap" | "gridColumnsSizing" | "gridRowsSizing" => o(vec![("entries", arr(Vec::new()))]), "mask" | "rectangleCornerRadiiIndependent" | "borderStrokeWeightsIndependent" => b(false), - "effects" | "dashPattern" | "layoutGrids" | "exportSettings" | "prototypeInteractions" | "fillGeometry" | "variableWidthPoints" => { - arr(Vec::new()) - } + "effects" + | "dashPattern" + | "layoutGrids" + | "exportSettings" + | "prototypeInteractions" + | "fillGeometry" + | "variableWidthPoints" + | "guides" => arr(Vec::new()), "cornerSmoothing" | "stackChildPrimaryGrow" => fl(0.0), "stackMode" => e("NONE"), "stackChildAlignSelf" | "stackPositioning" => e("AUTO"), diff --git a/crates/format/src/fig/export/layer.rs b/crates/format/src/fig/export/layer.rs index 0ab593f1a..3b718cfc2 100644 --- a/crates/format/src/fig/export/layer.rs +++ b/crates/format/src/fig/export/layer.rs @@ -23,9 +23,7 @@ impl<'d> Exporter<'d> { f.extend([("type", e("CANVAS")), ("name", s(&n.name))]); f.extend(root_fields()); f.extend([("backgroundColor", color(*background)), ("backgroundOpacity", fl(background.a.into())), ("backgroundEnabled", b(true))]); - if !n.guides.is_empty() { - self.warn("ruler guides were left out"); - } + self.guides(&n.guides, &mut f); let defaults = figcraft_doc::proto::PrototypeSettings::default(); // Every page writes its colour, so Figma shows the same one (a page without the field shows Figma's own default). // The colour is written opaque: the record measured has alpha 1, and the import reads the colour as opaque and @@ -318,9 +316,7 @@ impl<'d> Exporter<'d> { f.push(("variableConsumptionMap", o(vec![("entries", arr(bound.entries))]))); } self.modes(n, f); - if !n.guides.is_empty() { - self.warn("ruler guides were left out"); - } + self.guides(&n.guides, f); if !n.annotations.is_empty() || !n.dev_resources.is_empty() || !n.code_links.is_empty() diff --git a/crates/format/src/fig/guides_tests.rs b/crates/format/src/fig/guides_tests.rs new file mode 100644 index 000000000..bf4a6a8e8 --- /dev/null +++ b/crates/format/src/fig/guides_tests.rs @@ -0,0 +1,162 @@ +//! Ruler guides in `.fig` exports: a page's and a frame's `guides`, as a synthetic file saved from +//! Figma's web app wrote them. + +use std::collections::BTreeMap; + +use figcraft_doc::{Document, Guide, NodeId, NodeKind}; + +use super::kiwi::Kv; +use super::{Archive, decode_canvas, export}; + +/// A document with a page guide at `page` and a frame guide at `frame` (both vertical and +/// horizontal), and the frame's id. +fn doc_with(page: &[Guide], frame: &[Guide]) -> (Document, NodeId) { + let mut doc = Document::new("t"); + let p = doc.first_page().unwrap(); + let f = doc.create(p, NodeKind::Frame, "Frame 1", 1000.0, 500.0, 400.0, 300.0).unwrap(); + doc.node_mut(p).unwrap().guides = page.to_vec(); + doc.node_mut(f).unwrap().guides = frame.to_vec(); + (doc, f) +} + +fn vertical(offset: f64) -> Guide { + Guide { vertical: true, offset } +} + +fn horizontal(offset: f64) -> Guide { + Guide { vertical: false, offset } +} + +/// The `guides` of the CANVAS record and of the FRAME record, as (axis, offset, sessionID, localID). +type Written = Option>; + +fn written(doc: &Document) -> (Written, Written, Vec) { + let (bytes, warnings) = export(doc, None).unwrap(); + let archive = Archive::open(&bytes).unwrap(); + let (schema, message) = decode_canvas(&archive.canvas).unwrap(); + let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap(); + let nodes = msg.get("nodeChanges").unwrap().list(); + let of = |ty: &str| { + let n = nodes + .iter() + .find(|n| n.get("type").and_then(Kv::str) == Some(ty) && n.get("name").and_then(Kv::str) != Some("Internal Only Canvas")) + .unwrap(); + n.get("guides").map(|g| { + g.list() + .iter() + .map(|x| { + let id = x.get("guid").unwrap(); + ( + x.get("axis").and_then(Kv::str).unwrap().to_string(), + x.get("offset").and_then(Kv::f64).unwrap() as f32, + id.get("sessionID").and_then(Kv::f64).unwrap() as u64, + id.get("localID").and_then(Kv::f64).unwrap() as u64, + ) + }) + .collect() + }) + }; + (of("CANVAS"), of("FRAME"), warnings) +} + +/// A component with a vertical guide at 24 that holds a frame with a vertical guide at 7, and an instance of it as the +/// engine makes one: its root a copy of the main's, guides included, and its layer mirroring the main's. Returns the +/// instance. +fn component_and_instance() -> (Document, NodeId) { + let mut doc = Document::new("t"); + let p = doc.first_page().unwrap(); + let kind = NodeKind::Component { description: String::new(), props: BTreeMap::new(), prop_order: Vec::new() }; + let main = doc.create(p, kind, "Card", 0.0, 0.0, 200.0, 100.0).unwrap(); + let inner = doc.create(main, NodeKind::Frame, "Inner", 20.0, 30.0, 100.0, 50.0).unwrap(); + doc.node_mut(main).unwrap().guides = vec![vertical(24.0)]; + doc.node_mut(inner).unwrap().guides = vec![vertical(7.0)]; + let inst = doc.alloc_id(); + let mut root = doc.node(main).unwrap().clone(); + (root.id, root.kind, root.parent, root.source) = (inst, NodeKind::Instance { component: main, props: BTreeMap::new() }, None, Some(main)); + root.children.clear(); + doc.insert(root, p, None).unwrap(); + let mut layer = doc.node(inner).unwrap().clone(); + (layer.id, layer.parent, layer.source) = (doc.alloc_id(), None, Some(inner)); + doc.insert(layer, inst, None).unwrap(); + (doc, inst) +} + +/// The `guides` of every instance override row in the file, as (axis, offset). +fn overridden(doc: &Document) -> Vec> { + let (bytes, _) = export(doc, None).unwrap(); + let archive = Archive::open(&bytes).unwrap(); + let (schema, message) = decode_canvas(&archive.canvas).unwrap(); + let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap(); + let nodes = msg.get("nodeChanges").unwrap().list(); + let rows = nodes.iter().flat_map(|n| n.get("symbolData").and_then(|d| d.get("symbolOverrides")).map(Kv::list).unwrap_or_default()); + rows.filter_map(|row| row.get("guides")) + .map(|g| { + g.list() + .iter() + .map(|x| (x.get("axis").and_then(Kv::str).unwrap().to_string(), x.get("offset").and_then(Kv::f64).unwrap() as f32)) + .collect() + }) + .collect() +} + +#[test] +fn a_page_guide_at_120_and_a_frame_guide_at_40_are_written_as_figma_writes_them() { + let (doc, _) = doc_with(&[horizontal(120.0), vertical(120.0)], &[horizontal(40.0), vertical(40.0)]); + let (page, frame, warnings) = written(&doc); + // Axis Y is a horizontal guide and X a vertical one; the offsets are the ruler readings (a frame's in its own + // coordinates); localID is 1 and sessionID counts the file's guides from 3. + assert_eq!(page, Some(vec![("Y".into(), 120.0, 3, 1), ("X".into(), 120.0, 4, 1)])); + assert_eq!(frame, Some(vec![("Y".into(), 40.0, 5, 1), ("X".into(), 40.0, 6, 1)])); + assert!(warnings.iter().all(|w| !w.contains("ruler guides")), "{warnings:?}"); +} + +#[test] +fn a_frame_without_guides_and_a_page_without_guides_write_no_field() { + let (doc, _) = doc_with(&[], &[]); + let (page, frame, warnings) = written(&doc); + assert_eq!(page, None); + assert_eq!(frame, None); + assert!(warnings.iter().all(|w| !w.contains("ruler guides")), "{warnings:?}"); +} + +#[test] +fn a_frame_guide_is_not_shifted_by_the_frames_position() { + let (doc, _) = doc_with(&[], &[vertical(78.0)]); + let (_, frame, _) = written(&doc); + assert_eq!(frame, Some(vec![("X".into(), 78.0, 3, 1)])); +} + +#[test] +fn an_instance_overrides_guides_only_where_they_differ_from_its_mains() { + let (mut doc, inst) = component_and_instance(); + // Untouched: the instance's guides and its layer's are the main's. + assert_eq!(overridden(&doc), Vec::>::new()); + // Its own guide: one override, on the instance. + doc.node_mut(inst).unwrap().guides = vec![horizontal(60.0)]; + assert_eq!(overridden(&doc), vec![vec![("Y".to_string(), 60.0)]]); + // Its guides removed: an empty list, or it would show the main's. + doc.node_mut(inst).unwrap().guides.clear(); + assert_eq!(overridden(&doc), vec![Vec::new()]); +} + +#[test] +fn a_guide_whose_offset_is_not_finite_is_left_out() { + let (doc, _) = doc_with(&[vertical(f64::NAN), vertical(10.0), horizontal(f64::INFINITY)], &[horizontal(f64::NEG_INFINITY)]); + let (page, frame, _) = written(&doc); + assert_eq!(page, Some(vec![("X".into(), 10.0, 3, 1)])); + assert_eq!(frame, None); +} + +#[test] +fn the_schema_numbers_the_guides() { + let s = super::kiwi::Schema::parse(super::export::SCHEMA).unwrap(); + let def = |n: &str| s.defs.iter().find(|d| d.name == n).unwrap(); + let field = |d: &str, f: &str| def(d).fields.iter().find(|x| x.name == f).unwrap().value; + assert_eq!(field("NodeChange", "guides"), 138); + assert_eq!(field("Guide", "axis"), 1); + assert_eq!(field("Guide", "offset"), 2); + assert_eq!(field("Guide", "guid"), 3); + let axis = def("Axis"); + assert_eq!(axis.fields.iter().find(|x| x.name == "X").unwrap().value, 0); + assert_eq!(axis.fields.iter().find(|x| x.name == "Y").unwrap().value, 1); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index cee929d66..c5d777bcf 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-17 · **Change:** minor (`.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.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-19 · **Change:** minor (`.fig` export writes ruler guides (#2336); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.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 @@ -90,7 +90,7 @@ an inherited style link keep their own values and the link; stale copies on the still yield to the style. These cases have synthetic export/import regressions, including nested scales and empty-style clears; they have not been checked in other software. -- **Written:** pages (name, background, prototype background as an opaque colour, for every page); frames, groups, sections, rectangles (as rounded +- **Written:** pages (name, background, ruler guides, prototype background as an opaque colour, for every page); the ruler guides of frames, components and instances, in the layer's own coordinates; frames, groups, sections, rectangles (as rounded rectangles, with their four radii), ellipses (arcs), polygons, stars, lines, vectors (editable network blobs with per-point corner radius, handle mirroring, caps and joins, each filled area's own paints, plus the outline of their filled areas), text, boolean groups, slices; the fill outline of frames and shapes and the @@ -136,8 +136,7 @@ scales and empty-style clears; they have not been checked in other software. properties, arc fields, font weight: written as the values they give), text styles on part of a text (written as values), the paint frames of vector regions, variables' publishing, code syntax and inheritance settings, extended collections (written as collections of their own), comments, Developer Mode annotations, statuses, - resources, measurements and code links, plugin data, ruler - guides, a page's prototype device settings (device, rotation, colour, custom size, responsive), the opacity of a page's prototype background (written opaque), slot properties and slot content, brush + resources, measurements and code links, plugin data, a page's prototype device settings (device, rotation, colour, custom size, responsive), the opacity of a page's prototype background (written opaque), slot properties and slot content, brush strokes (written plain), strokes wider on one side of their path (written as filled outlines, or with the width on both sides when the shape has a fill too), pattern fills, WebP export settings (written as PNG), glass settings other than frost, springs other than Gentle (written as ease @@ -196,6 +195,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | M6, #2336: `.fig` export writes ruler guides: a page's and a frame's `guides` (each an `Axis` Y for a horizontal guide and X for a vertical one, the offset as the ruler reads it, a frame's in its own coordinates, and a guid of its own: local id 1 and a session id counted up from 3), as measured on a page and an unrotated frame in a synthetic file saved from Figma's web app. The "ruler guides were left out" warnings are gone. An instance writes a `guides` override only where its guides differ from its main's, and a guide whose offset isn't finite is left out. Our own import does not read guides yet, so this is checked by reading the written records only, not in other software. Numbers unchanged. | | 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. | | 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Pasted content from other apps, PNG. | | 2026-11-12 | minor | M6, #2302: the `.fig` export writes the paints of a vector's own regions: each region with paints of its own (an empty list means unfilled) names an entry of the network's style table (`styleOverrideTable[].fillPaints`), equal lists share one entry, and a region without paints writes style 0. The fill outline is still one path with style 0. A region's kept paint frame is still left out, with a narrower warning. The importer already read this; not checked in other software |