mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-26 04:58:50 +00:00
The change from #2337 by @TrevorBrown-dev, as one commit.
This commit is contained in:
@@ -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;
|
||||
|
||||
@@ -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<NodeId, (Vec<u32>, Vec<u32>)>,
|
||||
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<NodeId, Overlay>,
|
||||
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<Kv<'static>> = 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
|
||||
|
||||
@@ -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<Kv<'static>> {
|
||||
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<Kv<'static>> {
|
||||
}
|
||||
"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"),
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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<Vec<(String, f32, u64, u64)>>;
|
||||
|
||||
fn written(doc: &Document) -> (Written, Written, Vec<String>) {
|
||||
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<Vec<(String, f32)>> {
|
||||
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::<Vec<(String, f32)>>::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);
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user